Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(docs): stop a discussion's runs when it is deleted (#11505)
pseudoyu171eca8e2f5b
diff --git a/server/internal/handler/doc_comment.go b/server/internal/handler/doc_comment.goindex 6971d52e6b..d39cee7ae3 100644--- a/server/internal/handler/doc_comment.go+++ b/server/internal/handler/doc_comment.go@@ -2,6 +2,7 @@ package handlerimport ("encoding/json"+ "log/slog""net/http""strings""time"@@ -268,6 +269,13 @@ func (h *Handler) DeleteDocComment(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to delete comment")return}+ // Runs answering a deleted discussion have nothing left to answer. A run+ // triggered by a deleted reply still has the discussion to read.+ if !comment.ParentID.Valid {+ if err := h.TaskService.CancelTasksForDocThread(r.Context(), doc.ID, comment.ID); err != nil {+ slog.Warn("delete doc discussion: cancel runs failed", "doc_id", uuidToString(doc.ID), "thread_id", uuidToString(comment.ID), "error", err)+ }+ }h.publish(protocol.EventDocCommentChanged, workspaceID, actorType, actorID, map[string]any{"doc_id": uuidToString(doc.ID), "comment_id": uuidToString(comment.ID),})diff --git a/server/internal/handler/doc_task_test.go b/server/internal/handler/doc_task_test.goindex 867c6a381e..873bdf2d77 100644--- a/server/internal/handler/doc_task_test.go+++ b/server/internal/handler/doc_task_test.go@@ -3,6 +3,7 @@ package handlerimport ("context""fmt"+ "maps""net/http""testing""time"@@ -229,6 +230,58 @@ func TestDocCommentClaimCarriesDiscussionAndResumesDocSession(t *testing.T) {testPool.Exec(context.Background(), "DELETE FROM agent_task_queue WHERE id = $1", tasks[1].ID)}+// Deleting a discussion stops its runs: they have nothing left to answer, and+// the page no longer shows them to stop. A deleted reply stops nothing, and+// other discussions keep their runs.+func TestDocCommentDeleteStopsTheDiscussionsRuns(t *testing.T) {+ doc := createDocForTest(t)+ t.Cleanup(func() {+ ctx := context.Background()+ testPool.Exec(ctx, "DELETE FROM agent_task_queue WHERE doc_id = $1", doc.ID)+ testPool.Exec(ctx, "DELETE FROM doc_comment WHERE doc_id = $1", doc.ID)+ })+ stamp := time.Now().UnixNano()+ runner := createHandlerTestAgent(t, fmt.Sprintf("Doc Runner %d", stamp), nil)+ waiter := createHandlerTestAgent(t, fmt.Sprintf("Doc Waiter %d", stamp), nil)+ post := func(body map[string]any) DocCommentResponse {+ t.Helper()+ var c DocCommentResponse+ testutil.Call(t, testHandler.CreateDocComment, withURLParam(newRequest("POST", "/comments", body), "id", doc.ID)).Want(http.StatusCreated).JSON(&c)+ return c+ }+ remove := func(id string) {+ t.Helper()+ testutil.Call(t, testHandler.DeleteDocComment, withURLParams(newRequest("DELETE", "/comments", nil), "id", doc.ID, "docCommentId", id)).Want(http.StatusNoContent)+ }+ mention := func(id string) string { return "[@A](mention://agent/" + id + ")" }+ statuses := func() map[string]string {+ out := map[string]string{}+ for _, task := range docTasksFor(t, doc.ID) {+ out[task.ThreadID+"/"+task.AgentID] = task.Status+ }+ return out+ }++ root := post(map[string]any{"content": "Tighten this. " + mention(runner), "anchor_quote": "Original"})+ dbfx.Exec(t, "UPDATE agent_task_queue SET status = 'running', started_at = now(), dispatched_at = now() WHERE doc_id = $1 AND agent_id = $2", doc.ID, runner)+ reply := post(map[string]any{"content": "And check it. " + mention(waiter), "parent_id": root.ID})+ other := post(map[string]any{"content": "Expand this. " + mention(waiter), "anchor_quote": "First"})++ want := map[string]string{root.ID + "/" + runner: "running", root.ID + "/" + waiter: "queued", other.ID + "/" + waiter: "queued"}+ if got := statuses(); !maps.Equal(got, want) {+ t.Fatalf("runs before any delete = %v, want %v", got, want)+ }+ remove(reply.ID)+ if got := statuses(); !maps.Equal(got, want) {+ t.Fatalf("runs after deleting a reply = %v, want %v", got, want)+ }+ remove(root.ID)+ want[root.ID+"/"+runner], want[root.ID+"/"+waiter] = "cancelled", "cancelled"+ if got := statuses(); !maps.Equal(got, want) {+ t.Fatalf("runs after deleting the discussion = %v, want %v", got, want)+ }+}+// A run that ends without replying still answers its discussion with its// final output; one that replied gets no second reply.func TestDocCommentRunWithoutReplyPostsItsOutput(t *testing.T) {diff --git a/server/internal/service/doc_task.go b/server/internal/service/doc_task.goindex 91e8becfb9..34258b5576 100644--- a/server/internal/service/doc_task.go+++ b/server/internal/service/doc_task.go@@ -173,10 +173,23 @@ func (s *TaskService) attributionFromDocComment(ctx context.Context, comment db.// CancelTasksForDoc cancels every active run on a deleted doc, the doc// counterpart of CancelTasksForIssue.func (s *TaskService) CancelTasksForDoc(ctx context.Context, docID pgtype.UUID) error {+ return s.cancelDocTasks(ctx, func(qtx *db.Queries) ([]db.AgentTaskQueue, error) {+ return qtx.CancelAgentTasksByDoc(ctx, docID)+ })+}++// CancelTasksForDocThread cancels every active run on a deleted discussion.+func (s *TaskService) CancelTasksForDocThread(ctx context.Context, docID, threadID pgtype.UUID) error {+ return s.cancelDocTasks(ctx, func(qtx *db.Queries) ([]db.AgentTaskQueue, error) {+ return qtx.CancelAgentTasksByDocThread(ctx, db.CancelAgentTasksByDocThreadParams{DocID: docID, DocThreadID: threadID})+ })+}++func (s *TaskService) cancelDocTasks(ctx context.Context, cancel func(*db.Queries) ([]db.AgentTaskQueue, error)) error {var cancelled []db.AgentTaskQueueif err := s.runInTx(ctx, func(qtx *db.Queries) error {var err error- cancelled, err = qtx.CancelAgentTasksByDoc(ctx, docID)+ cancelled, err = cancel(qtx)if err != nil {return err}diff --git a/server/pkg/db/generated/doc_task.sql.go b/server/pkg/db/generated/doc_task.sql.goindex 82cd5ad598..9970941997 100644--- a/server/pkg/db/generated/doc_task.sql.go+++ b/server/pkg/db/generated/doc_task.sql.go@@ -106,6 +106,106 @@ func (q *Queries) CancelAgentTasksByDoc(ctx context.Context, docID pgtype.UUID)return items, nil}+const cancelAgentTasksByDocThread = `-- name: CancelAgentTasksByDocThread :many+UPDATE agent_task_queue+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,+ cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL+WHERE doc_id = $1 AND doc_thread_id = $2+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+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, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id+`++type CancelAgentTasksByDocThreadParams struct {+ DocID pgtype.UUID `json:"doc_id"`+ DocThreadID pgtype.UUID `json:"doc_thread_id"`+}++// Discussion deletion cleanup, the counterpart of CancelAgentTasksByDoc.+func (q *Queries) CancelAgentTasksByDocThread(ctx context.Context, arg CancelAgentTasksByDocThreadParams) ([]AgentTaskQueue, error) {+ rows, err := q.db.Query(ctx, cancelAgentTasksByDocThread, arg.DocID, arg.DocThreadID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AgentTaskQueue{}+ for rows.Next() {+ var i AgentTaskQueue+ if err := rows.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ &i.ChatFinalizeDeferredAt,+ &i.OriginatorSource,+ &i.DelegatedFromTaskID,+ &i.RetryOfTaskID,+ &i.RerunOfTaskID,+ &i.RuleVersionID,+ &i.TriggerEvidenceKind,+ &i.TriggerEvidenceRefID,+ &i.AccountableUserID,+ &i.SessionRolloutMissing,+ &i.RetiredSessionID,+ &i.QuickActionsDisabled,+ &i.RegenerateQuickActionsFor,+ &i.BranchName,+ &i.DurableWorkDir,+ &i.ChannelContextRevision,+ &i.CommentThreadID,+ &i.CancelledByType,+ &i.CancelledByID,+ &i.CancelledByName,+ &i.IssueSnapshot,+ &i.WorkflowStep,+ &i.UsageSquadID,+ &i.DocID,+ &i.DocThreadID,+ &i.DocCommentID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const createDocCommentTask = `-- name: CreateDocCommentTask :oneWITH enqueue_agent AS MATERIALIZED (diff --git a/server/pkg/db/queries/doc_task.sql b/server/pkg/db/queries/doc_task.sqlindex afda870c21..13c4b9d4a7 100644--- a/server/pkg/db/queries/doc_task.sql+++ b/server/pkg/db/queries/doc_task.sql@@ -103,6 +103,15 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,WHERE doc_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')RETURNING *;+-- name: CancelAgentTasksByDocThread :many+-- Discussion deletion cleanup, the counterpart of CancelAgentTasksByDoc.+UPDATE agent_task_queue+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,+ cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL+WHERE doc_id = @doc_id AND doc_thread_id = @doc_thread_id+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+RETURNING *;+-- name: GetLastDocTaskSession :one-- Resume context for an agent on a doc: one session and workdir per (doc,-- agent), the doc analogue of GetLastTaskSession. Keep the per-session