Skip to content

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

Go

fix(daemon): add fallback for failed session resume (#818)

LinYushen265d1854c91e
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 42da52d116..a25340698e 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -976,17 +976,89 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLo
taskStart := time.Now()
- session, err := backend.Execute(ctx, prompt, agent.ExecOptions{
+ execOpts := agent.ExecOptions{
Cwd: env.WorkDir,
Model: entry.Model,
Timeout: d.cfg.AgentTimeout,
ResumeSessionID: task.PriorSessionID,
- })
+ }
+
+ result, tools, err := d.executeAndDrain(ctx, backend, prompt, execOpts, taskLog, task.ID)
if err != nil {
return TaskResult{}, err
}
- // Drain message channel — forward to server for live output + log locally.
+ // 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 == "" {
+ firstUsage := result.Usage
+ taskLog.Warn("session resume failed, retrying with fresh session", "error", result.Error)
+ execOpts.ResumeSessionID = ""
+ retryResult, retryTools, retryErr := d.executeAndDrain(ctx, backend, prompt, execOpts, taskLog, task.ID)
+ if retryErr != nil {
+ taskLog.Error("fresh session also failed to start", "error", retryErr)
+ } else {
+ result = retryResult
+ result.Usage = mergeUsage(firstUsage, result.Usage)
+ tools = retryTools
+ }
+ }
+
+ elapsed := time.Since(taskStart).Round(time.Second)
+ taskLog.Info("agent finished",
+ "status", result.Status,
+ "duration", elapsed.String(),
+ "tools", tools,
+ )
+
+ // Convert agent usage map to task usage entries.
+ var usageEntries []TaskUsageEntry
+ for model, u := range result.Usage {
+ if u.InputTokens == 0 && u.OutputTokens == 0 && u.CacheReadTokens == 0 && u.CacheWriteTokens == 0 {
+ continue
+ }
+ usageEntries = append(usageEntries, TaskUsageEntry{
+ Provider: provider,
+ Model: model,
+ InputTokens: u.InputTokens,
+ OutputTokens: u.OutputTokens,
+ CacheReadTokens: u.CacheReadTokens,
+ CacheWriteTokens: u.CacheWriteTokens,
+ })
+ }
+
+ switch result.Status {
+ case "completed":
+ if result.Output == "" {
+ return TaskResult{}, fmt.Errorf("%s returned empty output", provider)
+ }
+ return TaskResult{
+ Status: "completed",
+ Comment: result.Output,
+ SessionID: result.SessionID,
+ WorkDir: env.WorkDir,
+ Usage: usageEntries,
+ }, nil
+ case "timeout":
+ return TaskResult{}, fmt.Errorf("%s timed out after %s", provider, d.cfg.AgentTimeout)
+ default:
+ errMsg := result.Error
+ if errMsg == "" {
+ errMsg = fmt.Sprintf("%s execution %s", provider, result.Status)
+ }
+ return TaskResult{Status: "blocked", Comment: errMsg, Usage: usageEntries}, nil
+ }
+}
+
+// executeAndDrain runs a backend, drains its message stream (forwarding to the
+// server), and waits for the final result.
+func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, prompt string, opts agent.ExecOptions, taskLog *slog.Logger, taskID string) (agent.Result, int32, error) {
+ session, err := backend.Execute(ctx, prompt, opts)
+ if err != nil {
+ return agent.Result{}, 0, err
+ }
+
var toolCount atomic.Int32
go func() {
var seq atomic.Int32
@@ -994,11 +1066,10 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLo
var pendingText strings.Builder
var pendingThinking strings.Builder
var batch []TaskMessageData
- callIDToTool := map[string]string{} // track callID → tool name for tool_result
+ callIDToTool := map[string]string{}
flush := func() {
mu.Lock()
- // Flush any accumulated thinking as a single message.
if pendingThinking.Len() > 0 {
s := seq.Add(1)
batch = append(batch, TaskMessageData{
@@ -1008,7 +1079,6 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLo
})
pendingThinking.Reset()
}
- // Flush any accumulated text as a single message.
if pendingText.Len() > 0 {
s := seq.Add(1)
batch = append(batch, TaskMessageData{
@@ -1024,14 +1094,13 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLo
if len(toSend) > 0 {
sendCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- if err := d.client.ReportTaskMessages(sendCtx, task.ID, toSend); err != nil {
+ if err := d.client.ReportTaskMessages(sendCtx, taskID, toSend); err != nil {
taskLog.Debug("failed to report task messages", "error", err)
}
cancel()
}
}
- // Periodically flush accumulated text/thinking messages.
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
@@ -1072,7 +1141,6 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLo
if len(output) > 8192 {
output = output[:8192]
}
- // Resolve tool name from callID if not set directly.
toolName := msg.Tool
if toolName == "" && msg.CallID != "" {
mu.Lock()
@@ -1114,54 +1182,33 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLo
}
close(done)
- flush() // Final flush after channel closes.
+ flush()
}()
result := <-session.Result
- elapsed := time.Since(taskStart).Round(time.Second)
- taskLog.Info("agent finished",
- "status", result.Status,
- "duration", elapsed.String(),
- "tools", toolCount.Load(),
- )
+ return result, toolCount.Load(), nil
+}
- // Convert agent usage map to task usage entries.
- var usageEntries []TaskUsageEntry
- for model, u := range result.Usage {
- if u.InputTokens == 0 && u.OutputTokens == 0 && u.CacheReadTokens == 0 && u.CacheWriteTokens == 0 {
- continue
- }
- usageEntries = append(usageEntries, TaskUsageEntry{
- Provider: provider,
- Model: model,
- InputTokens: u.InputTokens,
- OutputTokens: u.OutputTokens,
- CacheReadTokens: u.CacheReadTokens,
- CacheWriteTokens: u.CacheWriteTokens,
- })
+func mergeUsage(a, b map[string]agent.TokenUsage) map[string]agent.TokenUsage {
+ if len(a) == 0 {
+ return b
}
-
- switch result.Status {
- case "completed":
- if result.Output == "" {
- return TaskResult{}, fmt.Errorf("%s returned empty output", provider)
- }
- return TaskResult{
- Status: "completed",
- Comment: result.Output,
- SessionID: result.SessionID,
- WorkDir: env.WorkDir,
- Usage: usageEntries,
- }, nil
- case "timeout":
- return TaskResult{}, fmt.Errorf("%s timed out after %s", provider, d.cfg.AgentTimeout)
- default:
- errMsg := result.Error
- if errMsg == "" {
- errMsg = fmt.Sprintf("%s execution %s", provider, result.Status)
- }
- return TaskResult{Status: "blocked", Comment: errMsg, Usage: usageEntries}, nil
+ if len(b) == 0 {
+ return a
+ }
+ merged := make(map[string]agent.TokenUsage, len(a)+len(b))
+ for model, u := range a {
+ merged[model] = u
+ }
+ for model, u := range b {
+ existing := merged[model]
+ existing.InputTokens += u.InputTokens
+ existing.OutputTokens += u.OutputTokens
+ existing.CacheReadTokens += u.CacheReadTokens
+ existing.CacheWriteTokens += u.CacheWriteTokens
+ merged[model] = existing
}
+ return merged
}
// repoDataToInfo converts daemon RepoData to repocache RepoInfo.
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 5ea9cd0155..6a416692b8 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -1,9 +1,15 @@
package daemon
import (
+ "context"
+ "log/slog"
"net/http"
+ "net/http/httptest"
"strings"
+ "sync/atomic"
"testing"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
)
func TestNormalizeServerBaseURL(t *testing.T) {
@@ -130,3 +136,147 @@ func TestIsWorkspaceNotFoundError(t *testing.T) {
t.Fatal("did not expect 500 to be treated as workspace not found")
}
}
+
+func TestMergeUsage(t *testing.T) {
+ t.Parallel()
+
+ a := map[string]agent.TokenUsage{
+ "model-a": {InputTokens: 10, OutputTokens: 5},
+ }
+ b := map[string]agent.TokenUsage{
+ "model-a": {InputTokens: 20, OutputTokens: 10, CacheReadTokens: 3},
+ "model-b": {InputTokens: 100},
+ }
+ merged := mergeUsage(a, b)
+
+ if got := merged["model-a"]; got.InputTokens != 30 || got.OutputTokens != 15 || got.CacheReadTokens != 3 {
+ t.Fatalf("model-a: expected {30,15,3,0}, got %+v", got)
+ }
+ if got := merged["model-b"]; got.InputTokens != 100 {
+ t.Fatalf("model-b: expected InputTokens=100, got %+v", got)
+ }
+
+ if got := mergeUsage(nil, b); len(got) != 2 {
+ t.Fatal("mergeUsage(nil, b) should return b")
+ }
+ if got := mergeUsage(a, nil); len(got) != 1 {
+ t.Fatal("mergeUsage(a, nil) should return a")
+ }
+}
+
+// fakeBackend is a test double for agent.Backend that returns preconfigured
+// results. Each call to Execute pops the next entry from the results slice.
+type fakeBackend struct {
+ calls []agent.ExecOptions
+ results []agent.Result
+ errors []error
+ idx atomic.Int32
+}
+
+func (b *fakeBackend) Execute(_ context.Context, _ string, opts agent.ExecOptions) (*agent.Session, error) {
+ i := int(b.idx.Add(1)) - 1
+ b.calls = append(b.calls, opts)
+ if i < len(b.errors) && b.errors[i] != nil {
+ return nil, b.errors[i]
+ }
+ msgCh := make(chan agent.Message)
+ resCh := make(chan agent.Result, 1)
+ close(msgCh)
+ resCh <- b.results[i]
+ return &agent.Session{Messages: msgCh, Result: resCh}, nil
+}
+
+func newTestDaemon(t *testing.T) *Daemon {
+ t.Helper()
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+ t.Cleanup(srv.Close)
+ return &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.Default(),
+ }
+}
+
+func TestExecuteAndDrain_ResumeFailureFallback(t *testing.T) {
+ t.Parallel()
+
+ d := newTestDaemon(t)
+ ctx := context.Background()
+ taskLog := slog.Default()
+
+ fb := &fakeBackend{
+ results: []agent.Result{
+ {Status: "failed", Error: "session not found", Usage: map[string]agent.TokenUsage{
+ "m1": {InputTokens: 5},
+ }},
+ {Status: "completed", Output: "done", SessionID: "new-sess", Usage: map[string]agent.TokenUsage{
+ "m1": {InputTokens: 10, OutputTokens: 20},
+ }},
+ },
+ }
+
+ // First attempt: resume fails (no SessionID in result).
+ opts := agent.ExecOptions{ResumeSessionID: "stale-id"}
+ result, _, err := d.executeAndDrain(ctx, fb, "prompt", opts, taskLog, "task-1")
+ if err != nil {
+ t.Fatalf("first call error: %v", err)
+ }
+ if result.Status != "failed" || result.SessionID != "" {
+ t.Fatalf("expected failed result with empty SessionID, got %+v", result)
+ }
+
+ // Simulate the retry logic from runTask.
+ if result.Status == "failed" && result.SessionID == "" {
+ firstUsage := result.Usage
+ opts.ResumeSessionID = ""
+ retryResult, _, retryErr := d.executeAndDrain(ctx, fb, "prompt", opts, taskLog, "task-1")
+ if retryErr != nil {
+ t.Fatalf("retry error: %v", retryErr)
+ }
+ result = retryResult
+ result.Usage = mergeUsage(firstUsage, result.Usage)
+ }
+
+ if result.Status != "completed" || result.Output != "done" {
+ t.Fatalf("expected completed result, got %+v", result)
+ }
+ if result.SessionID != "new-sess" {
+ t.Fatalf("expected new-sess, got %s", result.SessionID)
+ }
+ // Usage should be merged.
+ if u := result.Usage["m1"]; u.InputTokens != 15 || u.OutputTokens != 20 {
+ t.Fatalf("expected merged usage {15,20}, got %+v", u)
+ }
+ // Second call should NOT have ResumeSessionID.
+ if fb.calls[1].ResumeSessionID != "" {
+ t.Fatal("retry should not have ResumeSessionID")
+ }
+}
+
+func TestExecuteAndDrain_NoRetryWhenSessionEstablished(t *testing.T) {
+ t.Parallel()
+
+ d := newTestDaemon(t)
+
+ fb := &fakeBackend{
+ results: []agent.Result{
+ {Status: "failed", Error: "model error", SessionID: "valid-sess"},
+ },
+ }
+
+ opts := agent.ExecOptions{ResumeSessionID: "some-id"}
+ result, _, err := d.executeAndDrain(context.Background(), fb, "p", opts, slog.Default(), "t")
+ 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")
+ }
+ if int(fb.idx.Load()) != 1 {
+ t.Fatalf("expected 1 call, got %d", fb.idx.Load())
+ }
+}