Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix: guard session resume by runtime (#1905)
Bright Zhengcf47d9b70231
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 4f38601e2e..2904a97a14 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -970,7 +970,9 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {AgentID: task.AgentID,IssueID: task.IssueID,}); err == nil && prior.SessionID.Valid {- resp.PriorSessionID = prior.SessionID.String+ if prior.RuntimeID == task.RuntimeID {+ resp.PriorSessionID = prior.SessionID.String+ }if prior.WorkDir.Valid {resp.PriorWorkDir = prior.WorkDir.String}@@ -989,24 +991,21 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {resp.Repos = repos}}- // 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 {+ // Resume chat sessions only when the stored pointer was produced+ // by the same runtime as the claiming task. Legacy rows with no+ // chat_session.runtime_id fall back to the task-row lookup below.+ if cs.SessionID.Valid && cs.RuntimeID.Valid && cs.RuntimeID == task.RuntimeID {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 {+ if prior, err := h.Queries.GetLastChatTaskSession(r.Context(), cs.ID); err == nil && prior.SessionID.Valid {+ if resp.PriorSessionID == "" && prior.RuntimeID == task.RuntimeID {resp.PriorSessionID = prior.SessionID.String- if prior.WorkDir.Valid && resp.PriorWorkDir == "" {- resp.PriorWorkDir = prior.WorkDir.String- }+ }+ if prior.WorkDir.Valid && resp.PriorWorkDir == "" {+ resp.PriorWorkDir = prior.WorkDir.String}}// Load the latest user message for the chat prompt.diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex 1d62e1d11c..aa653c40d1 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -1796,3 +1796,390 @@ func TestCompleteTask_CommentTriggered_SkipsSynthesisWhenAgentAlreadyCommented(tt.Fatalf("expected 1 agent comment (the agent's own reply), got %d — synthesis duplicated", count)}}++type claimRuntimeGuardTask struct {+ PriorSessionID string `json:"prior_session_id"`+ PriorWorkDir string `json:"prior_work_dir"`+}++func claimTaskForRuntimeGuard(t *testing.T, runtimeID, daemonID string) *claimRuntimeGuardTask {+ t.Helper()++ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil,+ testWorkspaceID, daemonID)+ rctx := chi.NewRouteContext()+ rctx.URLParams.Add("runtimeId", runtimeID)+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))++ testHandler.ClaimTaskByRuntime(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var resp struct {+ Task *claimRuntimeGuardTask `json:"task"`+ }+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp.Task == nil {+ t.Fatal("expected a task in response, got nil")+ }+ return resp.Task+}++func createRuntimeGuardAgent(t *testing.T, ctx context.Context) (agentID, runtimeID, daemonID string) {+ t.Helper()++ daemonID = "runtime-guard-" + strings.ToLower(strings.ReplaceAll(t.Name(), "/", "-"))+ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{+ "workspace_id": testWorkspaceID,+ "daemon_id": daemonID,+ "device_name": "runtime-guard-test",+ "runtimes": []map[string]any{+ {"name": "runtime-guard-current", "type": "opencode", "version": "test", "status": "online"},+ },+ }, testWorkspaceID, daemonID)++ testHandler.DaemonRegister(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("setup: DaemonRegister: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp map[string]any+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("setup: decode DaemonRegister response: %v", err)+ }+ runtimes, ok := resp["runtimes"].([]any)+ if !ok || len(runtimes) == 0 {+ t.Fatalf("setup: expected registered runtime, got %v", resp)+ }+ runtimeID = runtimes[0].(map[string]any)["id"].(string)+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID) })++ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent (+ workspace_id, name, runtime_mode, runtime_config,+ runtime_id, visibility, max_concurrent_tasks+ )+ VALUES ($1, $2, 'local', '{}'::jsonb, $3, 'workspace', 3)+ RETURNING id+ `, testWorkspaceID, "Runtime Guard Agent "+t.Name(), runtimeID).Scan(&agentID); err != nil {+ t.Fatalf("setup: create runtime guard agent: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent WHERE id = $1`, agentID) })++ return agentID, runtimeID, daemonID+}++func createRuntimeGuardRuntime(t *testing.T, ctx context.Context, provider string) string {+ t.Helper()++ var runtimeID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_runtime (+ workspace_id, daemon_id, name, runtime_mode, provider, status,+ device_info, metadata, owner_id, last_seen_at+ )+ VALUES ($1, 'runtime-guard-' || gen_random_uuid()::text, 'Runtime Guard Fixture',+ 'local', $2, 'offline', '{}'::jsonb, '{}'::jsonb, $3, now())+ RETURNING id+ `, testWorkspaceID, provider, testUserID).Scan(&runtimeID); err != nil {+ t.Fatalf("setup: create runtime: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID) })+ return runtimeID+}++func TestChatSessionRuntimeBackfillRequiresMatchingSessionID(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ tx, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin tx: %v", err)+ }+ defer tx.Rollback(ctx)++ if _, err := tx.Exec(ctx, `+ CREATE TEMP TABLE chat_session (+ id uuid PRIMARY KEY,+ session_id text,+ runtime_id uuid+ ) ON COMMIT DROP;+ `); err != nil {+ t.Fatalf("setup temp chat_session table: %v", err)+ }+ if _, err := tx.Exec(ctx, `+ CREATE TEMP TABLE agent_task_queue (+ chat_session_id uuid,+ runtime_id uuid,+ session_id text,+ status text,+ completed_at timestamptz,+ started_at timestamptz,+ dispatched_at timestamptz,+ created_at timestamptz+ ) ON COMMIT DROP;+ `); err != nil {+ t.Fatalf("setup temp agent_task_queue table: %v", err)+ }++ const (+ poisonedChatID = "00000000-0000-0000-0000-000000000101"+ matchedChatID = "00000000-0000-0000-0000-000000000102"+ oldRuntimeID = "00000000-0000-0000-0000-000000000201"+ newRuntimeID = "00000000-0000-0000-0000-000000000202"+ )++ if _, err := tx.Exec(ctx, `+ INSERT INTO chat_session (id, session_id, runtime_id)+ VALUES+ ($1, 'old-runtime-session', NULL),+ ($2, 'matched-runtime-session', NULL);+ `, poisonedChatID, matchedChatID); err != nil {+ t.Fatalf("seed temp chat sessions: %v", err)+ }+ if _, err := tx.Exec(ctx, `+ INSERT INTO agent_task_queue (+ chat_session_id, runtime_id, session_id, status,+ completed_at, started_at, dispatched_at, created_at+ )+ VALUES+ ($1, $3, 'old-runtime-session', 'completed',+ now() - interval '2 hours', now() - interval '2 hours', now() - interval '2 hours', now() - interval '2 hours'),+ ($1, $4, 'new-runtime-session', 'completed',+ now() - interval '1 hour', now() - interval '1 hour', now() - interval '1 hour', now() - interval '1 hour'),+ ($2, $4, 'matched-runtime-session', 'completed',+ now() - interval '30 minutes', now() - interval '30 minutes', now() - interval '30 minutes', now() - interval '30 minutes');+ `, poisonedChatID, matchedChatID, oldRuntimeID, newRuntimeID); err != nil {+ t.Fatalf("seed temp task sessions: %v", err)+ }++ if _, err := tx.Exec(ctx, `+ UPDATE chat_session cs+ SET runtime_id = latest.runtime_id+ FROM (+ SELECT DISTINCT ON (chat_session_id)+ chat_session_id,+ runtime_id,+ session_id+ FROM agent_task_queue+ WHERE chat_session_id IS NOT NULL+ AND session_id IS NOT NULL+ AND status IN ('completed', 'failed')+ ORDER BY chat_session_id, COALESCE(completed_at, started_at, dispatched_at, created_at) DESC+ ) latest+ WHERE latest.chat_session_id = cs.id+ AND latest.session_id = cs.session_id+ `); err != nil {+ t.Fatalf("run runtime backfill: %v", err)+ }++ var poisonedRuntimeID *string+ if err := tx.QueryRow(ctx, `+ SELECT runtime_id::text FROM chat_session WHERE id = $1+ `, poisonedChatID).Scan(&poisonedRuntimeID); err != nil {+ t.Fatalf("query poisoned chat runtime: %v", err)+ }+ if poisonedRuntimeID != nil {+ t.Fatalf("expected stale session mismatch to remain NULL, got %s", *poisonedRuntimeID)+ }++ var matchedRuntimeID string+ if err := tx.QueryRow(ctx, `+ SELECT runtime_id::text FROM chat_session WHERE id = $1+ `, matchedChatID).Scan(&matchedRuntimeID); err != nil {+ t.Fatalf("query matched chat runtime: %v", err)+ }+ if matchedRuntimeID != newRuntimeID {+ t.Fatalf("expected matched session to backfill runtime %s, got %s", newRuntimeID, matchedRuntimeID)+ }+}++func TestClaimTask_IssuePriorSessionRuntimeGuard(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()++ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)+ oldRuntimeID := createRuntimeGuardRuntime(t, ctx, "kimi")++ var skipIssueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)+ VALUES ($1, 'runtime-session-skip fixture', 'in_progress', 'none', $2, 'member', 81203, 0)+ RETURNING id+ `, testWorkspaceID, testUserID).Scan(&skipIssueID); err != nil {+ t.Fatalf("setup: create skip issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, skipIssueID) })++ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id,+ status, priority, started_at, completed_at,+ session_id, work_dir+ )+ VALUES ($1, $2, $3, 'completed', 0, now(), now(), 'old-runtime-session', '/tmp/old-runtime-workdir')+ `, agentID, oldRuntimeID, skipIssueID); err != nil {+ t.Fatalf("setup: create old-runtime prior task: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id,+ status, priority+ )+ VALUES ($1, $2, $3, 'queued', 0)+ `, agentID, runtimeID, skipIssueID); err != nil {+ t.Fatalf("setup: create current-runtime task: %v", err)+ }++ task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)+ if task.PriorSessionID != "" {+ t.Fatalf("runtime mismatch: expected empty PriorSessionID, got %q", task.PriorSessionID)+ }+ if task.PriorWorkDir != "/tmp/old-runtime-workdir" {+ t.Fatalf("runtime mismatch: expected PriorWorkDir='/tmp/old-runtime-workdir', got %q", task.PriorWorkDir)+ }+ if _, err := testPool.Exec(ctx, `+ UPDATE agent_task_queue+ SET status = 'completed', completed_at = now()+ WHERE issue_id = $1 AND status IN ('dispatched', 'running')+ `, skipIssueID); err != nil {+ t.Fatalf("setup: complete claimed skip task: %v", err)+ }++ var resumeIssueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)+ VALUES ($1, 'runtime-session-resume fixture', 'in_progress', 'none', $2, 'member', 81204, 0)+ RETURNING id+ `, testWorkspaceID, testUserID).Scan(&resumeIssueID); err != nil {+ t.Fatalf("setup: create resume issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, resumeIssueID) })++ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id,+ status, priority, started_at, completed_at,+ session_id, work_dir+ )+ VALUES ($1, $2, $3, 'completed', 0, now(), now(), 'same-runtime-session', '/tmp/same-runtime-workdir')+ `, agentID, runtimeID, resumeIssueID); err != nil {+ t.Fatalf("setup: create same-runtime prior task: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id,+ status, priority+ )+ VALUES ($1, $2, $3, 'queued', 0)+ `, agentID, runtimeID, resumeIssueID); err != nil {+ t.Fatalf("setup: create same-runtime task: %v", err)+ }++ task = claimTaskForRuntimeGuard(t, runtimeID, daemonID)+ if task.PriorSessionID != "same-runtime-session" {+ t.Fatalf("runtime match: expected PriorSessionID='same-runtime-session', got %q", task.PriorSessionID)+ }+ if task.PriorWorkDir != "/tmp/same-runtime-workdir" {+ t.Fatalf("runtime match: expected PriorWorkDir='/tmp/same-runtime-workdir', got %q", task.PriorWorkDir)+ }+}++func TestClaimTask_ChatPriorSessionRuntimeGuard(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()++ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)+ oldRuntimeID := createRuntimeGuardRuntime(t, ctx, "kimi")++ var skipSessionID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO chat_session (+ workspace_id, agent_id, creator_id, title,+ session_id, work_dir, runtime_id+ )+ VALUES ($1, $2, $3, 'runtime guard skip chat', 'old-chat-session', '/tmp/old-chat-workdir', $4)+ RETURNING id+ `, testWorkspaceID, agentID, testUserID, oldRuntimeID).Scan(&skipSessionID); err != nil {+ t.Fatalf("setup: create skip chat session: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, skipSessionID) })++ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, chat_session_id,+ status, priority, started_at, completed_at,+ session_id, work_dir+ )+ VALUES ($1, $2, $3, 'completed', 0, now(), now(), 'old-chat-session', '/tmp/old-chat-workdir')+ `, agentID, oldRuntimeID, skipSessionID); err != nil {+ t.Fatalf("setup: create old-runtime chat task: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, chat_session_id,+ status, priority+ )+ VALUES ($1, $2, $3, 'queued', 0)+ `, agentID, runtimeID, skipSessionID); err != nil {+ t.Fatalf("setup: create current-runtime chat task: %v", err)+ }++ task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)+ if task.PriorSessionID != "" {+ t.Fatalf("chat runtime mismatch: expected empty PriorSessionID, got %q", task.PriorSessionID)+ }+ if task.PriorWorkDir != "/tmp/old-chat-workdir" {+ t.Fatalf("chat runtime mismatch: expected PriorWorkDir='/tmp/old-chat-workdir', got %q", task.PriorWorkDir)+ }+ if _, err := testPool.Exec(ctx, `+ UPDATE agent_task_queue+ SET status = 'completed', completed_at = now()+ WHERE chat_session_id = $1 AND status IN ('dispatched', 'running')+ `, skipSessionID); err != nil {+ t.Fatalf("setup: complete claimed skip chat task: %v", err)+ }++ var resumeSessionID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO chat_session (+ workspace_id, agent_id, creator_id, title,+ session_id, work_dir, runtime_id+ )+ VALUES ($1, $2, $3, 'runtime guard resume chat', 'same-chat-session', '/tmp/same-chat-workdir', $4)+ RETURNING id+ `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&resumeSessionID); err != nil {+ t.Fatalf("setup: create resume chat session: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, resumeSessionID) })++ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, chat_session_id,+ status, priority+ )+ VALUES ($1, $2, $3, 'queued', 0)+ `, agentID, runtimeID, resumeSessionID); err != nil {+ t.Fatalf("setup: create same-runtime chat task: %v", err)+ }++ task = claimTaskForRuntimeGuard(t, runtimeID, daemonID)+ if task.PriorSessionID != "same-chat-session" {+ t.Fatalf("chat runtime match: expected PriorSessionID='same-chat-session', got %q", task.PriorSessionID)+ }+ if task.PriorWorkDir != "/tmp/same-chat-workdir" {+ t.Fatalf("chat runtime match: expected PriorWorkDir='/tmp/same-chat-workdir', got %q", task.PriorWorkDir)+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex ff95b8b02e..152ac72ddf 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -605,12 +605,15 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resutask = tif t.ChatSessionID.Valid {+ sessionRuntimeID := t.RuntimeID+ sessionRuntimeID.Valid = sessionID != ""// 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 != ""},+ RuntimeID: sessionRuntimeID,}); err != nil {return fmt.Errorf("update chat session resume pointer: %w", err)}@@ -754,10 +757,13 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,task = tif t.ChatSessionID.Valid {+ sessionRuntimeID := t.RuntimeID+ sessionRuntimeID.Valid = sessionID != ""if err := qtx.UpdateChatSessionSession(ctx, db.UpdateChatSessionSessionParams{ID: t.ChatSessionID,SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},+ RuntimeID: sessionRuntimeID,}); err != nil {return fmt.Errorf("update chat session resume pointer: %w", err)}diff --git a/server/migrations/060_chat_session_runtime_id.down.sql b/server/migrations/060_chat_session_runtime_id.down.sqlnew file mode 100644index 0000000000..25ba554fd8--- /dev/null+++ b/server/migrations/060_chat_session_runtime_id.down.sql@@ -0,0 +1,2 @@+ALTER TABLE chat_session+DROP COLUMN IF EXISTS runtime_id;diff --git a/server/migrations/060_chat_session_runtime_id.up.sql b/server/migrations/060_chat_session_runtime_id.up.sqlnew file mode 100644index 0000000000..b238583da5--- /dev/null+++ b/server/migrations/060_chat_session_runtime_id.up.sql@@ -0,0 +1,21 @@+ALTER TABLE chat_session+ADD COLUMN runtime_id UUID REFERENCES agent_runtime(id) ON DELETE SET NULL;++-- Backfill only sessions with a recorded resume pointer from a completed or+-- failed task. Sessions with no prior task remain NULL and will fail closed+-- until a future successful task writes a session_id/runtime_id pair.+UPDATE chat_session cs+SET runtime_id = latest.runtime_id+FROM (+ SELECT DISTINCT ON (chat_session_id)+ chat_session_id,+ runtime_id,+ session_id+ FROM agent_task_queue+ WHERE chat_session_id IS NOT NULL+ AND session_id IS NOT NULL+ AND status IN ('completed', 'failed')+ ORDER BY chat_session_id, COALESCE(completed_at, started_at, dispatched_at, created_at) DESC+) latest+WHERE latest.chat_session_id = cs.id+ AND latest.session_id = cs.session_id;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 8ea886f2c5..3c390b485a 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -985,7 +985,7 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu}const getLastTaskSession = `-- name: GetLastTaskSession :one-SELECT session_id, work_dir FROM agent_task_queue+SELECT session_id, work_dir, runtime_id FROM agent_task_queueWHERE agent_id = $1 AND issue_id = $2AND (status = 'completed'@@ -1004,6 +1004,7 @@ type GetLastTaskSessionParams struct {type GetLastTaskSessionRow struct {SessionID pgtype.Text `json:"session_id"`WorkDir pgtype.Text `json:"work_dir"`+ RuntimeID pgtype.UUID `json:"runtime_id"`}// Returns the session_id and work_dir from the most recent task for a given@@ -1022,7 +1023,7 @@ type GetLastTaskSessionRow struct {func (q *Queries) GetLastTaskSession(ctx context.Context, arg GetLastTaskSessionParams) (GetLastTaskSessionRow, error) {row := q.db.QueryRow(ctx, getLastTaskSession, arg.AgentID, arg.IssueID)var i GetLastTaskSessionRow- err := row.Scan(&i.SessionID, &i.WorkDir)+ err := row.Scan(&i.SessionID, &i.WorkDir, &i.RuntimeID)return i, err}diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex f2f7797e60..d1a67b149f 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -60,9 +60,9 @@ func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessagePa}const createChatSession = `-- name: CreateChatSession :one-INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)-VALUES ($1, $2, $3, $4)-RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since+INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id)+VALUES ($1, $2, $3, $4, (SELECT runtime_id FROM agent WHERE id = $2))+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id`type CreateChatSessionParams struct {@@ -92,6 +92,7 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPa&i.CreatedAt,&i.UpdatedAt,&i.UnreadSince,+ &i.RuntimeID,)return i, err}@@ -169,7 +170,7 @@ func (q *Queries) GetChatMessage(ctx context.Context, id pgtype.UUID) (ChatMessa}const getChatSession = `-- name: GetChatSession :one-SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since FROM chat_session+SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id FROM chat_sessionWHERE id = $1`@@ -188,12 +189,13 @@ func (q *Queries) GetChatSession(ctx context.Context, id pgtype.UUID) (ChatSessi&i.CreatedAt,&i.UpdatedAt,&i.UnreadSince,+ &i.RuntimeID,)return i, err}const getChatSessionInWorkspace = `-- name: GetChatSessionInWorkspace :one-SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since FROM chat_session+SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id FROM chat_sessionWHERE id = $1 AND workspace_id = $2`@@ -217,12 +219,13 @@ func (q *Queries) GetChatSessionInWorkspace(ctx context.Context, arg GetChatSess&i.CreatedAt,&i.UpdatedAt,&i.UnreadSince,+ &i.RuntimeID,)return i, err}const getLastChatTaskSession = `-- name: GetLastChatTaskSession :one-SELECT session_id, work_dir FROM agent_task_queue+SELECT session_id, work_dir, runtime_id FROM agent_task_queueWHERE chat_session_id = $1AND status IN ('completed', 'failed')AND session_id IS NOT NULL@@ -233,6 +236,7 @@ LIMIT 1type GetLastChatTaskSessionRow struct {SessionID pgtype.Text `json:"session_id"`WorkDir pgtype.Text `json:"work_dir"`+ RuntimeID pgtype.UUID `json:"runtime_id"`}// Returns the most recent task in this chat session that managed to record a@@ -243,7 +247,7 @@ type GetLastChatTaskSessionRow struct {func (q *Queries) GetLastChatTaskSession(ctx context.Context, chatSessionID pgtype.UUID) (GetLastChatTaskSessionRow, error) {row := q.db.QueryRow(ctx, getLastChatTaskSession, chatSessionID)var i GetLastChatTaskSessionRow- err := row.Scan(&i.SessionID, &i.WorkDir)+ err := row.Scan(&i.SessionID, &i.WorkDir, &i.RuntimeID)return i, err}@@ -273,7 +277,7 @@ func (q *Queries) GetPendingChatTask(ctx context.Context, chatSessionID pgtype.U}const listAllChatSessionsByCreator = `-- name: ListAllChatSessionsByCreator :many-SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since,+SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id,(cs.unread_since IS NOT NULL)::bool AS has_unreadFROM chat_session csWHERE cs.workspace_id = $1 AND cs.creator_id = $2@@ -297,6 +301,7 @@ type ListAllChatSessionsByCreatorRow struct {CreatedAt pgtype.Timestamptz `json:"created_at"`UpdatedAt pgtype.Timestamptz `json:"updated_at"`UnreadSince pgtype.Timestamptz `json:"unread_since"`+ RuntimeID pgtype.UUID `json:"runtime_id"`HasUnread bool `json:"has_unread"`}@@ -321,6 +326,7 @@ func (q *Queries) ListAllChatSessionsByCreator(ctx context.Context, arg ListAllC&i.CreatedAt,&i.UpdatedAt,&i.UnreadSince,+ &i.RuntimeID,&i.HasUnread,); err != nil {return nil, err@@ -369,7 +375,7 @@ func (q *Queries) ListChatMessages(ctx context.Context, chatSessionID pgtype.UUI}const listChatSessionsByCreator = `-- name: ListChatSessionsByCreator :many-SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since,+SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id,(cs.unread_since IS NOT NULL)::bool AS has_unreadFROM chat_session csWHERE cs.workspace_id = $1 AND cs.creator_id = $2 AND cs.status = 'active'@@ -393,6 +399,7 @@ type ListChatSessionsByCreatorRow struct {CreatedAt pgtype.Timestamptz `json:"created_at"`UpdatedAt pgtype.Timestamptz `json:"updated_at"`UnreadSince pgtype.Timestamptz `json:"unread_since"`+ RuntimeID pgtype.UUID `json:"runtime_id"`HasUnread bool `json:"has_unread"`}@@ -420,6 +427,7 @@ func (q *Queries) ListChatSessionsByCreator(ctx context.Context, arg ListChatSes&i.CreatedAt,&i.UpdatedAt,&i.UnreadSince,+ &i.RuntimeID,&i.HasUnread,); err != nil {return nil, err@@ -514,13 +522,15 @@ const updateChatSessionSession = `-- name: UpdateChatSessionSession :execUPDATE chat_sessionSET session_id = COALESCE($1, session_id),work_dir = COALESCE($2, work_dir),+ runtime_id = COALESCE($3, runtime_id),updated_at = now()-WHERE id = $3+WHERE id = $4`type UpdateChatSessionSessionParams struct {SessionID pgtype.Text `json:"session_id"`WorkDir pgtype.Text `json:"work_dir"`+ RuntimeID pgtype.UUID `json:"runtime_id"`ID pgtype.UUID `json:"id"`}@@ -530,14 +540,19 @@ type UpdateChatSessionSessionParams struct {// 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.SessionID, arg.WorkDir, arg.ID)+ _, err := q.db.Exec(ctx, updateChatSessionSession,+ arg.SessionID,+ arg.WorkDir,+ arg.RuntimeID,+ arg.ID,+ )return err}const updateChatSessionTitle = `-- name: UpdateChatSessionTitle :oneUPDATE chat_session SET title = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id`type UpdateChatSessionTitleParams struct {@@ -560,6 +575,7 @@ func (q *Queries) UpdateChatSessionTitle(ctx context.Context, arg UpdateChatSess&i.CreatedAt,&i.UpdatedAt,&i.UnreadSince,+ &i.RuntimeID,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 9776aa640f..e9421fbc90 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -178,6 +178,7 @@ type ChatSession struct {CreatedAt pgtype.Timestamptz `json:"created_at"`UpdatedAt pgtype.Timestamptz `json:"updated_at"`UnreadSince pgtype.Timestamptz `json:"unread_since"`+ RuntimeID pgtype.UUID `json:"runtime_id"`}type Comment struct {diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 7bdd292d91..f5fd947389 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -225,7 +225,7 @@ RETURNING *;-- a rerun does not inherit the bad session. The daemon classifies these-- failures (iteration_limit, agent_fallback_message) when it detects the-- agent emitted a fallback marker instead of a real result.-SELECT session_id, work_dir FROM agent_task_queue+SELECT session_id, work_dir, runtime_id FROM agent_task_queueWHERE agent_id = $1 AND issue_id = $2AND (status = 'completed'diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex 3bb5744ccf..624f8448d7 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -1,6 +1,6 @@-- name: CreateChatSession :one-INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)-VALUES ($1, $2, $3, $4)+INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id)+VALUES ($1, $2, $3, $4, (SELECT runtime_id FROM agent WHERE id = $2))RETURNING *;-- name: GetChatSession :one@@ -42,6 +42,7 @@ RETURNING *;UPDATE chat_sessionSET session_id = COALESCE(sqlc.narg('session_id'), session_id),work_dir = COALESCE(sqlc.narg('work_dir'), work_dir),+ runtime_id = COALESCE(sqlc.narg('runtime_id'), runtime_id),updated_at = now()WHERE id = sqlc.arg('id');@@ -78,7 +79,7 @@ RETURNING *;-- 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+SELECT session_id, work_dir, runtime_id FROM agent_task_queueWHERE chat_session_id = $1AND status IN ('completed', 'failed')AND session_id IS NOT NULL