Skip to content

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

Go

fix(chat): preserve chat session resume pointer across failures (#1360)

devv-eve5fa1da448f0f
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 754dd320df..e76611a6fc 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -77,7 +77,7 @@ func main() {
// Start background workers.
sweepCtx, sweepCancel := context.WithCancel(context.Background())
autopilotCtx, autopilotCancel := context.WithCancel(context.Background())
- taskSvc := service.NewTaskService(queries, hub, bus)
+ taskSvc := service.NewTaskService(queries, pool, hub, bus)
autopilotSvc := service.NewAutopilotService(queries, pool, bus, taskSvc)
registerAutopilotListeners(bus, autopilotSvc)
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 89ecd85603..0149db0260 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -122,10 +122,15 @@ func (c *Client) ReportTaskUsage(ctx context.Context, taskID string, usage []Tas
}, nil)
}
-func (c *Client) FailTask(ctx context.Context, taskID, errMsg string) error {
- return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/fail", taskID), map[string]any{
- "error": errMsg,
- }, nil)
+func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDir string) error {
+ body := map[string]any{"error": errMsg}
+ if sessionID != "" {
+ body["session_id"] = sessionID
+ }
+ if workDir != "" {
+ body["work_dir"] = workDir
+ }
+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/fail", taskID), body, nil)
}
// GetTaskStatus returns the current status of a task. Used by the daemon to
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 3ab9fc0b42..38f98a867d 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -790,7 +790,7 @@ func (d *Daemon) handleTask(ctx context.Context, task Task) {
if err := d.client.StartTask(ctx, task.ID); err != nil {
taskLog.Error("start task failed", "error", err)
- if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("start task failed: %s", err.Error())); failErr != nil {
+ if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("start task failed: %s", err.Error()), "", ""); failErr != nil {
taskLog.Error("fail task after start error", "error", failErr)
}
return
@@ -835,7 +835,9 @@ func (d *Daemon) handleTask(ctx context.Context, task Task) {
if err != nil {
taskLog.Error("task failed", "error", err)
- if failErr := d.client.FailTask(ctx, task.ID, err.Error()); failErr != nil {
+ // runTask returned without a TaskResult, so we don't have a SessionID
+ // to forward — best we can do is record the failure.
+ if failErr := d.client.FailTask(ctx, task.ID, err.Error(), "", ""); failErr != nil {
taskLog.Error("fail task callback failed", "error", failErr)
}
return
@@ -860,14 +862,18 @@ func (d *Daemon) handleTask(ctx context.Context, task Task) {
switch result.Status {
case "blocked":
- if err := d.client.FailTask(ctx, task.ID, result.Comment); err != nil {
+ // Forward SessionID/WorkDir even on the blocked path: the agent may
+ // have built a real session before getting stuck (rate-limit, tool
+ // error, etc.) and we want the next chat turn to resume there
+ // rather than start over and "forget" the conversation.
+ if err := d.client.FailTask(ctx, task.ID, result.Comment, result.SessionID, result.WorkDir); err != nil {
taskLog.Error("report blocked task failed", "error", err)
}
default:
taskLog.Info("task completed", "status", result.Status)
if err := d.client.CompleteTask(ctx, task.ID, result.Comment, result.BranchName, result.SessionID, result.WorkDir); err != nil {
taskLog.Error("complete task failed, falling back to fail", "error", err)
- if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("complete task failed: %s", err.Error())); failErr != nil {
+ if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("complete task failed: %s", err.Error()), result.SessionID, result.WorkDir); failErr != nil {
taskLog.Error("fail task fallback also failed", "error", failErr)
}
}
@@ -1069,7 +1075,17 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLo
switch result.Status {
case "completed":
if result.Output == "" {
- return TaskResult{}, fmt.Errorf("%s returned empty output", provider)
+ // Even an empty-output completion may have established a real
+ // session — surface it through the blocked path so the next chat
+ // turn can still resume from where this one left off.
+ return TaskResult{
+ Status: "blocked",
+ Comment: fmt.Sprintf("%s returned empty output", provider),
+ SessionID: result.SessionID,
+ WorkDir: env.WorkDir,
+ EnvRoot: env.RootDir,
+ Usage: usageEntries,
+ }, nil
}
return TaskResult{
Status: "completed",
@@ -1080,13 +1096,36 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLo
Usage: usageEntries,
}, nil
case "timeout":
- return TaskResult{}, fmt.Errorf("%s timed out after %s", provider, d.cfg.AgentTimeout)
+ // Surface session_id/work_dir so the chat resume pointer is kept
+ // in sync even when the agent times out after building a session.
+ // We mark as "blocked" (not a hard error return) so handleTask
+ // goes through the FailTask path that forwards session info.
+ return TaskResult{
+ Status: "blocked",
+ Comment: fmt.Sprintf("%s timed out after %s", provider, d.cfg.AgentTimeout),
+ SessionID: result.SessionID,
+ WorkDir: env.WorkDir,
+ EnvRoot: env.RootDir,
+ Usage: usageEntries,
+ }, nil
default:
errMsg := result.Error
if errMsg == "" {
errMsg = fmt.Sprintf("%s execution %s", provider, result.Status)
}
- return TaskResult{Status: "blocked", Comment: errMsg, EnvRoot: env.RootDir, Usage: usageEntries}, nil
+ // Forward SessionID/WorkDir on the blocked path: backends commonly
+ // emit a real session_id before failing (rate-limit, tool error,
+ // model reject, …). Without this the chat_session resume pointer
+ // would either be left stale or overwritten with NULL on the
+ // server, causing the next chat turn to lose context.
+ return TaskResult{
+ Status: "blocked",
+ Comment: errMsg,
+ SessionID: result.SessionID,
+ WorkDir: env.WorkDir,
+ EnvRoot: env.RootDir,
+ Usage: usageEntries,
+ }, nil
}
}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index a6498e9317..8d29bca60d 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -594,13 +594,26 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
resp.Repos = repos
}
}
- // Resume from the chat session's persistent session.
+ // Resume from the chat session's persistent session, falling back
+ // to the most recent task that recorded a session_id when the
+ // chat_session pointer is missing or stale (e.g. a previous task
+ // failed before reporting completion). Without this fallback a
+ // single failed turn would silently drop the entire conversation
+ // memory on the next message.
if cs.SessionID.Valid {
resp.PriorSessionID = cs.SessionID.String
}
if cs.WorkDir.Valid {
resp.PriorWorkDir = cs.WorkDir.String
}
+ if resp.PriorSessionID == "" {
+ if prior, err := h.Queries.GetLastChatTaskSession(r.Context(), cs.ID); err == nil && prior.SessionID.Valid {
+ resp.PriorSessionID = prior.SessionID.String
+ if prior.WorkDir.Valid && resp.PriorWorkDir == "" {
+ resp.PriorWorkDir = prior.WorkDir.String
+ }
+ }
+ }
// Load the latest user message for the chat prompt.
if msgs, err := h.Queries.ListChatMessages(r.Context(), cs.ID); err == nil && len(msgs) > 0 {
// Find the last user message.
@@ -807,7 +820,9 @@ func (h *Handler) GetTaskStatus(w http.ResponseWriter, r *http.Request) {
// FailTask marks a running task as failed.
type TaskFailRequest struct {
- Error string `json:"error"`
+ Error string `json:"error"`
+ SessionID string `json:"session_id,omitempty"`
+ WorkDir string `json:"work_dir,omitempty"`
}
func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {
@@ -824,7 +839,7 @@ func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {
return
}
- task, err := h.TaskService.FailTask(r.Context(), parseUUID(taskID), req.Error)
+ task, err := h.TaskService.FailTask(r.Context(), parseUUID(taskID), req.Error, req.SessionID, req.WorkDir)
if err != nil {
slog.Warn("fail task failed", "task_id", taskID, "error", err)
writeError(w, http.StatusBadRequest, err.Error())
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index fc75396448..66c0c12d06 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -59,7 +59,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
executor = candidate
}
- taskSvc := service.NewTaskService(queries, hub, bus)
+ taskSvc := service.NewTaskService(queries, txStarter, hub, bus)
return &Handler{
Queries: queries,
DB: executor,
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index aacbe0b4ef..5151e91d74 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -21,13 +21,14 @@ import (
)
type TaskService struct {
- Queries *db.Queries
- Hub *realtime.Hub
- Bus *events.Bus
+ Queries *db.Queries
+ TxStarter TxStarter
+ Hub *realtime.Hub
+ Bus *events.Bus
}
-func NewTaskService(q *db.Queries, hub *realtime.Hub, bus *events.Bus) *TaskService {
- return &TaskService{Queries: q, Hub: hub, Bus: bus}
+func NewTaskService(q *db.Queries, tx TxStarter, hub *realtime.Hub, bus *events.Bus) *TaskService {
+ return &TaskService{Queries: q, TxStarter: tx, Hub: hub, Bus: bus}
}
// EnqueueTaskForIssue creates a queued task for an agent-assigned issue.
@@ -248,21 +249,48 @@ func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.Ag
// CompleteTask marks a task as completed.
// Issue status is NOT changed here — the agent manages it via the CLI.
+//
+// For chat tasks, CompleteAgentTask and the chat_session resume-pointer
+// update run in a single transaction. This closes a race where the next
+// queued chat message could be claimed in the window between the task
+// flipping to 'completed' and chat_session.session_id being refreshed,
+// causing the new task to resume against a stale (or NULL) session.
func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, result []byte, sessionID, workDir string) (*db.AgentTaskQueue, error) {
- task, err := s.Queries.CompleteAgentTask(ctx, db.CompleteAgentTaskParams{
- ID: taskID,
- Result: result,
- SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
- WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
- })
- if err != nil {
+ var task db.AgentTaskQueue
+ if err := s.runInTx(ctx, func(qtx *db.Queries) error {
+ t, err := qtx.CompleteAgentTask(ctx, db.CompleteAgentTaskParams{
+ ID: taskID,
+ Result: result,
+ SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
+ WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
+ })
+ if err != nil {
+ return err
+ }
+ task = t
+
+ if t.ChatSessionID.Valid {
+ // COALESCE in SQL guarantees empty inputs don't wipe the
+ // existing resume pointer; we still surface DB errors.
+ if err := qtx.UpdateChatSessionSession(ctx, db.UpdateChatSessionSessionParams{
+ ID: t.ChatSessionID,
+ SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
+ WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
+ }); err != nil {
+ return fmt.Errorf("update chat session resume pointer: %w", err)
+ }
+ }
+ return nil
+ }); err != nil {
// Log the current task state to help debug why the update matched no rows.
if existing, lookupErr := s.Queries.GetAgentTask(ctx, taskID); lookupErr == nil {
- slog.Warn("complete task failed: task not in running state",
+ slog.Warn("complete task failed",
"task_id", util.UUIDToString(taskID),
"current_status", existing.Status,
"issue_id", util.UUIDToString(existing.IssueID),
+ "chat_session_id", util.UUIDToString(existing.ChatSessionID),
"agent_id", util.UUIDToString(existing.AgentID),
+ "error", err,
)
} else {
slog.Warn("complete task failed: task not found",
@@ -296,7 +324,8 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
}
}
- // For chat tasks, save assistant reply, update session, and broadcast chat:done.
+ // For chat tasks, save assistant reply and broadcast chat:done. The
+ // resume pointer was already persisted inside the transaction above.
if task.ChatSessionID.Valid {
var payload protocol.TaskCompletedPayload
if err := json.Unmarshal(result, &payload); err == nil && payload.Output != "" {
@@ -317,11 +346,6 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
}
}
}
- s.Queries.UpdateChatSessionSession(ctx, db.UpdateChatSessionSessionParams{
- ID: task.ChatSessionID,
- SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
- WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
- })
s.broadcastChatDone(ctx, task)
}
@@ -336,18 +360,45 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
// FailTask marks a task as failed.
// Issue status is NOT changed here — the agent manages it via the CLI.
-func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg string) (*db.AgentTaskQueue, error) {
- task, err := s.Queries.FailAgentTask(ctx, db.FailAgentTaskParams{
- ID: taskID,
- Error: pgtype.Text{String: errMsg, Valid: true},
- })
- if err != nil {
+//
+// sessionID/workDir are optional: when the agent established a real session
+// before failing (e.g. crashed mid-conversation, was cancelled, or hit a
+// tool error), the daemon should pass them so we can preserve the resume
+// pointer on both the task row and the chat_session — otherwise the next
+// chat turn would silently start a brand-new session and lose memory.
+func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg, sessionID, workDir string) (*db.AgentTaskQueue, error) {
+ var task db.AgentTaskQueue
+ if err := s.runInTx(ctx, func(qtx *db.Queries) error {
+ t, err := qtx.FailAgentTask(ctx, db.FailAgentTaskParams{
+ ID: taskID,
+ Error: pgtype.Text{String: errMsg, Valid: true},
+ SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
+ WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
+ })
+ if err != nil {
+ return err
+ }
+ task = t
+
+ if t.ChatSessionID.Valid {
+ if err := qtx.UpdateChatSessionSession(ctx, db.UpdateChatSessionSessionParams{
+ ID: t.ChatSessionID,
+ SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
+ WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
+ }); err != nil {
+ return fmt.Errorf("update chat session resume pointer: %w", err)
+ }
+ }
+ return nil
+ }); err != nil {
if existing, lookupErr := s.Queries.GetAgentTask(ctx, taskID); lookupErr == nil {
- slog.Warn("fail task failed: task not in dispatched/running state",
+ slog.Warn("fail task failed",
"task_id", util.UUIDToString(taskID),
"current_status", existing.Status,
"issue_id", util.UUIDToString(existing.IssueID),
+ "chat_session_id", util.UUIDToString(existing.ChatSessionID),
"agent_id", util.UUIDToString(existing.AgentID),
+ "error", err,
)
} else {
slog.Warn("fail task failed: task not found",
@@ -372,6 +423,24 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg s
return &task, nil
}
+// runInTx executes fn inside a single DB transaction. If TxStarter is nil
+// (e.g. some tests construct TaskService directly), fn runs against the
+// regular Queries handle without transactional guarantees.
+func (s *TaskService) runInTx(ctx context.Context, fn func(*db.Queries) error) error {
+ if s.TxStarter == nil {
+ return fn(s.Queries)
+ }
+ tx, err := s.TxStarter.Begin(ctx)
+ if err != nil {
+ return fmt.Errorf("begin tx: %w", err)
+ }
+ defer tx.Rollback(ctx)
+ if err := fn(s.Queries.WithTx(tx)); err != nil {
+ return err
+ }
+ return tx.Commit(ctx)
+}
+
// ReportProgress broadcasts a progress update via the event bus.
func (s *TaskService) ReportProgress(ctx context.Context, taskID string, workspaceID string, summary string, step, total int) {
s.Bus.Publish(events.Event{
diff --git a/server/pkg/agent/copilot.go b/server/pkg/agent/copilot.go
index bc32f0d380..f19d41ebcb 100644
--- a/server/pkg/agent/copilot.go
+++ b/server/pkg/agent/copilot.go
@@ -51,8 +51,18 @@ func handleCopilotEvent(evt copilotEvent, st *copilotEventState) []Message {
switch evt.Type {
case "session.start":
var ss copilotSessionStart
- if err := json.Unmarshal(evt.Data, &ss); err == nil && ss.SelectedModel != "" {
- st.activeModel = ss.SelectedModel
+ if err := json.Unmarshal(evt.Data, &ss); err == nil {
+ if ss.SelectedModel != "" {
+ st.activeModel = ss.SelectedModel
+ }
+ // Capture sessionId from session.start as well: the synthetic
+ // "result" event may never arrive (timeout, cancel, crash, or a
+ // session.error before result), and without this the daemon
+ // reports SessionID="" and the chat-session resume pointer can
+ // drift to a stale turn. result still wins when it does arrive.
+ if ss.SessionID != "" {
+ st.sessionID = ss.SessionID
+ }
}
case "assistant.message_delta":
@@ -158,7 +168,9 @@ func handleCopilotEvent(evt copilotEvent, st *copilotEventState) []Message {
}
case "result":
- st.sessionID = evt.SessionID
+ if evt.SessionID != "" {
+ st.sessionID = evt.SessionID
+ }
if evt.ExitCode != 0 {
st.finalStatus = "failed"
st.finalError = fmt.Sprintf("copilot exited with code %d", evt.ExitCode)
@@ -238,6 +250,7 @@ func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOp
var evt copilotEvent
if err := json.Unmarshal([]byte(line), &evt); err != nil {
+ slog.Warn("copilot event parse failed", "err", err, "line", line)
continue
}
@@ -245,6 +258,9 @@ func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOp
trySend(msgCh, m)
}
}
+ if err := scanner.Err(); err != nil {
+ slog.Warn("copilot stdout scanner error", "err", err)
+ }
exitErr := cmd.Wait()
duration := time.Since(startTime)
@@ -372,7 +388,7 @@ type copilotSessionWarning struct {
// copilotResultUsage is the usage on the final "result" line.
type copilotResultUsage struct {
- PremiumRequests int `json:"premiumRequests"`
+ PremiumRequests float64 `json:"premiumRequests"`
TotalAPIDurationMs int64 `json:"totalApiDurationMs"`
SessionDurationMs int64 `json:"sessionDurationMs"`
CodeChanges *copilotCodeChanges `json:"codeChanges,omitempty"`
diff --git a/server/pkg/agent/copilot_test.go b/server/pkg/agent/copilot_test.go
index b5cf5738b2..1d9960a0dc 100644
--- a/server/pkg/agent/copilot_test.go
+++ b/server/pkg/agent/copilot_test.go
@@ -155,6 +155,24 @@ func TestCopilotParseToolExecCompleteError(t *testing.T) {
}
}
+func TestCopilotParseResultFractionalPremiumRequests(t *testing.T) {
+ t.Parallel()
+ // Regression: real Copilot CLI v1.0.32 emits premiumRequests as a float
+ // (e.g. 7.5). Decoding into an int field used to fail the entire result
+ // line, dropping sessionId and breaking chat-session resume.
+ const line = `{"type":"result","timestamp":"2026-04-20T05:34:30.469Z","sessionId":"349793b7-7067-49d4-a807-8788561643bd","exitCode":0,"usage":{"premiumRequests":7.5,"totalApiDurationMs":1500,"sessionDurationMs":5842,"codeChanges":{"linesAdded":0,"linesRemoved":0,"filesModified":[]}}}`
+ var evt copilotEvent
+ if err := json.Unmarshal([]byte(line), &evt); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if evt.SessionID != "349793b7-7067-49d4-a807-8788561643bd" {
+ t.Fatalf("unexpected sessionId: %q", evt.SessionID)
+ }
+ if evt.Usage == nil || evt.Usage.PremiumRequests != 7.5 {
+ t.Fatalf("expected premiumRequests=7.5, got %#v", evt.Usage)
+ }
+}
+
func TestCopilotParseResult(t *testing.T) {
t.Parallel()
evt := parseCopilotEvent(t, fixtureResult)
@@ -172,7 +190,7 @@ func TestCopilotParseResult(t *testing.T) {
t.Fatal("expected usage to be present")
}
if evt.Usage.PremiumRequests != 3 {
- t.Fatalf("expected 3 premiumRequests, got %d", evt.Usage.PremiumRequests)
+ t.Fatalf("expected 3 premiumRequests, got %v", evt.Usage.PremiumRequests)
}
if evt.Usage.TotalAPIDurationMs != 1763 {
t.Fatalf("expected totalApiDurationMs 1763, got %d", evt.Usage.TotalAPIDurationMs)
@@ -354,6 +372,54 @@ func TestCopilotEventLoopToolExecError(t *testing.T) {
}
}
+func TestCopilotEventLoopSessionStartCapturesSessionID(t *testing.T) {
+ t.Parallel()
+ // session.start arrives but the run is killed (timeout/cancel/crash) before
+ // the synthetic "result" line is emitted. We must still report the session
+ // id from session.start so the chat-session resume pointer can advance.
+ lines := []string{fixtureSessionStart}
+
+ _, sessionID, _, _ := simulateCopilotEventLoop(t, lines)
+
+ if sessionID != "35059dc3-d928-4ffb-8616-b78938621d85" {
+ t.Fatalf("expected session id captured from session.start, got %q", sessionID)
+ }
+}
+
+func TestCopilotEventLoopResultOverridesSessionStart(t *testing.T) {
+ t.Parallel()
+ // When both session.start and result carry a session id, the result event
+ // wins (it is the authoritative end-of-turn record).
+ lines := []string{
+ fixtureSessionStart,
+ // Different sessionId on the result event (defensive: in practice
+ // they should match, but the contract is "result wins").
+ `{"type":"result","sessionId":"final-id","exitCode":0}`,
+ }
+
+ _, sessionID, _, _ := simulateCopilotEventLoop(t, lines)
+
+ if sessionID != "final-id" {
+ t.Fatalf("expected result session id to win, got %q", sessionID)
+ }
+}
+
+func TestCopilotEventLoopResultWithoutSessionIDPreservesSessionStart(t *testing.T) {
+ t.Parallel()
+ // Defensive: if a result line arrives without a sessionId (older CLI,
+ // truncated output), the session.start id must not be wiped.
+ lines := []string{
+ fixtureSessionStart,
+ `{"type":"result","exitCode":0}`,
+ }
+
+ _, sessionID, _, _ := simulateCopilotEventLoop(t, lines)
+
+ if sessionID != "35059dc3-d928-4ffb-8616-b78938621d85" {
+ t.Fatalf("expected session.start id to be preserved when result has none, got %q", sessionID)
+ }
+}
+
func TestCopilotEventLoopNonZeroExit(t *testing.T) {
t.Parallel()
lines := []string{fixtureResultNonZero}
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index d6dccb966f..0d7e05deb1 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -50,40 +50,6 @@ func (q *Queries) ArchiveAgent(ctx context.Context, arg ArchiveAgentParams) (Age
return i, err
}
-const clearAgentMcpConfig = `-- name: ClearAgentMcpConfig :one
-UPDATE agent SET mcp_config = NULL, updated_at = now()
-WHERE id = $1
-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config
-`
-
-func (q *Queries) ClearAgentMcpConfig(ctx context.Context, id pgtype.UUID) (Agent, error) {
- row := q.db.QueryRow(ctx, clearAgentMcpConfig, id)
- var i Agent
- err := row.Scan(
- &i.ID,
- &i.WorkspaceID,
- &i.Name,
- &i.AvatarUrl,
- &i.RuntimeMode,
- &i.RuntimeConfig,
- &i.Visibility,
- &i.Status,
- &i.MaxConcurrentTasks,
- &i.OwnerID,
- &i.CreatedAt,
- &i.UpdatedAt,
- &i.Description,
- &i.RuntimeID,
- &i.Instructions,
- &i.ArchivedAt,
- &i.ArchivedBy,
- &i.CustomEnv,
- &i.CustomArgs,
- &i.McpConfig,
- )
- return i, err
-}
-
const cancelAgentTask = `-- name: CancelAgentTask :one
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
@@ -192,6 +158,40 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, agentID pgtype.UUID) (Agen
return i, err
}
+const clearAgentMcpConfig = `-- name: ClearAgentMcpConfig :one
+UPDATE agent SET mcp_config = NULL, updated_at = now()
+WHERE id = $1
+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config
+`
+
+func (q *Queries) ClearAgentMcpConfig(ctx context.Context, id pgtype.UUID) (Agent, error) {
+ row := q.db.QueryRow(ctx, clearAgentMcpConfig, id)
+ var i Agent
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.AvatarUrl,
+ &i.RuntimeMode,
+ &i.RuntimeConfig,
+ &i.Visibility,
+ &i.Status,
+ &i.MaxConcurrentTasks,
+ &i.OwnerID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Description,
+ &i.RuntimeID,
+ &i.Instructions,
+ &i.ArchivedAt,
+ &i.ArchivedBy,
+ &i.CustomEnv,
+ &i.CustomArgs,
+ &i.McpConfig,
+ )
+ return i, err
+}
+
const completeAgentTask = `-- name: CompleteAgentTask :one
UPDATE agent_task_queue
SET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4
@@ -366,18 +366,35 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
const failAgentTask = `-- name: FailAgentTask :one
UPDATE agent_task_queue
-SET status = 'failed', completed_at = now(), error = $2
+SET status = 'failed',
+ completed_at = now(),
+ error = $2,
+ session_id = COALESCE($3, session_id),
+ work_dir = COALESCE($4, work_dir)
WHERE id = $1 AND status IN ('dispatched', 'running')
RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id
`
type FailAgentTaskParams struct {
- ID pgtype.UUID `json:"id"`
- Error pgtype.Text `json:"error"`
+ ID pgtype.UUID `json:"id"`
+ Error pgtype.Text `json:"error"`
+ SessionID pgtype.Text `json:"session_id"`
+ WorkDir pgtype.Text `json:"work_dir"`
}
+// Marks a task as failed. session_id and work_dir are merged via COALESCE so
+// if the agent already established a real session before failing (e.g. it
+// crashed mid-conversation, was cancelled, or hit a tool error) the resume
+// pointer is preserved on the task row. The next chat task can then fall
+// back to GetLastChatTaskSession and continue the conversation instead of
+// silently starting over.
func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (AgentTaskQueue, error) {
- row := q.db.QueryRow(ctx, failAgentTask, arg.ID, arg.Error)
+ row := q.db.QueryRow(ctx, failAgentTask,
+ arg.ID,
+ arg.Error,
+ arg.SessionID,
+ arg.WorkDir,
+ )
var i AgentTaskQueue
err := row.Scan(
&i.ID,
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 9b340437fc..283b911f46 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -208,7 +208,9 @@ func (q *Queries) GetChatSessionInWorkspace(ctx context.Context, arg GetChatSess
const getLastChatTaskSession = `-- name: GetLastChatTaskSession :one
SELECT session_id, work_dir FROM agent_task_queue
-WHERE chat_session_id = $1 AND status = 'completed' AND session_id IS NOT NULL
+WHERE chat_session_id = $1
+ AND status IN ('completed', 'failed')
+ AND session_id IS NOT NULL
ORDER BY completed_at DESC
LIMIT 1
`
@@ -218,6 +220,11 @@ type GetLastChatTaskSessionRow struct {
WorkDir pgtype.Text `json:"work_dir"`
}
+// Returns the most recent task in this chat session that managed to record a
+// session_id. Includes both completed and failed tasks: even a failed task
+// may have established a real agent session before failing, and we'd rather
+// resume there than start over and lose conversation memory. Used as a
+// fallback when chat_session.session_id is NULL.
func (q *Queries) GetLastChatTaskSession(ctx context.Context, chatSessionID pgtype.UUID) (GetLastChatTaskSessionRow, error) {
row := q.db.QueryRow(ctx, getLastChatTaskSession, chatSessionID)
var i GetLastChatTaskSessionRow
@@ -483,18 +490,26 @@ func (q *Queries) TouchChatSession(ctx context.Context, id pgtype.UUID) error {
}
const updateChatSessionSession = `-- name: UpdateChatSessionSession :exec
-UPDATE chat_session SET session_id = $2, work_dir = $3, updated_at = now()
-WHERE id = $1
+UPDATE chat_session
+SET session_id = COALESCE($1, session_id),
+ work_dir = COALESCE($2, work_dir),
+ updated_at = now()
+WHERE id = $3
`
type UpdateChatSessionSessionParams struct {
- ID pgtype.UUID `json:"id"`
SessionID pgtype.Text `json:"session_id"`
WorkDir pgtype.Text `json:"work_dir"`
+ ID pgtype.UUID `json:"id"`
}
+// Updates the resume pointer for a chat session. Empty/NULL inputs are
+// ignored via COALESCE so a task that completes without a session_id (e.g.
+// the agent crashed before establishing one) cannot wipe out a previously
+// recorded resume pointer. This makes the chat memory robust against
+// intermittent agent failures.
func (q *Queries) UpdateChatSessionSession(ctx context.Context, arg UpdateChatSessionSessionParams) error {
- _, err := q.db.Exec(ctx, updateChatSessionSession, arg.ID, arg.SessionID, arg.WorkDir)
+ _, err := q.db.Exec(ctx, updateChatSessionSession, arg.SessionID, arg.WorkDir, arg.ID)
return err
}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index c2734f614f..1ecadbe872 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -129,8 +129,18 @@ ORDER BY completed_at DESC
LIMIT 1;
-- name: FailAgentTask :one
+-- Marks a task as failed. session_id and work_dir are merged via COALESCE so
+-- if the agent already established a real session before failing (e.g. it
+-- crashed mid-conversation, was cancelled, or hit a tool error) the resume
+-- pointer is preserved on the task row. The next chat task can then fall
+-- back to GetLastChatTaskSession and continue the conversation instead of
+-- silently starting over.
UPDATE agent_task_queue
-SET status = 'failed', completed_at = now(), error = $2
+SET status = 'failed',
+ completed_at = now(),
+ error = $2,
+ session_id = COALESCE(sqlc.narg('session_id'), session_id),
+ work_dir = COALESCE(sqlc.narg('work_dir'), work_dir)
WHERE id = $1 AND status IN ('dispatched', 'running')
RETURNING *;
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 2e1bf0d049..d27b99a9c9 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -34,8 +34,16 @@ WHERE id = $1
RETURNING *;
-- name: UpdateChatSessionSession :exec
-UPDATE chat_session SET session_id = $2, work_dir = $3, updated_at = now()
-WHERE id = $1;
+-- Updates the resume pointer for a chat session. Empty/NULL inputs are
+-- ignored via COALESCE so a task that completes without a session_id (e.g.
+-- the agent crashed before establishing one) cannot wipe out a previously
+-- recorded resume pointer. This makes the chat memory robust against
+-- intermittent agent failures.
+UPDATE chat_session
+SET session_id = COALESCE(sqlc.narg('session_id'), session_id),
+ work_dir = COALESCE(sqlc.narg('work_dir'), work_dir),
+ updated_at = now()
+WHERE id = sqlc.arg('id');
-- name: ArchiveChatSession :exec
UPDATE chat_session SET status = 'archived', updated_at = now()
@@ -65,8 +73,15 @@ VALUES ($1, $2, NULL, 'queued', $3, $4)
RETURNING *;
-- name: GetLastChatTaskSession :one
+-- Returns the most recent task in this chat session that managed to record a
+-- session_id. Includes both completed and failed tasks: even a failed task
+-- may have established a real agent session before failing, and we'd rather
+-- resume there than start over and lose conversation memory. Used as a
+-- fallback when chat_session.session_id is NULL.
SELECT session_id, work_dir FROM agent_task_queue
-WHERE chat_session_id = $1 AND status = 'completed' AND session_id IS NOT NULL
+WHERE chat_session_id = $1
+ AND status IN ('completed', 'failed')
+ AND session_id IS NOT NULL
ORDER BY completed_at DESC
LIMIT 1;