Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(comments): enforce single resolution per thread (#3984)
Naiyuan Qing34c68e1e4c30
diff --git a/packages/core/issues/mutations.test.tsx b/packages/core/issues/mutations.test.tsxindex 546564ed38..997ab8a6df 100644--- a/packages/core/issues/mutations.test.tsx+++ b/packages/core/issues/mutations.test.tsx@@ -8,7 +8,7 @@ import type { ReactNode } from "react";import { setApiInstance } from "../api";import type { ApiClient } from "../api/client";-import { useLoadMoreByAssigneeGroup, useLoadMoreByStatus } from "./mutations";+import { useLoadMoreByAssigneeGroup, useLoadMoreByStatus, useResolveComment } from "./mutations";import {issueKeys,type IssueSortParam,@@ -20,6 +20,7 @@ import type {ListIssuesParams,ListGroupedIssuesParams,ListIssuesResponse,+ TimelineEntry,} from "../types";vi.mock("../hooks", () => ({@@ -312,3 +313,114 @@ describe("useLoadMoreByAssigneeGroup", () => {]);});});++describe("useResolveComment", () => {+ const ISSUE_ID = "issue-1";++ function makeComment(+ id: string,+ parentId: string | null,+ resolvedAt: string | null,+ ): TimelineEntry {+ return {+ type: "comment",+ id,+ actor_type: "member",+ actor_id: "user-1",+ content: id,+ parent_id: parentId,+ comment_type: "comment",+ reactions: [],+ attachments: [],+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ resolved_at: resolvedAt,+ resolved_by_type: resolvedAt ? "member" : null,+ resolved_by_id: resolvedAt ? "user-1" : null,+ };+ }++ // Two independent threads on one issue:+ // root1 ─ a1 (resolved), b1+ // root2 ─ a2 (resolved)+ function seedTimeline(qc: QueryClient) {+ const entries: TimelineEntry[] = [+ makeComment("root1", null, null),+ makeComment("a1", "root1", "2026-01-01T00:01:00Z"),+ makeComment("b1", "root1", null),+ makeComment("root2", null, null),+ makeComment("a2", "root2", "2026-01-01T00:05:00Z"),+ ];+ qc.setQueryData<TimelineEntry[]>(issueKeys.timeline(ISSUE_ID), entries);+ }++ function resolvedIds(qc: QueryClient): string[] {+ const cache = qc.getQueryData<TimelineEntry[]>(issueKeys.timeline(ISSUE_ID)) ?? [];+ return cache.filter((e) => e.resolved_at).map((e) => e.id).sort();+ }++ let qc: QueryClient;++ beforeEach(() => {+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ setApiInstance({+ resolveComment: vi.fn().mockResolvedValue({ id: "b1" }),+ unresolveComment: vi.fn().mockResolvedValue({ id: "b1" }),+ } as unknown as ApiClient);+ });++ afterEach(() => {+ qc.clear();+ vi.restoreAllMocks();+ });++ it("clears the prior resolution in the same thread when resolving another comment", async () => {+ seedTimeline(qc);++ const { result } = renderHook(() => useResolveComment(ISSUE_ID), {+ wrapper: createWrapper(qc),+ });++ await act(async () => {+ await result.current.mutateAsync({ commentId: "b1", resolved: true });+ });++ // b1 replaces a1 inside thread 1; a2 (thread 2) is untouched.+ expect(resolvedIds(qc)).toEqual(["a2", "b1"]);+ });++ it("does not clear resolutions in other threads", async () => {+ seedTimeline(qc);++ const { result } = renderHook(() => useResolveComment(ISSUE_ID), {+ wrapper: createWrapper(qc),+ });++ // Resolving root1 (thread 1) must leave a2 (thread 2) resolved.+ await act(async () => {+ await result.current.mutateAsync({ commentId: "root1", resolved: true });+ });++ expect(resolvedIds(qc)).toEqual(["a2", "root1"]);+ });++ it("unresolve only clears its own row, never siblings", async () => {+ // Legacy state: two resolved comments coexist in one thread.+ qc.setQueryData<TimelineEntry[]>(issueKeys.timeline(ISSUE_ID), [+ makeComment("root1", null, null),+ makeComment("a1", "root1", "2026-01-01T00:01:00Z"),+ makeComment("b1", "root1", "2026-01-01T00:02:00Z"),+ ]);++ const { result } = renderHook(() => useResolveComment(ISSUE_ID), {+ wrapper: createWrapper(qc),+ });++ await act(async () => {+ await result.current.mutateAsync({ commentId: "b1", resolved: false });+ });++ // Only b1 is cleared; a1 stays resolved (unresolve never mirrors the clear).+ expect(resolvedIds(qc)).toEqual(["a1"]);+ });+});diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.tsindex f3ebd2340f..f1fee46764 100644--- a/packages/core/issues/mutations.ts+++ b/packages/core/issues/mutations.ts@@ -709,6 +709,51 @@ export function useDeleteComment(issueId: string) {});}+// Every comment id in the same thread as `commentId` — the thread root plus+// every descendant. Mirrors the server's thread walk in+// ClearOtherThreadResolutions so the resolve optimistic update can clear sibling+// resolutions exactly as the backend will, instead of briefly showing two+// resolutions until the refetch settles.+function collectThreadCommentIds(+ entries: TimelineCache,+ commentId: string,+): Set<string> {+ const byId = new Map<string, TimelineEntry>();+ for (const e of entries) {+ if (e.type === "comment") byId.set(e.id, e);+ }+ // Walk up to the thread root (cycle-guarded against malformed parent chains).+ let rootId = commentId;+ const guard = new Set<string>();+ let cur = byId.get(commentId);+ while (cur?.parent_id && byId.has(cur.parent_id) && !guard.has(cur.id)) {+ guard.add(cur.id);+ rootId = cur.parent_id;+ cur = byId.get(cur.parent_id);+ }+ // Expand back down over the whole subtree.+ const childrenByParent = new Map<string, string[]>();+ for (const e of byId.values()) {+ if (e.parent_id) {+ const list = childrenByParent.get(e.parent_id) ?? [];+ list.push(e.id);+ childrenByParent.set(e.parent_id, list);+ }+ }+ const ids = new Set<string>([rootId]);+ const stack = [rootId];+ while (stack.length > 0) {+ const id = stack.pop()!;+ for (const child of childrenByParent.get(id) ?? []) {+ if (!ids.has(child)) {+ ids.add(child);+ stack.push(child);+ }+ }+ }+ return ids;+}+export function useResolveComment(issueId: string) {const qc = useQueryClient();return useMutation({@@ -717,18 +762,29 @@ export function useResolveComment(issueId: string) {onMutate: async ({ commentId, resolved }) => {await qc.cancelQueries({ queryKey: issueKeys.timeline(issueId) });const prev = qc.getQueryData<TimelineCache>(issueKeys.timeline(issueId));- qc.setQueryData<TimelineCache>(issueKeys.timeline(issueId), (old) =>- old?.map((e) =>- e.id === commentId- ? {- ...e,- resolved_at: resolved ? new Date().toISOString() : null,- resolved_by_type: resolved ? e.resolved_by_type ?? null : null,- resolved_by_id: resolved ? e.resolved_by_id ?? null : null,- }- : e,- ),- );+ qc.setQueryData<TimelineCache>(issueKeys.timeline(issueId), (old) => {+ if (!old) return old;+ // Resolving makes this comment the sole resolution in its thread, so+ // mirror the server (ClearOtherThreadResolutions) and clear every other+ // resolution in the same thread. Without this the cache shows two+ // resolutions until the settle refetch, which is exactly the flash the+ // single-resolution fix removes. Unresolve only clears its own row.+ const threadIds = resolved ? collectThreadCommentIds(old, commentId) : null;+ return old.map((e) => {+ if (e.id === commentId) {+ return {+ ...e,+ resolved_at: resolved ? new Date().toISOString() : null,+ resolved_by_type: resolved ? e.resolved_by_type ?? null : null,+ resolved_by_id: resolved ? e.resolved_by_id ?? null : null,+ };+ }+ if (resolved && e.resolved_at && threadIds?.has(e.id)) {+ return { ...e, resolved_at: null, resolved_by_type: null, resolved_by_id: null };+ }+ return e;+ });+ });return { prev };},onError: (_err, _vars, ctx) => {diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex afe9d96f3c..f0089218f8 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -1444,7 +1444,31 @@ func (h *Handler) ResolveComment(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "invalid actor id")return}- updated, err := h.Queries.ResolveComment(r.Context(), db.ResolveCommentParams{++ // Single-resolution invariant: a thread has at most one resolved comment, so+ // resolving this one must clear any other resolution in the same thread. Both+ // writes run in one tx — clearing the old resolution and setting the new one+ // is atomic, so a crash can never leave two resolutions (or none) visible.+ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to resolve comment")+ return+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)++ cleared, err := qtx.ClearOtherThreadResolutions(r.Context(), db.ClearOtherThreadResolutionsParams{+ TargetID: comment.ID,+ IssueID: comment.IssueID,+ WorkspaceID: comment.WorkspaceID,+ })+ if err != nil {+ slog.Warn("clear other thread resolutions failed", append(logger.RequestAttrs(r), "error", err, "comment_id", uuidToString(comment.ID))...)+ writeError(w, http.StatusInternalServerError, "failed to resolve comment")+ return+ }++ updated, err := qtx.ResolveComment(r.Context(), db.ResolveCommentParams{ID: comment.ID,ResolvedByType: pgtype.Text{String: actorType, Valid: true},ResolvedByID: actorUUID,@@ -1455,13 +1479,33 @@ func (h *Handler) ResolveComment(w http.ResponseWriter, r *http.Request) {return}+ if err := tx.Commit(r.Context()); err != nil {+ slog.Warn("resolve comment commit failed", append(logger.RequestAttrs(r), "error", err, "comment_id", uuidToString(comment.ID))...)+ writeError(w, http.StatusInternalServerError, "failed to resolve comment")+ return+ }++ // Emit a comment:unresolved per cleared sibling so granular realtime+ // consumers (which patch a single comment in place) drop the stale+ // resolution instead of showing two. Published after commit so no event ever+ // describes an uncommitted state.+ for _, c := range cleared {+ clearedID := uuidToString(c.ID)+ clearedReactions := h.groupReactions(r, []pgtype.UUID{c.ID})+ clearedAtt := h.groupAttachments(r, []pgtype.UUID{c.ID})+ clearedResp := commentToResponse(c, clearedReactions[clearedID], clearedAtt[clearedID])+ slog.Info("comment unresolved (replaced)", append(logger.RequestAttrs(r), "comment_id", clearedID)...)+ h.publish(protocol.EventCommentUnresolved, workspaceID, actorType, actorID, map[string]any{"comment": clearedResp})+ }+grouped := h.groupReactions(r, []pgtype.UUID{updated.ID})groupedAtt := h.groupAttachments(r, []pgtype.UUID{updated.ID})cid := uuidToString(updated.ID)resp := commentToResponse(updated, grouped[cid], groupedAtt[cid])- // Suppress the event on a re-resolve no-op so consumers do not re-process- // an unchanged thread (notifications, log spam).+ // Suppress the target event on a re-resolve no-op so consumers do not+ // re-process an unchanged thread (notifications, log spam). Cleared siblings+ // still get their own events above — those rows did change.if !wasResolved {slog.Info("comment resolved", append(logger.RequestAttrs(r), "comment_id", cid)...)h.publish(protocol.EventCommentResolved, workspaceID, actorType, actorID, map[string]any{"comment": resp})diff --git a/server/internal/handler/comment_resolve_test.go b/server/internal/handler/comment_resolve_test.gonew file mode 100644index 0000000000..3465a4038b--- /dev/null+++ b/server/internal/handler/comment_resolve_test.go@@ -0,0 +1,254 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "sync"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// resolveCommentHTTP drives the POST /api/comments/{id}/resolve handler and+// returns the decoded response. Mirrors the resolve path the web/desktop client+// hits.+func resolveCommentHTTP(t *testing.T, commentID string) CommentResponse {+ t.Helper()+ w := httptest.NewRecorder()+ r := newRequest("POST", "/api/comments/"+commentID+"/resolve", nil)+ r = withURLParam(r, "commentId", commentID)+ testHandler.ResolveComment(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("resolve %s: status %d: %s", commentID, w.Code, w.Body.String())+ }+ var resp CommentResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode resolve response: %v", err)+ }+ return resp+}++// commentResolved reports whether a comment currently has resolved_at set,+// read straight from the row so the assertion sees committed state.+func commentResolved(t *testing.T, id string) bool {+ t.Helper()+ var resolvedAt *time.Time+ if err := testPool.QueryRow(context.Background(),+ `SELECT resolved_at FROM comment WHERE id = $1`, id,+ ).Scan(&resolvedAt); err != nil {+ t.Fatalf("query resolved_at for %s: %v", id, err)+ }+ return resolvedAt != nil+}++// commentResolvedAt returns the raw resolved_at timestamp (nil when cleared).+func commentResolvedAt(t *testing.T, id string) *time.Time {+ t.Helper()+ var resolvedAt *time.Time+ if err := testPool.QueryRow(context.Background(),+ `SELECT resolved_at FROM comment WHERE id = $1`, id,+ ).Scan(&resolvedAt); err != nil {+ t.Fatalf("query resolved_at for %s: %v", id, err)+ }+ return resolvedAt+}++// commentEventCapture records comment:resolved / comment:unresolved events for a+// single issue. The handler bus has no Unsubscribe, so the closure filters by+// issue id; events for other tests' issues are ignored.+type commentEventCapture struct {+ mu sync.Mutex+ events []struct {+ Type string+ CommentID string+ }+}++func captureCommentEvents(t *testing.T, issueID string) *commentEventCapture {+ t.Helper()+ cap := &commentEventCapture{}+ record := func(e events.Event) {+ m, ok := e.Payload.(map[string]any)+ if !ok {+ return+ }+ c, ok := m["comment"].(CommentResponse)+ if !ok || c.IssueID != issueID {+ return+ }+ cap.mu.Lock()+ cap.events = append(cap.events, struct {+ Type string+ CommentID string+ }{e.Type, c.ID})+ cap.mu.Unlock()+ }+ testHandler.Bus.Subscribe(protocol.EventCommentResolved, record)+ testHandler.Bus.Subscribe(protocol.EventCommentUnresolved, record)+ return cap+}++func (c *commentEventCapture) countFor(eventType, commentID string) int {+ c.mu.Lock()+ defer c.mu.Unlock()+ n := 0+ for _, e := range c.events {+ if e.Type == eventType && e.CommentID == commentID {+ n+++ }+ }+ return n+}++// resolveTestFixture seeds an issue with two independent threads so the tests+// can prove the single-resolution invariant is thread-scoped, not issue-scoped:+//+// root1+// ├── a1+// └── b1+// root2 (separate thread)+// └── a2+type resolveTestFixture struct {+ IssueID string+ Root1 string+ A1 string+ B1 string+ Root2 string+ A2 string+}++func newResolveTestFixture(t *testing.T) resolveTestFixture {+ t.Helper()+ ctx := context.Background()++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, creator_type, creator_id, title)+ VALUES ($1, 'member', $2, $3)+ RETURNING id+ `, testWorkspaceID, testUserID, "resolve fixture").Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)+ })++ base := time.Now().UTC().Add(-1 * time.Hour).Truncate(time.Second)+ insert := func(parent *string, offset time.Duration, body string) string {+ t.Helper()+ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, created_at)+ VALUES ($1, $2, 'member', $3, $4, 'comment', $5, $6)+ RETURNING id+ `, issueID, testWorkspaceID, testUserID, body, parent, base.Add(offset)).Scan(&id); err != nil {+ t.Fatalf("insert comment %q: %v", body, err)+ }+ return id+ }++ root1 := insert(nil, 0, "root1")+ a1 := insert(&root1, 1*time.Minute, "a1")+ b1 := insert(&root1, 2*time.Minute, "b1")+ root2 := insert(nil, 10*time.Minute, "root2")+ a2 := insert(&root2, 11*time.Minute, "a2")++ return resolveTestFixture{IssueID: issueID, Root1: root1, A1: a1, B1: b1, Root2: root2, A2: a2}+}++// TestResolveComment_ReplacesPriorThreadResolution is the core regression for+// MUL-3180: a thread must have at most one resolved comment, and resolving a new+// one atomically clears the previous resolution (instead of leaving two resolved+// rows that the UI only papered over).+func TestResolveComment_ReplacesPriorThreadResolution(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ fx := newResolveTestFixture(t)+ cap := captureCommentEvents(t, fx.IssueID)++ // Resolve a1 → it is the resolution.+ resolveCommentHTTP(t, fx.A1)+ if !commentResolved(t, fx.A1) {+ t.Fatalf("a1 should be resolved after first resolve")+ }++ // Resolve b1 → b1 becomes the resolution and a1 is cleared in the same write.+ resolveCommentHTTP(t, fx.B1)+ if !commentResolved(t, fx.B1) {+ t.Fatalf("b1 should be resolved")+ }+ if commentResolved(t, fx.A1) {+ t.Fatalf("a1 should have been cleared when b1 was resolved (single-resolution invariant)")+ }++ // The cleared sibling must broadcast comment:unresolved so granular realtime+ // consumers drop the stale resolution; b1 must broadcast comment:resolved.+ if got := cap.countFor(protocol.EventCommentUnresolved, fx.A1); got != 1 {+ t.Fatalf("expected exactly 1 comment:unresolved for a1, got %d", got)+ }+ if got := cap.countFor(protocol.EventCommentResolved, fx.B1); got != 1 {+ t.Fatalf("expected exactly 1 comment:resolved for b1, got %d", got)+ }+}++// TestResolveComment_ScopedToThread proves the clear never reaches across into a+// sibling thread on the same issue.+func TestResolveComment_ScopedToThread(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ fx := newResolveTestFixture(t)++ resolveCommentHTTP(t, fx.B1) // thread 1 resolution+ resolveCommentHTTP(t, fx.A2) // thread 2 resolution — must NOT touch thread 1+ if !commentResolved(t, fx.B1) {+ t.Fatalf("b1 (thread 1) must stay resolved when a separate thread is resolved")+ }+ if !commentResolved(t, fx.A2) {+ t.Fatalf("a2 (thread 2) should be resolved")+ }++ // Resolving the root of thread 1 overrides the reply resolution (override+ // works in both directions: reply→reply and reply→root).+ resolveCommentHTTP(t, fx.Root1)+ if !commentResolved(t, fx.Root1) {+ t.Fatalf("root1 should be resolved")+ }+ if commentResolved(t, fx.B1) {+ t.Fatalf("b1 should be cleared when root1 becomes the resolution")+ }+ if !commentResolved(t, fx.A2) {+ t.Fatalf("a2 (other thread) must remain resolved throughout")+ }+}++// TestResolveComment_ReResolveIsIdempotent pins the COALESCE idempotency ++// event suppression: re-resolving the current resolution keeps its original+// timestamp and emits no second comment:resolved event.+func TestResolveComment_ReResolveIsIdempotent(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ fx := newResolveTestFixture(t)+ cap := captureCommentEvents(t, fx.IssueID)++ resolveCommentHTTP(t, fx.A1)+ first := commentResolvedAt(t, fx.A1)+ if first == nil {+ t.Fatalf("a1 should be resolved")+ }++ resolveCommentHTTP(t, fx.A1) // re-resolve same comment+ second := commentResolvedAt(t, fx.A1)+ if second == nil || !second.Equal(*first) {+ t.Fatalf("re-resolve must keep the original resolved_at (got %v, want %v)", second, first)+ }+ if got := cap.countFor(protocol.EventCommentResolved, fx.A1); got != 1 {+ t.Fatalf("re-resolve no-op must not emit a second comment:resolved (got %d)", got)+ }+}diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.goindex 2785792c08..d096b601b2 100644--- a/server/pkg/db/generated/comment.sql.go+++ b/server/pkg/db/generated/comment.sql.go@@ -11,6 +11,93 @@ import ("github.com/jackc/pgx/v5/pgtype")+const clearOtherThreadResolutions = `-- name: ClearOtherThreadResolutions :many+WITH RECURSIVE root_of AS (+ -- Walk up from the target to its thread root.+ SELECT c.id, c.parent_id+ FROM comment c+ WHERE c.id = $1 AND c.issue_id = $2 AND c.workspace_id = $3+ UNION ALL+ SELECT p.id, p.parent_id+ FROM comment p+ JOIN root_of r ON p.id = r.parent_id+),+thread_root AS (+ SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1+),+descendants AS (+ -- Expand back down from the root over the whole subtree. Cycle-safe under+ -- the PK constraint (a comment cannot be its own ancestor).+ SELECT c.id+ FROM comment c+ JOIN thread_root tr ON c.id = tr.id+ UNION+ SELECT c.id+ FROM comment c+ JOIN descendants d ON c.parent_id = d.id+ WHERE c.issue_id = $2 AND c.workspace_id = $3+)+UPDATE comment SET+ resolved_at = NULL,+ resolved_by_type = NULL,+ resolved_by_id = NULL,+ updated_at = now()+WHERE comment.id IN (SELECT id FROM descendants)+ AND comment.id <> $1+ AND comment.resolved_at IS NOT NULL+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id+`++type ClearOtherThreadResolutionsParams struct {+ TargetID pgtype.UUID `json:"target_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// Single-resolution invariant: a thread has at most one resolved comment.+// Resolving @target_id makes it the sole resolution, so this clears resolved_at+// on every OTHER currently-resolved comment in the same thread (the root of+// @target_id plus every descendant). The handler runs this in the SAME tx as+// ResolveComment so the replace is atomic — a crash can never leave two+// resolutions or zero. Scope is the thread only (id IN descendants AND+// id <> @target_id), never the whole issue. Returns each cleared row so the+// handler can emit a comment:unresolved event per row; granular realtime+// consumers replace a single comment in place and would otherwise keep+// displaying the stale resolution.+func (q *Queries) ClearOtherThreadResolutions(ctx context.Context, arg ClearOtherThreadResolutionsParams) ([]Comment, error) {+ rows, err := q.db.Query(ctx, clearOtherThreadResolutions, arg.TargetID, arg.IssueID, arg.WorkspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []Comment{}+ for rows.Next() {+ var i Comment+ if err := rows.Scan(+ &i.ID,+ &i.IssueID,+ &i.AuthorType,+ &i.AuthorID,+ &i.Content,+ &i.Type,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.ParentID,+ &i.WorkspaceID,+ &i.ResolvedAt,+ &i.ResolvedByType,+ &i.ResolvedByID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const countComments = `-- name: CountComments :oneSELECT count(*) FROM commentWHERE issue_id = $1 AND workspace_id = $2diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sqlindex 15362cc621..50029814ce 100644--- a/server/pkg/db/queries/comment.sql+++ b/server/pkg/db/queries/comment.sql@@ -381,6 +381,52 @@ UPDATE comment SETWHERE id = $1RETURNING *;+-- name: ClearOtherThreadResolutions :many+-- Single-resolution invariant: a thread has at most one resolved comment.+-- Resolving @target_id makes it the sole resolution, so this clears resolved_at+-- on every OTHER currently-resolved comment in the same thread (the root of+-- @target_id plus every descendant). The handler runs this in the SAME tx as+-- ResolveComment so the replace is atomic — a crash can never leave two+-- resolutions or zero. Scope is the thread only (id IN descendants AND+-- id <> @target_id), never the whole issue. Returns each cleared row so the+-- handler can emit a comment:unresolved event per row; granular realtime+-- consumers replace a single comment in place and would otherwise keep+-- displaying the stale resolution.+WITH RECURSIVE root_of AS (+ -- Walk up from the target to its thread root.+ SELECT c.id, c.parent_id+ FROM comment c+ WHERE c.id = @target_id AND c.issue_id = @issue_id AND c.workspace_id = @workspace_id+ UNION ALL+ SELECT p.id, p.parent_id+ FROM comment p+ JOIN root_of r ON p.id = r.parent_id+),+thread_root AS (+ SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1+),+descendants AS (+ -- Expand back down from the root over the whole subtree. Cycle-safe under+ -- the PK constraint (a comment cannot be its own ancestor).+ SELECT c.id+ FROM comment c+ JOIN thread_root tr ON c.id = tr.id+ UNION+ SELECT c.id+ FROM comment c+ JOIN descendants d ON c.parent_id = d.id+ WHERE c.issue_id = @issue_id AND c.workspace_id = @workspace_id+)+UPDATE comment SET+ resolved_at = NULL,+ resolved_by_type = NULL,+ resolved_by_id = NULL,+ updated_at = now()+WHERE comment.id IN (SELECT id FROM descendants)+ AND comment.id <> @target_id+ AND comment.resolved_at IS NOT NULL+RETURNING *;+-- name: UnresolveComment :one-- Idempotent: a no-op clear (already unresolved) just returns the row.UPDATE comment SET