Skip to content

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

Go

fix(agent): clear stale session id when a resumed ACP session is gone [MUL-3216] (#4015)

Truffle6acca84c28f2
diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.go
index ad03246a48..930e575308 100644
--- a/server/pkg/agent/hermes.go
+++ b/server/pkg/agent/hermes.go
@@ -5,6 +5,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"log/slog"
@@ -298,6 +299,17 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
b.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) {
+ // 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
+ // the daemon's resume-failure fallback retries fresh.
+ b.cfg.Logger.Warn("resumed session not found at set_model time; clearing session id so the daemon retries fresh",
+ "backend", "hermes",
+ "session_id", sessionID,
+ )
+ sessionID = ""
+ }
resCh <- Result{
Status: finalStatus,
Error: finalError,
@@ -338,6 +350,23 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
} else {
finalStatus = "failed"
finalError = fmt.Sprintf("hermes session/prompt failed: %v", err)
+ if opts.ResumeSessionID != "" && isACPSessionNotFound(err) {
+ // The agent no longer knows the session we resumed.
+ // Hermes echoes the requested id back from
+ // session/resume even when the session is gone, so
+ // resolveResumedSessionID can't catch this — it only
+ // surfaces here, at prompt time. Return an empty
+ // SessionID so the daemon's resume-failure fallback
+ // retries with a fresh session and stores the
+ // replacement id; keeping the stale id makes every
+ // future dispatch on this (agent, issue) fail the
+ // same way.
+ b.cfg.Logger.Warn("resumed session not found at prompt time; clearing session id so the daemon retries fresh",
+ "backend", "hermes",
+ "session_id", sessionID,
+ )
+ sessionID = ""
+ }
}
} else {
// The prompt completed. Check if we got a promptDone result
@@ -607,6 +636,46 @@ func (c *hermesClient) handleAgentRequest(raw map[string]json.RawMessage) {
}
}
+// acpRPCError is a JSON-RPC error frame returned by the agent process.
+// It renders exactly like the flat string handleResponse used to build
+// with fmt.Errorf, so logs and surfaced task errors are unchanged, but
+// keeps the code and message structured so callers can branch on the
+// error class (see isACPSessionNotFound) instead of parsing text.
+type acpRPCError struct {
+ Method string
+ Code int
+ Message string
+ Data string
+}
+
+func (e *acpRPCError) Error() string {
+ if e.Data != "" {
+ return fmt.Sprintf("%s: %s (code=%d, data=%s)", e.Method, e.Message, e.Code, e.Data)
+ }
+ return fmt.Sprintf("%s: %s (code=%d)", e.Method, e.Message, e.Code)
+}
+
+// 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
+// (Internal error), Kiro puts "No session found with id ..." in
+// `data` under -32603, and kimi-cli raises invalid_params (-32602)
+// with {"session_id": "Session not found"} in `data` for every
+// unknown-session path (src/kimi_cli/acp/server.py) — so neither the
+// code nor the text alone is discriminating and both are matched.
+func isACPSessionNotFound(err error) bool {
+ var rpcErr *acpRPCError
+ if !errors.As(err, &rpcErr) {
+ return false
+ }
+ if rpcErr.Code != -32603 && rpcErr.Code != -32602 {
+ return false
+ }
+ text := strings.ToLower(rpcErr.Message + " " + rpcErr.Data)
+ return strings.Contains(text, "session not found") ||
+ strings.Contains(text, "no session found")
+}
+
func (c *hermesClient) handleResponse(raw map[string]json.RawMessage) {
var id int
if err := json.Unmarshal(raw["id"], &id); err != nil {
@@ -651,11 +720,7 @@ func (c *hermesClient) handleResponse(raw map[string]json.RawMessage) {
detail = string(rpcErr.Data)
}
}
- if detail != "" {
- pr.ch <- rpcResult{err: fmt.Errorf("%s: %s (code=%d, data=%s)", pr.method, rpcErr.Message, rpcErr.Code, detail)}
- } else {
- pr.ch <- rpcResult{err: fmt.Errorf("%s: %s (code=%d)", pr.method, rpcErr.Message, rpcErr.Code)}
- }
+ pr.ch <- rpcResult{err: &acpRPCError{Method: pr.method, Code: rpcErr.Code, Message: rpcErr.Message, Data: detail}}
} else {
// If this is a prompt response, extract usage and stop reason.
if pr.method == "session/prompt" {
diff --git a/server/pkg/agent/hermes_test.go b/server/pkg/agent/hermes_test.go
index bc2ec9f1e9..c3d052e37d 100644
--- a/server/pkg/agent/hermes_test.go
+++ b/server/pkg/agent/hermes_test.go
@@ -3,6 +3,7 @@ package agent
import (
"context"
"encoding/json"
+ "fmt"
"log/slog"
"os"
"path/filepath"
@@ -1512,6 +1513,231 @@ func TestHermesBackendPromotesProviderErrorWithNonEmptyOutput(t *testing.T) {
}
}
+// TestIsACPSessionNotFound pins the discrimination the resumed-session
+// recovery relies on: only a JSON-RPC -32603 whose text names a missing
+// session counts. Provider errors (429s, auth failures) and plain
+// transport errors must NOT match — those failures happen on sessions
+// that still exist, and clearing the id for them would discard a
+// healthy session.
+func TestIsACPSessionNotFound(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ err error
+ want bool
+ }{
+ {
+ name: "hermes session not found in message",
+ err: &acpRPCError{Method: "session/prompt", Code: -32603, Message: "Session not found"},
+ want: true,
+ },
+ {
+ name: "kiro no session found in data",
+ err: &acpRPCError{Method: "session/prompt", Code: -32603, Message: "Internal error", Data: "No session found with id ses_abc"},
+ want: true,
+ },
+ {
+ name: "internal error without session wording",
+ err: &acpRPCError{Method: "session/prompt", Code: -32603, Message: "Internal error", Data: "upstream provider returned HTTP 429"},
+ want: false,
+ },
+ {
+ name: "kimi session not found as invalid_params data",
+ // kimi-cli raises RequestError.invalid_params({"session_id":
+ // "Session not found"}) for every unknown-session path
+ // (src/kimi_cli/acp/server.py), so -32602 must match too.
+ err: &acpRPCError{Method: "session/set_model", Code: -32602, Message: "Invalid params", Data: `{"session_id": "Session not found"}`},
+ want: true,
+ },
+ {
+ name: "invalid params without session wording",
+ err: &acpRPCError{Method: "session/set_model", Code: -32602, Message: "model not available: bogus-model"},
+ want: false,
+ },
+ {
+ name: "session wording under an unrelated code",
+ err: &acpRPCError{Method: "session/prompt", Code: -32601, Message: "Session not found"},
+ want: false,
+ },
+ {
+ name: "plain error",
+ err: fmt.Errorf("session/prompt: Session not found (code=-32603)"),
+ want: false,
+ },
+ {
+ name: "wrapped rpc error",
+ err: fmt.Errorf("request failed: %w", &acpRPCError{Method: "session/prompt", Code: -32603, Message: "Session not found"}),
+ want: true,
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ if got := isACPSessionNotFound(tc.err); got != tc.want {
+ t.Errorf("isACPSessionNotFound(%v) = %v, want %v", tc.err, got, tc.want)
+ }
+ })
+ }
+}
+
+// fakeHermesACPStaleResumeScript impersonates the failure shape from
+// GitHub multica#4010: session/resume succeeds and echoes back the
+// requested sessionId (hermes' observed behavior even when it no longer
+// knows the session), and the subsequent session/prompt then fails with
+// JSON-RPC -32603 "Session not found".
+func fakeHermesACPStaleResumeScript() string {
+ return `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ;;
+ *'"method":"session/resume"'*)
+ sid=$(printf '%s' "$line" | sed -n 's/.*"sessionId":"\([^"]*\)".*/\1/p')
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"%s"}}\n' "$id" "$sid"
+ ;;
+ *'"method":"session/prompt"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Session not found"}}\n' "$id"
+ exit 0
+ ;;
+ esac
+done
+`
+}
+
+// TestHermesBackendClearsSessionIDWhenResumedSessionNotFound pins the
+// fix for GitHub multica#4010: when a resumed session turns out to be
+// gone on the agent side (resume echoes the requested id, prompt then
+// fails -32603 "Session not found"), the Result must carry an empty
+// SessionID. The daemon's resume-failure fallback keys on
+// `SessionID == ""` — with the stale id still in the Result, the retry
+// never fires and every future dispatch on the same (agent, issue)
+// loops on the dead session.
+func TestHermesBackendClearsSessionIDWhenResumedSessionNotFound(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "hermes")
+ writeTestExecutable(t, fakePath, []byte(fakeHermesACPStaleResumeScript()))
+
+ backend, err := New("hermes", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new hermes backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Timeout: 5 * time.Second,
+ ResumeSessionID: "ses_stale",
+ })
+ 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 !strings.Contains(result.Error, "Session not found") {
+ t.Errorf("expected error to surface the session-not-found message, got %q", result.Error)
+ }
+ if result.SessionID != "" {
+ t.Errorf("expected empty session id so the daemon's fresh-session retry fires, got %q", result.SessionID)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
+
+// fakeHermesACPStaleResumeSetModelScript is the model-override variant
+// of fakeHermesACPStaleResumeScript: session/resume echoes the requested
+// sessionId back, and the dead session then surfaces at
+// session/set_model (which runs before session/prompt whenever the
+// caller picked a model) with the same -32603 "Session not found".
+func fakeHermesACPStaleResumeSetModelScript() string {
+ return `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ;;
+ *'"method":"session/resume"'*)
+ sid=$(printf '%s' "$line" | sed -n 's/.*"sessionId":"\([^"]*\)".*/\1/p')
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"%s"}}\n' "$id" "$sid"
+ ;;
+ *'"method":"session/set_model"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Session not found"}}\n' "$id"
+ exit 0
+ ;;
+ esac
+done
+`
+}
+
+// TestHermesBackendClearsSessionIDWhenSetModelSessionNotFound pins the
+// set_model sibling of the prompt-path fix above: with a model
+// override, session/set_model runs before session/prompt, so a dead
+// resumed session surfaces there instead. The Result must carry an
+// empty SessionID here too, or the daemon's fresh-session retry never
+// fires for any agent configured with a model.
+func TestHermesBackendClearsSessionIDWhenSetModelSessionNotFound(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "hermes")
+ writeTestExecutable(t, fakePath, []byte(fakeHermesACPStaleResumeSetModelScript()))
+
+ backend, err := New("hermes", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new hermes backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Timeout: 5 * time.Second,
+ ResumeSessionID: "ses_stale",
+ Model: "some-model",
+ })
+ 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 !strings.Contains(result.Error, `could not switch to model "some-model"`) {
+ t.Errorf("expected error to name the requested model, got %q", result.Error)
+ }
+ if result.SessionID != "" {
+ t.Errorf("expected empty session id so the daemon's fresh-session retry fires, got %q", result.SessionID)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
+
// fakeHermesACPTransientRetryScript emits a single retryable per-
// attempt warning to stderr and then completes with a normal agent
// text turn — the situation where the upstream LLM blipped on
diff --git a/server/pkg/agent/kimi.go b/server/pkg/agent/kimi.go
index 896b276e79..db266e4f5b 100644
--- a/server/pkg/agent/kimi.go
+++ b/server/pkg/agent/kimi.go
@@ -273,6 +273,17 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
b.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) {
+ // 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
+ // the daemon's resume-failure fallback retries fresh.
+ b.cfg.Logger.Warn("resumed session not found at set_model time; clearing session id so the daemon retries fresh",
+ "backend", "kimi",
+ "session_id", sessionID,
+ )
+ sessionID = ""
+ }
resCh <- Result{
Status: finalStatus,
Error: finalError,
@@ -307,6 +318,19 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
} else {
finalStatus = "failed"
finalError = fmt.Sprintf("kimi session/prompt failed: %v", err)
+ if opts.ResumeSessionID != "" && isACPSessionNotFound(err) {
+ // See the hermes backend: the runtime echoes the
+ // requested id back from session/resume even when
+ // the session is gone, so the stale id only fails
+ // here, at prompt time. Empty SessionID lets the
+ // daemon's resume-failure fallback retry fresh and
+ // store the replacement id.
+ b.cfg.Logger.Warn("resumed session not found at prompt time; clearing session id so the daemon retries fresh",
+ "backend", "kimi",
+ "session_id", sessionID,
+ )
+ sessionID = ""
+ }
}
} else {
select {
diff --git a/server/pkg/agent/kimi_test.go b/server/pkg/agent/kimi_test.go
index b4df8124dd..5734908130 100644
--- a/server/pkg/agent/kimi_test.go
+++ b/server/pkg/agent/kimi_test.go
@@ -149,6 +149,85 @@ func TestKimiBackendSetModelFailureFailsTask(t *testing.T) {
}
}
+// fakeKimiACPStaleResumeSetModelScript impersonates kimi-cli when a
+// resumed session is gone and the caller picked a model:
+// session/resume echoes the requested sessionId back, then
+// session/set_model rejects the unknown session the way kimi-cli
+// actually does — RequestError.invalid_params (-32602) with
+// {"session_id": "Session not found"} in data
+// (src/kimi_cli/acp/server.py, set_session_model).
+func fakeKimiACPStaleResumeSetModelScript() string {
+ return `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ;;
+ *'"method":"session/resume"'*)
+ sid=$(printf '%s' "$line" | sed -n 's/.*"sessionId":"\([^"]*\)".*/\1/p')
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"%s"}}\n' "$id" "$sid"
+ ;;
+ *'"method":"session/set_model"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32602,"message":"Invalid params","data":{"session_id":"Session not found"}}}\n' "$id"
+ exit 0
+ ;;
+ esac
+done
+`
+}
+
+// TestKimiBackendClearsSessionIDWhenSetModelSessionNotFound pins the
+// set_model sibling of the resumed-session fix: with a model override,
+// session/set_model runs before session/prompt, so a dead resumed
+// session surfaces there. The Result must carry an empty SessionID so
+// the daemon's fresh-session retry (gated on SessionID == "") fires.
+func TestKimiBackendClearsSessionIDWhenSetModelSessionNotFound(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "kimi")
+ writeTestExecutable(t, fakePath, []byte(fakeKimiACPStaleResumeSetModelScript()))
+
+ backend, err := New("kimi", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new kimi backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Timeout: 5 * time.Second,
+ ResumeSessionID: "ses_stale",
+ Model: "kimi-for-coding",
+ })
+ 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 !strings.Contains(result.Error, `could not switch to model "kimi-for-coding"`) {
+ t.Errorf("expected error to name the requested model, got %q", result.Error)
+ }
+ if result.SessionID != "" {
+ t.Errorf("expected empty session id so the daemon's fresh-session retry fires, got %q", result.SessionID)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
+
// TestKimiBackendInvokesACPSubcommand pins the argv for `kimi`. An
// earlier fix tried passing `--yolo` to bypass per-tool approval
// prompts, but the `acp` subcommand in kimi-cli takes no options
diff --git a/server/pkg/agent/kiro.go b/server/pkg/agent/kiro.go
index d85f2fea23..f6d79473d0 100644
--- a/server/pkg/agent/kiro.go
+++ b/server/pkg/agent/kiro.go
@@ -257,6 +257,17 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
b.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) {
+ // 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
+ // the daemon's resume-failure fallback retries fresh.
+ b.cfg.Logger.Warn("resumed session not found at set_model time; clearing session id so the daemon retries fresh",
+ "backend", "kiro",
+ "session_id", sessionID,
+ )
+ sessionID = ""
+ }
resCh <- Result{
Status: finalStatus,
Error: finalError,
@@ -296,6 +307,19 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
} else {
finalStatus = "failed"
finalError = fmt.Sprintf("kiro session/prompt failed: %v", err)
+ if opts.ResumeSessionID != "" && isACPSessionNotFound(err) {
+ // See the hermes backend: the runtime echoes the
+ // requested id back from session/resume even when
+ // the session is gone, so the stale id only fails
+ // here, at prompt time. Empty SessionID lets the
+ // daemon's resume-failure fallback retry fresh and
+ // store the replacement id.
+ b.cfg.Logger.Warn("resumed session not found at prompt time; clearing session id so the daemon retries fresh",
+ "backend", "kiro",
+ "session_id", sessionID,
+ )
+ sessionID = ""
+ }
}
} else {
select {
diff --git a/server/pkg/agent/kiro_test.go b/server/pkg/agent/kiro_test.go
index 5ac23f34f8..7175f0440f 100644
--- a/server/pkg/agent/kiro_test.go
+++ b/server/pkg/agent/kiro_test.go
@@ -162,6 +162,82 @@ func TestKiroBackendSetModelFailureFailsTask(t *testing.T) {
}
}
+// fakeKiroACPStaleLoadSetModelScript impersonates kiro when a resumed
+// session is gone and the caller picked a model: session/load returns
+// an empty result (so the requested id is kept), then
+// session/set_model rejects the unknown session with kiro's observed
+// wording — -32603 with "No session found with id ..." in data.
+func fakeKiroACPStaleLoadSetModelScript() string {
+ return `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true}}}\n' "$id"
+ ;;
+ *'"method":"session/load"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
+ ;;
+ *'"method":"session/set_model"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Internal error","data":"No session found with id ses_stale"}}\n' "$id"
+ exit 0
+ ;;
+ esac
+done
+`
+}
+
+// TestKiroBackendClearsSessionIDWhenSetModelSessionNotFound pins the
+// set_model sibling of the resumed-session fix: with a model override,
+// session/set_model runs before session/prompt, so a dead resumed
+// session surfaces there. The Result must carry an empty SessionID so
+// the daemon's fresh-session retry (gated on SessionID == "") fires.
+func TestKiroBackendClearsSessionIDWhenSetModelSessionNotFound(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "kiro-cli")
+ writeTestExecutable(t, fakePath, []byte(fakeKiroACPStaleLoadSetModelScript()))
+
+ backend, err := New("kiro", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new kiro backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Timeout: 5 * time.Second,
+ ResumeSessionID: "ses_stale",
+ Model: "auto",
+ })
+ 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 !strings.Contains(result.Error, `could not switch to model "auto"`) {
+ t.Errorf("expected error to name the requested model, got %q", result.Error)
+ }
+ if result.SessionID != "" {
+ t.Errorf("expected empty session id so the daemon's fresh-session retry fires, got %q", result.SessionID)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
+
func TestKiroBackendInvokesACPWithTrustAllTools(t *testing.T) {
t.Parallel()