Skip to content

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

Go

MUL-7282: fix(comments): delete only the selected comment and keep its replies (#8323)

Bohan Jianga9e82c797394
diff --git a/apps/docs/content/docs/comments.ja.mdx b/apps/docs/content/docs/comments.ja.mdx
index 1e8aebdc9c..f61609d73a 100644
--- a/apps/docs/content/docs/comments.ja.mdx
+++ b/apps/docs/content/docs/comments.ja.mdx
@@ -60,7 +60,7 @@ Web と Desktop では、自分を含む誰のコメントでも選択して選
コメントを編集すると、Multica は新しい内容でトリガーを再計算します。編集で追加した @メンションも同様に実行を作成します。保存前に、入力欄の下にトリガープレビューが表示されます。
<Callout type="warning">
-コメントの削除は元に戻せません。トップレベルのコメントを削除すると、その下のすべての返信も削除されます。内容が間違っている場合は編集してください。
+コメントの削除は元に戻せません。削除されるのはそのコメントだけです。返信がある場合、返信はスレッドに残り、元の位置には「このコメントは削除されました」と表示されます。内容が間違っている場合は編集してください。
</Callout>
## 次のステップ
diff --git a/apps/docs/content/docs/comments.ko.mdx b/apps/docs/content/docs/comments.ko.mdx
index f0014a6ce9..ac18e83a91 100644
--- a/apps/docs/content/docs/comments.ko.mdx
+++ b/apps/docs/content/docs/comments.ko.mdx
@@ -60,7 +60,7 @@ Web과 Desktop에서 본인 댓글을 포함한 모든 댓글의 텍스트를
댓글을 수정하면 Multica가 새 내용을 기준으로 트리거를 다시 계산합니다. 수정하면서 새로 추가한 @멘션도 실행을 생성하며, 저장하기 전에 입력란 아래에 트리거 미리보기가 표시됩니다.
<Callout type="warning">
-댓글 삭제는 취소할 수 없습니다. 최상위 댓글을 삭제하면 그 아래의 모든 답글도 함께 삭제됩니다. 내용이 잘못되었다면 수정하세요.
+댓글 삭제는 취소할 수 없습니다. 해당 댓글만 삭제되며, 답글이 있으면 답글은 스레드에 남고 원래 자리에는 "삭제된 댓글입니다"가 표시됩니다. 내용이 잘못되었다면 수정하세요.
</Callout>
## 다음 단계
diff --git a/apps/docs/content/docs/comments.mdx b/apps/docs/content/docs/comments.mdx
index 62ffb0b6d8..fec87bbf50 100644
--- a/apps/docs/content/docs/comments.mdx
+++ b/apps/docs/content/docs/comments.mdx
@@ -60,7 +60,7 @@ Comment authors can edit or delete their own comments; workspace `owner`s and `a
After a comment is edited, Multica recalculates triggers from the new content. @-mentions added during the edit create runs too; the trigger preview shows under the input before you save.
<Callout type="warning">
-Deleting a comment cannot be undone. Deleting a top-level comment deletes every reply under it. If the content is wrong, edit it instead.
+Deleting a comment cannot be undone. Only that comment is deleted: if it has replies, they stay in the thread under a "This comment was deleted" placeholder. If the content is wrong, edit it instead.
</Callout>
## Next steps
diff --git a/apps/docs/content/docs/comments.zh.mdx b/apps/docs/content/docs/comments.zh.mdx
index b10c9e6052..ee778eac63 100644
--- a/apps/docs/content/docs/comments.zh.mdx
+++ b/apps/docs/content/docs/comments.zh.mdx
@@ -60,7 +60,7 @@ import { Callout } from "fumadocs-ui/components/callout";
编辑评论后,Multica 会按新内容重新计算触发。编辑时新增的 @提及同样会创建运行;保存前输入框下方会显示触发预览。
<Callout type="warning">
-删除评论无法撤销。删除顶层评论时,其下所有回复一并删除。内容有误时编辑即可。
+删除评论无法撤销。删除只作用于这一条评论:如果它有回复,回复会保留在讨论中,原位置显示“评论已删除”。内容有误时编辑即可。
</Callout>
## 接下来
diff --git a/apps/mobile/components/issue/comment-card.tsx b/apps/mobile/components/issue/comment-card.tsx
index ccf4b338cf..77cb335a03 100644
--- a/apps/mobile/components/issue/comment-card.tsx
+++ b/apps/mobile/components/issue/comment-card.tsx
@@ -33,6 +33,7 @@ import Animated, {
} from "react-native-reanimated";
import { Ionicons } from "@expo/vector-icons";
import type { Reaction, TimelineEntry } from "@multica/core/types";
+import { isDeletedComment } from "@multica/core/issues/comment-deletion";
import { Text } from "@/components/ui/text";
import { ActorAvatar } from "@/components/ui/actor-avatar";
import { useActorLookup } from "@/data/use-actor-name";
@@ -225,6 +226,8 @@ function ResolvedThreadBar({
const ordered: { type: string | null; id: string | null; name?: string }[] =
[];
for (const e of [entry, ...replies]) {
+ // A deleted comment names no author (mirrors web's useAuthorsLabel).
+ if (isDeletedComment(e)) continue;
const key = `${e.actor_type}:${e.actor_id}`;
if (seen.has(key)) continue;
seen.add(key);
@@ -484,6 +487,17 @@ function CommentBody({
onPressChange?.(entry.id, longPress.isPressed);
}, [longPress.isPressed, entry.id, isSelecting, onPressChange]);
+ if (isDeletedComment(entry)) {
+ // Kept only so the replies to it stay attached (#8296): no author, body
+ // or long-press actions. Mirrors CommentRow's placeholder in
+ // packages/views/issues/components/comment-card.tsx.
+ return (
+ <Text className="text-sm italic text-muted-foreground">
+ This comment was deleted
+ </Text>
+ );
+ }
+
const body = (
<View className="gap-2">
<View className="flex-row items-center gap-2">
diff --git a/apps/mobile/components/issue/comment-context-menu.tsx b/apps/mobile/components/issue/comment-context-menu.tsx
index d3bcd3d0ba..b91937d4a9 100644
--- a/apps/mobile/components/issue/comment-context-menu.tsx
+++ b/apps/mobile/components/issue/comment-context-menu.tsx
@@ -22,6 +22,7 @@ import { ActionSheetIOS, Alert } from "react-native";
import { router } from "expo-router";
import * as Clipboard from "expo-clipboard";
import * as Haptics from "expo-haptics";
+import { useQuery } from "@tanstack/react-query";
import type { Reaction, TimelineEntry } from "@multica/core/types";
import { useAuthStore } from "@/data/auth-store";
import { useWorkspaceStore } from "@/data/workspace-store";
@@ -29,10 +30,12 @@ import { useCommentSelectStore } from "@/data/comment-select-store";
import { useReplyTargetStore } from "@/data/stores/reply-target-store";
import { useActorLookup } from "@/data/use-actor-name";
import {
+ commentDeleteKeepsReplies,
useDeleteComment,
useResolveComment,
useToggleCommentReaction,
} from "@/data/mutations/issues";
+import { appConfigOptions } from "@/data/queries/billing";
import { QUICK_EMOJIS } from "@/lib/quick-emojis";
const QUICK_ROW_SIZE = 5;
@@ -49,6 +52,12 @@ export function useCommentLongPress(
const deleteComment = useDeleteComment(issueId);
const resolveComment = useResolveComment(issueId);
const { getName } = useActorLookup();
+ // Same config cache useDeleteComment reads when it runs, so the copy and
+ // the delete route agree.
+ const { data: keepReplies = false } = useQuery({
+ ...appConfigOptions(),
+ select: commentDeleteKeepsReplies,
+ });
const onLongPress = useCallback(() => {
const isOwn = entry.actor_type === "member" && entry.actor_id === userId;
@@ -177,7 +186,11 @@ export function useCommentLongPress(
case "delete":
Alert.alert(
"Delete comment?",
- "This comment will be permanently deleted. Replies in the thread will also be removed. This cannot be undone.",
+ // Promise kept replies only when the server declares it (#8296);
+ // older servers delete the replies too.
+ keepReplies
+ ? "This comment will be permanently deleted. Any replies to it stay in the thread. This cannot be undone."
+ : "This comment will be permanently deleted. Replies in the thread will also be removed. This cannot be undone.",
[
{ text: "Cancel", style: "cancel" },
{
@@ -201,6 +214,7 @@ export function useCommentLongPress(
deleteComment,
resolveComment,
getName,
+ keepReplies,
]);
return { onLongPress, isPressed };
diff --git a/apps/mobile/data/api.test.ts b/apps/mobile/data/api.test.ts
new file mode 100644
index 0000000000..ba24f37655
--- /dev/null
+++ b/apps/mobile/data/api.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { api } from "./api";
+
+// api.ts refuses to load without a base URL; set it before the import runs.
+vi.hoisted(() => {
+ process.env.EXPO_PUBLIC_API_URL = "https://api.example.test";
+});
+
+// The real store pulls in expo-secure-store; the client only needs the slug.
+vi.mock("@/data/workspace-store", () => ({ getCurrentSlug: () => null }));
+
+describe("api.deleteComment", () => {
+ const fetchMock = vi.fn(async () => new Response(null, { status: 204 }));
+
+ beforeEach(() => {
+ fetchMock.mockClear();
+ vi.stubGlobal("fetch", fetchMock);
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ // #8296: servers that keep a deleted comment's replies also route
+ // /keep-replies; older servers do not, so a keep-replies delete that reaches
+ // one fails instead of deleting the replies too.
+ it.each([
+ [{ keepReplies: true }, "https://api.example.test/api/comments/comment-1/keep-replies"],
+ [{ keepReplies: false }, "https://api.example.test/api/comments/comment-1"],
+ [undefined, "https://api.example.test/api/comments/comment-1"],
+ ])("with %j sends DELETE %s", async (opts, url) => {
+ await api.deleteComment("comment-1", opts);
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock).toHaveBeenCalledWith(url, expect.objectContaining({ method: "DELETE" }));
+ });
+});
diff --git a/apps/mobile/data/api.ts b/apps/mobile/data/api.ts
index 4cbfa35cdd..cc49784332 100644
--- a/apps/mobile/data/api.ts
+++ b/apps/mobile/data/api.ts
@@ -786,9 +786,19 @@ class ApiClient {
}
// DELETE /api/comments/:id — 204 No Content on success; this.fetch
- // already short-circuits 204 → undefined.
- async deleteComment(commentId: string): Promise<void> {
- await this.fetch<void>(`/api/comments/${commentId}`, { method: "DELETE" });
+ // already short-circuits 204 → undefined. `keepReplies` calls the route
+ // only servers that keep a deleted comment's replies expose (#8296): if the
+ // request reaches an older server it fails instead of deleting the replies
+ // too. Pass it only when the server declared
+ // `comment_delete_keep_replies_supported`. Mirrors packages/core/api/client.ts.
+ async deleteComment(
+ commentId: string,
+ opts: { keepReplies?: boolean } = {},
+ ): Promise<void> {
+ const path = opts.keepReplies === true
+ ? `/api/comments/${commentId}/keep-replies`
+ : `/api/comments/${commentId}`;
+ await this.fetch<void>(path, { method: "DELETE" });
}
// POST /api/comments/:id/resolve — marks the thread root resolved; only
diff --git a/apps/mobile/data/mutations/issues.test.ts b/apps/mobile/data/mutations/issues.test.ts
new file mode 100644
index 0000000000..06dba7dadb
--- /dev/null
+++ b/apps/mobile/data/mutations/issues.test.ts
@@ -0,0 +1,121 @@
+import { QueryClient } from "@tanstack/react-query";
+import { EMPTY_APP_CONFIG } from "@multica/core/api/schemas";
+import type { AppConfigResponse } from "@multica/core/api/schemas";
+import type { Issue, TimelineEntry } from "@multica/core/types";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { api } from "@/data/api";
+import { appConfigOptions } from "@/data/queries/billing";
+import { issueKeys } from "@/data/queries/issue-keys";
+import { useDeleteComment } from "./issues";
+
+const state = vi.hoisted(() => ({
+ qc: undefined as unknown as QueryClient,
+}));
+
+vi.mock("@tanstack/react-query", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@tanstack/react-query")>();
+ return {
+ ...actual,
+ useQueryClient: () => state.qc,
+ // Drive the hook's options through a real MutationObserver so the test
+ // runs the same mutate → onSuccess → onSettled lifecycle as the app.
+ useMutation: (
+ options: ConstructorParameters<typeof actual.MutationObserver>[1],
+ ) => {
+ const observer = new actual.MutationObserver(state.qc, options);
+ return { mutateAsync: (variables: unknown) => observer.mutate(variables) };
+ },
+ };
+});
+
+vi.mock("@/data/api", () => ({
+ api: { deleteComment: vi.fn(async () => undefined) },
+}));
+
+vi.mock("@/data/auth-store", () => ({ useAuthStore: vi.fn() }));
+
+vi.mock("@/data/workspace-store", () => ({
+ useWorkspaceStore: (
+ selector: (s: { currentWorkspaceId: string }) => unknown,
+ ) => selector({ currentWorkspaceId: "workspace-1" }),
+}));
+
+const wsId = "workspace-1";
+const issueId = "issue-1";
+const timelineKey = issueKeys.timeline(wsId, issueId);
+
+function comment(id: string, parentId: string | null = null): TimelineEntry {
+ return {
+ type: "comment",
+ id,
+ actor_type: "member",
+ actor_id: "user-1",
+ created_at: "2026-09-11T07:00:00Z",
+ content: `content of ${id}`,
+ parent_id: parentId,
+ };
+}
+
+// A thread whose root has a reply chain, plus an unrelated comment.
+function seedThread() {
+ state.qc.setQueryData<TimelineEntry[]>(timelineKey, [
+ comment("comment-1"),
+ comment("reply-1", "comment-1"),
+ comment("reply-2", "reply-1"),
+ comment("comment-2"),
+ ]);
+}
+
+describe("useDeleteComment", () => {
+ beforeEach(() => {
+ state.qc = new QueryClient();
+ vi.mocked(api.deleteComment).mockClear();
+ });
+
+ it("uses the keep-replies route and tombstones a comment with replies when the server declares it", async () => {
+ state.qc.setQueryData(appConfigOptions().queryKey, {
+ ...EMPTY_APP_CONFIG,
+ comment_delete_keep_replies_supported: true,
+ });
+ seedThread();
+
+ await useDeleteComment(issueId).mutateAsync("comment-1");
+
+ expect(api.deleteComment).toHaveBeenCalledWith("comment-1", { keepReplies: true });
+ const timeline = state.qc.getQueryData<TimelineEntry[]>(timelineKey);
+ expect(timeline?.map((e) => e.id)).toEqual(["comment-1", "reply-1", "reply-2", "comment-2"]);
+ expect(timeline?.[0]).toMatchObject({ content: "" });
+ expect(timeline?.[0]?.deleted_at).toEqual(expect.any(String));
+ });
+
+ it.each<[string, AppConfigResponse | undefined]>([
+ ["has not loaded", undefined],
+ ["omits the capability", { cdn_domain: "", allow_signup: true }],
+ ["declares it false", { ...EMPTY_APP_CONFIG, comment_delete_keep_replies_supported: false }],
+ ])("uses the legacy route and drops every cached reply when the config %s", async (_label, config) => {
+ if (config) state.qc.setQueryData(appConfigOptions().queryKey, config);
+ seedThread();
+
+ await useDeleteComment(issueId).mutateAsync("comment-1");
+
+ expect(api.deleteComment).toHaveBeenCalledWith("comment-1", { keepReplies: false });
+ expect(state.qc.getQueryData<TimelineEntry[]>(timelineKey)?.map((e) => e.id)).toEqual([
+ "comment-2",
+ ]);
+ });
+
+ it("refetches the owner issue projections because the 204 carries no issue_revision", async () => {
+ const issue = { id: issueId, revision: 3 } as Issue;
+ const myKey = issueKeys.myList(wsId, "assigned", { assignee_id: "user-1" });
+ state.qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), issue);
+ state.qc.setQueryData<Issue[]>(myKey, [issue]);
+ state.qc.setQueryData<Issue[]>(issueKeys.list(wsId), [issue]);
+
+ await useDeleteComment(issueId).mutateAsync("comment-1");
+
+ for (const key of [issueKeys.detail(wsId, issueId), myKey, issueKeys.list(wsId)]) {
+ expect(state.qc.getQueryState(key)?.isInvalidated).toBe(true);
+ }
+ });
+});
diff --git a/apps/mobile/data/mutations/issues.ts b/apps/mobile/data/mutations/issues.ts
index 4c06efbc56..7b9dd05bc2 100644
--- a/apps/mobile/data/mutations/issues.ts
+++ b/apps/mobile/data/mutations/issues.ts
@@ -25,8 +25,14 @@ import type {
TimelineEntry,
UpdateIssueRequest,
} from "@multica/core/types";
+import type { AppConfigResponse } from "@multica/core/api/schemas";
+import {
+ applyCommentDeletion,
+ removeCommentSubtree,
+} from "@multica/core/issues/comment-deletion";
import { api } from "@/data/api";
import { isIssueStatusCategory } from "@/lib/issue-status";
+import { appConfigOptions } from "@/data/queries/billing";
import { issueKeys } from "@/data/queries/issues";
import { inboxKeys } from "@/data/queries/inbox";
import { useAuthStore } from "@/data/auth-store";
@@ -38,6 +44,7 @@ import {
} from "@/data/revision";
import {
advanceCommentRevision,
+ invalidateIssueOwnerProjections,
onIssueAuxiliaryRevision,
reconcileIssueFullSnapshotRevision,
commentToTimelineEntry,
@@ -313,36 +320,52 @@ export function useEditComment(issueId: string) {
}
/**
- * Delete a comment. Strips the matching TimelineEntry (and any replies
- * with parent_id === commentId) from the timeline cache optimistically.
- * Backend cascades reply deletion server-side; we mirror the cascade
- * locally so the optimistic patch leaves no orphans on screen.
+ * Whether the server keeps a deleted comment's replies (#8296). Older servers
+ * omit `comment_delete_keep_replies_supported` and delete the replies too, so
+ * anything but an explicit `true` — including a config that has not loaded —
+ * fails closed. Shared by the confirm copy and `useDeleteComment`.
+ */
+export function commentDeleteKeepsReplies(
+ config: AppConfigResponse | undefined,
+): boolean {
+ return config?.comment_delete_keep_replies_supported === true;
+}
+
+/**
+ * Delete a comment. On a server that declares
+ * `comment_delete_keep_replies_supported`, only that comment goes (#8296): one
+ * with replies stays as a tombstone so they keep their parent. Older servers
+ * delete the replies too. Not optimistic — which outcome applies depends on
+ * replies only the server sees for certain. Once it confirms, mirror its
+ * outcome with the same pure helpers web uses (`useDeleteComment` in
+ * packages/core/issues/mutations.ts); realtime events and the settle refetch
+ * reconcile the rest.
*/
export function useDeleteComment(issueId: string) {
const qc = useQueryClient();
const wsId = useWorkspaceStore((s) => s.currentWorkspaceId);
return useMutation({
- mutationFn: (commentId: string) => api.deleteComment(commentId),
- onMutate: async (commentId) => {
- const key = issueKeys.timeline(wsId, issueId);
- await qc.cancelQueries({ queryKey: key });
- const prev = qc.getQueryData<TimelineEntry[]>(key);
- qc.setQueryData<TimelineEntry[]>(key, (old) =>
- old?.filter(
- (entry) =>
- !(
- entry.type === "comment" &&
- (entry.id === commentId || entry.parent_id === commentId)
- ),
- ),
+ // The capability is read when the delete runs, from the same config cache
+ // the confirm copy reads, so the route matches what the user was told.
+ mutationFn: async (commentId: string) => {
+ const keepReplies = commentDeleteKeepsReplies(
+ qc.getQueryData(appConfigOptions().queryKey),
);
- return { prev, key };
+ await api.deleteComment(commentId, { keepReplies });
+ return keepReplies;
},
- onError: (_err, _vars, ctx) => {
- if (ctx?.prev !== undefined && ctx.key) {
- qc.setQueryData(ctx.key, ctx.prev);
- }
+ onSuccess: (keptReplies, commentId) => {
+ qc.setQueryData<TimelineEntry[]>(issueKeys.timeline(wsId, issueId), (old) => {
+ if (!old) return old;
+ return keptReplies
+ ? applyCommentDeletion(old, commentId, new Date().toISOString())
+ : removeCommentSubtree(old, commentId);
+ });
+ // The endpoint remains 204 for compatibility, so the local caller has
+ // no body carrying issue_revision. The realtime event narrows this
+ // with its revision when connected; this is the no-WS safety net.
+ if (wsId) invalidateIssueOwnerProjections(qc, wsId, issueId);
},
onSettled: () => {
qc.invalidateQueries({ queryKey: issueKeys.timeline(wsId, issueId) });
diff --git a/apps/mobile/data/realtime/issue-ws-updaters.test.ts b/apps/mobile/data/realtime/issue-ws-updaters.test.ts
index 11aa443566..167eb34494 100644
--- a/apps/mobile/data/realtime/issue-ws-updaters.test.ts
+++ b/apps/mobile/data/realtime/issue-ws-updaters.test.ts
@@ -6,8 +6,10 @@ import { issueKeys } from "@/data/queries/issue-keys";
import {
addCommentReaction,
addIssueReaction,
+ commentToTimelineEntry,
onIssueAuxiliaryRevision,
invalidateIssueAfterReconnect,
+ invalidateIssueOwnerProjections,
patchIssueDetail,
patchIssueLabels,
removeIssueReaction,
@@ -33,6 +35,31 @@ describe("invalidateIssueAfterReconnect", () => {
});
});
+describe("invalidateIssueOwnerProjections", () => {
+ it("refetches every loaded projection holding the issue, whatever its revision", () => {
+ const qc = new QueryClient();
+ const wsId = "workspace-1";
+ const issueId = "issue-1";
+ const owner = { id: issueId, revision: 9 } as Issue;
+ const other = { id: "issue-2", revision: 1 } as Issue;
+ const withOwner = issueKeys.myList(wsId, "assigned", { assignee_id: "user-1" });
+ const withoutOwner = issueKeys.myList(wsId, "created", { creator_id: "user-1" });
+ qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), owner);
+ qc.setQueryData<Issue[]>(withOwner, [owner]);
+ qc.setQueryData<Issue[]>(withoutOwner, [other]);
+ qc.setQueryData<Issue[]>(issueKeys.list(wsId), [other, owner]);
+
+ invalidateIssueOwnerProjections(qc, wsId, issueId);
+
+ const isInvalidated = (key: readonly unknown[]) =>
+ qc.getQueryState(key)?.isInvalidated;
+ expect(isInvalidated(issueKeys.detail(wsId, issueId))).toBe(true);
+ expect(isInvalidated(withOwner)).toBe(true);
+ expect(isInvalidated(issueKeys.list(wsId))).toBe(true);
+ expect(isInvalidated(withoutOwner)).toBe(false);
+ });
+});
+
describe("mobile issue revision gates", () => {
const wsId = "workspace-1";
const issueId = "issue-1";
@@ -290,3 +317,30 @@ describe("mobile issue revision gates", () => {
expect(qc.getQueryData<Issue>(key)?.reactions).toEqual([]);
});
});
+
+// #8296: a delete tombstones a comment that has replies and announces it as
+// comment:updated. The snapshot must keep deleted_at, or the card would render
+// an empty comment instead of the placeholder.
+describe("commentToTimelineEntry", () => {
+ it("carries the tombstone marker through a comment snapshot", () => {
+ const entry = commentToTimelineEntry({
+ id: "comment-1",
+ issue_id: "issue-1",
+ author_type: "member",
+ author_id: "user-1",
+ content: "",
+ type: "comment",
+ parent_id: null,
+ reactions: [],
+ attachments: [],
+ created_at: "2026-09-11T07:00:00Z",
+ updated_at: "2026-09-11T08:00:00Z",
+ resolved_at: null,
+ resolved_by_type: null,
+ resolved_by_id: null,
+ deleted_at: "2026-09-11T08:00:00Z",
+ });
+
+ expect(entry.deleted_at).toBe("2026-09-11T08:00:00Z");
+ });
+});
diff --git a/apps/mobile/data/realtime/issue-ws-updaters.ts b/apps/mobile/data/realtime/issue-ws-updaters.ts
index c01cce6006..60ae28f4ef 100644
--- a/apps/mobile/data/realtime/issue-ws-updaters.ts
+++ b/apps/mobile/data/realtime/issue-ws-updaters.ts
@@ -154,34 +154,64 @@ export function onIssueAuxiliaryRevision(
invalidateStaleIssueOwnerProjections(qc, wsId, issueId, revision);
}
-function invalidateStaleIssueOwnerProjections(
+function invalidateIssueOwnerProjectionsWhere(
qc: QueryClient,
wsId: string,
issueId: string,
- revision: number,
+ shouldInvalidate: (issue: Issue | undefined) => boolean,
) {
- const isStale = (issue: Issue | undefined) =>
- issue !== undefined &&
- (issue.revision === undefined || issue.revision < revision);
const detailKey = issueKeys.detail(wsId, issueId);
- if (isStale(qc.getQueryData<Issue>(detailKey))) {
+ if (shouldInvalidate(qc.getQueryData<Issue>(detailKey))) {
qc.invalidateQueries({ queryKey: detailKey, exact: true });
}
for (const [key, data] of qc.getQueriesData<Issue[]>({
queryKey: issueKeys.myAll(wsId),
})) {
- if (data?.some((issue) => issue.id === issueId && isStale(issue))) {
+ if (data?.some((issue) => issue.id === issueId && shouldInvalidate(issue))) {
qc.invalidateQueries({ queryKey: key, exact: true });
}
}
const listKey = issueKeys.list(wsId);
if (qc.getQueryData<Issue[]>(listKey)?.some(
- (issue) => issue.id === issueId && isStale(issue),
+ (issue) => issue.id === issueId && shouldInvalidate(issue),
)) {
qc.invalidateQueries({ queryKey: listKey, exact: true });
}
}
+function invalidateStaleIssueOwnerProjections(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ revision: number,
+) {
+ invalidateIssueOwnerProjectionsWhere(
+ qc,
+ wsId,
+ issueId,
+ (issue) =>
+ issue !== undefined &&
+ (issue.revision === undefined || issue.revision < revision),
+ );
+}
+
+/** Fallback when an owner change arrives without its revision (the 204
+ * comment delete response, or an older server's comment event). Mirrors
+ * web's `invalidateIssueOwnerProjections`: only loaded projections that
+ * contain the issue are refetched. */
+export function invalidateIssueOwnerProjections(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+) {
+ invalidateIssueOwnerProjectionsWhere(
+ qc,
+ wsId,
+ issueId,
+ (issue) => issue !== undefined,
+ );
+}
+
export function clearIssueDetail(
qc: QueryClient,
wsId: string,
@@ -303,12 +333,14 @@ export function removeTimelineEntry(
}
/**
- * Cascade-delete a comment and every descendant reply (reply-to-reply
- * chains included). Mirrors the server's cascade in `comment.go:DeleteComment`
- * and web's `comment:deleted` handler at
- * `packages/views/issues/hooks/use-issue-timeline.ts:164-194`.
+ * Remove a deleted comment and every cached descendant reply (reply-to-reply
+ * chains included). Mirrors web's `comment:deleted` handler in
+ * `packages/views/issues/hooks/use-issue-timeline.ts`. The server never
+ * removes a comment that still has replies — it tombstones it and sends
+ * comment:updated (#8296) — so a cached descendant of a removed comment is
+ * stale: older servers cascaded the delete to every reply.
*
- * Without this, removing only the root entry leaves the replies as
+ * Without the sweep, removing only the root entry would leave the replies as
* "orphans" — `buildTimelineRows` then promotes them to top-level rows
* (its orphan-rescue branch), so the user would see ghost replies after a
* thread delete on another client. Same-N rule violation.
@@ -637,5 +669,8 @@ export function commentToTimelineEntry(comment: Comment): TimelineEntry {
resolved_by_id: comment.resolved_by_id,
source_task_id: comment.source_task_id,
revision: comment.revision,
+ // A delete tombstones a comment that has replies and announces it as
+ // comment:updated; dropping this would render it as an empty comment.
+ deleted_at: comment.deleted_at,
};
}
diff --git a/apps/mobile/data/realtime/use-issue-realtime.test.ts b/apps/mobile/data/realtime/use-issue-realtime.test.ts
new file mode 100644
index 0000000000..a1db6336b6
--- /dev/null
+++ b/apps/mobile/data/realtime/use-issue-realtime.test.ts
@@ -0,0 +1,129 @@
+import { QueryClient } from "@tanstack/react-query";
+import type {
+ CommentDeletedPayload,
+ CommentUpdatedPayload,
+ Issue,
+} from "@multica/core/types";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { issueKeys } from "@/data/queries/issue-keys";
+import { useIssueRealtime } from "./use-issue-realtime";
+
+type EventHandler = (payload: unknown) => void;
+
+interface MockWS {
+ on: ReturnType<typeof vi.fn>;
+ onReconnect: ReturnType<typeof vi.fn>;
+}
+
+type SubscriptionSetup = (ws: MockWS, wsId: string) => (() => void)[];
+
+const state = vi.hoisted(() => ({
+ qc: undefined as unknown as QueryClient,
+ subscriptionSetups: [] as SubscriptionSetup[],
+}));
+
+vi.mock("@tanstack/react-query", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),
+ useQueryClient: () => state.qc,
+}));
+
+vi.mock("@/lib/use-ws-subscriptions", () => ({
+ useWSSubscriptions: (setup: SubscriptionSetup) => {
+ state.subscriptionSetups.push(setup);
+ },
+}));
+
+const wsId = "workspace-1";
+const issueId = "issue-1";
+const detailKey = issueKeys.detail(wsId, issueId);
+
+// Runs the setup useIssueRealtime registered and returns an emitter for the
+// events it subscribed to.
+function connect() {
+ expect(state.subscriptionSetups).toHaveLength(1);
+ const handlers = new Map<string, EventHandler>();
+ const ws: MockWS = {
+ on: vi.fn((event: string, handler: EventHandler) => {
+ handlers.set(event, handler);
+ return () => {};
+ }),
+ onReconnect: vi.fn(() => () => {}),
+ };
+ state.subscriptionSetups[0](ws, wsId);
+ return (event: string, payload: unknown) => {
+ const handler = handlers.get(event);
+ if (!handler) throw new Error(`no handler for ${event}`);
+ handler(payload);
+ };
+}
+
+function deletedPayload(issueRevision?: number): CommentDeletedPayload {
+ return { comment_id: "comment-1", issue_id: issueId, issue_revision: issueRevision };
+}
+
+// #8296: deleting a comment that has replies tombstones it via comment:updated.
+function tombstonePayload(issueRevision?: number): CommentUpdatedPayload {
+ return {
+ comment: {
+ id: "comment-1",
+ issue_id: issueId,
+ author_type: "member",
+ author_id: "user-1",
+ content: "",
+ type: "comment",
+ parent_id: null,
+ reactions: [],
+ attachments: [],
+ created_at: "2026-09-11T07:00:00Z",
+ updated_at: "2026-09-11T08:00:00Z",
+ revision: 2,
+ resolved_at: null,
+ resolved_by_type: null,
+ resolved_by_id: null,
+ deleted_at: "2026-09-11T08:00:00Z",
+ },
+ issue_revision: issueRevision,
+ };
+}
+
+describe("useIssueRealtime owner issue revision on comment deletes", () => {
+ beforeEach(() => {
+ state.qc = new QueryClient();
+ state.subscriptionSetups.length = 0;
+ });
+
+ it.each([
+ ["comment:deleted", deletedPayload],
+ ["comment:updated", tombstonePayload],
+ ] as const)("%s with issue_revision refetches only an older cached issue", (event, payload) => {
+ state.qc.setQueryData<Issue>(detailKey, { id: issueId, revision: 5 } as Issue);
+ useIssueRealtime(issueId);
+ const emit = connect();
+
+ emit(event, payload(5));
+ expect(state.qc.getQueryState(detailKey)?.isInvalidated).toBe(false);
+
+ emit(event, payload(6));
+ expect(state.qc.getQueryState(detailKey)?.isInvalidated).toBe(true);
+ });
+
+ it.each([
+ ["comment:deleted", deletedPayload],
+ ["comment:updated", tombstonePayload],
+ ] as const)("%s without issue_revision refetches every loaded owner projection", (event, payload) => {
+ const issue = { id: issueId, revision: 7 } as Issue;
+ const myKey = issueKeys.myList(wsId, "assigned", { assignee_id: "user-1" });
+ state.qc.setQueryData<Issue>(detailKey, issue);
+ state.qc.setQueryData<Issue[]>(myKey, [issue]);
+ state.qc.setQueryData<Issue[]>(issueKeys.list(wsId), [issue]);
+ useIssueRealtime(issueId);
+ const emit = connect();
+
+ emit(event, payload());
+
+ for (const key of [detailKey, myKey, issueKeys.list(wsId)]) {
+ expect(state.qc.getQueryState(key)?.isInvalidated).toBe(true);
+ }
+ });
+});
diff --git a/apps/mobile/data/realtime/use-issue-realtime.ts b/apps/mobile/data/realtime/use-issue-realtime.ts
index fb857cdc68..0e9ea333c7 100644
--- a/apps/mobile/data/realtime/use-issue-realtime.ts
+++ b/apps/mobile/data/realtime/use-issue-realtime.ts
@@ -5,7 +5,8 @@
* Handles:
* - issue:updated / issue:deleted / issue_labels:changed → detail cache
* - issue_attachments:changed → attachment cache
- * - comment:created / comment:updated / comment:deleted → timeline
+ * - comment:created / comment:updated / comment:deleted → timeline +
+ * owner issue revision (detail / list projections)
* - activity:created → timeline
* - reaction:added / reaction:removed → comment reactions on timeline
* - issue_reaction:added / issue_reaction:removed → issue-level reactions on detail
@@ -43,6 +44,7 @@ import {
clearIssueDetail,
commentToTimelineEntry,
invalidateIssueAfterReconnect,
+ invalidateIssueOwnerProjections,
patchIssueDetail,
patchIssueLabels,
patchIssuesList,
@@ -141,6 +143,14 @@ export function useIssueRealtime(
if (payload.comment.issue_id !== issueId) return;
const entry = commentToTimelineEntry(payload.comment);
replaceCommentTimelineEntry(qc, wsId, issueId, entry);
+ // Edits and tombstoning deletes can advance the owner issue
+ // (revision, last_activity_at). Mirrors web's comment handlers: apply
+ // issue_revision when present, otherwise refetch the owner projections.
+ if (payload.issue_revision) {
+ onIssueAuxiliaryRevision(qc, wsId, issueId, payload.issue_revision);
+ } else {
+ invalidateIssueOwnerProjections(qc, wsId, issueId);
+ }
}),
// Resolve / unresolve broadcast from any client. Payload carries the
// full Comment with the new resolved_at/resolved_by_* fields, so we
@@ -160,11 +170,16 @@ export function useIssueRealtime(
}),
ws.on("comment:deleted", (payload) => {
if (payload.issue_id !== issueId) return;
- // Cascade: descendant replies must come out alongside the parent,
- // otherwise buildTimelineRows promotes them to top-level rows and
- // the user sees ghost replies after another client deletes the
- // thread. Server already cascades; this mirrors it in the cache.
+ // A comment with replies is tombstoned (comment:updated), never
+ // removed, so any cached reply of a removed comment is stale (older
+ // servers cascaded the delete). Sweep them so buildTimelineRows
+ // does not promote them to ghost top-level rows.
removeCommentCascade(qc, wsId, issueId, payload.comment_id);
+ if (payload.issue_revision) {
+ onIssueAuxiliaryRevision(qc, wsId, issueId, payload.issue_revision);
+ } else {
+ invalidateIssueOwnerProjections(qc, wsId, issueId);
+ }
}),
ws.on("activity:created", (payload) => {
if (payload.issue_id !== issueId) return;
diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.ts
index 74be0341e4..18aaddb1f9 100644
--- a/apps/mobile/data/schemas.ts
+++ b/apps/mobile/data/schemas.ts
@@ -92,6 +92,8 @@ export const CommentSchema = z.object({
resolved_by_type: z.string().nullable().default(null),
resolved_by_id: z.string().nullable().default(null),
source_task_id: z.string().nullable().optional(),
+ // Tombstone marker (#8296); a malformed value reads as a live comment.
+ deleted_at: z.string().nullable().optional().catch(undefined),
}).loose() as unknown as z.ZodType<Comment>;
export const EMPTY_COMMENT: Comment = {
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index aaf477b64f..0cece5f5da 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -1361,8 +1361,17 @@ export class ApiClient {
});
}
- async deleteComment(commentId: string): Promise<void> {
- await this.fetch(`/api/comments/${commentId}`, { method: "DELETE" });
+ /**
+ * `keepReplies` calls the route only servers that keep a deleted comment's
+ * replies expose (#8296): if the request reaches an older server it fails
+ * instead of deleting the replies too. Pass it only when the server declared
+ * `comment_delete_keep_replies_supported`.
+ */
+ async deleteComment(commentId: string, opts: { keepReplies?: boolean } = {}): Promise<void> {
+ const path = opts.keepReplies === true
+ ? `/api/comments/${commentId}/keep-replies`
+ : `/api/comments/${commentId}`;
+ await this.fetch(path, { method: "DELETE" });
}
async resolveComment(commentId: string): Promise<Comment> {
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index c797b91f5a..abea4dbc80 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -577,6 +577,39 @@ describe("TimelineEntriesSchema", () => {
"https://profiles.example.com/former.png",
);
});
+
+ it("preserves the deleted-comment tombstone marker", () => {
+ const parsed = TimelineEntriesSchema.parse([
+ {
+ type: "comment",
+ id: "comment-1",
+ actor_type: "member",
+ actor_id: "user-1",
+ created_at: "2026-01-01T00:00:00Z",
+ content: "",
+ deleted_at: "2026-01-02T00:00:00Z",
+ },
+ ]);
+
+ expect(parsed[0]?.deleted_at).toBe("2026-01-02T00:00:00Z");
+ });
+
+ it("reads a malformed tombstone marker as a live comment instead of failing the timeline", () => {
+ const parsed = TimelineEntriesSchema.parse([
+ {
+ type: "comment",
+ id: "comment-1",
+ actor_type: "member",
+ actor_id: "user-1",
+ created_at: "2026-01-01T00:00:00Z",
+ content: "still here",
+ deleted_at: 42,
+ },
+ ]);
+
+ expect(parsed).toHaveLength(1);
+ expect(parsed[0]?.deleted_at).toBeUndefined();
+ });
});
describe("AgentTaskListSchema", () => {
@@ -1187,6 +1220,23 @@ describe("dashboard + runtime usage schema drift", () => {
// it does not reject the mode either — it drops execution_mode and answers 201,
// leaving the task to run in the user's working copy (#7113). So the absent
// case has to parse as false, not as "unknown, probably fine".
+// An older server deletes a comment's replies with it and omits this field,
+// so absent or malformed must parse as false: the client then promises nothing
+// about replies and keeps the legacy delete route (#8296).
+describe("AppConfigSchema comment_delete_keep_replies_supported drift", () => {
+ it.each([
+ [undefined, false],
+ ["yes", false],
+ [true, true],
+ ])("%j parses as %s", (value, expected) => {
+ const parsed = AppConfigSchema.parse({
+ cdn_domain: "cdn.example.com",
+ comment_delete_keep_replies_supported: value,
+ });
+ expect(parsed.comment_delete_keep_replies_supported).toBe(expected);
+ });
+});
+
describe("AppConfigSchema local_worktree_supported drift", () => {
it("defaults to false when the server predates the signal", () => {
const parsed = AppConfigSchema.parse({ cdn_domain: "cdn.example.com" });
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 84a6170677..9db080fdd0 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -753,6 +753,10 @@ export interface AppConfigResponse {
/** Whether agent create/update persists `conversation_starters`. Older servers
* silently ignored the unknown field, so absent must be treated as false. */
agent_conversation_starters_supported?: boolean;
+ /** Whether deleting a comment keeps its replies and the server routes
+ * DELETE /api/comments/{id}/keep-replies. Older servers deleted the replies
+ * too, so absent must be treated as false (#8296). */
+ comment_delete_keep_replies_supported?: boolean;
server_version?: string;
}
@@ -908,6 +912,9 @@ const TimelineEntrySchema = z.object({
reactions: z.array(ReactionSchema).optional(),
attachments: z.array(AttachmentSchema).optional(),
source_task_id: z.string().nullable().optional(),
+ // Tombstone marker (#8296). Lenient: a malformed value reads as a live
+ // comment instead of failing the whole timeline.
+ deleted_at: z.string().nullable().optional().catch(undefined),
coalesced_count: z.number().optional(),
}).loose();
@@ -952,6 +959,7 @@ export const AppConfigSchema = z.object({
feature_flags: FeatureFlagsSchema,
local_worktree_supported: BooleanWithDefaultSchema(false),
agent_conversation_starters_supported: BooleanWithDefaultSchema(false),
+ comment_delete_keep_replies_supported: BooleanWithDefaultSchema(false),
server_version: OptionalStringSchema,
}).loose();
@@ -969,6 +977,8 @@ export const EMPTY_APP_CONFIG: AppConfigResponse = {
local_worktree_supported: false,
// Fail closed: old servers returned success while dropping the field.
agent_conversation_starters_supported: false,
+ // Fail closed: old servers delete a comment's replies with it.
+ comment_delete_keep_replies_supported: false,
feature_flags: {},
};
@@ -1010,6 +1020,7 @@ export const CommentSchema = z.object({
source_task_id: z.string().nullable().optional(),
// Set only on comments a quick action produced (MUL-5465). Server-only.
quick_action_id: z.string().nullable().optional(),
+ deleted_at: z.string().nullable().optional().catch(undefined),
}).loose();
export const CommentsListSchema = z.array(CommentSchema);
@@ -1131,6 +1142,7 @@ const SourceContextCommentSnapshotSchema = z.object({
updated_at: z.string(),
revision: z.number(),
attachments: SourceContextAttachmentsSchema,
+ deleted: z.boolean().optional().catch(undefined),
}).loose();
export const SourceContextSnapshotSchema = z.object({
diff --git a/packages/core/config/index.ts b/packages/core/config/index.ts
index 64ba83afbe..43ea146172 100644
--- a/packages/core/config/index.ts
+++ b/packages/core/config/index.ts
@@ -36,6 +36,10 @@ interface ConfigState {
// Older handlers accepted the unknown field and returned success while
// dropping it, so absent must fail closed.
agentConversationStartersSupported: boolean;
+ // Whether deleting a comment keeps its replies (#8296). Older servers
+ // deleted the replies too, so absent must fail closed: the client then
+ // promises nothing about replies and uses the legacy delete route.
+ commentDeleteKeepRepliesSupported: boolean;
setCdnConfig: (config: { cdnDomain: string; cdnSigned?: boolean }) => void;
setAuthConfig: (config: {
allowSignup: boolean;
@@ -51,6 +55,7 @@ interface ConfigState {
setServerVersion: (version?: string) => void;
setLocalWorktreeSupported: (supported?: boolean) => void;
setAgentConversationStartersSupported: (supported?: boolean) => void;
+ setCommentDeleteKeepRepliesSupported: (supported?: boolean) => void;
}
export const configStore = createStore<ConfigState>((set) => ({
@@ -66,6 +71,7 @@ export const configStore = createStore<ConfigState>((set) => ({
serverVersion: "",
localWorktreeSupported: false,
agentConversationStartersSupported: false,
+ commentDeleteKeepRepliesSupported: false,
setCdnConfig: ({ cdnDomain, cdnSigned = false }) => set({ cdnDomain, cdnSigned }),
setAuthConfig: ({
allowSignup,
@@ -81,6 +87,8 @@ export const configStore = createStore<ConfigState>((set) => ({
set({ localWorktreeSupported: supported === true }),
setAgentConversationStartersSupported: (supported = false) =>
set({ agentConversationStartersSupported: supported === true }),
+ setCommentDeleteKeepRepliesSupported: (supported = false) =>
+ set({ commentDeleteKeepRepliesSupported: supported === true }),
}));
export function useConfigStore(): ConfigState;
diff --git a/packages/core/issues/comment-deletion.test.ts b/packages/core/issues/comment-deletion.test.ts
new file mode 100644
index 0000000000..a7ff4a06af
--- /dev/null
+++ b/packages/core/issues/comment-deletion.test.ts
@@ -0,0 +1,97 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { TimelineEntry } from "../types";
+import { applyCommentDeletion, isDeletedComment, removeCommentSubtree } from "./comment-deletion";
+
+const DELETED_AT = "2026-09-11T08:00:00Z";
+
+function comment(id: string, parentId: string | null, extra: Partial<TimelineEntry> = {}): TimelineEntry {
+ return {
+ type: "comment",
+ id,
+ actor_type: "member",
+ actor_id: "user-1",
+ content: `body ${id}`,
+ parent_id: parentId,
+ comment_type: "comment",
+ reactions: [],
+ attachments: [],
+ created_at: "2026-09-11T07:00:00Z",
+ updated_at: "2026-09-11T07:00:00Z",
+ ...extra,
+ };
+}
+
+const ids = (entries: TimelineEntry[]) => entries.map((e) => e.id);
+
+describe("isDeletedComment", () => {
+ it.each([
+ [DELETED_AT, true],
+ ["", false],
+ [null, false],
+ [undefined, false],
+ ])("deleted_at %j → %s", (deletedAt, expected) => {
+ expect(isDeletedComment({ deleted_at: deletedAt })).toBe(expected);
+ });
+});
+
+describe("applyCommentDeletion", () => {
+ it("tombstones a comment that has replies and keeps every reply", () => {
+ // A → B → C, plus A → D.
+ const timeline = [
+ comment("a", null),
+ comment("b", "a", {
+ reactions: [{ id: "r", comment_id: "b", actor_type: "member", actor_id: "u", emoji: "👍", created_at: DELETED_AT }],
+ resolved_at: DELETED_AT,
+ resolved_by_type: "member",
+ resolved_by_id: "u",
+ }),
+ comment("c", "b"),
+ comment("d", "a"),
+ ];
+
+ const next = applyCommentDeletion(timeline, "b", DELETED_AT);
+
+ expect(ids(next)).toEqual(["a", "b", "c", "d"]);
+ expect(next[1]).toMatchObject({
+ content: "",
+ reactions: [],
+ attachments: [],
+ resolved_at: null,
+ deleted_at: DELETED_AT,
+ });
+ expect(next[2]).toBe(timeline[2]);
+ });
+
+ it("removes a comment without replies and leaves a live parent alone", () => {
+ const timeline = [comment("a", null), comment("b", "a")];
+ expect(applyCommentDeletion(timeline, "b", DELETED_AT)).toEqual([timeline[0]]);
+ });
+
+ it("prunes every tombstone ancestor left without replies", () => {
+ const timeline = [
+ comment("a", null, { deleted_at: DELETED_AT, content: "" }),
+ comment("b", "a", { deleted_at: DELETED_AT, content: "" }),
+ comment("c", "b"),
+ comment("other", null),
+ ];
+ expect(ids(applyCommentDeletion(timeline, "c", DELETED_AT))).toEqual(["other"]);
+ });
+
+ it("stops at a tombstone that still holds another reply", () => {
+ const timeline = [
+ comment("a", null, { deleted_at: DELETED_AT, content: "" }),
+ comment("b", "a", { deleted_at: DELETED_AT, content: "" }),
+ comment("c", "b"),
+ comment("d", "a"),
+ ];
+ expect(ids(applyCommentDeletion(timeline, "c", DELETED_AT))).toEqual(["a", "d"]);
+ });
+});
+
+describe("removeCommentSubtree", () => {
+ it("removes the comment and every descendant, and nothing else", () => {
+ const timeline = [comment("a", null), comment("b", "a"), comment("c", "b"), comment("d", null)];
+ expect(ids(removeCommentSubtree(timeline, "a"))).toEqual(["d"]);
+ });
+});
diff --git a/packages/core/issues/comment-deletion.ts b/packages/core/issues/comment-deletion.ts
new file mode 100644
index 0000000000..58b9eeb98f
--- /dev/null
+++ b/packages/core/issues/comment-deletion.ts
@@ -0,0 +1,78 @@
+import type { TimelineEntry } from "@multica/core/types";
+
+/**
+ * True for a comment deleted while it still had replies (#8296). The server
+ * keeps its row as a tombstone — empty content, no attachments, reactions or
+ * resolution — so every reply keeps its direct parent. Clients render a
+ * placeholder in its place and offer no actions on it.
+ */
+export function isDeletedComment(entry: { deleted_at?: string | null }): boolean {
+ return typeof entry.deleted_at === "string" && entry.deleted_at !== "";
+}
+
+function hasReplies(entries: readonly TimelineEntry[], commentId: string): boolean {
+ return entries.some((e) => e.type === "comment" && e.parent_id === commentId);
+}
+
+/**
+ * Removes a comment and every cached descendant: what a server from before
+ * #8296 does on delete, and the only safe reading of a removal event, since a
+ * newer server never removes a comment that still has replies.
+ */
+export function removeCommentSubtree(entries: TimelineEntry[], commentId: string): TimelineEntry[] {
+ const removed = new Set([commentId]);
+ let changed = true;
+ while (changed) {
+ changed = false;
+ for (const e of entries) {
+ if (e.parent_id && removed.has(e.parent_id) && !removed.has(e.id)) {
+ removed.add(e.id);
+ changed = true;
+ }
+ }
+ }
+ return entries.filter((e) => !removed.has(e.id));
+}
+
+/**
+ * Applies a confirmed comment delete to a flat timeline cache the way the
+ * server does: a comment with replies becomes a tombstone; one without is
+ * removed, together with every tombstone ancestor it leaves without replies.
+ * The cache may not hold every reply, so callers still reconcile with the
+ * server (realtime events plus a refetch).
+ */
+export function applyCommentDeletion(
+ entries: TimelineEntry[],
+ commentId: string,
+ deletedAt: string,
+): TimelineEntry[] {
+ if (hasReplies(entries, commentId)) {
+ return entries.map((e) =>
+ e.id === commentId
+ ? {
+ ...e,
+ content: "",
+ attachments: [],
+ reactions: [],
+ resolved_at: null,
+ resolved_by_type: null,
+ resolved_by_id: null,
+ deleted_at: deletedAt,
+ }
+ : e,
+ );
+ }
+
+ const byId = new Map(entries.map((e) => [e.id, e]));
+ let remaining = entries.filter((e) => e.id !== commentId);
+ const visited = new Set([commentId]);
+ let parentId = byId.get(commentId)?.parent_id;
+ while (parentId && !visited.has(parentId)) {
+ visited.add(parentId);
+ const parent = byId.get(parentId);
+ if (!parent || !isDeletedComment(parent) || hasReplies(remaining, parentId)) break;
+ remaining = remaining.filter((e) => e.id !== parentId);
+ parentId = parent.parent_id;
+ }
+ return remaining;
+}
diff --git a/packages/core/issues/mutations.test.tsx b/packages/core/issues/mutations.test.tsx
index d5f7e2238b..e3152e10ee 100644
--- a/packages/core/issues/mutations.test.tsx
+++ b/packages/core/issues/mutations.test.tsx
@@ -1,12 +1,13 @@
/**
* @vitest-environment jsdom
*/
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
import { act, renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
import type { ReactNode } from "react";
import { setApiInstance } from "../api";
+import { configStore } from "../config";
import type { ApiClient } from "../api/client";
import { createQueryClient } from "../query-client";
import {
@@ -1225,6 +1226,85 @@ describe("comment mutations — owner revision and last activity", () => {
expect(qc.getQueryState(positionKey)?.isInvalidated).toBe(true);
qc.clear();
});
+
+ // #8296: deleting a comment keeps its replies. The outcome (tombstone or
+ // removal) is applied only once the server confirms; the matrix itself lives
+ // in comment-deletion.test.ts.
+ it("keeps the timeline until the delete is confirmed, then keeps the replies", async () => {
+ configStore.getState().setCommentDeleteKeepRepliesSupported(true);
+ onTestFinished(() => configStore.getState().setCommentDeleteKeepRepliesSupported(false));
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ seed(qc);
+ const [root] = qc.getQueryData<TimelineEntry[]>(issueKeys.timeline(issueId))!;
+ const reply: TimelineEntry = { ...root!, id: "comment-2", parent_id: "comment-1", content: "reply" };
+ qc.setQueryData<TimelineEntry[]>(issueKeys.timeline(issueId), [root!, reply]);
+ let confirm!: () => void;
+ const deleteComment = vi.fn(() => new Promise<void>((resolve) => { confirm = resolve; }));
+ setApiInstance({ deleteComment } as unknown as ApiClient);
+ const { result } = renderHook(() => useDeleteComment(issueId), {
+ wrapper: createWrapper(qc),
+ });
+
+ let pending!: Promise<unknown>;
+ await act(async () => {
+ pending = result.current.mutateAsync("comment-1");
+ });
+ await waitFor(() => expect(deleteComment).toHaveBeenCalledWith("comment-1", { keepReplies: true }));
+ expect(qc.getQueryData<TimelineEntry[]>(issueKeys.timeline(issueId))).toEqual([root, reply]);
+
+ await act(async () => {
+ confirm();
+ await pending;
+ });
+ const timeline = qc.getQueryData<TimelineEntry[]>(issueKeys.timeline(issueId))!;
+ expect(timeline.map((e) => e.id)).toEqual(["comment-1", "comment-2"]);
+ expect(timeline[0]).toMatchObject({ content: "" });
+ expect(timeline[0]?.deleted_at).toEqual(expect.any(String));
+ expect(timeline[1]).toEqual(reply);
+ qc.clear();
+ });
+
+ // A server that has not declared the capability deletes the replies too:
+ // the client uses the legacy route and mirrors that outcome.
+ it("mirrors a reply-deleting server when the capability is not declared", async () => {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ seed(qc);
+ const [root] = qc.getQueryData<TimelineEntry[]>(issueKeys.timeline(issueId))!;
+ const reply: TimelineEntry = { ...root!, id: "comment-2", parent_id: "comment-1", content: "reply" };
+ qc.setQueryData<TimelineEntry[]>(issueKeys.timeline(issueId), [root!, reply]);
+ const deleteComment = vi.fn().mockResolvedValue(undefined);
+ setApiInstance({ deleteComment } as unknown as ApiClient);
+ const { result } = renderHook(() => useDeleteComment(issueId), {
+ wrapper: createWrapper(qc),
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync("comment-1");
+ });
+
+ expect(deleteComment).toHaveBeenCalledWith("comment-1", { keepReplies: false });
+ expect(qc.getQueryData<TimelineEntry[]>(issueKeys.timeline(issueId))).toEqual([]);
+ qc.clear();
+ });
+
+ it("leaves the timeline untouched when the delete fails", async () => {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ seed(qc);
+ const before = qc.getQueryData<TimelineEntry[]>(issueKeys.timeline(issueId));
+ setApiInstance({
+ deleteComment: vi.fn().mockRejectedValue(new Error("nope")),
+ } as unknown as ApiClient);
+ const { result } = renderHook(() => useDeleteComment(issueId), {
+ wrapper: createWrapper(qc),
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync("comment-1").catch(() => undefined);
+ });
+
+ expect(qc.getQueryData<TimelineEntry[]>(issueKeys.timeline(issueId))).toBe(before);
+ qc.clear();
+ });
});
describe("useResolveComment", () => {
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index 4df39178af..0f74716199 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -48,6 +48,8 @@ import type {
} from "../types";
import type { TimelineEntry, IssueSubscriber, Reaction } from "../types";
import { sortTimelineEntriesAsc } from "./timeline-sort";
+import { applyCommentDeletion, removeCommentSubtree } from "./comment-deletion";
+import { configStore } from "../config";
import {
onIssueAuxiliaryRevision,
invalidateIssueOwnerProjections,
@@ -930,41 +932,24 @@ export function useDeleteComment(issueId: string) {
const qc = useQueryClient();
const wsId = useWorkspaceId();
return useMutation({
- mutationFn: (commentId: string) => api.deleteComment(commentId),
- onMutate: async (commentId) => {
- await qc.cancelQueries({ queryKey: issueKeys.timeline(issueId) });
- const prev = qc.getQueryData<TimelineCache>(issueKeys.timeline(issueId));
-
- // Cascade: collect all descendants of the deleted comment.
- const toRemove = new Set<string>([commentId]);
- if (prev) {
- let changed = true;
- while (changed) {
- changed = false;
- for (const e of prev) {
- if (
- e.parent_id &&
- toRemove.has(e.parent_id) &&
- !toRemove.has(e.id)
- ) {
- toRemove.add(e.id);
- changed = true;
- }
- }
- }
- }
-
- qc.setQueryData<TimelineCache>(issueKeys.timeline(issueId), (old) =>
- old?.filter((e) => !toRemove.has(e.id)),
- );
- return { prev };
+ // The capability is read when the delete runs, so the route matches the
+ // copy the confirmation showed. Older servers delete the replies too.
+ mutationFn: async (commentId: string) => {
+ const keepReplies = configStore.getState().commentDeleteKeepRepliesSupported;
+ await api.deleteComment(commentId, { keepReplies });
+ return keepReplies;
},
- onError: (_err, _id, ctx) => {
- if (ctx?.prev !== undefined) {
- qc.setQueryData(issueKeys.timeline(issueId), ctx.prev);
- }
- },
- onSuccess: () => {
+ // Not optimistic: whether the comment disappears or stays as a tombstone
+ // depends on replies only the server sees for certain (#8296). Once it
+ // confirms, mirror its outcome; realtime events and the settle refetch
+ // reconcile the rest.
+ onSuccess: (keptReplies, commentId) => {
+ qc.setQueryData<TimelineCache>(issueKeys.timeline(issueId), (old) => {
+ if (!old) return old;
+ return keptReplies
+ ? applyCommentDeletion(old, commentId, new Date().toISOString())
+ : removeCommentSubtree(old, commentId);
+ });
// The endpoint remains 204 for compatibility, so the local caller has
// no body carrying issue_revision. The realtime event will narrow this
// with its revision when connected; this is the no-WS safety net.
diff --git a/packages/core/package.json b/packages/core/package.json
index d6c1c491d9..0d73747401 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -39,6 +39,7 @@
"./issues/queries": "./issues/queries.ts",
"./issues/mutations": "./issues/mutations.ts",
"./issues/timeline-sort": "./issues/timeline-sort.ts",
+ "./issues/comment-deletion": "./issues/comment-deletion.ts",
"./issues/comment-trigger-outcomes": "./issues/comment-trigger-outcomes.ts",
"./issues/date": "./issues/date.ts",
"./issues/ws-updaters": "./issues/ws-updaters.ts",
diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsx
index 7efdc1681a..70d8c1014a 100644
--- a/packages/core/platform/auth-initializer.tsx
+++ b/packages/core/platform/auth-initializer.tsx
@@ -94,6 +94,13 @@ export function AuthInitializer({
.setAgentConversationStartersSupported(
cfg.agent_conversation_starters_supported === true,
);
+ // Older servers delete a comment's replies with it; promise nothing
+ // about replies unless the server declares otherwise.
+ configStore
+ .getState()
+ .setCommentDeleteKeepRepliesSupported(
+ cfg.comment_delete_keep_replies_supported === true,
+ );
if (cfg.posthog_key) {
initAnalytics({
key: cfg.posthog_key,
diff --git a/packages/core/types/activity.ts b/packages/core/types/activity.ts
index 1a095f05ce..7a469e4b01 100644
--- a/packages/core/types/activity.ts
+++ b/packages/core/types/activity.ts
@@ -33,6 +33,12 @@ export interface TimelineEntry {
resolved_by_type?: CommentAuthorType | null;
resolved_by_id?: string | null;
source_task_id?: string | null;
+ /**
+ * Set only on a comment deleted while it still had replies: the server keeps
+ * it as an empty tombstone so the replies keep their parent. Read it through
+ * `isDeletedComment`.
+ */
+ deleted_at?: string | null;
/** Set by frontend coalescing when consecutive identical activities are merged. */
coalesced_count?: number;
}
diff --git a/packages/core/types/comment.ts b/packages/core/types/comment.ts
index 0c80d6623c..b0bcf5a8f6 100644
--- a/packages/core/types/comment.ts
+++ b/packages/core/types/comment.ts
@@ -40,6 +40,10 @@ export interface Comment {
// keys off the id rather than a dedicated `type`, because `type` is
// client-supplied on the generic comment endpoint and would be forgeable.
quick_action_id?: string | null;
+ // Set only on a comment deleted while it still had replies (#8296): the
+ // server keeps an empty tombstone so the replies keep their parent. Older
+ // servers omit it.
+ deleted_at?: string | null;
// Per-target result of every explicit @agent / @squad mention in this comment
// (MUL-4525 §2). Present only on create/edit responses; older servers omit it.
trigger_outcomes?: CommentTriggerOutcome[];
diff --git a/packages/core/types/issue.ts b/packages/core/types/issue.ts
index 6f24af6faf..ae000d3554 100644
--- a/packages/core/types/issue.ts
+++ b/packages/core/types/issue.ts
@@ -93,6 +93,8 @@ export interface SourceContextCommentSnapshot {
updated_at: string;
revision: number;
attachments: SourceContextAttachment[];
+ /** A comment deleted while it had replies: kept, empty, so they keep their parent. */
+ deleted?: boolean;
}
export interface SourceContextSnapshot {
diff --git a/packages/views/issues/components/comment-card-deleted.test.tsx b/packages/views/issues/components/comment-card-deleted.test.tsx
new file mode 100644
index 0000000000..5463f27920
--- /dev/null
+++ b/packages/views/issues/components/comment-card-deleted.test.tsx
@@ -0,0 +1,140 @@
+import { describe, expect, it, onTestFinished, vi } from "vitest";
+import { fireEvent, screen } from "@testing-library/react";
+import { forwardRef, type ReactNode } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { TimelineEntry } from "@multica/core/types";
+import { renderWithI18n } from "../../test/i18n";
+
+// #8296: deleting a comment keeps its replies. A comment deleted while it had
+// replies arrives as a tombstone (`deleted_at` set, empty body) and renders as
+// a placeholder with no actions. The cache rules live in
+// packages/core/issues/comment-deletion.test.ts.
+
+vi.mock("@multica/core/api", () => ({
+ api: { uploadFile: vi.fn() },
+ dispatchReasonCode: () => undefined,
+ errorCode: () => undefined,
+}));
+
+vi.mock("../../navigation", () => ({
+ useNavigation: () => ({
+ push: vi.fn(),
+ pathname: "/acme/issues",
+ getShareableUrl: (p: string) => `https://app.example${p}`,
+ }),
+}));
+
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({ getActorName: () => "Ada" }),
+}));
+
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: () => null,
+}));
+
+vi.mock("../hooks/use-comment-trigger-preview", () => ({
+ useCommentTriggerPreview: () => ({ agents: [], blocked: [] }),
+}));
+
+vi.mock("../../editor", async () => ({
+ ...(await vi.importActual<typeof import("../../editor/use-upload-gate")>("../../editor/use-upload-gate")),
+ ...(await vi.importActual<typeof import("../../editor/use-lazy-editor")>("../../editor/use-lazy-editor")),
+ ...(await vi.importActual<typeof import("../../editor/use-composer-submit")>("../../editor/use-composer-submit")),
+ useEditorUpload: () => ({ uploadWithToast: vi.fn(), upload: vi.fn(), uploading: false }),
+ useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),
+ FileDropOverlay: () => null,
+ ReadonlyContent: ({ content }: { content: string }) => <div>{content}</div>,
+ Attachment: () => null,
+ AttachmentDownloadProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
+ ContentEditor: forwardRef(function MockContentEditor() {
+ return <textarea data-testid="editor" />;
+ }),
+}));
+
+import { configStore } from "@multica/core/config";
+import { CommentCard } from "./comment-card";
+
+const DELETED_AT = "2026-09-11T08:00:00Z";
+
+function comment(id: string, parentId: string | null, extra: Partial<TimelineEntry> = {}): TimelineEntry {
+ return {
+ type: "comment",
+ id,
+ actor_type: "member",
+ actor_id: "user-1",
+ content: `body ${id}`,
+ parent_id: parentId,
+ comment_type: "comment",
+ reactions: [],
+ attachments: [],
+ created_at: `2026-09-11T07:0${id.length}:00Z`,
+ updated_at: "2026-09-11T07:00:00Z",
+ revision: 1,
+ ...extra,
+ };
+}
+
+const tombstone = (id: string, parentId: string | null) =>
+ comment(id, parentId, { content: "", deleted_at: DELETED_AT });
+
+function renderThread(root: TimelineEntry, replies: TimelineEntry[]) {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return renderWithI18n(
+ <QueryClientProvider client={qc}>
+ <CommentCard
+ issueId="issue-1"
+ entry={root}
+ replies={replies}
+ currentUserId="user-1"
+ onReply={vi.fn().mockResolvedValue(true)}
+ onEdit={vi.fn().mockResolvedValue(undefined)}
+ onDelete={vi.fn()}
+ onToggleReaction={vi.fn()}
+ />
+ </QueryClientProvider>,
+ );
+}
+
+const actionMenus = () => screen.queryAllByRole("button", { name: "Comment actions" });
+
+describe("CommentCard — deleted comments", () => {
+ it("renders a deleted reply as a placeholder and keeps the replies to it", () => {
+ renderThread(comment("a", null), [tombstone("bb", "a"), comment("ccc", "bb")]);
+
+ expect(screen.getByText("This comment was deleted")).toBeTruthy();
+ expect(screen.getByText("body ccc")).toBeTruthy();
+ // Root and the live reply keep their actions; the placeholder has none.
+ expect(actionMenus()).toHaveLength(2);
+ });
+
+ it("renders a deleted root as a placeholder and keeps the thread open for replies", () => {
+ renderThread(tombstone("a", null), [comment("bb", "a")]);
+
+ expect(screen.getByText("This comment was deleted")).toBeTruthy();
+ expect(screen.getByText("body bb")).toBeTruthy();
+ expect(actionMenus()).toHaveLength(1);
+ expect(screen.getByText("Leave a reply...")).toBeTruthy();
+ });
+
+ it("tells the user the replies are kept when the server keeps them", async () => {
+ configStore.getState().setCommentDeleteKeepRepliesSupported(true);
+ onTestFinished(() => configStore.getState().setCommentDeleteKeepRepliesSupported(false));
+ renderThread(comment("a", null), [comment("bb", "a")]);
+
+ fireEvent.click(actionMenus()[0]!);
+ fireEvent.click(await screen.findByText("Delete"));
+
+ expect(await screen.findByText(/Its replies stay in the thread/)).toBeTruthy();
+ });
+
+ // An older server deletes the replies with the comment; the copy must not
+ // promise otherwise.
+ it("warns that the replies go too when the server has not declared it keeps them", async () => {
+ renderThread(comment("a", null), [comment("bb", "a")]);
+
+ fireEvent.click(actionMenus()[0]!);
+ fireEvent.click(await screen.findByText("Delete"));
+
+ expect(await screen.findByText(/and all its replies will be permanently deleted/)).toBeTruthy();
+ });
+});
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index f2fc510ece..69824e5575 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -39,6 +39,8 @@ import { CommentTriggerChips } from "./comment-trigger-chips";
import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";
import type { TimelineEntry, Attachment } from "@multica/core/types";
import { contentReferencesAttachment } from "@multica/core/types";
+import { isDeletedComment } from "@multica/core/issues/comment-deletion";
+import { useConfigStore } from "@multica/core/config";
import { selectStandaloneAttachments } from "@multica/core/attachments/image-sequence";
import { useCommentCollapseStore, useCommentDraftStore } from "@multica/core/issues/stores";
import { useT } from "../../i18n";
@@ -159,15 +161,20 @@ function DeleteCommentDialog({
hasReplies?: boolean;
}) {
const { t } = useT("issues");
+ // Only a server that declares it keeps the replies (#8296); an older one
+ // deletes them with the comment, and the copy must say so.
+ const keepsReplies = useConfigStore((s) => s.commentDeleteKeepRepliesSupported);
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t(($) => $.comment.delete_title)}</AlertDialogTitle>
<AlertDialogDescription>
- {hasReplies
- ? t(($) => $.comment.delete_desc_with_replies)
- : t(($) => $.comment.delete_desc)}
+ {!hasReplies
+ ? t(($) => $.comment.delete_desc)
+ : keepsReplies
+ ? t(($) => $.comment.delete_desc_replies_kept)
+ : t(($) => $.comment.delete_desc_with_replies)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
@@ -605,6 +612,7 @@ function CommentRow({
canModerate = false,
isResolution = false,
isHighlighted = false,
+ hasReplies = false,
onEdit,
onDelete,
onToggleReaction,
@@ -619,6 +627,8 @@ function CommentRow({
canModerate?: boolean;
/** True when this reply is the thread's resolution (shows the green badge). */
isResolution?: boolean;
+ /** True when other replies answer this one; they are kept when it is deleted. */
+ hasReplies?: boolean;
/** True when this row is the deep-link target currently being highlighted. */
isHighlighted?: boolean;
onEdit: (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[], contentBase?: string) => Promise<void>;
@@ -641,6 +651,16 @@ function CommentRow({
const reactions = entry.reactions ?? [];
+ if (isDeletedComment(entry)) {
+ // Kept only so the replies to it stay attached (#8296): nothing is left
+ // to show or act on.
+ return (
+ <div data-comment-block className="py-3 pl-12 pr-4 max-md:pl-3 max-md:pr-3 text-body italic text-muted-foreground">
+ {t(($) => $.comment.deleted_placeholder)}
+ </div>
+ );
+ }
+
return (
<div data-comment-block className="pb-3">
{/* Header pins to the timeline's scroll parent within this reply's own
@@ -761,6 +781,7 @@ function CommentRow({
open={confirmDelete}
onOpenChange={setConfirmDelete}
onConfirm={() => onDelete(entry.id)}
+ hasReplies={hasReplies}
/>
</div>
</StickyHeaderShell>
@@ -943,7 +964,9 @@ function CommentCardImpl({
const { getActorName } = useActorName();
const replyTarget = useCommentDraftStore((s) => s.drafts[`reply:${issueId}:${entry.id}`]?.replyTarget);
const replyTargetId = replyTarget?.commentId ?? entry.id;
- const replyTargetMissing = !!replyTarget && replyTargetId !== entry.id && !replies.some((r) => r.id === replyTargetId);
+ // A deleted target's tombstone is as gone as a removed row.
+ const replyTargetMissing = !!replyTarget && replyTargetId !== entry.id
+ && !replies.some((r) => r.id === replyTargetId && !isDeletedComment(r));
const annotation = useCommentAnnotations({
draftKey: `reply:${issueId}:${entry.id}`,
sources: [entry, ...replies].filter((e) => e.type === "comment")
@@ -985,6 +1008,8 @@ function CommentCardImpl({
});
const replyCount = allNestedReplies.length;
+ const repliedToIds = new Set(allNestedReplies.map((reply) => reply.parent_id));
+ const deleted = isDeletedComment(entry);
const contentPreview = (entry.content ?? "").replace(/\n/g, " ").slice(0, 80);
const reactions = entry.reactions ?? [];
@@ -1049,33 +1074,42 @@ function CommentCardImpl({
className={cn("px-4 max-md:px-3", open ? "pt-3 pb-2" : "py-3")}
>
<div className="flex items-center gap-2.5">
- <ActorAvatar
- actorType={entry.actor_type}
- actorId={entry.actor_id}
- name={entry.actor_name}
- avatarUrl={entry.actor_avatar_url}
- profileRequiresDirectoryEntry
- size="md"
- enableHoverCard
- showStatusDot
- />
- <span className="shrink-0 cursor-pointer text-body font-medium">
- {entry.actor_name || getActorName(entry.actor_type, entry.actor_id)}
- </span>
- <Tooltip>
- <TooltipTrigger
- render={
- <span className="shrink-0 text-caption text-muted-foreground cursor-default">
- {timeAgo(entry.created_at)}
- </span>
- }
- />
- <TooltipContent side="top">
- {new Date(entry.created_at).toLocaleString(locale)}
- </TooltipContent>
- </Tooltip>
+ {deleted ? (
+ // The thread's root was deleted; its replies still hang off it.
+ <span className="min-w-0 truncate text-body italic text-muted-foreground">
+ {t(($) => $.comment.deleted_placeholder)}
+ </span>
+ ) : (
+ <>
+ <ActorAvatar
+ actorType={entry.actor_type}
+ actorId={entry.actor_id}
+ name={entry.actor_name}
+ avatarUrl={entry.actor_avatar_url}
+ profileRequiresDirectoryEntry
+ size="md"
+ enableHoverCard
+ showStatusDot
+ />
+ <span className="shrink-0 cursor-pointer text-body font-medium">
+ {entry.actor_name || getActorName(entry.actor_type, entry.actor_id)}
+ </span>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span className="shrink-0 text-caption text-muted-foreground cursor-default">
+ {timeAgo(entry.created_at)}
+ </span>
+ }
+ />
+ <TooltipContent side="top">
+ {new Date(entry.created_at).toLocaleString(locale)}
+ </TooltipContent>
+ </Tooltip>
- {renderRuns(entry.id, "header")}
+ {renderRuns(entry.id, "header")}
+ </>
+ )}
{!open && contentPreview && (
<span className="min-w-0 flex-1 truncate text-caption text-muted-foreground">
@@ -1102,7 +1136,7 @@ function CommentCardImpl({
>
<ChevronRight aria-hidden className={cn("h-3.5 w-3.5 transition-transform motion-reduce:transition-none", open && "rotate-90")} />
</Button>
- {open && <>
+ {open && !deleted && <>
{!edit.editing && <QuickEmojiPicker
onSelect={(emoji) => onToggleReaction(entry.id, emoji)}
ariaLabel={t(($) => $.comment.add_reaction)}
@@ -1179,7 +1213,7 @@ function CommentCardImpl({
open={confirmDelete}
onOpenChange={setConfirmDelete}
onConfirm={() => onDelete(entry.id)}
- hasReplies
+ hasReplies={replyCount > 0}
/>
</>}
</div>
@@ -1189,7 +1223,7 @@ function CommentCardImpl({
{/* Root comment body. Avoid Base UI's Panel here: every mounted panel
probes computed styles to detect animations, forcing a style
recalculation across long issue-detail documents. */}
- {open && (
+ {open && !deleted && (
<div id={`comment-body-${entry.id}`} className="px-4 max-md:px-3 pb-3">
{edit.editing ? (
<div
@@ -1334,6 +1368,7 @@ function CommentCardImpl({
canModerate={canModerate}
isResolution
isHighlighted={highlightedCommentId === resolutionReply.id}
+ hasReplies={repliedToIds.has(resolutionReply.id)}
onEdit={onEdit}
onDelete={onDelete}
onToggleReaction={onToggleReaction}
@@ -1378,6 +1413,7 @@ function CommentCardImpl({
canModerate={canModerate}
isResolution={reply.id === replyResolutionId}
isHighlighted={highlightedCommentId === reply.id}
+ hasReplies={repliedToIds.has(reply.id)}
onEdit={onEdit}
onDelete={onDelete}
onToggleReaction={onToggleReaction}
diff --git a/packages/views/issues/components/resolved-thread-bar.tsx b/packages/views/issues/components/resolved-thread-bar.tsx
index 6fdef7cdb5..1f33ac38bb 100644
--- a/packages/views/issues/components/resolved-thread-bar.tsx
+++ b/packages/views/issues/components/resolved-thread-bar.tsx
@@ -2,6 +2,7 @@ import { CheckCircle2, ChevronRight } from "lucide-react";
import { useActorName } from "@multica/core/workspace/hooks";
import { Card } from "@multica/ui/components/ui/card";
import type { TimelineEntry } from "@multica/core/types";
+import { isDeletedComment } from "@multica/core/issues/comment-deletion";
import { useT } from "../../i18n";
interface ResolvedThreadBarProps {
@@ -21,6 +22,7 @@ const MAX_NAMED_AUTHORS = 2;
// Distinct authors across `entries`, first-seen order, collapsed to a label
// ("Alice", "Alice, Bob", "Alice, Bob and 2 others"). Shared by both bars.
+// Deleted comments name no author.
function useAuthorsLabel(entries: TimelineEntry[]): string {
const { t } = useT("issues");
const { getActorName } = useActorName();
@@ -28,6 +30,7 @@ function useAuthorsLabel(entries: TimelineEntry[]): string {
const seen = new Set<string>();
const authors: Array<{ type: string; id: string; name?: string }> = [];
for (const e of entries) {
+ if (isDeletedComment(e)) continue;
const key = `${e.actor_type}:${e.actor_id}`;
if (seen.has(key)) continue;
seen.add(key);
diff --git a/packages/views/issues/components/source-context-comment-list.tsx b/packages/views/issues/components/source-context-comment-list.tsx
index 0ccd17ed8a..213ff87e3a 100644
--- a/packages/views/issues/components/source-context-comment-list.tsx
+++ b/packages/views/issues/components/source-context-comment-list.tsx
@@ -82,7 +82,11 @@ export function SourceContextCommentList({
{changeLabel && <span className="sr-only">{changeLabel}</span>}
</div>
<div className="mt-1.5 break-words">
- <ReadonlyContent content={comment.content} />
+ {comment.deleted === true ? (
+ <p className="italic text-muted-foreground">{t(($) => $.comment.deleted_placeholder)}</p>
+ ) : (
+ <ReadonlyContent content={comment.content} />
+ )}
</div>
</div>
</li>
diff --git a/packages/views/issues/components/thread-minimap.tsx b/packages/views/issues/components/thread-minimap.tsx
index 739a9b975c..c5d8b525b6 100644
--- a/packages/views/issues/components/thread-minimap.tsx
+++ b/packages/views/issues/components/thread-minimap.tsx
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { CheckCircle2 } from "lucide-react";
import type { TimelineEntry } from "@multica/core/types";
+import { isDeletedComment } from "@multica/core/issues/comment-deletion";
import { useActorName } from "@multica/core/workspace/hooks";
import { cn } from "@multica/ui/lib/utils";
import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
@@ -448,10 +449,11 @@ export function ThreadMinimap({
className="pointer-events-auto flex max-h-full flex-col overflow-hidden"
>
{threads.map((thread, i) => {
- const title =
- previews[i]!.title ||
- thread.entry.actor_name ||
- getActorName(thread.entry.actor_type, thread.entry.actor_id);
+ const title = isDeletedComment(thread.entry)
+ ? t(($) => $.comment.deleted_placeholder)
+ : previews[i]!.title ||
+ thread.entry.actor_name ||
+ getActorName(thread.entry.actor_type, thread.entry.actor_id);
return (
<MinimapTick
key={thread.id}
@@ -480,8 +482,10 @@ export function ThreadMinimap({
>
<ul>
{threads.map((thread, index) => {
- const title = previews[index]!.title || thread.entry.actor_name ||
- getActorName(thread.entry.actor_type, thread.entry.actor_id);
+ const title = isDeletedComment(thread.entry)
+ ? t(($) => $.comment.deleted_placeholder)
+ : previews[index]!.title || thread.entry.actor_name ||
+ getActorName(thread.entry.actor_type, thread.entry.actor_id);
const participantNames = thread.participants.map((participant) =>
participant.actor_name || getActorName(participant.actor_type, participant.actor_id),
);
diff --git a/packages/views/issues/components/thread-utils.ts b/packages/views/issues/components/thread-utils.ts
index a45a303264..f8011883b5 100644
--- a/packages/views/issues/components/thread-utils.ts
+++ b/packages/views/issues/components/thread-utils.ts
@@ -1,4 +1,5 @@
import type { TimelineEntry } from "@multica/core/types";
+import { isDeletedComment } from "@multica/core/issues/comment-deletion";
import { sortTimelineEntriesAsc } from "@multica/core/issues/timeline-sort";
/**
@@ -31,7 +32,10 @@ export function collectThreadReplies(
return sortTimelineEntriesAsc(out);
}
-/** Unique member and agent authors, root first, followed by all nested replies. */
+/**
+ * Unique member and agent authors, root first, followed by all nested replies.
+ * A deleted comment's author no longer takes part in the thread.
+ */
export function collectThreadParticipants(
root: TimelineEntry,
replies: readonly TimelineEntry[],
@@ -39,6 +43,7 @@ export function collectThreadParticipants(
const seen = new Set<string>();
return [root, ...replies].filter((entry) => {
if (entry.actor_type !== "member" && entry.actor_type !== "agent") return false;
+ if (isDeletedComment(entry)) return false;
const key = `${entry.actor_type}:${entry.actor_id}`;
if (seen.has(key)) return false;
seen.add(key);
diff --git a/packages/views/issues/hooks/use-issue-timeline.ts b/packages/views/issues/hooks/use-issue-timeline.ts
index 4b28e11b55..cee70faf44 100644
--- a/packages/views/issues/hooks/use-issue-timeline.ts
+++ b/packages/views/issues/hooks/use-issue-timeline.ts
@@ -40,6 +40,7 @@ import {
mentionLabelsByTarget,
} from "@multica/core/issues/comment-trigger-outcomes";
import { useWSEvent, useWSReconnect } from "@multica/core/realtime";
+import { removeCommentSubtree } from "@multica/core/issues/comment-deletion";
import { toast } from "sonner";
import { useT } from "../../i18n";
import { blockedShortReasonLabel } from "../blocked-trigger-copy";
@@ -64,6 +65,7 @@ function commentToTimelineEntry(c: Comment): TimelineEntry {
resolved_by_type: c.resolved_by_type,
resolved_by_id: c.resolved_by_id,
source_task_id: c.source_task_id,
+ deleted_at: c.deleted_at,
};
}
@@ -202,27 +204,12 @@ export function useIssueTimeline(issueId: string, userId?: string) {
(payload: unknown) => {
const { comment_id, issue_id } = payload as CommentDeletedPayload;
if (issue_id !== issueId) return;
- qc.setQueryData<TLCache>(issueKeys.timeline(issueId), (old) => {
- if (!old) return old;
- // Cascade through replies (full timeline now lives in this single
- // cache, so a flat sweep is sufficient).
- const idsToRemove = new Set<string>([comment_id]);
- let changed = true;
- while (changed) {
- changed = false;
- for (const e of old) {
- if (
- e.parent_id &&
- idsToRemove.has(e.parent_id) &&
- !idsToRemove.has(e.id)
- ) {
- idsToRemove.add(e.id);
- changed = true;
- }
- }
- }
- return old.filter((e) => !idsToRemove.has(e.id));
- });
+ // A comment with replies is tombstoned (comment:updated), never
+ // removed, so any cached reply of a removed comment is stale: older
+ // servers cascaded the delete to every descendant.
+ qc.setQueryData<TLCache>(issueKeys.timeline(issueId), (old) =>
+ old ? removeCommentSubtree(old, comment_id) : old,
+ );
},
[qc, issueId],
),
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index e890c2be0c..217d46f4e8 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -498,6 +498,8 @@
"delete_title": "Delete comment",
"delete_desc": "This comment will be permanently deleted. This cannot be undone.",
"delete_desc_with_replies": "This comment and all its replies will be permanently deleted. This cannot be undone.",
+ "delete_desc_replies_kept": "This comment will be permanently deleted. Its replies stay in the thread. This cannot be undone.",
+ "deleted_placeholder": "This comment was deleted",
"delete_action": "Delete",
"cancel_action": "Cancel",
"edit_placeholder": "Edit comment...",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index bec50ffb7d..93d0c6a2cd 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -489,6 +489,8 @@
"delete_title": "コメントを削除",
"delete_desc": "このコメントは完全に削除されます。この操作は元に戻せません。",
"delete_desc_with_replies": "このコメントとすべての返信が完全に削除されます。この操作は元に戻せません。",
+ "delete_desc_replies_kept": "このコメントは完全に削除されます。返信はスレッドに残ります。この操作は元に戻せません。",
+ "deleted_placeholder": "このコメントは削除されました",
"delete_action": "削除",
"cancel_action": "キャンセル",
"edit_placeholder": "コメントを編集...",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 49b687f8e2..4dd67c12f3 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -489,6 +489,8 @@
"delete_title": "댓글 삭제",
"delete_desc": "이 댓글이 영구 삭제됩니다. 이 작업은 되돌릴 수 없습니다.",
"delete_desc_with_replies": "이 댓글과 모든 답글이 영구 삭제됩니다. 이 작업은 되돌릴 수 없습니다.",
+ "delete_desc_replies_kept": "이 댓글이 영구 삭제됩니다. 답글은 스레드에 남습니다. 이 작업은 되돌릴 수 없습니다.",
+ "deleted_placeholder": "삭제된 댓글입니다",
"delete_action": "삭제",
"cancel_action": "취소",
"edit_placeholder": "댓글 수정...",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 55479af0e7..afbb8a9c9c 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -489,6 +489,8 @@
"delete_title": "删除评论",
"delete_desc": "这条评论会被永久删除,无法撤销。",
"delete_desc_with_replies": "这条评论及其全部回复会被永久删除,无法撤销。",
+ "delete_desc_replies_kept": "这条评论会被永久删除,它的回复会保留在讨论中,无法撤销。",
+ "deleted_placeholder": "评论已删除",
"delete_action": "删除",
"cancel_action": "取消",
"edit_placeholder": "编辑评论...",
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index 7938c304c0..2173c4413b 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -270,8 +270,10 @@ var issueCommentAddCmd = &cobra.Command{
var issueCommentDeleteCmd = &cobra.Command{
Use: "delete <comment-id>",
Short: "Delete a comment",
- Args: exactArgs(1),
- RunE: runIssueCommentDelete,
+ Long: "Delete a single comment. Its replies are kept: a comment that has replies stays in the thread " +
+ "as an empty placeholder (deleted_at set) so they keep their place.",
+ Args: exactArgs(1),
+ RunE: runIssueCommentDelete,
}
var issueCommentResolveCmd = &cobra.Command{
@@ -2157,6 +2159,10 @@ func runIssueCommentList(cmd *cobra.Command, args []string) error {
rows := make([][]string, 0, len(comments))
for _, c := range comments {
content := strVal(c, "content")
+ if strVal(c, "deleted_at") != "" {
+ // A deleted comment kept only so its replies stay attached.
+ content = "(deleted)"
+ }
if utf8.RuneCountInString(content) > 80 {
runes := []rune(content)
content = string(runes[:77]) + "..."
@@ -2265,7 +2271,16 @@ func runIssueCommentDelete(cmd *cobra.Command, args []string) error {
ctx, cancel := cli.APIContext(context.Background())
defer cancel()
- if err := client.DeleteJSON(ctx, "/api/comments/"+args[0]); err != nil {
+ // The keep-replies route exists only on servers that keep a deleted
+ // comment's replies. An older server does not route it — a plain-text 404,
+ // unlike the JSON "comment not found" — and would delete the replies too,
+ // so refuse there rather than fall back.
+ err = client.DeleteJSON(ctx, "/api/comments/"+args[0]+"/keep-replies")
+ var httpErr *cli.HTTPError
+ if errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusNotFound && !strings.HasPrefix(httpErr.Body, "{") {
+ return fmt.Errorf("delete comment: this server would delete the comment's replies too; upgrade the server first")
+ }
+ if err != nil {
return fmt.Errorf("delete comment: %w", err)
}
diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.go
index 460d6ba99e..63ce9f3054 100644
--- a/server/cmd/multica/cmd_issue_test.go
+++ b/server/cmd/multica/cmd_issue_test.go
@@ -10,6 +10,7 @@ import (
"net/url"
"os"
"path/filepath"
+ "slices"
"strconv"
"strings"
"testing"
@@ -4824,3 +4825,64 @@ func TestRunIssueListTableFooterReportsPage(t *testing.T) {
})
}
}
+
+// #8296: the CLI deletes through the keep-replies route, which only servers
+// that keep a deleted comment's replies expose. An older server does not route
+// it, and the CLI refuses rather than falling back to a delete that would
+// remove the replies too.
+func TestRunIssueCommentDeleteKeepsReplies(t *testing.T) {
+ commentID := "comment-123"
+ tests := []struct {
+ name string
+ respond func(http.ResponseWriter)
+ wantErr string
+ }{
+ {
+ name: "server keeps replies",
+ respond: func(w http.ResponseWriter) { w.WriteHeader(http.StatusNoContent) },
+ },
+ {
+ name: "older server without the route",
+ respond: func(w http.ResponseWriter) { http.Error(w, "404 page not found", http.StatusNotFound) },
+ wantErr: "would delete the comment's replies too",
+ },
+ {
+ name: "comment not found",
+ respond: func(w http.ResponseWriter) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusNotFound)
+ json.NewEncoder(w).Encode(map[string]string{"error": "comment not found"})
+ },
+ wantErr: "comment not found",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ var paths []string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodDelete {
+ t.Errorf("method = %s, want DELETE", r.Method)
+ }
+ paths = append(paths, r.URL.Path)
+ tt.respond(w)
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ err := runIssueCommentDelete(newIssueCommentResolutionTestCmd("delete"), []string{commentID})
+ if tt.wantErr == "" && err != nil {
+ t.Fatalf("run command: %v", err)
+ }
+ if tt.wantErr != "" && (err == nil || !strings.Contains(err.Error(), tt.wantErr)) {
+ t.Fatalf("error = %v, want it to mention %q", err, tt.wantErr)
+ }
+ if want := []string{"/api/comments/" + commentID + "/keep-replies"}; !slices.Equal(paths, want) {
+ t.Fatalf("requests = %v, want only %v", paths, want)
+ }
+ })
+ }
+}
diff --git a/server/cmd/multica/cmd_issue_timeline.go b/server/cmd/multica/cmd_issue_timeline.go
index 9f6316d1b4..c1fd84e038 100644
--- a/server/cmd/multica/cmd_issue_timeline.go
+++ b/server/cmd/multica/cmd_issue_timeline.go
@@ -275,6 +275,9 @@ func timelineActor(actorType, actorID, actorName string, actors actorDisplayLook
// rather than being dropped.
func timelineDetail(entry map[string]any, actors actorDisplayLookup, fullID bool) string {
if strVal(entry, "type") == "comment" {
+ if strVal(entry, "deleted_at") != "" {
+ return "(deleted)"
+ }
return clipTimelineText(singleLineText(strVal(entry, "content")), 60)
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index e1dcdb1417..26ceba0ed4 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -2065,6 +2065,12 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.With(handler.RequireHumanActor).Post("/sub-issues", h.CreateCommentSubIssue)
r.Put("/", h.UpdateComment)
r.Delete("/", h.DeleteComment)
+ // Same handler under a path servers from before #8296 do not
+ // route. Clients that promise "replies are kept" call this one,
+ // so a request that reaches an older server — mid-rollout, after
+ // a rollback, or self-hosted — fails instead of deleting the
+ // replies with the comment.
+ r.Delete("/keep-replies", h.DeleteComment)
r.Post("/resolve", h.ResolveComment)
r.Delete("/resolve", h.UnresolveComment)
r.Post("/reactions", h.AddReaction)
diff --git a/server/cmd/server/workspace_scope_guard_test.go b/server/cmd/server/workspace_scope_guard_test.go
index 7a1ff14e4b..9e5017967f 100644
--- a/server/cmd/server/workspace_scope_guard_test.go
+++ b/server/cmd/server/workspace_scope_guard_test.go
@@ -49,9 +49,11 @@ func TestWorkspaceScopeGuard(t *testing.T) {
id := seedComment(t, ctx, issueID)
t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, util.UUIDToString(id)) })
- deleted, err := queries.DeleteComment(ctx, db.DeleteCommentParams{ID: id, WorkspaceID: wsB})
- if err != nil || deleted.Changed {
- t.Fatalf("cross-workspace DeleteComment = (%+v, %v), want unchanged result", deleted, err)
+ if _, err := queries.DeleteLeafComment(ctx, db.DeleteLeafCommentParams{ID: id, WorkspaceID: wsB}); !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("cross-workspace DeleteLeafComment: expected pgx.ErrNoRows, got %v", err)
+ }
+ if _, err := queries.TombstoneComment(ctx, db.TombstoneCommentParams{ID: id, WorkspaceID: wsB}); !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("cross-workspace TombstoneComment: expected pgx.ErrNoRows, got %v", err)
}
assertRowExists(t, ctx, "comment", id)
})
diff --git a/server/internal/handler/activity.go b/server/internal/handler/activity.go
index 4ad4314d34..a072b93d6f 100644
--- a/server/internal/handler/activity.go
+++ b/server/internal/handler/activity.go
@@ -46,6 +46,8 @@ type TimelineEntry struct {
ResolvedByType *string `json:"resolved_by_type,omitempty"`
ResolvedByID *string `json:"resolved_by_id,omitempty"`
SourceTaskID *string `json:"source_task_id,omitempty"`
+ // Set only on a tombstone: a comment deleted while it still had replies.
+ DeletedAt *string `json:"deleted_at,omitempty"`
}
// timelineHardCap bounds the per-issue timeline payload. Sized as a defensive
@@ -305,6 +307,7 @@ func (h *Handler) commentsToEntries(r *http.Request, comments []db.Comment) []Ti
ResolvedByType: textToPtr(c.ResolvedByType),
ResolvedByID: uuidToPtr(c.ResolvedByID),
SourceTaskID: uuidToPtr(c.SourceTaskID),
+ DeletedAt: timestampToPtr(c.DeletedAt),
}
}
return out
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 9dfb03ee55..44ca5b4aa8 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -41,6 +41,11 @@ type CommentResponse struct {
ResolvedByType *string `json:"resolved_by_type"`
ResolvedByID *string `json:"resolved_by_id"`
SourceTaskID *string `json:"source_task_id,omitempty"`
+ // DeletedAt marks a tombstone: a comment deleted while it still had
+ // replies (#8296). Its content is empty and it carries no attachments or
+ // reactions; it stays only so the replies keep their direct parent.
+ // Omitted for every live comment.
+ DeletedAt *string `json:"deleted_at,omitempty"`
// QuickActionID marks a comment produced by a quick action run (MUL-5465).
// The timeline renders those as a collapsed one-line card instead of the
// raw prompt body. It is NOT settable through this endpoint — there is no
@@ -114,6 +119,7 @@ func commentToResponse(c db.Comment, reactions []ReactionResponse, attachments [
ResolvedByType: textToPtr(c.ResolvedByType),
ResolvedByID: uuidToPtr(c.ResolvedByID),
SourceTaskID: uuidToPtr(c.SourceTaskID),
+ DeletedAt: timestampToPtr(c.DeletedAt),
QuickActionID: uuidToPtr(c.QuickActionID),
Reactions: reactions,
Attachments: attachments,
@@ -804,6 +810,7 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
SourceTaskID: r.SourceTaskID,
QuickActionID: r.QuickActionID,
Revision: r.Revision,
+ DeletedAt: r.DeletedAt,
}
if !r.ParentID.Valid {
root := c
@@ -898,6 +905,7 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
SourceTaskID: r.SourceTaskID,
QuickActionID: r.QuickActionID,
Revision: r.Revision,
+ DeletedAt: r.DeletedAt,
}
if !r.ParentID.Valid {
root := c
@@ -986,6 +994,7 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
SourceTaskID: r.SourceTaskID,
QuickActionID: r.QuickActionID,
Revision: r.Revision,
+ DeletedAt: r.DeletedAt,
})
}
@@ -1045,6 +1054,7 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
ParentID: r.ParentID, WorkspaceID: r.WorkspaceID, ResolvedAt: r.ResolvedAt,
ResolvedByType: r.ResolvedByType, ResolvedByID: r.ResolvedByID,
SourceTaskID: r.SourceTaskID, QuickActionID: r.QuickActionID, Revision: r.Revision,
+ DeletedAt: r.DeletedAt,
}
stats[uuidToString(r.ID)] = rootStat{ReplyCount: int(r.ReplyCount), LastActivityAt: r.LastActivityAt}
}
@@ -1075,6 +1085,7 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
ParentID: r.ParentID, WorkspaceID: r.WorkspaceID, ResolvedAt: r.ResolvedAt,
ResolvedByType: r.ResolvedByType, ResolvedByID: r.ResolvedByID,
SourceTaskID: r.SourceTaskID, QuickActionID: r.QuickActionID, Revision: r.Revision,
+ DeletedAt: r.DeletedAt,
}
stats[uuidToString(r.ID)] = rootStat{ReplyCount: int(r.ReplyCount), LastActivityAt: r.LastActivityAt}
}
@@ -1837,7 +1848,7 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
}
}
- created, err := h.Queries.CreateComment(r.Context(), db.CreateCommentParams{
+ createParams := db.CreateCommentParams{
ID: dbid.NewV7(),
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
@@ -1847,7 +1858,63 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
Type: req.Type,
ParentID: parentID,
SourceTaskID: sourceTaskID,
- })
+ }
+ var created db.CreateCommentRow
+ var err error
+ if len(attachmentIDs) > 0 {
+ // A comment and the attachments it was posted with are one visible
+ // change, and one database outcome. Committing the comment first leaves
+ // a window in which it can gain a reply and be deleted into a
+ // tombstone, and the link would then bind uploaded objects to that
+ // placeholder — invisible, and missed by the prune's storage cleanup
+ // (#8296 review). Inside this transaction the row is not yet visible to
+ // a delete, so there is no window at all. Mirrors the attachment-set
+ // edit in UpdateComment.
+ //
+ // Owner first: the CreateComment statement takes the issue row, and only
+ // then are the attachments locked — the issue -> comment -> child order
+ // LockIssueForDelete, UpdateComment, LockLiveComment and DeleteAttachment
+ // all share. Taking the attachments first inverts it against issue
+ // teardown, which holds the issue and then reaches the same rows through
+ // the issue_id cascade, and Postgres aborts one side. Locking them at all
+ // still pins the requested set: an attachment deleted while this waited
+ // is refused before the comment is committed, rather than the comment
+ // committing without it.
+ tx, beginErr := h.TxStarter.Begin(r.Context())
+ if beginErr != nil {
+ slog.Warn("create comment failed", append(logger.RequestAttrs(r), "error", beginErr, "issue_id", issueID)...)
+ writeError(w, http.StatusInternalServerError, "failed to create comment: "+beginErr.Error())
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+ created, err = qtx.CreateComment(r.Context(), createParams)
+ if err == nil {
+ var missing pgtype.UUID
+ missing, err = lockCommentAttachments(r.Context(), qtx, issue.WorkspaceID, issue.ID, attachmentIDs)
+ if err == nil && missing.Valid {
+ writeError(w, http.StatusConflict, "attachment "+uuidToString(missing)+" is no longer available")
+ return
+ }
+ }
+ if err == nil {
+ err = qtx.LinkAttachmentsToComment(r.Context(), db.LinkAttachmentsToCommentParams{
+ CommentID: created.ID,
+ IssueID: issue.ID,
+ Column3: attachmentIDs,
+ })
+ }
+ if err == nil {
+ err = tx.Commit(r.Context())
+ }
+ } else {
+ created, err = h.Queries.CreateComment(r.Context(), createParams)
+ }
+ if errors.Is(err, pgx.ErrNoRows) {
+ // The issue was deleted, possibly while this waited for its row lock.
+ writeError(w, http.StatusNotFound, "issue not found")
+ return
+ }
if err != nil {
slog.Warn("create comment failed", append(logger.RequestAttrs(r), "error", err, "issue_id", issueID)...)
writeError(w, http.StatusInternalServerError, "failed to create comment: "+err.Error())
@@ -1855,11 +1922,6 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
}
comment := created.Comment()
- // Link uploaded attachments to this comment.
- if len(attachmentIDs) > 0 {
- h.linkAttachmentsByIDs(r.Context(), comment.ID, issue.ID, attachmentIDs)
- }
-
// Fetch linked attachments so the response includes them.
groupedAtt := h.groupAttachments(r, []pgtype.UUID{comment.ID})
resp := commentToResponse(comment, nil, groupedAtt[uuidToString(comment.ID)])
@@ -2636,7 +2698,8 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issu
return nil, nil
}
- if parentComment != nil && parentComment.AuthorType == "agent" {
+ // A deleted parent no longer speaks for its agent author (#8296).
+ if parentComment != nil && parentComment.AuthorType == "agent" && !parentComment.DeletedAt.Valid {
trigger, ok := h.routeReplyToParentAuthor(ctx, issue, parentComment, actorType, actorID, opts)
if !ok {
return nil, nil
@@ -2654,8 +2717,9 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issu
}
// A plain member-to-member reply must not start the issue assignee just
// because the thread has no agent owner. Explicit mentions and existing
- // conversation owners were already resolved above.
- if parentComment.AuthorType == "member" {
+ // conversation owners were already resolved above. The same holds for a
+ // reply under a deleted comment: it is still a reply, not a new request.
+ if parentComment.AuthorType == "member" || parentComment.DeletedAt.Valid {
return nil, nil
}
}
@@ -3209,7 +3273,8 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
ID: commentUUID,
WorkspaceID: wsUUID,
})
- if err != nil {
+ // A deleted comment's tombstone has nothing left to edit.
+ if err != nil || existing.DeletedAt.Valid {
writeError(w, http.StatusNotFound, "comment not found")
return
}
@@ -3396,9 +3461,14 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
// original batch, including the still-valid unchanged comment.
h.retriggerCancelledTaskSurvivors(r.Context(), *triggerIssue, cancelled, pgtype.UUID{})
}
- if errors.Is(err, pgx.ErrNoRows) && strictContentEdit {
+ if errors.Is(err, pgx.ErrNoRows) {
current, reloadErr := h.Queries.GetCommentInWorkspace(r.Context(), db.GetCommentInWorkspaceParams{ID: commentUUID, WorkspaceID: wsUUID})
- if reloadErr == nil {
+ if errors.Is(reloadErr, pgx.ErrNoRows) || (reloadErr == nil && current.DeletedAt.Valid) {
+ // Deleted while the edit waited for it.
+ writeError(w, http.StatusNotFound, "comment not found")
+ return
+ }
+ if reloadErr == nil && strictContentEdit {
if req.ExpectedRevision != nil {
writeRevisionConflict(w, "comment", current.ID, *req.ExpectedRevision, current.Revision)
} else {
@@ -3501,54 +3571,239 @@ func (h *Handler) DeleteComment(w http.ResponseWriter, r *http.Request) {
slog.Info("comment parent issue no longer exists", "issue_id", uuidToString(comment.IssueID), "comment_id", commentId)
}
- // Collect attachment URLs before CASCADE delete removes them.
- attachmentURLs, _ := h.Queries.ListAttachmentURLsByCommentID(r.Context(), comment.ID)
+ if comment.DeletedAt.Valid {
+ writeError(w, http.StatusNotFound, "comment not found")
+ return
+ }
// Cancel any active task whose planned batch contains this comment so the
// agent does not run with the now-deleted content already embedded. Must
- // run before DeleteComment because the FK ON DELETE SET NULL would
- // otherwise nullify trigger_comment_id and orphan those tasks in queued.
+ // run before the delete: a removed row would nullify trigger_comment_id
+ // through ON DELETE SET NULL and orphan those tasks in queued.
cancelled, cancelErr := h.TaskService.CancelTasksByTriggerComment(r.Context(), comment.ID)
if cancelErr != nil {
slog.Warn("cancel tasks for deleted trigger comment failed", append(logger.RequestAttrs(r), "error", cancelErr, "comment_id", commentId)...)
}
- deleted, err := h.Queries.DeleteComment(r.Context(), db.DeleteCommentParams{
- ID: comment.ID,
- WorkspaceID: comment.WorkspaceID,
- })
- if err != nil || !deleted.Changed {
- slog.Warn("delete comment failed", append(logger.RequestAttrs(r), "error", err, "changed", deleted.Changed, "comment_id", commentId)...)
+ deleted, err := h.deleteComment(r.Context(), comment.ID, comment.WorkspaceID)
+ if err != nil {
+ slog.Warn("delete comment failed", append(logger.RequestAttrs(r), "error", err, "comment_id", commentId)...)
// Cancellation already committed but deletion did not. If the parent
// issue still exists, rebuild the complete cancelled batch (including
// this trigger) before reporting the storage error or concurrent no-op.
if hasIssue {
h.retriggerCancelledTaskSurvivors(r.Context(), issue, cancelled, pgtype.UUID{})
}
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to delete comment")
- } else {
+ if errors.Is(err, pgx.ErrNoRows) {
writeError(w, http.StatusNotFound, "comment not found")
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to delete comment")
}
return
}
- h.deleteS3Objects(r.Context(), attachmentURLs)
- slog.Info("comment deleted", append(logger.RequestAttrs(r), "comment_id", commentId, "issue_id", uuidToString(comment.IssueID))...)
- eventPayload := map[string]any{
- "comment_id": uuidToString(comment.ID),
- "issue_id": uuidToString(comment.IssueID),
+ h.deleteS3Objects(r.Context(), deleted.AttachmentURLs)
+ slog.Info("comment deleted", append(logger.RequestAttrs(r),
+ "comment_id", commentId,
+ "issue_id", uuidToString(comment.IssueID),
+ "tombstoned", deleted.Tombstone != nil,
+ "removed_count", len(deleted.RemovedIDs),
+ )...)
+ // A tombstone is still part of the thread, so clients replace it in place
+ // through the ordinary update event; removed rows get one delete event each.
+ if deleted.Tombstone != nil {
+ resp := commentToResponse(*deleted.Tombstone, nil, nil)
+ resp.IssueRevision = deleted.IssueRevision
+ eventPayload := map[string]any{"comment": resp}
+ if deleted.IssueRevision > 0 {
+ eventPayload["issue_revision"] = deleted.IssueRevision
+ }
+ h.publish(protocol.EventCommentUpdated, workspaceID, actorType, actorID, eventPayload)
}
- if deleted.IssueRevision > 0 {
- eventPayload["issue_revision"] = deleted.IssueRevision
+ for _, removedID := range deleted.RemovedIDs {
+ eventPayload := map[string]any{
+ "comment_id": uuidToString(removedID),
+ "issue_id": uuidToString(comment.IssueID),
+ }
+ if deleted.IssueRevision > 0 {
+ eventPayload["issue_revision"] = deleted.IssueRevision
+ }
+ h.publish(protocol.EventCommentDeleted, workspaceID, actorType, actorID, eventPayload)
}
- h.publish(protocol.EventCommentDeleted, workspaceID, actorType, actorID, eventPayload)
if hasIssue {
h.retriggerCancelledTaskSurvivors(r.Context(), issue, cancelled, comment.ID)
}
w.WriteHeader(http.StatusNoContent)
}
+// commentDeletion is the committed outcome of deleteComment.
+type commentDeletion struct {
+ // Tombstone is the cleared row when the comment still had replies.
+ Tombstone *db.Comment
+ // RemovedIDs lists every row removed outright: the comment itself when it
+ // had no replies, followed by each tombstone ancestor that lost its last
+ // reply as a result, nearest first.
+ RemovedIDs []pgtype.UUID
+ // AttachmentURLs are the deleted comment's storage objects, for cleanup
+ // after commit.
+ AttachmentURLs []string
+ IssueRevision int64
+}
+
+// lockCommentAttachments locks the unbound issue attachments a comment is
+// being created with and reports the first requested id that is not among
+// them: never eligible, or deleted while the lock waited. The caller must
+// already hold the issue's row lock — these are its children, and taking them
+// first is the inversion CreateComment documents.
+func lockCommentAttachments(ctx context.Context, qtx *db.Queries, workspaceID, issueID pgtype.UUID, ids []pgtype.UUID) (missing pgtype.UUID, err error) {
+ locked, err := qtx.LockAttachmentsForCommentLink(ctx, db.LockAttachmentsForCommentLinkParams{
+ WorkspaceID: workspaceID,
+ IssueID: issueID,
+ AttachmentIds: ids,
+ })
+ if err != nil {
+ return pgtype.UUID{}, err
+ }
+ have := make(map[pgtype.UUID]struct{}, len(locked))
+ for _, id := range locked {
+ have[id] = struct{}{}
+ }
+ for _, id := range ids {
+ if _, ok := have[id]; !ok {
+ return id, nil
+ }
+ }
+ return pgtype.UUID{}, nil
+}
+
+// withLiveCommentLock runs write in a transaction that first locks the
+// comment's issue and then the comment — the order every comment mutation
+// takes — and only while the comment is live. Writes to a comment's children
+// (reactions, attachments) go through it so none can land on a tombstone, even
+// when the delete commits while this waits. Returns pgx.ErrNoRows when the
+// comment is gone or deleted.
+func (h *Handler) withLiveCommentLock(ctx context.Context, commentID, workspaceID pgtype.UUID, write func(*db.Queries) error) error {
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+ if _, err := qtx.LockLiveComment(ctx, db.LockLiveCommentParams{ID: commentID, WorkspaceID: workspaceID}); err != nil {
+ return err
+ }
+ if err := write(qtx); err != nil {
+ return err
+ }
+ return tx.Commit(ctx)
+}
+
+// commentTombstonePruneDepth bounds the upward walk over tombstone ancestors,
+// matching the depth bound of the ancestor path queries.
+const commentTombstonePruneDepth = 256
+
+// deleteComment deletes exactly one comment (#8296). A comment that still has
+// replies becomes a tombstone — content, attachments, reactions and resolution
+// cleared, row kept — so each reply stays attached to its direct parent. A
+// comment without replies is removed, along with every tombstone ancestor
+// that is left without replies. Nothing here relies on the parent_id cascade.
+//
+// Returns pgx.ErrNoRows when the comment is already gone or already deleted.
+func (h *Handler) deleteComment(ctx context.Context, commentID, workspaceID pgtype.UUID) (commentDeletion, error) {
+ var out commentDeletion
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ return out, err
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+
+ target, err := qtx.LockCommentForDelete(ctx, db.LockCommentForDeleteParams{
+ ID: commentID,
+ WorkspaceID: workspaceID,
+ })
+ if err != nil {
+ return out, err
+ }
+ // Separate statement on purpose: its snapshot postdates the locks above,
+ // so it sees every committed reply, and none can be added while they are
+ // held.
+ hasReplies, err := qtx.CommentHasReplies(ctx, db.CommentHasRepliesParams{
+ ID: target.ID,
+ WorkspaceID: target.WorkspaceID,
+ })
+ if err != nil {
+ return out, err
+ }
+ out.AttachmentURLs, err = qtx.DeleteCommentAttachments(ctx, db.DeleteCommentAttachmentsParams{
+ CommentID: target.ID,
+ WorkspaceID: target.WorkspaceID,
+ })
+ if err != nil {
+ return out, err
+ }
+ if err := qtx.DeleteCommentReactions(ctx, db.DeleteCommentReactionsParams{
+ CommentID: target.ID,
+ WorkspaceID: target.WorkspaceID,
+ }); err != nil {
+ return out, err
+ }
+
+ if hasReplies {
+ tombstone, err := qtx.TombstoneComment(ctx, db.TombstoneCommentParams{
+ ID: target.ID,
+ WorkspaceID: target.WorkspaceID,
+ })
+ if err != nil {
+ return out, err
+ }
+ // A deleted delegated-failure recovery signal is withdrawn: settle it so
+ // the recovery sweeper stops scanning its row. A no-op for every other
+ // comment.
+ if _, err := qtx.SettleDelegatedFailureRecoveryComment(ctx, target.ID); err != nil {
+ return out, err
+ }
+ out.Tombstone = &tombstone
+ } else {
+ removed, err := qtx.DeleteLeafComment(ctx, db.DeleteLeafCommentParams{
+ ID: target.ID,
+ WorkspaceID: target.WorkspaceID,
+ })
+ if err != nil {
+ return out, err
+ }
+ out.RemovedIDs = append(out.RemovedIDs, removed.ID)
+ parentID := removed.ParentID
+ for depth := 0; parentID.Valid && depth < commentTombstonePruneDepth; depth++ {
+ pruned, err := qtx.DeleteReplylessCommentTombstone(ctx, db.DeleteReplylessCommentTombstoneParams{
+ ID: parentID,
+ WorkspaceID: target.WorkspaceID,
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ // A live comment, or a tombstone other replies still hold.
+ break
+ }
+ if err != nil {
+ return out, err
+ }
+ out.RemovedIDs = append(out.RemovedIDs, pruned.ID)
+ parentID = pruned.ParentID
+ }
+ }
+
+ out.IssueRevision, err = qtx.TouchIssueForCommentDelete(ctx, db.TouchIssueForCommentDeleteParams{
+ IssueID: target.IssueID,
+ WorkspaceID: target.WorkspaceID,
+ })
+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ return out, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return out, err
+ }
+ return out, nil
+}
+
// retriggerCancelledTaskSurvivors repairs the surviving inputs from a
// batch containing a comment that was edited or deleted. Cancellation releases
// the one-pending-task constraint; every other comment is replayed through the
@@ -3588,7 +3843,8 @@ func (h *Handler) retriggerCancelledTaskSurvivors(ctx context.Context, issue db.
"issue_id", uuidToString(issue.ID), "comment_id", commentID, "error", err)
continue
}
- if comment.IssueID != issue.ID {
+ // A tombstone is a deleted input, not a survivor.
+ if comment.IssueID != issue.ID || comment.DeletedAt.Valid {
continue
}
comments = append(comments, comment)
@@ -3677,7 +3933,8 @@ func (h *Handler) loadCommentForActor(w http.ResponseWriter, r *http.Request) (d
ID: commentUUID,
WorkspaceID: wsUUID,
})
- if err != nil {
+ // A deleted comment's tombstone cannot be a thread's resolution.
+ if err != nil || comment.DeletedAt.Valid {
writeError(w, http.StatusNotFound, "comment not found")
return db.Comment{}, "", "", "", false
}
@@ -3726,6 +3983,11 @@ func (h *Handler) ResolveComment(w http.ResponseWriter, r *http.Request) {
ResolvedByType: pgtype.Text{String: actorType, Valid: true},
ResolvedByID: actorUUID,
})
+ if errors.Is(err, pgx.ErrNoRows) {
+ // Deleted after it was loaded.
+ writeError(w, http.StatusNotFound, "comment not found")
+ return
+ }
if err != nil {
slog.Warn("resolve comment failed", append(logger.RequestAttrs(r), "error", err, "comment_id", uuidToString(comment.ID))...)
writeError(w, http.StatusInternalServerError, "failed to resolve comment")
diff --git a/server/internal/handler/comment_create_attachment_test.go b/server/internal/handler/comment_create_attachment_test.go
new file mode 100644
index 0000000000..f13042dde9
--- /dev/null
+++ b/server/internal/handler/comment_create_attachment_test.go
@@ -0,0 +1,344 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// A comment and the attachments it was posted with are one database outcome
+// (#8296 review). Committing the comment first left a window in which it could
+// gain a reply and be deleted into a tombstone, and the link would then bind
+// the uploaded objects to that placeholder — invisible in the timeline, and
+// missed by the prune's storage cleanup.
+
+// failLinkAttachmentsTxStarter begins real transactions whose
+// LinkAttachmentsToComment statement fails, standing in for any failure
+// between creating the comment and linking its attachments.
+type failLinkAttachmentsTxStarter struct {
+ delegate *pgxpool.Pool
+}
+
+type failLinkAttachmentsTx struct {
+ pgx.Tx
+}
+
+func (s *failLinkAttachmentsTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.delegate.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return failLinkAttachmentsTx{Tx: tx}, nil
+}
+
+func (t failLinkAttachmentsTx) Exec(ctx context.Context, query string, args ...interface{}) (pgconn.CommandTag, error) {
+ if strings.Contains(query, "-- name: LinkAttachmentsToComment") {
+ return pgconn.CommandTag{}, errors.New("injected attachment link failure")
+ }
+ return t.Tx.Exec(ctx, query, args...)
+}
+
+func createCommentWithAttachment(t *testing.T, h *Handler, issueID, attachmentID string) *testutil.Response {
+ t.Helper()
+ req := newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{
+ "content": "see the screenshot",
+ "attachment_ids": []string{attachmentID},
+ })
+ return testutil.Call(t, h.CreateComment, withURLParam(req, "id", issueID))
+}
+
+func unlinkedIssueAttachment(t *testing.T, issueID string) string {
+ t.Helper()
+ return dbfx.Insert(t, "attachment", testutil.Cols{
+ "workspace_id": testWorkspaceID, "issue_id": issueID,
+ "uploader_type": "member", "uploader_id": testUserID,
+ "filename": "shot.png", "url": "https://example.test/shot.png",
+ "content_type": "image/png", "size_bytes": 1,
+ })
+}
+
+func TestCreateCommentLinksItsAttachmentsInOneTransaction(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ issueID := dbfx.Issue(t, "comment with attachments")
+ attachmentID := unlinkedIssueAttachment(t, issueID)
+
+ var resp CommentResponse
+ createCommentWithAttachment(t, testHandler, issueID, attachmentID).Want(http.StatusCreated).JSON(&resp)
+ if len(resp.Attachments) != 1 || resp.Attachments[0].ID != attachmentID {
+ t.Fatalf("response attachments = %+v, want the posted one", resp.Attachments)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE id = $1 AND comment_id = $2`, attachmentID, resp.ID); n != 1 {
+ t.Fatalf("attachment linked rows = %d, want 1", n)
+ }
+}
+
+// A link that fails takes the comment with it: no comment may exist whose
+// attachments were never bound.
+func TestCreateCommentRollsBackWhenAttachmentLinkFails(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ issueID := dbfx.Issue(t, "comment attachment link failure")
+ attachmentID := unlinkedIssueAttachment(t, issueID)
+
+ h := *testHandler
+ h.TxStarter = &failLinkAttachmentsTxStarter{delegate: testPool}
+ createCommentWithAttachment(t, &h, issueID, attachmentID).Want(http.StatusInternalServerError)
+
+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1`, issueID); n != 0 {
+ t.Fatalf("issue has %d comments after a failed link, want none", n)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE id = $1 AND comment_id IS NULL`, attachmentID); n != 1 {
+ t.Fatalf("attachment was left linked after the rollback")
+ }
+}
+
+// Every mutation here takes its owners first — the issue, then the comment,
+// then the attachment. A comment created with an attachment takes the issue in
+// its CreateComment statement and only then locks the attachment rows, so it
+// cannot close a cycle with the two writers that reach an attachment through
+// its issue: DeleteAttachment (issue, then the row) and issue teardown (issue,
+// then the rows its cascade removes). The holders below play each of those one
+// statement at a time.
+// waitForBlockedQuery waits until the request under test is blocked on a row
+// lock and returns which of names it is waiting in. Unlike waiting for one
+// specific statement, this lets the caller carry on and prove what the wrong
+// lock order actually costs: the holder's next statement deadlocking.
+func waitForBlockedQuery(t *testing.T, done <-chan error, names ...string) string {
+ t.Helper()
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) {
+ select {
+ case err := <-done:
+ t.Fatalf("request completed before it blocked on any row lock: %v", err)
+ default:
+ }
+ for _, name := range names {
+ var waiting bool
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT EXISTS (
+ SELECT 1 FROM pg_stat_activity
+ WHERE datname = current_database()
+ AND wait_event_type = 'Lock'
+ AND query LIKE '%' || $1 || '%'
+ )
+ `, "-- name: "+name+" :").Scan(&waiting); err != nil {
+ t.Fatalf("observe blocked %s: %v", name, err)
+ }
+ if waiting {
+ return name
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Fatalf("request blocked on none of %v", names)
+ return ""
+}
+
+func TestCreateCommentWithAttachmentFollowsOwnerFirstLockOrder(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ tests := []struct {
+ name string
+ holdSQL string
+ wantCode int
+ wantComments int
+ wantLinked int
+ }{
+ {
+ // The attachment is gone by the time the create proceeds: refuse
+ // before any comment exists rather than commit one without it.
+ name: "attachment deleted while the create waits",
+ holdSQL: `DELETE FROM attachment WHERE id = $1`,
+ wantCode: http.StatusConflict,
+ wantComments: 0,
+ wantLinked: 0,
+ },
+ {
+ // The holder took the issue and released it without touching the
+ // attachment: the create proceeds and links it.
+ name: "attachment kept",
+ holdSQL: `SELECT id FROM attachment WHERE id = $1`,
+ wantCode: http.StatusCreated,
+ wantComments: 1,
+ wantLinked: 1,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ issueID := dbfx.Issue(t, "comment attachment vs attachment delete")
+ attachmentID := unlinkedIssueAttachment(t, issueID)
+
+ holder, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin holder: %v", err)
+ }
+ defer holder.Rollback(context.Background())
+ // DeleteAttachment's own order, through its own query: the owner
+ // issue, then the row. Taking the lock here by hand would let a
+ // production mode too weak to serialize issue writers pass.
+ qtx := testHandler.Queries.WithTx(holder)
+ if _, err := qtx.LockIssueForAttachmentWrite(ctx, db.LockIssueForAttachmentWriteParams{
+ ID: parseUUID(issueID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ }); err != nil {
+ t.Fatalf("hold issue: %v", err)
+ }
+ if _, err := holder.Exec(ctx, tt.holdSQL, attachmentID); err != nil {
+ t.Fatalf("hold attachment: %v", err)
+ }
+
+ var got *testutil.Response
+ done := make(chan error, 1)
+ go func() {
+ got = createCommentWithAttachment(t, testHandler, issueID, attachmentID)
+ done <- nil
+ }()
+ // The create must wait for the issue while holding no attachment
+ // lock. Under a weaker owner lock it gets past the issue and waits
+ // on the attachment instead, which the bump below then deadlocks
+ // against.
+ blockedIn := waitForBlockedQuery(t, done, "CreateComment", "LockAttachmentsForCommentLink")
+
+ // The issue revision bump the delete statement performs last. The
+ // create is already waiting for the issue, so this cannot wait for
+ // the attachment the holder still owns.
+ _, holdErr := holder.Exec(ctx, `UPDATE issue SET revision = revision + 1 WHERE id = $1`, issueID)
+ if holdErr == nil {
+ holdErr = holder.Commit(ctx)
+ }
+ <-done
+ if holdErr != nil {
+ t.Fatalf("attachment delete deadlocked or failed while the create waited in %s: %v", blockedIn, holdErr)
+ }
+ if blockedIn != "CreateComment" {
+ t.Fatalf("create blocked in %s, want the owner issue in CreateComment", blockedIn)
+ }
+ got.Want(tt.wantCode)
+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1`, issueID); n != tt.wantComments {
+ t.Fatalf("issue has %d comments, want %d", n, tt.wantComments)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE id = $1 AND comment_id IS NOT NULL`, attachmentID); n != tt.wantLinked {
+ t.Fatalf("attachment linked rows = %d, want %d", n, tt.wantLinked)
+ }
+ })
+ }
+}
+
+// The symmetric side: issue teardown holds the issue and then reaches the
+// attachment through the issue_id cascade. A create that took the attachment
+// first would deadlock with it; taking the issue first means the create simply
+// waits, and then finds the issue gone.
+func TestCreateCommentWithAttachmentDoesNotDeadlockWithIssueTeardown(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ issueID := dbfx.Issue(t, "comment attachment vs issue teardown")
+ attachmentID := unlinkedIssueAttachment(t, issueID)
+
+ teardown, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin issue teardown: %v", err)
+ }
+ defer teardown.Rollback(context.Background())
+ qtx := testHandler.Queries.WithTx(teardown)
+ if _, err := qtx.LockIssueForDelete(ctx, db.LockIssueForDeleteParams{
+ ID: parseUUID(issueID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ }); err != nil {
+ t.Fatalf("lock issue for teardown: %v", err)
+ }
+
+ var got *testutil.Response
+ done := make(chan error, 1)
+ go func() {
+ got = createCommentWithAttachment(t, testHandler, issueID, attachmentID)
+ done <- nil
+ }()
+ waitForCommentMutationLock(t, "CreateComment", done)
+
+ // The cascade reaches the attachment the blocked create asked for.
+ deleteErr := qtx.DeleteIssue(ctx, db.DeleteIssueParams{
+ ID: parseUUID(issueID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if deleteErr == nil {
+ deleteErr = teardown.Commit(ctx)
+ }
+ <-done
+ if deleteErr != nil {
+ t.Fatalf("issue teardown deadlocked or failed: %v", deleteErr)
+ }
+ got.Want(http.StatusNotFound)
+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1`, issueID); n != 0 {
+ t.Fatalf("deleted issue kept %d comments", n)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE id = $1`, attachmentID); n != 0 {
+ t.Fatalf("deleted issue kept its attachment")
+ }
+}
+
+// DeleteAttachment itself must take the issue before the attachment row, so it
+// queues behind issue teardown instead of deadlocking with it.
+func TestDeleteAttachmentTakesTheIssueBeforeTheRow(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ // The owner lock has to hold against both kinds of issue writer: teardown,
+ // which takes FOR UPDATE, and an ordinary one such as CreateComment's
+ // revision bump, which takes FOR NO KEY UPDATE. A mode that only conflicts
+ // with the first leaves the create/delete cycle open.
+ for _, holderMode := range []string{"FOR UPDATE", "FOR NO KEY UPDATE"} {
+ t.Run(holderMode, func(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ issueID := dbfx.Issue(t, "attachment delete vs issue lock")
+ attachmentID := unlinkedIssueAttachment(t, issueID)
+
+ holder, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin holder: %v", err)
+ }
+ defer holder.Rollback(context.Background())
+ if _, err := holder.Exec(ctx, `SELECT id FROM issue WHERE id = $1 `+holderMode, issueID); err != nil {
+ t.Fatalf("hold issue: %v", err)
+ }
+
+ var got *testutil.Response
+ done := make(chan error, 1)
+ go func() {
+ req := newRequest(http.MethodDelete, "/api/attachments/"+attachmentID, nil)
+ got = testutil.Call(t, testHandler.DeleteAttachment, withURLParam(req, "id", attachmentID))
+ done <- nil
+ }()
+ waitForCommentMutationLock(t, "LockIssueForAttachmentWrite", done)
+
+ if err := holder.Commit(ctx); err != nil {
+ t.Fatalf("release issue: %v", err)
+ }
+ <-done
+ got.Want(http.StatusNoContent)
+ if n := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE id = $1`, attachmentID); n != 0 {
+ t.Fatalf("attachment survived its delete")
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/comment_delete_test.go b/server/internal/handler/comment_delete_test.go
new file mode 100644
index 0000000000..85b5ec66bd
--- /dev/null
+++ b/server/internal/handler/comment_delete_test.go
@@ -0,0 +1,475 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// Deleting a comment removes only that comment (#8296). These tests pin the
+// three outcomes: a comment with replies becomes a tombstone that keeps them
+// attached, a comment without replies is removed, and a tombstone is removed
+// once its last reply is gone.
+
+type commentRowState struct {
+ exists bool
+ content string
+ parentID string
+ deleted bool
+ resolved bool
+}
+
+func loadCommentRowState(t *testing.T, id string) commentRowState {
+ t.Helper()
+ var state commentRowState
+ var parentID *string
+ var deletedAt, resolvedAt *time.Time
+ err := testPool.QueryRow(context.Background(),
+ `SELECT content, parent_id::text, deleted_at, resolved_at FROM comment WHERE id = $1`, id,
+ ).Scan(&state.content, &parentID, &deletedAt, &resolvedAt)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return commentRowState{}
+ }
+ if err != nil {
+ t.Fatalf("load comment %s: %v", id, err)
+ }
+ state.exists = true
+ if parentID != nil {
+ state.parentID = *parentID
+ }
+ state.deleted = deletedAt != nil
+ state.resolved = resolvedAt != nil
+ return state
+}
+
+// commentEventRecorder is a handler copy whose bus records the comment events
+// a delete publishes, in order.
+type commentEventRecorder struct {
+ h *Handler
+ events []events.Event
+}
+
+func newCommentEventRecorder() *commentEventRecorder {
+ h := *testHandler
+ h.Bus = events.New()
+ rec := &commentEventRecorder{h: &h}
+ for _, eventType := range []string{protocol.EventCommentUpdated, protocol.EventCommentDeleted} {
+ h.Bus.Subscribe(eventType, func(event events.Event) {
+ rec.events = append(rec.events, event)
+ })
+ }
+ return rec
+}
+
+func (rec *commentEventRecorder) delete(t *testing.T, commentID string) *testutil.Response {
+ t.Helper()
+ rec.events = nil
+ req := withURLParam(newRequest(http.MethodDelete, "/api/comments/"+commentID, nil), "commentId", commentID)
+ return testutil.Call(t, rec.h.DeleteComment, req)
+}
+
+// deletedIDs returns the comment ids of the recorded comment:deleted events.
+func (rec *commentEventRecorder) deletedIDs() []string {
+ var ids []string
+ for _, event := range rec.events {
+ if event.Type == protocol.EventCommentDeleted {
+ ids = append(ids, event.Payload.(map[string]any)["comment_id"].(string))
+ }
+ }
+ return ids
+}
+
+func TestDeleteCommentWithRepliesLeavesTombstone(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ issueID := dbfx.Issue(t, "delete keeps replies")
+ // A → B → C → E, plus A → D.
+ a := dbfx.Comment(t, issueID, "root A")
+ b := dbfx.Comment(t, issueID, "reply B", testutil.Cols{"parent_id": a})
+ c := dbfx.Comment(t, issueID, "reply C", testutil.Cols{"parent_id": b})
+ e := dbfx.Comment(t, issueID, "reply E", testutil.Cols{"parent_id": c})
+ d := dbfx.Comment(t, issueID, "reply D", testutil.Cols{"parent_id": a})
+ dbfx.Insert(t, "attachment", testutil.Cols{
+ "workspace_id": testWorkspaceID, "issue_id": issueID, "comment_id": b,
+ "uploader_type": "member", "uploader_id": testUserID,
+ "filename": "b.png", "url": "https://example.test/b.png", "content_type": "image/png", "size_bytes": 1,
+ })
+ dbfx.Insert(t, "comment_reaction", testutil.Cols{
+ "comment_id": b, "workspace_id": testWorkspaceID, "actor_type": "member", "actor_id": testUserID, "emoji": "👍",
+ })
+ dbfx.Exec(t, `UPDATE comment SET resolved_at = now(), resolved_by_type = 'member', resolved_by_id = $2 WHERE id = $1`, b, testUserID)
+
+ rec := newCommentEventRecorder()
+ rec.delete(t, b).Want(http.StatusNoContent)
+
+ if got := loadCommentRowState(t, b); !got.exists || !got.deleted || got.content != "" || got.resolved || got.parentID != a {
+ t.Fatalf("B = %+v, want a tombstone under A with its body and resolution cleared", got)
+ }
+ for id, content := range map[string]string{a: "root A", c: "reply C", e: "reply E", d: "reply D"} {
+ if got := loadCommentRowState(t, id); !got.exists || got.deleted || got.content != content {
+ t.Fatalf("comment %q = %+v, want it untouched", content, got)
+ }
+ }
+ if got := loadCommentRowState(t, c); got.parentID != b {
+ t.Fatalf("C parent = %s, want it still attached to B", got.parentID)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE comment_id = $1`, b); n != 0 {
+ t.Fatalf("tombstone kept %d attachments", n)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM comment_reaction WHERE comment_id = $1`, b); n != 0 {
+ t.Fatalf("tombstone kept %d reactions", n)
+ }
+
+ if len(rec.events) != 1 || rec.events[0].Type != protocol.EventCommentUpdated {
+ t.Fatalf("events = %+v, want exactly one comment:updated", rec.events)
+ }
+ tombstone := rec.events[0].Payload.(map[string]any)["comment"].(CommentResponse)
+ if tombstone.ID != b || tombstone.DeletedAt == nil || tombstone.Content != "" || len(tombstone.Attachments) != 0 {
+ t.Fatalf("comment:updated payload = %+v, want B's tombstone", tombstone)
+ }
+
+ entries, status := fetchTimeline(t, issueID)
+ if status != http.StatusOK {
+ t.Fatalf("timeline status = %d", status)
+ }
+ var sawTombstone bool
+ for _, entry := range entries {
+ if entry.ID == b {
+ sawTombstone = entry.DeletedAt != nil && entry.Content != nil && *entry.Content == ""
+ }
+ }
+ if !sawTombstone {
+ t.Fatalf("timeline did not return B as a tombstone: %+v", entries)
+ }
+
+ // The tombstone is no longer a comment anyone can act on.
+ rec.delete(t, b).Want(http.StatusNotFound)
+ testutil.Call(t, testHandler.UpdateComment, withURLParam(newRequest(http.MethodPut, "/api/comments/"+b, map[string]any{
+ "content": "resurrected",
+ }), "commentId", b)).Want(http.StatusNotFound)
+ testutil.Call(t, testHandler.AddReaction, withURLParam(newRequest(http.MethodPost, "/api/comments/"+b+"/reactions", map[string]any{
+ "emoji": "🎉",
+ }), "commentId", b)).Want(http.StatusNotFound)
+ testutil.Call(t, testHandler.ResolveComment, withURLParam(newRequest(http.MethodPost, "/api/comments/"+b+"/resolve", nil), "commentId", b)).
+ Want(http.StatusNotFound)
+
+ // Deleting a leaf under a live parent removes the leaf alone.
+ rec.delete(t, e).Want(http.StatusNoContent)
+ if got := loadCommentRowState(t, e); got.exists {
+ t.Fatalf("E = %+v, want it removed", got)
+ }
+ if got := loadCommentRowState(t, c); !got.exists || got.deleted {
+ t.Fatalf("C = %+v, want it untouched", got)
+ }
+ if ids := rec.deletedIDs(); len(ids) != 1 || ids[0] != e {
+ t.Fatalf("comment:deleted ids = %v, want only E", ids)
+ }
+}
+
+func TestDeleteCommentPrunesTombstonesLeftWithoutReplies(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ issueID := dbfx.Issue(t, "delete prunes tombstones")
+ // A → B → C, plus A → D.
+ a := dbfx.Comment(t, issueID, "root A")
+ b := dbfx.Comment(t, issueID, "reply B", testutil.Cols{"parent_id": a})
+ c := dbfx.Comment(t, issueID, "reply C", testutil.Cols{"parent_id": b})
+ d := dbfx.Comment(t, issueID, "reply D", testutil.Cols{"parent_id": a})
+
+ rec := newCommentEventRecorder()
+ rec.delete(t, b).Want(http.StatusNoContent)
+ rec.delete(t, a).Want(http.StatusNoContent)
+ for _, id := range []string{a, b} {
+ if got := loadCommentRowState(t, id); !got.exists || !got.deleted {
+ t.Fatalf("comment %s = %+v, want a tombstone", id, got)
+ }
+ }
+
+ // A still holds B's branch, so removing D leaves A in place.
+ rec.delete(t, d).Want(http.StatusNoContent)
+ if ids := rec.deletedIDs(); len(ids) != 1 || ids[0] != d {
+ t.Fatalf("comment:deleted ids = %v, want only D", ids)
+ }
+ if got := loadCommentRowState(t, a); !got.exists || !got.deleted {
+ t.Fatalf("A = %+v, want it kept as a tombstone", got)
+ }
+
+ // C was the last live reply: it goes, and so do the tombstones above it.
+ rec.delete(t, c).Want(http.StatusNoContent)
+ if ids := rec.deletedIDs(); len(ids) != 3 || ids[0] != c || ids[1] != b || ids[2] != a {
+ t.Fatalf("comment:deleted ids = %v, want C, B, A in that order", ids)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1`, issueID); n != 0 {
+ t.Fatalf("issue still has %d comments, want none", n)
+ }
+}
+
+// A tombstone carries no input: it must not count as a new comment for the
+// claim hint, nor be replayed by completion reconciliation.
+func TestCommentTombstoneIsNotTriggerInput(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ issueID := dbfx.Issue(t, "tombstone is not input")
+ since := time.Now().Add(-time.Minute)
+ root := dbfx.Comment(t, issueID, "please look at this")
+ dbfx.Comment(t, issueID, "a reply keeps the root", testutil.Cols{"parent_id": root})
+
+ countSince := func() int64 {
+ t.Helper()
+ n, err := testHandler.Queries.CountNewCommentsSince(ctx, db.CountNewCommentsSinceParams{
+ IssueID: parseUUID(issueID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ Since: pgtype.Timestamptz{Time: since, Valid: true},
+ // Neither id may be NULL: the query compares against both.
+ AnchorID: parseUUID("00000000-0000-0000-0000-000000000001"),
+ AuthorID: parseUUID(testUserID),
+ })
+ if err != nil {
+ t.Fatalf("CountNewCommentsSince: %v", err)
+ }
+ return n
+ }
+ if got := countSince(); got != 2 {
+ t.Fatalf("new comments before delete = %d, want 2", got)
+ }
+
+ if _, err := testHandler.deleteComment(ctx, parseUUID(root), parseUUID(testWorkspaceID)); err != nil {
+ t.Fatalf("deleteComment: %v", err)
+ }
+ if got := countSince(); got != 1 {
+ t.Fatalf("new comments after delete = %d, want the tombstone excluded", got)
+ }
+ reconcilable, err := testHandler.Queries.ListReconcilableCommentsForIssueSince(ctx, db.ListReconcilableCommentsForIssueSinceParams{
+ IssueID: parseUUID(issueID),
+ PlannedCommentIds: []pgtype.UUID{parseUUID(root)},
+ Since: pgtype.Timestamptz{Time: since, Valid: true},
+ })
+ if err != nil {
+ t.Fatalf("ListReconcilableCommentsForIssueSince: %v", err)
+ }
+ for _, comment := range reconcilable {
+ if comment.ID == parseUUID(root) {
+ t.Fatal("completion reconciliation would replay the tombstone")
+ }
+ }
+}
+
+// A reply under a deleted agent comment continues the thread: it wakes neither
+// the deleted comment's author nor, as a fallback, the issue assignee. The web
+// reply box posts under the thread root, so this is every later reply once an
+// agent-authored root with replies is deleted.
+func TestReplyUnderDeletedAgentCommentWakesNoOne(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ authorID := createHandlerTestAgent(t, "Deleted Comment Author", nil)
+ assigneeID := createHandlerTestAgent(t, "Issue Assignee", nil)
+ issueID := dbfx.Issue(t, "reply under deleted agent comment", testutil.Cols{
+ "assignee_type": "agent", "assignee_id": assigneeID,
+ })
+ root := dbfx.Comment(t, issueID, "I am handling this", testutil.Cols{"author_type": "agent", "author_id": authorID})
+ dbfx.Comment(t, issueID, "earlier reply", testutil.Cols{"parent_id": root})
+ if _, err := testHandler.deleteComment(ctx, parseUUID(root), parseUUID(testWorkspaceID)); err != nil {
+ t.Fatalf("deleteComment: %v", err)
+ }
+
+ body := map[string]any{"content": "please follow up", "parent_id": root}
+ requirePreviewAgents(t, previewCommentTriggersForTest(t, issueID, body))
+ postCommentForTriggerPreviewTest(t, issueID, body)
+ tasks, err := testHandler.Queries.ListTasksByIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(tasks) != 0 {
+ t.Fatalf("reply under a deleted comment started %d runs, want none: %+v", len(tasks), tasks)
+ }
+}
+
+// A comment deleted after capture reads as removed, not as emptied; one that
+// was already a tombstone when captured is not a change at all.
+func TestSourceContextThreadChangesTreatTombstonesAsAbsent(t *testing.T) {
+ root := "00000000-0000-0000-0000-00000000000a"
+ node := func(id string, deleted bool) service.SourceContextCommentSnapshot {
+ parent := root
+ comment := service.SourceContextCommentSnapshot{ID: id, ParentID: &parent, Type: "comment", Content: "body " + id, Deleted: deleted}
+ if deleted {
+ comment.Content = ""
+ }
+ if id == root {
+ comment.ParentID = nil
+ }
+ return comment
+ }
+ snapshot := func(nodes ...service.SourceContextCommentSnapshot) service.SourceContextSnapshot {
+ return service.SourceContextSnapshot{AnchorCommentID: root, CommentThread: nodes}
+ }
+
+ deletedAfterCapture := sourceContextThreadChangeDetails(
+ snapshot(node(root, false), node("b", false), node("c", false)),
+ snapshot(node(root, false), node("b", true), node("c", false)),
+ )
+ if len(deletedAfterCapture.RemovedCommentIDs) != 1 || deletedAfterCapture.RemovedCommentIDs[0] != "b" || len(deletedAfterCapture.ChangedCommentIDs) != 0 {
+ t.Fatalf("changes = %+v, want b removed and nothing edited", deletedAfterCapture)
+ }
+
+ alreadyDeleted := sourceContextThreadChangeDetails(
+ snapshot(node(root, false), node("b", true), node("c", false)),
+ snapshot(node(root, false), node("b", true), node("c", false)),
+ )
+ if len(alreadyDeleted.Reasons) != 0 {
+ t.Fatalf("changes = %+v, want an unchanged thread", alreadyDeleted)
+ }
+}
+
+func TestPublicPluginCommentExposesTombstone(t *testing.T) {
+ live := publicPluginComment(db.Comment{Content: "hello"})
+ if live.DeletedAt != "" {
+ t.Fatalf("live comment deleted_at = %q, want empty", live.DeletedAt)
+ }
+ deletedAt := time.Date(2026, time.September, 11, 8, 0, 0, 0, time.UTC)
+ tombstone := publicPluginComment(db.Comment{DeletedAt: pgtype.Timestamptz{Time: deletedAt, Valid: true}})
+ if tombstone.DeletedAt == "" || tombstone.Content != "" {
+ t.Fatalf("tombstone = %+v, want deleted_at set and empty content", tombstone)
+ }
+}
+
+// recordingStorage records which stored objects a handler cleaned up.
+type recordingStorage struct {
+ mockStorage
+ mu sync.Mutex
+ deleted []string
+}
+
+func (s *recordingStorage) DeleteKeys(_ context.Context, keys []string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.deleted = append(s.deleted, keys...)
+}
+
+// A write to a comment's children that waited on the comment while a delete
+// tombstoned it must not land on the tombstone. The holder transaction stands
+// in for a delete that already holds the comment lock: the write blocks on
+// LockLiveComment, the tombstone commits, and the write must be refused.
+func TestCommentChildWritesWaitingOnDeleteDoNotLandOnTombstone(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ storage := &recordingStorage{}
+ h := *testHandler
+ h.Storage = storage
+
+ tests := []struct {
+ name string
+ run func(commentID, issueID string) *httptest.ResponseRecorder
+ wantCode int
+ leftovers string
+ }{
+ {
+ name: "reaction",
+ run: func(commentID, _ string) *httptest.ResponseRecorder {
+ w := httptest.NewRecorder()
+ h.AddReaction(w, withURLParam(newRequest(http.MethodPost, "/api/comments/"+commentID+"/reactions", map[string]any{
+ "emoji": "👍",
+ }), "commentId", commentID))
+ return w
+ },
+ wantCode: http.StatusNotFound,
+ leftovers: `SELECT count(*) FROM comment_reaction WHERE comment_id = $1`,
+ },
+ {
+ name: "attachment upload",
+ run: func(commentID, issueID string) *httptest.ResponseRecorder {
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+ part, _ := writer.CreateFormFile("file", "late.txt")
+ part.Write([]byte("late"))
+ writer.WriteField("issue_id", issueID)
+ writer.WriteField("comment_id", commentID)
+ writer.Close()
+ req := httptest.NewRequest(http.MethodPost, "/api/upload-file", &body)
+ req.Header.Set("Content-Type", writer.FormDataContentType())
+ req.Header.Set("X-User-ID", testUserID)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+ w := httptest.NewRecorder()
+ h.UploadFile(w, req)
+ return w
+ },
+ wantCode: http.StatusForbidden,
+ leftovers: `SELECT count(*) FROM attachment WHERE comment_id = $1`,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ ctx := context.Background()
+ issueID := dbfx.Issue(t, "child write races delete "+tt.name)
+ target := dbfx.Comment(t, issueID, "about to be deleted")
+ dbfx.Comment(t, issueID, "reply keeps it as a tombstone", testutil.Cols{"parent_id": target})
+
+ holder, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin holder: %v", err)
+ }
+ defer holder.Rollback(ctx)
+ if _, err := holder.Exec(ctx, `SELECT id FROM comment WHERE id = $1 FOR UPDATE`, target); err != nil {
+ t.Fatalf("lock comment: %v", err)
+ }
+
+ var got *httptest.ResponseRecorder
+ done := make(chan error, 1)
+ go func() {
+ got = tt.run(target, issueID)
+ done <- nil
+ }()
+ waitForCommentMutationLock(t, "LockLiveComment", done)
+
+ if _, err := holder.Exec(ctx, `UPDATE comment SET content = '', deleted_at = now() WHERE id = $1`, target); err != nil {
+ t.Fatalf("tombstone comment: %v", err)
+ }
+ if err := holder.Commit(ctx); err != nil {
+ t.Fatalf("commit holder: %v", err)
+ }
+ <-done
+
+ if got.Code != tt.wantCode {
+ t.Fatalf("%s after delete = %d, want %d: %s", tt.name, got.Code, tt.wantCode, got.Body.String())
+ }
+ if n := dbfx.Count(t, tt.leftovers, target); n != 0 {
+ t.Fatalf("%s landed on the tombstone (%d rows)", tt.name, n)
+ }
+ })
+ }
+ if len(storage.deleted) != 1 {
+ t.Fatalf("refused upload cleaned up %v, want its one stored object", storage.deleted)
+ }
+}
+
+func TestRemoveReactionOnTombstoneIsNotFound(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ issueID := dbfx.Issue(t, "remove reaction on tombstone")
+ target := dbfx.Comment(t, issueID, "deleted", testutil.Cols{"deleted_at": testutil.Raw("now()"), "content": ""})
+ testutil.Call(t, testHandler.RemoveReaction, withURLParam(newRequest(http.MethodDelete, "/api/comments/"+target+"/reactions", map[string]any{
+ "emoji": "👍",
+ }), "commentId", target)).Want(http.StatusNotFound)
+}
diff --git a/server/internal/handler/comment_touch_issue_test.go b/server/internal/handler/comment_touch_issue_test.go
index 14f561ca8b..35628f083e 100644
--- a/server/internal/handler/comment_touch_issue_test.go
+++ b/server/internal/handler/comment_touch_issue_test.go
@@ -181,12 +181,9 @@ func TestUpdateAndDeleteCommentBumpIssueActivity(t *testing.T) {
}
setBase()
- deleted, err := testHandler.Queries.DeleteComment(ctx, db.DeleteCommentParams{
- ID: comment.ID,
- WorkspaceID: parseUUID(testWorkspaceID),
- })
- if err != nil || !deleted.Changed {
- t.Fatalf("DeleteComment = (%+v, %v), want changed result", deleted, err)
+ deleted, err := testHandler.deleteComment(ctx, comment.ID, parseUUID(testWorkspaceID))
+ if err != nil || len(deleted.RemovedIDs) != 1 {
+ t.Fatalf("deleteComment = (%+v, %v), want the comment removed", deleted, err)
}
if deleted.IssueRevision == 0 {
t.Fatal("comment delete omitted the advanced issue revision")
@@ -293,8 +290,8 @@ func TestUpdateCommentLosingRaceDoesNotTouchIssue(t *testing.T) {
}
// A delete that loses after waiting for the same comment row likewise must not
-// mutate the issue. The issue touch now depends on DELETE ... RETURNING, so an
-// empty delete result is an empty activity source.
+// mutate the issue. The issue touch runs in the delete transaction only after
+// the comment lock was won, so a lost race rolls back without touching it.
func TestDeleteCommentLosingRaceDoesNotTouchIssue(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
@@ -315,28 +312,19 @@ func TestDeleteCommentLosingRaceDoesNotTouchIssue(t *testing.T) {
t.Fatalf("lock comment: %v", err)
}
- type deleteResult struct {
- row db.DeleteCommentRow
- err error
- }
- done := make(chan deleteResult, 1)
- go func() {
- row, deleteErr := testHandler.Queries.DeleteComment(context.Background(), db.DeleteCommentParams{
- ID: parseUUID(commentID),
- WorkspaceID: parseUUID(testWorkspaceID),
- })
- done <- deleteResult{row: row, err: deleteErr}
- }()
lockDone := make(chan error, 1)
go func() {
- result := <-done
- if result.err == nil && result.row.Changed {
+ _, deleteErr := testHandler.deleteComment(context.Background(), parseUUID(commentID), parseUUID(testWorkspaceID))
+ if deleteErr == nil {
lockDone <- errors.New("losing delete unexpectedly changed a row")
return
}
- lockDone <- result.err
+ if errors.Is(deleteErr, pgx.ErrNoRows) {
+ deleteErr = nil
+ }
+ lockDone <- deleteErr
}()
- waitForCommentMutationLock(t, "DeleteComment", lockDone)
+ waitForCommentMutationLock(t, "LockCommentForDelete", lockDone)
if _, err := holder.Exec(ctx, `DELETE FROM comment WHERE id = $1`, commentID); err != nil {
t.Fatalf("commit winning delete: %v", err)
@@ -383,19 +371,16 @@ func TestCommentMutationsFollowIssueTeardownLockOrder(t *testing.T) {
},
{
name: "delete",
- queryName: "DeleteComment",
+ queryName: "LockCommentForDelete",
mutate: func(ctx context.Context, commentID string) error {
- result, err := testHandler.Queries.DeleteComment(ctx, db.DeleteCommentParams{
- ID: parseUUID(commentID),
- WorkspaceID: parseUUID(testWorkspaceID),
- })
+ _, err := testHandler.deleteComment(ctx, parseUUID(commentID), parseUUID(testWorkspaceID))
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil
+ }
if err != nil {
return err
}
- if result.Changed {
- return errors.New("comment delete changed a row after its issue was deleted")
- }
- return nil
+ return errors.New("comment delete changed a row after its issue was deleted")
},
},
}
@@ -467,7 +452,7 @@ func waitForCommentMutationLock(t *testing.T, queryName string, done <-chan erro
AND wait_event_type = 'Lock'
AND query LIKE '%' || $1 || '%'
)
- `, "-- name: "+queryName+" :one").Scan(&waiting); err != nil {
+ `, "-- name: "+queryName+" :").Scan(&waiting); err != nil {
t.Fatalf("observe blocked %s: %v", queryName, err)
}
if waiting {
diff --git a/server/internal/handler/config.go b/server/internal/handler/config.go
index b5b210b5c8..8ec6468190 100644
--- a/server/internal/handler/config.go
+++ b/server/internal/handler/config.go
@@ -81,6 +81,13 @@ type AppConfig struct {
// must fail closed when this declaration is absent.
AgentConversationStartersSupported bool `json:"agent_conversation_starters_supported"`
+ // CommentDeleteKeepRepliesSupported tells clients that deleting a comment
+ // removes only that comment and keeps its replies (#8296), and that
+ // DELETE /api/comments/{id}/keep-replies exists. Older servers deleted the
+ // replies too and omit this, so clients must promise nothing about
+ // replies unless it is declared.
+ CommentDeleteKeepRepliesSupported bool `json:"comment_delete_keep_replies_supported"`
+
// ServerVersion is the running API build version, so self-hosted
// operators can confirm what's deployed and include it in bug reports.
// Only emitted on self-hosted deployments — omitted on the managed cloud,
@@ -99,6 +106,7 @@ func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {
// running, the save gate is running with it.
LocalWorktreeSupported: true,
AgentConversationStartersSupported: true,
+ CommentDeleteKeepRepliesSupported: true,
AllowSignup: os.Getenv("ALLOW_SIGNUP") != "false",
GoogleClientID: os.Getenv("GOOGLE_CLIENT_ID"),
WorkspaceCreationDisabled: os.Getenv("DISABLE_WORKSPACE_CREATION") == "true",
diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.go
index 7748cc1fe1..a158289971 100644
--- a/server/internal/handler/config_test.go
+++ b/server/internal/handler/config_test.go
@@ -557,3 +557,22 @@ func TestGetConfigDeclaresAgentConversationStartersSupport(t *testing.T) {
t.Fatal("agent_conversation_starters_supported missing from the JSON body")
}
}
+
+// Web/Desktop, mobile and the CLI promise that a delete keeps the replies only
+// when the server declares it (#8296). Older servers omit the field and delete
+// the replies too, so this build must advertise the contract explicitly.
+func TestGetConfigDeclaresCommentDeleteKeepsReplies(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/api/config", nil)
+ w := httptest.NewRecorder()
+ testHandler.GetConfig(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("GetConfig: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var raw map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &raw); err != nil {
+ t.Fatalf("decode raw config: %v", err)
+ }
+ if raw["comment_delete_keep_replies_supported"] != true {
+ t.Fatalf("comment_delete_keep_replies_supported = %v, want true", raw["comment_delete_keep_replies_supported"])
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index bdf4c8ed10..e59ab18db0 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1633,10 +1633,11 @@ func parseRuntimeConnectedAppsForClaim(raw []byte, taskID pgtype.UUID) []runtime
}
// repairStaleCommentPlanIfNeeded handles the edit/delete race where a claimed
-// task's trigger_comment_id was cleared but coalesced_comment_ids survive: such
-// a task must never be dispatched as a generic assignment — its user-scoped MCP
-// overlay still belongs to the deleted author, and the prompt would read issue
-// history exposing that stale user's capabilities. When it applies, the task is
+// task's trigger was deleted (trigger_comment_id cleared, or pointing at a
+// tombstone) but coalesced_comment_ids survive: such a task must never be
+// dispatched as a generic assignment — its user-scoped MCP overlay still
+// belongs to the deleted author, and the prompt would read issue history
+// exposing that stale user's capabilities. When it applies, the task is
// cancelled and its surviving comments are replayed through normal routing
// (which recomputes originator + connected-app context).
//
@@ -1646,9 +1647,17 @@ func parseRuntimeConnectedAppsForClaim(raw []byte, taskID pgtype.UUID) []runtime
// proceed with a normal claim. Shared by the per-runtime and batch claim
// handlers so the batch path can't silently drop surviving comments (MUL-4257).
func (h *Handler) repairStaleCommentPlanIfNeeded(ctx context.Context, task *db.AgentTaskQueue, runtimeWorkspaceID string) (handled bool, failure *claimBuildFailure) {
- if task.TriggerCommentID.Valid || len(task.CoalescedCommentIds) == 0 {
+ if len(task.CoalescedCommentIds) == 0 {
return false, nil
}
+ if task.TriggerCommentID.Valid {
+ // A trigger deleted while it had replies stays as a tombstone instead of
+ // clearing trigger_comment_id (#8296); repair it like a removed one.
+ trigger, err := h.Queries.GetComment(ctx, task.TriggerCommentID)
+ if err != nil || !trigger.DeletedAt.Valid {
+ return false, nil
+ }
+ }
if !task.IssueID.Valid {
return true, &claimBuildFailure{outcome: "error_stale_comment_plan", status: http.StatusInternalServerError, message: "comment task has no issue"}
}
@@ -2629,10 +2638,11 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
// comment UUID can never pull another workspace's comment text into
// this agent's prompt. The task's issue workspace is asserted equal
// to runtime.WorkspaceID below, so this is the right tenant (MUL-4252).
+ // A deleted trigger's tombstone is treated like a removed row.
if comment, err := h.Queries.GetCommentInWorkspace(r.Context(), db.GetCommentInWorkspaceParams{
ID: effectiveTriggerUUID,
WorkspaceID: runtime.WorkspaceID,
- }); err == nil {
+ }); err == nil && !comment.DeletedAt.Valid {
resp.TriggerCommentContent = comment.Content
resp.TriggerThreadID = uuidToString(comment.ID)
if comment.ParentID.Valid {
@@ -3497,7 +3507,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
outcome = "no_task"
return
}
- if !task.TriggerCommentID.Valid && len(task.CoalescedCommentIds) > 0 {
+ if len(task.CoalescedCommentIds) > 0 {
handled, failure := h.repairStaleCommentPlanIfNeeded(r.Context(), task, runtimeWorkspaceID)
if handled {
if failure != nil {
@@ -4320,7 +4330,9 @@ func (h *Handler) buildCoalescedCommentData(ctx context.Context, workspaceID pgt
ID: id,
WorkspaceID: workspaceID,
})
- if err != nil {
+ // A tombstone (deleted while it still had replies) is as missing as a
+ // removed row: there is no body left to deliver.
+ if err != nil || comment.DeletedAt.Valid {
continue
}
data := CoalescedCommentData{
diff --git a/server/internal/handler/daemon_comment_delivery_test.go b/server/internal/handler/daemon_comment_delivery_test.go
index e351a6fcd2..7a7eb6cf43 100644
--- a/server/internal/handler/daemon_comment_delivery_test.go
+++ b/server/internal/handler/daemon_comment_delivery_test.go
@@ -12,7 +12,6 @@ import (
"time"
"github.com/jackc/pgx/v5"
- "github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/multica-ai/multica/server/internal/testutil"
@@ -112,62 +111,36 @@ type failNthBegin struct {
calls int
}
-type failDeleteCommentDB struct {
- delegate db.DBTX
-}
-
-type zeroDeleteCommentDB struct {
- delegate db.DBTX
-}
-
-type deleteCommentResultRow struct {
- changed bool
- err error
-}
-
-func (r deleteCommentResultRow) Scan(dest ...interface{}) error {
- if r.err != nil {
- return r.err
- }
- *(dest[0].(*bool)) = r.changed
- *(dest[1].(*int64)) = 0
- return nil
+// lockCommentForDeleteTxStarter begins real transactions whose
+// LockCommentForDelete statement answers with lockErr instead: an error
+// simulates a storage failure, pgx.ErrNoRows a concurrent delete that won.
+type lockCommentForDeleteTxStarter struct {
+ delegate *pgxpool.Pool
+ lockErr error
}
-func (f *failDeleteCommentDB) Exec(ctx context.Context, query string, args ...interface{}) (pgconn.CommandTag, error) {
- if strings.Contains(query, "-- name: DeleteComment") {
- return pgconn.CommandTag{}, errors.New("injected comment deletion failure")
- }
- return f.delegate.Exec(ctx, query, args...)
+type lockCommentForDeleteTx struct {
+ pgx.Tx
+ lockErr error
}
-func (f *failDeleteCommentDB) Query(ctx context.Context, query string, args ...interface{}) (pgx.Rows, error) {
- return f.delegate.Query(ctx, query, args...)
-}
+type errorRow struct{ err error }
-func (f *failDeleteCommentDB) QueryRow(ctx context.Context, query string, args ...interface{}) pgx.Row {
- if strings.Contains(query, "-- name: DeleteComment") {
- return deleteCommentResultRow{err: errors.New("injected comment deletion failure")}
- }
- return f.delegate.QueryRow(ctx, query, args...)
-}
+func (r errorRow) Scan(...interface{}) error { return r.err }
-func (z *zeroDeleteCommentDB) Exec(ctx context.Context, query string, args ...interface{}) (pgconn.CommandTag, error) {
- if strings.Contains(query, "-- name: DeleteComment") {
- return pgconn.NewCommandTag("DELETE 0"), nil
+func (s *lockCommentForDeleteTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.delegate.Begin(ctx)
+ if err != nil {
+ return nil, err
}
- return z.delegate.Exec(ctx, query, args...)
+ return lockCommentForDeleteTx{Tx: tx, lockErr: s.lockErr}, nil
}
-func (z *zeroDeleteCommentDB) Query(ctx context.Context, query string, args ...interface{}) (pgx.Rows, error) {
- return z.delegate.Query(ctx, query, args...)
-}
-
-func (z *zeroDeleteCommentDB) QueryRow(ctx context.Context, query string, args ...interface{}) pgx.Row {
- if strings.Contains(query, "-- name: DeleteComment") {
- return deleteCommentResultRow{changed: false}
+func (t lockCommentForDeleteTx) QueryRow(ctx context.Context, query string, args ...interface{}) pgx.Row {
+ if strings.Contains(query, "-- name: LockCommentForDelete") {
+ return errorRow{err: t.lockErr}
}
- return z.delegate.QueryRow(ctx, query, args...)
+ return t.Tx.QueryRow(ctx, query, args...)
}
func (f *failNthBegin) Begin(ctx context.Context) (pgx.Tx, error) {
@@ -359,16 +332,35 @@ func TestClaimTaskByRuntime_CoalescedDeliveryMatrix(t *testing.T) {
})
}
+// deletedTriggerStates are the two shapes a deleted trigger leaves behind: a
+// removed row (trigger_comment_id cleared by ON DELETE SET NULL), or a
+// tombstone for a trigger that still had replies (#8296), which keeps the id.
+var deletedTriggerStates = []struct {
+ name string
+ sql string
+}{
+ {name: "removed", sql: `DELETE FROM comment WHERE id = $1`},
+ {name: "tombstoned", sql: `UPDATE comment SET content = '', deleted_at = now() WHERE id = $1`},
+}
+
func TestClaimTaskByRuntime_CoalescedOnlyStaleTaskDoesNotReuseDeletedTriggerCapabilities(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
+ for _, state := range deletedTriggerStates {
+ t.Run(state.name, func(t *testing.T) {
+ testClaimRepairsDeletedTrigger(t, state.sql)
+ })
+ }
+}
+
+func testClaimRepairsDeletedTrigger(t *testing.T, deleteTriggerSQL string) {
fixture := createCommentDeliveryFixture(t, "Deleted trigger stale claim")
makeCommentDeliverySingleThread(t, fixture)
if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
t.Fatalf("assign stale-claim issue: %v", err)
}
- if _, err := testPool.Exec(context.Background(), `DELETE FROM comment WHERE id = $1`, fixture.commentID[2]); err != nil {
+ if _, err := testPool.Exec(context.Background(), deleteTriggerSQL, fixture.commentID[2]); err != nil {
t.Fatalf("delete trigger directly: %v", err)
}
@@ -506,7 +498,7 @@ func TestDeleteComment_FailureRestoresCancelledCompleteBatch(t *testing.T) {
}
failingHandler := *testHandler
- failingHandler.Queries = db.New(&failDeleteCommentDB{delegate: testPool})
+ failingHandler.TxStarter = &lockCommentForDeleteTxStarter{delegate: testPool, lockErr: errors.New("injected comment deletion failure")}
w := httptest.NewRecorder()
req := newRequest(http.MethodDelete, "/api/comments/"+fixture.commentID[2], nil)
req = withURLParam(req, "commentId", fixture.commentID[2])
@@ -536,7 +528,7 @@ func TestDeleteComment_ConcurrentNoOpIsReportedAndRestoresCancelledBatch(t *test
}
zeroHandler := *testHandler
- zeroHandler.Queries = db.New(&zeroDeleteCommentDB{delegate: testPool})
+ zeroHandler.TxStarter = &lockCommentForDeleteTxStarter{delegate: testPool, lockErr: pgx.ErrNoRows}
w := httptest.NewRecorder()
req := newRequest(http.MethodDelete, "/api/comments/"+fixture.commentID[2], nil)
req = withURLParam(req, "commentId", fixture.commentID[2])
@@ -804,6 +796,14 @@ func TestRerunIssue_PromotesNewestSurvivorAfterSourceTriggerDeleted(t *testing.T
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
+ for _, state := range deletedTriggerStates {
+ t.Run(state.name, func(t *testing.T) {
+ testRerunPromotesSurvivorAfterTriggerDeleted(t, state.sql)
+ })
+ }
+}
+
+func testRerunPromotesSurvivorAfterTriggerDeleted(t *testing.T, deleteTriggerSQL string) {
ctx := context.Background()
fixture := createCommentDeliveryFixture(t, "Deleted trigger manual rerun")
if _, err := testPool.Exec(ctx, `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
@@ -816,7 +816,7 @@ func TestRerunIssue_PromotesNewestSurvivorAfterSourceTriggerDeleted(t *testing.T
`, fixture.taskID); err != nil {
t.Fatalf("complete deleted-trigger rerun source: %v", err)
}
- if _, err := testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, fixture.commentID[2]); err != nil {
+ if _, err := testPool.Exec(ctx, deleteTriggerSQL, fixture.commentID[2]); err != nil {
t.Fatalf("delete rerun source trigger: %v", err)
}
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index 80ad685251..be76c83c7d 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -2,6 +2,7 @@ package handler
import (
"context"
+ "errors"
"fmt"
"io"
"log/slog"
@@ -15,6 +16,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/storage"
"github.com/multica-ai/multica/server/internal/util"
@@ -481,7 +483,8 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
return
}
comment, err := h.Queries.GetComment(r.Context(), commentUUID)
- if err != nil || uuidToString(comment.WorkspaceID) != workspaceID {
+ // A deleted comment's tombstone takes no attachments.
+ if err != nil || uuidToString(comment.WorkspaceID) != workspaceID || comment.DeletedAt.Valid {
writeError(w, http.StatusForbidden, "invalid comment_id")
return
}
@@ -561,7 +564,24 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
}
params.Url = link
- att, err := h.Queries.CreateAttachment(r.Context(), params)
+ var att db.CreateAttachmentRow
+ if params.CommentID.Valid {
+ // A comment attachment is written under the comment's lock, so a
+ // delete that commits while the object uploaded cannot leave it on
+ // a tombstone. A refused upload takes its stored object with it.
+ err = h.withLiveCommentLock(r.Context(), params.CommentID, params.WorkspaceID, func(qtx *db.Queries) error {
+ var createErr error
+ att, createErr = qtx.CreateAttachment(r.Context(), params)
+ return createErr
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ h.deleteS3Objects(r.Context(), []string{link})
+ writeError(w, http.StatusForbidden, "invalid comment_id")
+ return
+ }
+ } else {
+ att, err = h.Queries.CreateAttachment(r.Context(), params)
+ }
if err != nil {
slog.Error("failed to create attachment record", "error", err)
// S3 upload succeeded but DB record failed — still return the link
@@ -1435,10 +1455,19 @@ func (h *Handler) DeleteAttachment(w http.ResponseWriter, r *http.Request) {
return
}
- deleted, err := h.Queries.DeleteAttachment(r.Context(), db.DeleteAttachmentParams{
- ID: att.ID,
- WorkspaceID: att.WorkspaceID,
+ var deleted db.DeleteAttachmentRow
+ deleteParams := db.DeleteAttachmentParams{ID: att.ID, WorkspaceID: att.WorkspaceID}
+ err = h.withAttachmentOwnerLock(r.Context(), att, func(qtx *db.Queries) error {
+ var deleteErr error
+ deleted, deleteErr = qtx.DeleteAttachment(r.Context(), deleteParams)
+ return deleteErr
})
+ if errors.Is(err, pgx.ErrNoRows) {
+ // The attachment is gone — with its comment, with its issue, or on its
+ // own — while this waited for the owner lock.
+ writeError(w, http.StatusNotFound, "attachment not found")
+ return
+ }
if err != nil {
slog.Error("failed to delete attachment", "error", err)
writeError(w, http.StatusInternalServerError, "failed to delete attachment")
@@ -1484,16 +1513,85 @@ func (h *Handler) linkAttachmentsByIssueIDs(ctx context.Context, issueID, worksp
})
}
-// linkAttachmentsByIDs links the given attachment IDs to a comment.
-// Only updates attachments that belong to the same issue and have no comment_id yet.
-func (h *Handler) linkAttachmentsByIDs(ctx context.Context, commentID, issueID pgtype.UUID, ids []pgtype.UUID) {
- if err := h.Queries.LinkAttachmentsToComment(ctx, db.LinkAttachmentsToCommentParams{
- CommentID: commentID,
- IssueID: issueID,
- Column3: ids,
- }); err != nil {
- slog.Error("failed to link attachments to comment", "error", err)
+// attachmentOwnerLockAttempts bounds the re-read below. An attachment gains an
+// owner once, when the issue or comment it was uploaded for links it, so one
+// retry is enough in practice; the bound is what keeps a pathological
+// interleaving from looping.
+const attachmentOwnerLockAttempts = 3
+
+// withAttachmentOwnerLock runs write in a transaction that locks the
+// attachment's owners first — the issue, then the comment when it has one —
+// which is the issue -> comment -> child order LockIssueForDelete,
+// UpdateComment, LockLiveComment and CreateComment all take. Locking the
+// attachment row and then touching its issue is the opposite order, and closes
+// a deadlock cycle with issue teardown: teardown holds the issue and reaches
+// the same attachment through the issue_id cascade.
+//
+// The row is re-read under those locks, so a link that committed while this
+// waited is seen before the write; an attachment that gained an owner is
+// retried with that owner locked. Returns pgx.ErrNoRows when the attachment,
+// or the comment owning it, is gone.
+func (h *Handler) withAttachmentOwnerLock(ctx context.Context, att db.Attachment, write func(*db.Queries) error) error {
+ for attempt := 0; ; attempt++ {
+ fresh, err := h.attachmentOwnerLockAttempt(ctx, att, write)
+ if !errors.Is(err, errAttachmentOwnerChanged) {
+ return err
+ }
+ if attempt+1 >= attachmentOwnerLockAttempts {
+ return errors.New("attachment owner kept changing under the lock")
+ }
+ att = fresh
+ }
+}
+
+// errAttachmentOwnerChanged reports that the attachment gained or changed an
+// owner while the transaction was waiting, so the locks it took are the wrong
+// ones and the attempt must be retried against the new owner.
+var errAttachmentOwnerChanged = errors.New("attachment owner changed")
+
+func (h *Handler) attachmentOwnerLockAttempt(ctx context.Context, att db.Attachment, write func(*db.Queries) error) (db.Attachment, error) {
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ return db.Attachment{}, err
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+ if att.IssueID.Valid {
+ // A missing issue is not an error here: its cascade took the attachment
+ // with it, which the re-read below reports as pgx.ErrNoRows.
+ if _, err := qtx.LockIssueForAttachmentWrite(ctx, db.LockIssueForAttachmentWriteParams{
+ ID: att.IssueID,
+ WorkspaceID: att.WorkspaceID,
+ }); err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ return db.Attachment{}, err
+ }
+ }
+ if att.CommentID.Valid {
+ if _, err := qtx.LockLiveComment(ctx, db.LockLiveCommentParams{
+ ID: att.CommentID,
+ WorkspaceID: att.WorkspaceID,
+ }); err != nil {
+ return db.Attachment{}, err
+ }
+ }
+ var fresh db.Attachment
+ if att.IssueID.Valid || att.CommentID.Valid {
+ fresh, err = qtx.GetAttachment(ctx, db.GetAttachmentParams{ID: att.ID, WorkspaceID: att.WorkspaceID})
+ } else {
+ // Nothing to lock above: take the row itself so it cannot gain an owner
+ // between this read and the write.
+ fresh, err = qtx.LockAttachmentRow(ctx, db.LockAttachmentRowParams{ID: att.ID, WorkspaceID: att.WorkspaceID})
+ }
+ if err != nil {
+ return db.Attachment{}, err
+ }
+ if fresh.IssueID != att.IssueID || fresh.CommentID != att.CommentID {
+ return fresh, errAttachmentOwnerChanged
+ }
+ if err := write(qtx); err != nil {
+ return db.Attachment{}, err
}
+ return fresh, tx.Commit(ctx)
}
// deleteS3Object removes a single file from S3 by its CDN URL.
diff --git a/server/internal/handler/plugin_action.go b/server/internal/handler/plugin_action.go
index b920eaaab7..5f937f5369 100644
--- a/server/internal/handler/plugin_action.go
+++ b/server/internal/handler/plugin_action.go
@@ -506,7 +506,7 @@ func (h *Handler) ListPluginComments(w http.ResponseWriter, r *http.Request) {
}
func publicPluginComment(comment db.Comment) publicapiv1.Comment {
- return publicapiv1.Comment{
+ out := publicapiv1.Comment{
ID: uuidToString(comment.ID),
AuthorType: comment.AuthorType,
AuthorID: uuidToString(comment.AuthorID),
@@ -515,6 +515,10 @@ func publicPluginComment(comment db.Comment) publicapiv1.Comment {
ParentID: uuidToString(comment.ParentID),
CreatedAt: comment.CreatedAt.Time.UTC().Format(timeFormatRFC3339),
}
+ if comment.DeletedAt.Valid {
+ out.DeletedAt = comment.DeletedAt.Time.UTC().Format(timeFormatRFC3339)
+ }
+ return out
}
// CreatePluginComment — POST /v1/issues/{issue_ref}/comments
diff --git a/server/internal/handler/reaction.go b/server/internal/handler/reaction.go
index a40834e71c..f01dde7f58 100644
--- a/server/internal/handler/reaction.go
+++ b/server/internal/handler/reaction.go
@@ -2,10 +2,12 @@ package handler
import (
"encoding/json"
+ "errors"
"log/slog"
"net/http"
"github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/logger"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -69,7 +71,8 @@ func (h *Handler) AddReaction(w http.ResponseWriter, r *http.Request) {
ID: commentUUID,
WorkspaceID: wsUUID,
})
- if err != nil {
+ // A deleted comment's tombstone takes no reactions.
+ if err != nil || comment.DeletedAt.Valid {
writeError(w, http.StatusNotFound, "comment not found")
return
}
@@ -88,13 +91,23 @@ func (h *Handler) AddReaction(w http.ResponseWriter, r *http.Request) {
actorType, actorID := h.resolveActor(r, userID, workspaceID)
- reaction, err := h.Queries.AddReaction(r.Context(), db.AddReactionParams{
- CommentID: comment.ID,
- WorkspaceID: wsUUID,
- ActorType: actorType,
- ActorID: parseUUID(actorID),
- Emoji: req.Emoji,
+ var reaction db.AddReactionRow
+ err = h.withLiveCommentLock(r.Context(), comment.ID, wsUUID, func(qtx *db.Queries) error {
+ var addErr error
+ reaction, addErr = qtx.AddReaction(r.Context(), db.AddReactionParams{
+ CommentID: comment.ID,
+ WorkspaceID: wsUUID,
+ ActorType: actorType,
+ ActorID: parseUUID(actorID),
+ Emoji: req.Emoji,
+ })
+ return addErr
})
+ if errors.Is(err, pgx.ErrNoRows) {
+ // Deleted after the check above.
+ writeError(w, http.StatusNotFound, "comment not found")
+ return
+ }
if err != nil {
slog.Warn("add reaction failed", append(logger.RequestAttrs(r), "error", err, "comment_id", commentId)...)
writeError(w, http.StatusInternalServerError, "failed to add reaction")
@@ -147,7 +160,8 @@ func (h *Handler) RemoveReaction(w http.ResponseWriter, r *http.Request) {
ID: commentUUID,
WorkspaceID: wsUUID,
})
- if err != nil {
+ // A deleted comment's tombstone has no reactions left to remove.
+ if err != nil || comment.DeletedAt.Valid {
writeError(w, http.StatusNotFound, "comment not found")
return
}
@@ -166,12 +180,23 @@ func (h *Handler) RemoveReaction(w http.ResponseWriter, r *http.Request) {
actorType, actorID := h.resolveActor(r, userID, workspaceID)
- removed, err := h.Queries.RemoveReaction(r.Context(), db.RemoveReactionParams{
- CommentID: comment.ID,
- ActorType: actorType,
- ActorID: parseUUID(actorID),
- Emoji: req.Emoji,
+ // Owner first, like every comment mutation: removing the reaction row and
+ // then bumping the comment would invert the delete transaction's order.
+ var removed db.RemoveReactionRow
+ err = h.withLiveCommentLock(r.Context(), comment.ID, wsUUID, func(qtx *db.Queries) error {
+ var removeErr error
+ removed, removeErr = qtx.RemoveReaction(r.Context(), db.RemoveReactionParams{
+ CommentID: comment.ID,
+ ActorType: actorType,
+ ActorID: parseUUID(actorID),
+ Emoji: req.Emoji,
+ })
+ return removeErr
})
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "comment not found")
+ return
+ }
if err != nil {
slog.Warn("remove reaction failed", append(logger.RequestAttrs(r), "error", err, "comment_id", commentId)...)
writeError(w, http.StatusInternalServerError, "failed to remove reaction")
diff --git a/server/internal/handler/source_context.go b/server/internal/handler/source_context.go
index 4b660d5a34..6f687fb488 100644
--- a/server/internal/handler/source_context.go
+++ b/server/internal/handler/source_context.go
@@ -167,17 +167,28 @@ func sourceContextThreadChangeDetails(captured, current service.SourceContextSna
currentThread := make([]sourceContextComparableThreadNode, 0, len(current.CommentThread))
capturedComments := make(map[string]service.SourceContextCommentSnapshot, len(captured.CommentThread))
currentComments := make(map[string]service.SourceContextCommentSnapshot, len(current.CommentThread))
+ // A tombstone only holds its replies' place, so it compares as absent: a
+ // comment deleted after capture reads as removed, not as emptied.
for _, comment := range captured.CommentThread {
+ if comment.Deleted {
+ continue
+ }
capturedThread = append(capturedThread, sourceContextComparableThreadNode{ID: comment.ID, ParentID: comment.ParentID, Type: comment.Type})
capturedComments[comment.ID] = comment
}
for _, comment := range current.CommentThread {
+ if comment.Deleted {
+ continue
+ }
currentThread = append(currentThread, sourceContextComparableThreadNode{ID: comment.ID, ParentID: comment.ParentID, Type: comment.Type})
currentComments[comment.ID] = comment
}
threadChanged := captured.AnchorCommentID != current.AnchorCommentID || !jsonEqual(capturedThread, currentThread)
changedCommentIDs := make([]string, 0)
for _, capturedComment := range captured.CommentThread {
+ if capturedComment.Deleted {
+ continue
+ }
currentComment, exists := currentComments[capturedComment.ID]
if !exists {
continue
@@ -207,12 +218,18 @@ func sourceContextThreadChangeDetails(captured, current service.SourceContextSna
}
addedComments := make([]service.SourceContextCommentSnapshot, 0)
for _, currentComment := range current.CommentThread {
+ if currentComment.Deleted {
+ continue
+ }
if _, exists := capturedComments[currentComment.ID]; !exists {
addedComments = append(addedComments, currentComment)
}
}
removedCommentIDs := make([]string, 0)
for _, capturedComment := range captured.CommentThread {
+ if capturedComment.Deleted {
+ continue
+ }
if _, exists := currentComments[capturedComment.ID]; !exists {
removedCommentIDs = append(removedCommentIDs, capturedComment.ID)
}
@@ -247,7 +264,7 @@ func (h *Handler) issueSourceContextDetail(ctx context.Context, issue db.Issue)
anchor, anchorErr := h.Queries.GetCommentInWorkspace(ctx, db.GetCommentInWorkspaceParams{
ID: row.AnchorCommentID, WorkspaceID: issue.WorkspaceID,
})
- anchorExists := anchorErr == nil && anchor.Type == "comment"
+ anchorExists := anchorErr == nil && anchor.Type == "comment" && !anchor.DeletedAt.Valid
if anchorExists {
response.AnchorCommentState = "available"
response.CurrentSource = &sourceContextCurrentSource{
diff --git a/server/internal/service/builtin_skills/multica-platform/references/mentions.md b/server/internal/service/builtin_skills/multica-platform/references/mentions.md
index 4ed5883f13..687228b3ad 100644
--- a/server/internal/service/builtin_skills/multica-platform/references/mentions.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/mentions.md
@@ -202,6 +202,14 @@ re-evaluates surviving inputs. These cancelled runs expose
replies remain in execution history but do not create cancelled comment blocks;
manual cancellations and runs that already executed remain visible.
+Deleting removes only that comment, never its replies. A deleted comment that
+still has replies stays in `comment list` output as a placeholder — `deleted_at`
+set, `content` empty, no attachments — so the replies keep their `parent_id`.
+It carries no input: it never triggers a run, and there is nothing in it to
+answer. It can still be the `--parent` of a reply that continues its thread.
+Against a server that predates this, `comment delete` refuses instead of
+deleting the replies too.
+
An edit is treated as a fresh action — it re-derives the comment's lineage from
the editing action. Only the agent author editing its OWN comment re-stamps the
lineage to the editing task; any other editor — including a workspace owner/admin
diff --git a/server/internal/service/source_context.go b/server/internal/service/source_context.go
index bd3c6e2ca3..c49379906c 100644
--- a/server/internal/service/source_context.go
+++ b/server/internal/service/source_context.go
@@ -146,6 +146,10 @@ type SourceContextCommentSnapshot struct {
UpdatedAt string `json:"updated_at"`
Revision int64 `json:"revision"`
Attachments []SourceContextAttachment `json:"attachments"`
+ // Deleted marks a tombstone: a comment deleted while it still had replies,
+ // kept in the thread only so those replies keep their parent. Its Content
+ // is empty. Omitted otherwise, so existing snapshot digests are unchanged.
+ Deleted bool `json:"deleted,omitempty"`
}
type SourceContextSnapshot struct {
@@ -339,7 +343,7 @@ func buildSourceContextCommentSnapshots(
ID: commentID, ParentID: parentID, Type: row.Type, Content: row.Content,
Author: SourceContextAuthor{Type: row.AuthorType, ID: util.UUIDToString(row.AuthorID), Name: authorName},
CreatedAt: sourceContextTime(row.CreatedAt), UpdatedAt: sourceContextTime(row.UpdatedAt), Revision: row.Revision,
- Attachments: attachments,
+ Attachments: attachments, Deleted: row.DeletedAt.Valid,
})
}
return commentThread, commentAttachments, nil
@@ -405,6 +409,9 @@ func BuildSourceContext(ctx context.Context, q *db.Queries, workspaceID, anchorC
if err != nil {
return SourceContextBuild{}, fmt.Errorf("load anchor comment: %w", err)
}
+ if anchor.DeletedAt.Valid {
+ return SourceContextBuild{}, ErrAnchorCommentDeleted
+ }
if anchor.Type != "comment" {
return SourceContextBuild{}, ErrSourceContextInvalid
}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index a734def1de..8559dcc825 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -5492,7 +5492,18 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
// when the caller didn't pass one explicitly.
if !triggerCommentID.Valid {
coalescedCommentIDs = append([]pgtype.UUID{}, sourceTask.CoalescedCommentIds...)
- if sourceTask.TriggerCommentID.Valid {
+ sourceTriggerLive := sourceTask.TriggerCommentID.Valid
+ if sourceTriggerLive {
+ // A trigger deleted while it had replies keeps its row as a
+ // tombstone instead of clearing trigger_comment_id; repair the
+ // plan exactly as for a removed trigger.
+ trigger, err := s.Queries.GetComment(ctx, sourceTask.TriggerCommentID)
+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ return nil, fmt.Errorf("load source trigger comment: %w", err)
+ }
+ sourceTriggerLive = err == nil && !trigger.DeletedAt.Valid
+ }
+ if sourceTriggerLive {
triggerCommentID = sourceTask.TriggerCommentID
} else if len(coalescedCommentIDs) > 0 {
triggerCommentID, coalescedCommentIDs, err = s.promoteNewestSurvivingComment(ctx, coalescedCommentIDs)
@@ -5618,10 +5629,11 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
}
// promoteNewestSurvivingComment repairs a manual rerun whose original trigger
-// was deleted (the FK clears trigger_comment_id while the UUID-array plan
-// survives). Promoting before enqueue lets the normal enqueue path recompute
-// originator and user-scoped connected-app capabilities from the real comment,
-// rather than carrying the deleted trigger's stale security context.
+// was deleted (the FK clears trigger_comment_id, or the trigger is a tombstone,
+// while the UUID-array plan survives). Tombstones never count as survivors.
+// Promoting before enqueue lets the normal enqueue path recompute originator
+// and user-scoped connected-app capabilities from the real comment, rather
+// than carrying the deleted trigger's stale security context.
func (s *TaskService) promoteNewestSurvivingComment(ctx context.Context, ids []pgtype.UUID) (pgtype.UUID, []pgtype.UUID, error) {
type survivingComment struct {
id pgtype.UUID
@@ -5645,6 +5657,9 @@ func (s *TaskService) promoteNewestSurvivingComment(ctx context.Context, ids []p
if err != nil {
return pgtype.UUID{}, nil, err
}
+ if comment.DeletedAt.Valid {
+ continue
+ }
survivors = append(survivors, survivingComment{id: comment.ID, createdAt: comment.CreatedAt.Time})
}
if len(survivors) == 0 {
diff --git a/server/migrations/468_comment_deleted_at.down.sql b/server/migrations/468_comment_deleted_at.down.sql
new file mode 100644
index 0000000000..ebf15e5d72
--- /dev/null
+++ b/server/migrations/468_comment_deleted_at.down.sql
@@ -0,0 +1,14 @@
+-- Dropping the column turns every tombstone back into a live, empty comment
+-- that old code would let anyone edit or delete — and deleting it would then
+-- cascade to the replies it was kept for. Refuse while tombstones exist. To
+-- roll back, roll back the application only and keep this column: older
+-- builds ignore it.
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM comment WHERE deleted_at IS NOT NULL) THEN
+ RAISE EXCEPTION 'comment tombstones exist; roll back the application and keep comment.deleted_at instead of running this down migration';
+ END IF;
+END
+$$;
+
+ALTER TABLE comment DROP COLUMN IF EXISTS deleted_at;
diff --git a/server/migrations/468_comment_deleted_at.up.sql b/server/migrations/468_comment_deleted_at.up.sql
new file mode 100644
index 0000000000..8b09ff9a2f
--- /dev/null
+++ b/server/migrations/468_comment_deleted_at.up.sql
@@ -0,0 +1,9 @@
+-- Deleting a comment removes only that comment (#8296). A comment that still
+-- has replies keeps its row as a tombstone — content cleared, deleted_at set —
+-- so every reply stays attached to its direct parent. A comment without
+-- replies is removed outright, and a tombstone is removed once its last reply
+-- is gone. The application owns that lifecycle; nothing here relies on the
+-- legacy parent_id cascade.
+--
+-- Nullable with no default, so this is a metadata-only change.
+ALTER TABLE comment ADD COLUMN deleted_at TIMESTAMPTZ NULL;
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 18674c42a4..9be8361030 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -5704,7 +5704,7 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC
}
const listPendingDelegatedFailureRecoveries = `-- name: ListPendingDelegatedFailureRecoveries :many
-SELECT recovery.id, recovery.issue_id, recovery.author_type, recovery.author_id, recovery.content, recovery.type, recovery.created_at, recovery.updated_at, recovery.parent_id, recovery.workspace_id, recovery.resolved_at, recovery.resolved_by_type, recovery.resolved_by_id, recovery.source_task_id, recovery.quick_action_id, recovery.via_plugin_id, recovery.revision, recovery.recovery_settled_at
+SELECT recovery.id, recovery.issue_id, recovery.author_type, recovery.author_id, recovery.content, recovery.type, recovery.created_at, recovery.updated_at, recovery.parent_id, recovery.workspace_id, recovery.resolved_at, recovery.resolved_by_type, recovery.resolved_by_id, recovery.source_task_id, recovery.quick_action_id, recovery.via_plugin_id, recovery.revision, recovery.recovery_settled_at, recovery.deleted_at
FROM comment recovery
JOIN agent_task_queue failed ON failed.id = recovery.source_task_id
JOIN agent_task_queue source ON source.id = failed.delegated_from_task_id
@@ -5717,6 +5717,8 @@ WHERE recovery.author_type = 'system'
AND recovery.type = 'progress_update'
AND recovery.source_task_id IS NOT NULL
AND recovery.recovery_settled_at IS NULL
+ -- A deleted recovery signal is withdrawn, even when replies keep its row.
+ AND recovery.deleted_at IS NULL
AND recovery.issue_id = source_issue.id
AND recovery.workspace_id = source_issue.workspace_id
AND failed.status = 'failed'
@@ -5804,6 +5806,7 @@ func (q *Queries) ListPendingDelegatedFailureRecoveries(ctx context.Context, max
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/attachment.sql.go b/server/pkg/db/generated/attachment.sql.go
index 23abfd5eea..1b117a9fad 100644
--- a/server/pkg/db/generated/attachment.sql.go
+++ b/server/pkg/db/generated/attachment.sql.go
@@ -326,6 +326,39 @@ func (q *Queries) DeleteAttachmentsBySourceContext(ctx context.Context, arg Dele
return items, nil
}
+const deleteCommentAttachments = `-- name: DeleteCommentAttachments :many
+DELETE FROM attachment
+WHERE comment_id = $1 AND workspace_id = $2
+RETURNING url
+`
+
+type DeleteCommentAttachmentsParams struct {
+ CommentID pgtype.UUID `json:"comment_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Part of the comment delete transaction: removes the deleted comment's
+// attachments and returns their storage URLs for cleanup after commit.
+func (q *Queries) DeleteCommentAttachments(ctx context.Context, arg DeleteCommentAttachmentsParams) ([]string, error) {
+ rows, err := q.db.Query(ctx, deleteCommentAttachments, arg.CommentID, arg.WorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []string{}
+ for rows.Next() {
+ var url string
+ if err := rows.Scan(&url); err != nil {
+ return nil, err
+ }
+ items = append(items, url)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const deleteSourceContextAttachmentsByWorkspace = `-- name: DeleteSourceContextAttachmentsByWorkspace :exec
DELETE FROM attachment
WHERE workspace_id = $1
@@ -1090,6 +1123,87 @@ func (q *Queries) ListSourceContextIssueAttachments(ctx context.Context, arg Lis
return items, nil
}
+const lockAttachmentRow = `-- name: LockAttachmentRow :one
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id FROM attachment
+WHERE id = $1 AND workspace_id = $2
+FOR UPDATE
+`
+
+type LockAttachmentRowParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Locks an attachment that has no owner to lock instead — a chat, avatar or
+// still-unbound upload. Reading it under its own lock is what keeps it from
+// gaining an owner between the read and the write, which would put the write
+// back in the attachment -> issue order issue teardown deadlocks with.
+func (q *Queries) LockAttachmentRow(ctx context.Context, arg LockAttachmentRowParams) (Attachment, error) {
+ row := q.db.QueryRow(ctx, lockAttachmentRow, arg.ID, arg.WorkspaceID)
+ var i Attachment
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.IssueID,
+ &i.CommentID,
+ &i.UploaderType,
+ &i.UploaderID,
+ &i.Filename,
+ &i.Url,
+ &i.ContentType,
+ &i.SizeBytes,
+ &i.CreatedAt,
+ &i.ChatSessionID,
+ &i.ChatMessageID,
+ &i.TaskID,
+ &i.SourceContextID,
+ )
+ return i, err
+}
+
+const lockAttachmentsForCommentLink = `-- name: LockAttachmentsForCommentLink :many
+SELECT id FROM attachment
+WHERE workspace_id = $1
+ AND issue_id = $2
+ AND comment_id IS NULL
+ AND source_context_id IS NULL
+ AND id = ANY($3::uuid[])
+ORDER BY id
+FOR UPDATE
+`
+
+type LockAttachmentsForCommentLinkParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ AttachmentIds []pgtype.UUID `json:"attachment_ids"`
+}
+
+// CreateComment binds attachments in the transaction that created the comment,
+// after the CreateComment statement has taken the issue row: issue -> comment
+// -> child, the order every owner-first mutation here uses. This pins the
+// requested set under that lock and returns the ids still eligible, so the
+// caller can refuse before the comment is committed when a requested
+// attachment was deleted while the issue lock was contended.
+func (q *Queries) LockAttachmentsForCommentLink(ctx context.Context, arg LockAttachmentsForCommentLinkParams) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, lockAttachmentsForCommentLink, arg.WorkspaceID, arg.IssueID, arg.AttachmentIds)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var id pgtype.UUID
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ items = append(items, id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const lockAttachmentsForIssueLink = `-- name: LockAttachmentsForIssueLink :many
SELECT id FROM attachment
WHERE workspace_id = $1
@@ -1105,9 +1219,12 @@ type LockAttachmentsForIssueLinkParams struct {
AttachmentIds []pgtype.UUID `json:"attachment_ids"`
}
-// Issue updates bind attachments and then touch the owner row. Lock eligible
-// attachment rows first so every attachment -> issue mutation uses the same
-// lock order as DeleteAttachment and cannot deadlock with it.
+// Issue updates bind attachments and then touch the owner row. Only rows that
+// belong to no issue yet are eligible, and nothing reaches those through an
+// issue — not teardown's cascade, not DeleteAttachment, which takes the owning
+// issue first — so locking them before the owner cannot deadlock.
+// Attachments that DO belong to the issue are locked after it; see
+// LockAttachmentsForCommentLink.
func (q *Queries) LockAttachmentsForIssueLink(ctx context.Context, arg LockAttachmentsForIssueLinkParams) ([]pgtype.UUID, error) {
rows, err := q.db.Query(ctx, lockAttachmentsForIssueLink, arg.WorkspaceID, arg.AttachmentIds)
if err != nil {
diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.go
index 83850f69a4..f11c556dd5 100644
--- a/server/pkg/db/generated/comment.sql.go
+++ b/server/pkg/db/generated/comment.sql.go
@@ -17,7 +17,7 @@ SET revision = revision + 1,
updated_at = now()
WHERE id = $1
AND workspace_id = $2
-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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at
+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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at
`
type BumpCommentRevisionParams struct {
@@ -47,6 +47,7 @@ func (q *Queries) BumpCommentRevision(ctx context.Context, arg BumpCommentRevisi
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
)
return i, err
}
@@ -86,7 +87,7 @@ UPDATE comment SET
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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at
+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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at
`
type ClearOtherThreadResolutionsParams struct {
@@ -133,6 +134,7 @@ func (q *Queries) ClearOtherThreadResolutions(ctx context.Context, arg ClearOthe
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
); err != nil {
return nil, err
}
@@ -144,6 +146,25 @@ func (q *Queries) ClearOtherThreadResolutions(ctx context.Context, arg ClearOthe
return items, nil
}
+const commentHasReplies = `-- name: CommentHasReplies :one
+SELECT EXISTS (
+ SELECT 1 FROM comment
+ WHERE parent_id = $1 AND workspace_id = $2
+) AS has_replies
+`
+
+type CommentHasRepliesParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) CommentHasReplies(ctx context.Context, arg CommentHasRepliesParams) (bool, error) {
+ row := q.db.QueryRow(ctx, commentHasReplies, arg.ID, arg.WorkspaceID)
+ var has_replies bool
+ err := row.Scan(&has_replies)
+ return has_replies, err
+}
+
const countComments = `-- name: CountComments :one
SELECT count(*) FROM comment
WHERE issue_id = $1 AND workspace_id = $2
@@ -167,6 +188,7 @@ WHERE issue_id = $1
AND workspace_id = $2
AND created_at > $3
AND id <> $4
+ AND deleted_at IS NULL
AND NOT (author_type = 'agent' AND author_id = $5)
`
@@ -211,9 +233,9 @@ WITH touched_issue AS (
INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id, via_plugin_id, id)
SELECT ti.id, ti.workspace_id, $3, $4, $5, $6, $7, $8, $9, $10, COALESCE($11::uuid, gen_random_uuid())
FROM touched_issue ti
- 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at
+ 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at
)
-SELECT inserted_comment.id, inserted_comment.issue_id, inserted_comment.author_type, inserted_comment.author_id, inserted_comment.content, inserted_comment.type, inserted_comment.created_at, inserted_comment.updated_at, inserted_comment.parent_id, inserted_comment.workspace_id, inserted_comment.resolved_at, inserted_comment.resolved_by_type, inserted_comment.resolved_by_id, inserted_comment.source_task_id, inserted_comment.quick_action_id, inserted_comment.via_plugin_id, inserted_comment.revision, inserted_comment.recovery_settled_at, touched_issue.revision AS issue_revision
+SELECT inserted_comment.id, inserted_comment.issue_id, inserted_comment.author_type, inserted_comment.author_id, inserted_comment.content, inserted_comment.type, inserted_comment.created_at, inserted_comment.updated_at, inserted_comment.parent_id, inserted_comment.workspace_id, inserted_comment.resolved_at, inserted_comment.resolved_by_type, inserted_comment.resolved_by_id, inserted_comment.source_task_id, inserted_comment.quick_action_id, inserted_comment.via_plugin_id, inserted_comment.revision, inserted_comment.recovery_settled_at, inserted_comment.deleted_at, touched_issue.revision AS issue_revision
FROM inserted_comment
JOIN touched_issue ON touched_issue.id = inserted_comment.issue_id
`
@@ -251,6 +273,7 @@ type CreateCommentRow struct {
ViaPluginID pgtype.UUID `json:"via_plugin_id"`
Revision int64 `json:"revision"`
RecoverySettledAt pgtype.Timestamptz `json:"recovery_settled_at"`
+ DeletedAt pgtype.Timestamptz `json:"deleted_at"`
IssueRevision int64 `json:"issue_revision"`
}
@@ -304,65 +327,69 @@ func (q *Queries) CreateComment(ctx context.Context, arg CreateCommentParams) (C
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
&i.IssueRevision,
)
return i, err
}
-const deleteComment = `-- name: DeleteComment :one
-WITH locked_issue AS MATERIALIZED (
- -- Lock the aggregate owner before its child so this cannot deadlock with
- -- issue teardown (which takes the same issue -> comment order).
- SELECT issue.id
- FROM issue
- JOIN comment ON comment.issue_id = issue.id
- AND comment.workspace_id = issue.workspace_id
- WHERE comment.id = $1 AND comment.workspace_id = $2
- FOR UPDATE OF issue
-), issue_fence AS MATERIALIZED (
- -- The consumed locked_count below is the ordering fence: the issue lock is
- -- acquired before DELETE can lock the comment. MATERIALIZED only prevents
- -- folding/re-evaluation and is not, by itself, a lock-order guarantee.
- SELECT count(*) AS locked_count FROM locked_issue
-), deleted_comment AS (
- DELETE FROM comment
- USING issue_fence
- WHERE comment.id = $1 AND comment.workspace_id = $2
- AND issue_fence.locked_count >= 0
- RETURNING issue_id, workspace_id
-), touched_issue AS (
- UPDATE issue
- SET revision = issue.revision + 1,
- last_activity_at = GREATEST(COALESCE(issue.last_activity_at, issue.updated_at), now())
- FROM deleted_comment
- WHERE issue.id = deleted_comment.issue_id
- AND issue.workspace_id = deleted_comment.workspace_id
- RETURNING issue.id, issue.revision
-)
-SELECT EXISTS(SELECT 1 FROM deleted_comment) AS changed,
- COALESCE((SELECT revision FROM touched_issue), 0)::bigint AS issue_revision
+const deleteLeafComment = `-- name: DeleteLeafComment :one
+DELETE FROM comment
+WHERE comment.id = $1 AND comment.workspace_id = $2
+ AND NOT EXISTS (SELECT 1 FROM comment child WHERE child.parent_id = comment.id)
+RETURNING comment.id, comment.parent_id
+`
+
+type DeleteLeafCommentParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+type DeleteLeafCommentRow struct {
+ ID pgtype.UUID `json:"id"`
+ ParentID pgtype.UUID `json:"parent_id"`
+}
+
+// Removes a comment that has no replies. The NOT EXISTS guard keeps this
+// statement from ever reaching the legacy parent_id cascade: a comment with a
+// reply is tombstoned instead, never deleted with its replies.
+func (q *Queries) DeleteLeafComment(ctx context.Context, arg DeleteLeafCommentParams) (DeleteLeafCommentRow, error) {
+ row := q.db.QueryRow(ctx, deleteLeafComment, arg.ID, arg.WorkspaceID)
+ var i DeleteLeafCommentRow
+ err := row.Scan(&i.ID, &i.ParentID)
+ return i, err
+}
+
+const deleteReplylessCommentTombstone = `-- name: DeleteReplylessCommentTombstone :one
+DELETE FROM comment
+WHERE comment.id = $1 AND comment.workspace_id = $2
+ AND comment.deleted_at IS NOT NULL
+ AND NOT EXISTS (SELECT 1 FROM comment child WHERE child.parent_id = comment.id)
+RETURNING comment.id, comment.parent_id
`
-type DeleteCommentParams struct {
+type DeleteReplylessCommentTombstoneParams struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
}
-type DeleteCommentRow struct {
- Changed bool `json:"changed"`
- IssueRevision int64 `json:"issue_revision"`
+type DeleteReplylessCommentTombstoneRow struct {
+ ID pgtype.UUID `json:"id"`
+ ParentID pgtype.UUID `json:"parent_id"`
}
-// Defense-in-depth: workspace_id is a SQL-layer tenant guard. See DeleteIssue.
-func (q *Queries) DeleteComment(ctx context.Context, arg DeleteCommentParams) (DeleteCommentRow, error) {
- row := q.db.QueryRow(ctx, deleteComment, arg.ID, arg.WorkspaceID)
- var i DeleteCommentRow
- err := row.Scan(&i.Changed, &i.IssueRevision)
+// Removes a tombstone whose last reply is gone. The delete transaction calls
+// this for each ancestor in turn, so a chain of placeholders never outlives
+// the replies it kept attached.
+func (q *Queries) DeleteReplylessCommentTombstone(ctx context.Context, arg DeleteReplylessCommentTombstoneParams) (DeleteReplylessCommentTombstoneRow, error) {
+ row := q.db.QueryRow(ctx, deleteReplylessCommentTombstone, arg.ID, arg.WorkspaceID)
+ var i DeleteReplylessCommentTombstoneRow
+ err := row.Scan(&i.ID, &i.ParentID)
return i, err
}
const getComment = `-- name: GetComment :one
-SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
+SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment
WHERE id = $1
`
@@ -388,12 +415,13 @@ func (q *Queries) GetComment(ctx context.Context, id pgtype.UUID) (Comment, erro
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
)
return i, err
}
const getCommentInWorkspace = `-- name: GetCommentInWorkspace :one
-SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
+SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment
WHERE id = $1 AND workspace_id = $2
`
@@ -424,12 +452,13 @@ func (q *Queries) GetCommentInWorkspace(ctx context.Context, arg GetCommentInWor
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
)
return i, err
}
const getDelegatedFailureRecoveryComment = `-- name: GetDelegatedFailureRecoveryComment :one
-SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
+SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment
WHERE issue_id = $1
AND workspace_id = $2
AND author_type = 'system'
@@ -471,12 +500,13 @@ func (q *Queries) GetDelegatedFailureRecoveryComment(ctx context.Context, arg Ge
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
)
return i, err
}
const getDelegatedFailureRecoveryExhaustionComment = `-- name: GetDelegatedFailureRecoveryExhaustionComment :one
-SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
+SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment
WHERE issue_id = $1
AND workspace_id = $2
AND author_type = 'system'
@@ -518,15 +548,17 @@ func (q *Queries) GetDelegatedFailureRecoveryExhaustionComment(ctx context.Conte
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
)
return i, err
}
const getLatestMemberCommentForIssueSince = `-- name: GetLatestMemberCommentForIssueSince :one
-SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
+SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment
WHERE issue_id = $1
AND author_type = 'member'
AND created_at > $2
+ AND deleted_at IS NULL
ORDER BY created_at DESC
LIMIT 1
`
@@ -567,6 +599,7 @@ func (q *Queries) GetLatestMemberCommentForIssueSince(ctx context.Context, arg G
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
)
return i, err
}
@@ -581,7 +614,7 @@ WITH RECURSIVE root_of AS (
FROM comment p
JOIN root_of r ON p.id = r.parent_id
)
-SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at FROM comment c
+SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at, c.deleted_at FROM comment c
WHERE c.id = (SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1)
`
@@ -617,6 +650,7 @@ func (q *Queries) GetThreadRoot(ctx context.Context, arg GetThreadRootParams) (C
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
)
return i, err
}
@@ -628,6 +662,7 @@ SELECT EXISTS (
AND author_type = 'agent'
AND author_id = $2
AND created_at >= $3
+ AND deleted_at IS NULL
) AS commented
`
@@ -665,7 +700,7 @@ func (q *Queries) HasAgentRepliedInThread(ctx context.Context, arg HasAgentRepli
}
const listChildCommentsForParents = `-- name: ListChildCommentsForParents :many
-SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
+SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment
WHERE parent_id = ANY($1::uuid[])
AND issue_id = $2
AND workspace_id = $3
@@ -727,6 +762,7 @@ func (q *Queries) ListChildCommentsForParents(ctx context.Context, arg ListChild
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
); err != nil {
return nil, err
}
@@ -740,7 +776,7 @@ func (q *Queries) ListChildCommentsForParents(ctx context.Context, arg ListChild
const listCommentAncestorPath = `-- name: ListCommentAncestorPath :many
WITH RECURSIVE ancestor_path AS (
- SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at, ARRAY[c.id]::uuid[] AS visited_ids, 1::integer AS depth, false AS cycle
+ SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at, c.deleted_at, ARRAY[c.id]::uuid[] AS visited_ids, 1::integer AS depth, false AS cycle
FROM comment c
WHERE c.id = $1
AND c.workspace_id = $2
@@ -748,7 +784,7 @@ WITH RECURSIVE ancestor_path AS (
UNION ALL
- SELECT parent.id, parent.issue_id, parent.author_type, parent.author_id, parent.content, parent.type, parent.created_at, parent.updated_at, parent.parent_id, parent.workspace_id, parent.resolved_at, parent.resolved_by_type, parent.resolved_by_id, parent.source_task_id, parent.quick_action_id, parent.via_plugin_id, parent.revision, parent.recovery_settled_at,
+ SELECT parent.id, parent.issue_id, parent.author_type, parent.author_id, parent.content, parent.type, parent.created_at, parent.updated_at, parent.parent_id, parent.workspace_id, parent.resolved_at, parent.resolved_by_type, parent.resolved_by_id, parent.source_task_id, parent.quick_action_id, parent.via_plugin_id, parent.revision, parent.recovery_settled_at, parent.deleted_at,
path.visited_ids || parent.id,
path.depth + 1,
parent.id = ANY(path.visited_ids)
@@ -762,7 +798,7 @@ WITH RECURSIVE ancestor_path AS (
SELECT id, issue_id, author_type, author_id, content, type, created_at,
updated_at, workspace_id, parent_id, resolved_at, resolved_by_type,
resolved_by_id, source_task_id, revision, quick_action_id, via_plugin_id,
- depth, cycle
+ deleted_at, depth, cycle
FROM ancestor_path
ORDER BY depth DESC
`
@@ -791,6 +827,7 @@ type ListCommentAncestorPathRow struct {
Revision int64 `json:"revision"`
QuickActionID pgtype.UUID `json:"quick_action_id"`
ViaPluginID pgtype.UUID `json:"via_plugin_id"`
+ DeletedAt pgtype.Timestamptz `json:"deleted_at"`
Depth int32 `json:"depth"`
Cycle bool `json:"cycle"`
}
@@ -822,6 +859,7 @@ func (q *Queries) ListCommentAncestorPath(ctx context.Context, arg ListCommentAn
&i.Revision,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.DeletedAt,
&i.Depth,
&i.Cycle,
); err != nil {
@@ -837,7 +875,7 @@ func (q *Queries) ListCommentAncestorPath(ctx context.Context, arg ListCommentAn
const listCommentThreadHistory = `-- name: ListCommentThreadHistory :many
WITH RECURSIVE thread_history AS (
- SELECT root.id, root.issue_id, root.author_type, root.author_id, root.content, root.type, root.created_at, root.updated_at, root.parent_id, root.workspace_id, root.resolved_at, root.resolved_by_type, root.resolved_by_id, root.source_task_id, root.quick_action_id, root.via_plugin_id, root.revision, root.recovery_settled_at
+ SELECT root.id, root.issue_id, root.author_type, root.author_id, root.content, root.type, root.created_at, root.updated_at, root.parent_id, root.workspace_id, root.resolved_at, root.resolved_by_type, root.resolved_by_id, root.source_task_id, root.quick_action_id, root.via_plugin_id, root.revision, root.recovery_settled_at, root.deleted_at
FROM comment root
WHERE root.id = $2
AND root.workspace_id = $3
@@ -850,7 +888,7 @@ WITH RECURSIVE thread_history AS (
UNION ALL
- SELECT child.id, child.issue_id, child.author_type, child.author_id, child.content, child.type, child.created_at, child.updated_at, child.parent_id, child.workspace_id, child.resolved_at, child.resolved_by_type, child.resolved_by_id, child.source_task_id, child.quick_action_id, child.via_plugin_id, child.revision, child.recovery_settled_at
+ SELECT child.id, child.issue_id, child.author_type, child.author_id, child.content, child.type, child.created_at, child.updated_at, child.parent_id, child.workspace_id, child.resolved_at, child.resolved_by_type, child.resolved_by_id, child.source_task_id, child.quick_action_id, child.via_plugin_id, child.revision, child.recovery_settled_at, child.deleted_at
FROM comment child
JOIN thread_history parent ON child.parent_id = parent.id
WHERE child.workspace_id = $3
@@ -860,7 +898,7 @@ WITH RECURSIVE thread_history AS (
$6::uuid
)
)
-SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at
+SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at
FROM thread_history
ORDER BY created_at, id
LIMIT $1
@@ -894,6 +932,7 @@ type ListCommentThreadHistoryRow struct {
ViaPluginID pgtype.UUID `json:"via_plugin_id"`
Revision int64 `json:"revision"`
RecoverySettledAt pgtype.Timestamptz `json:"recovery_settled_at"`
+ DeletedAt pgtype.Timestamptz `json:"deleted_at"`
}
// Capture the anchor comment's complete chronological thread through that
@@ -934,6 +973,7 @@ func (q *Queries) ListCommentThreadHistory(ctx context.Context, arg ListCommentT
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
); err != nil {
return nil, err
}
@@ -946,7 +986,7 @@ func (q *Queries) ListCommentThreadHistory(ctx context.Context, arg ListCommentT
}
const listCommentsByIDsForIssue = `-- name: ListCommentsByIDsForIssue :many
-SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
+SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment
WHERE id = ANY($1::uuid[])
AND issue_id = $2
AND workspace_id = $3
@@ -996,6 +1036,7 @@ func (q *Queries) ListCommentsByIDsForIssue(ctx context.Context, arg ListComment
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
); err != nil {
return nil, err
}
@@ -1008,8 +1049,8 @@ func (q *Queries) ListCommentsByIDsForIssue(ctx context.Context, arg ListComment
}
const listCommentsForIssue = `-- name: ListCommentsForIssue :many
-SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM (
- SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
+SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM (
+ SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment
WHERE issue_id = $1 AND workspace_id = $2
ORDER BY created_at DESC, id DESC
LIMIT $3
@@ -1068,6 +1109,7 @@ func (q *Queries) ListCommentsForIssue(ctx context.Context, arg ListCommentsForI
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
); err != nil {
return nil, err
}
@@ -1080,7 +1122,7 @@ func (q *Queries) ListCommentsForIssue(ctx context.Context, arg ListCommentsForI
}
const listCommentsSinceForIssue = `-- name: ListCommentsSinceForIssue :many
-SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
+SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment
WHERE issue_id = $1 AND workspace_id = $2 AND created_at > $3
ORDER BY created_at ASC, id ASC
LIMIT $4
@@ -1128,6 +1170,7 @@ func (q *Queries) ListCommentsSinceForIssue(ctx context.Context, arg ListComment
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
); err != nil {
return nil, err
}
@@ -1173,7 +1216,7 @@ picked AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
- c.source_task_id, c.quick_action_id, c.revision,
+ c.source_task_id, c.quick_action_id, c.revision, c.deleted_at,
p.root_id AS thread_root_id,
p.last_activity_at AS thread_last_activity_at
FROM picked p
@@ -1208,6 +1251,7 @@ type ListRecentThreadCommentsForIssueRow struct {
SourceTaskID pgtype.UUID `json:"source_task_id"`
QuickActionID pgtype.UUID `json:"quick_action_id"`
Revision int64 `json:"revision"`
+ DeletedAt pgtype.Timestamptz `json:"deleted_at"`
ThreadRootID pgtype.UUID `json:"thread_root_id"`
ThreadLastActivityAt pgtype.Timestamptz `json:"thread_last_activity_at"`
}
@@ -1273,6 +1317,7 @@ func (q *Queries) ListRecentThreadCommentsForIssue(ctx context.Context, arg List
&i.SourceTaskID,
&i.QuickActionID,
&i.Revision,
+ &i.DeletedAt,
&i.ThreadRootID,
&i.ThreadLastActivityAt,
); err != nil {
@@ -1287,10 +1332,12 @@ func (q *Queries) ListRecentThreadCommentsForIssue(ctx context.Context, arg List
}
const listReconcilableCommentsForIssueSince = `-- name: ListReconcilableCommentsForIssueSince :many
-SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
+SELECT 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment
WHERE issue_id = $1
AND (id = ANY($2::uuid[])
OR comment_thread_root_id(id) = $3::uuid)
+ -- A deleted comment is no longer input, even when replies keep its row.
+ AND deleted_at IS NULL
AND (
(
author_type IN ('member', 'agent')
@@ -1372,6 +1419,7 @@ func (q *Queries) ListReconcilableCommentsForIssueSince(ctx context.Context, arg
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
); err != nil {
return nil, err
}
@@ -1413,7 +1461,7 @@ thread_stats AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
- c.source_task_id, c.quick_action_id, c.revision,
+ c.source_task_id, c.quick_action_id, c.revision, c.deleted_at,
ts.reply_count AS reply_count,
ts.last_activity_at AS last_activity_at
FROM selected_roots sr
@@ -1445,6 +1493,7 @@ type ListRootCommentsForIssueRow struct {
SourceTaskID pgtype.UUID `json:"source_task_id"`
QuickActionID pgtype.UUID `json:"quick_action_id"`
Revision int64 `json:"revision"`
+ DeletedAt pgtype.Timestamptz `json:"deleted_at"`
ReplyCount int32 `json:"reply_count"`
LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`
}
@@ -1487,6 +1536,7 @@ func (q *Queries) ListRootCommentsForIssue(ctx context.Context, arg ListRootComm
&i.SourceTaskID,
&i.QuickActionID,
&i.Revision,
+ &i.DeletedAt,
&i.ReplyCount,
&i.LastActivityAt,
); err != nil {
@@ -1531,7 +1581,7 @@ thread_stats AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
- c.source_task_id, c.quick_action_id, c.revision,
+ c.source_task_id, c.quick_action_id, c.revision, c.deleted_at,
ts.reply_count AS reply_count,
ts.last_activity_at AS last_activity_at
FROM selected_roots sr
@@ -1564,6 +1614,7 @@ type ListRootCommentsSinceForIssueRow struct {
SourceTaskID pgtype.UUID `json:"source_task_id"`
QuickActionID pgtype.UUID `json:"quick_action_id"`
Revision int64 `json:"revision"`
+ DeletedAt pgtype.Timestamptz `json:"deleted_at"`
ReplyCount int32 `json:"reply_count"`
LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`
}
@@ -1606,6 +1657,7 @@ func (q *Queries) ListRootCommentsSinceForIssue(ctx context.Context, arg ListRoo
&i.SourceTaskID,
&i.QuickActionID,
&i.Revision,
+ &i.DeletedAt,
&i.ReplyCount,
&i.LastActivityAt,
); err != nil {
@@ -1637,14 +1689,14 @@ descendants AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
- c.source_task_id, c.quick_action_id, c.revision
+ c.source_task_id, c.quick_action_id, c.revision, c.deleted_at
FROM comment c
JOIN thread_root tr ON c.id = tr.id
UNION
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
- c.source_task_id, c.quick_action_id, c.revision
+ c.source_task_id, c.quick_action_id, c.revision, c.deleted_at
FROM comment c
JOIN descendants d ON c.parent_id = d.id
WHERE c.issue_id = $2 AND c.workspace_id = $3
@@ -1653,7 +1705,7 @@ reply_page AS (
SELECT d.id, d.issue_id, d.author_type, d.author_id, d.content, d.type,
d.created_at, d.updated_at, d.parent_id, d.workspace_id,
d.resolved_at, d.resolved_by_type, d.resolved_by_id,
- d.source_task_id, d.quick_action_id, d.revision
+ d.source_task_id, d.quick_action_id, d.revision, d.deleted_at
FROM descendants d
WHERE d.id NOT IN (SELECT id FROM thread_root)
AND (
@@ -1666,19 +1718,19 @@ reply_page AS (
SELECT 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,
- source_task_id, quick_action_id, revision
+ source_task_id, quick_action_id, revision, deleted_at
FROM (
SELECT d.id, d.issue_id, d.author_type, d.author_id, d.content, d.type,
d.created_at, d.updated_at, d.parent_id, d.workspace_id,
d.resolved_at, d.resolved_by_type, d.resolved_by_id,
- d.source_task_id, d.quick_action_id, d.revision
+ d.source_task_id, d.quick_action_id, d.revision, d.deleted_at
FROM descendants d
JOIN thread_root tr ON d.id = tr.id
UNION ALL
SELECT 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,
- source_task_id, quick_action_id, revision
+ source_task_id, quick_action_id, revision, deleted_at
FROM reply_page
) combined
ORDER BY created_at ASC, id ASC
@@ -1711,6 +1763,7 @@ type ListThreadCommentsForIssuePagedRow struct {
SourceTaskID pgtype.UUID `json:"source_task_id"`
QuickActionID pgtype.UUID `json:"quick_action_id"`
Revision int64 `json:"revision"`
+ DeletedAt pgtype.Timestamptz `json:"deleted_at"`
}
// Resolves @anchor_id to its thread root, recursively expands every descendant,
@@ -1762,6 +1815,7 @@ func (q *Queries) ListThreadCommentsForIssuePaged(ctx context.Context, arg ListT
&i.SourceTaskID,
&i.QuickActionID,
&i.Revision,
+ &i.DeletedAt,
); err != nil {
return nil, err
}
@@ -1824,6 +1878,131 @@ func (q *Queries) LockCommentAncestorPath(ctx context.Context, arg LockCommentAn
return items, nil
}
+const lockCommentForDelete = `-- name: LockCommentForDelete :one
+WITH locked_issue AS MATERIALIZED (
+ SELECT issue.id
+ FROM issue
+ JOIN comment ON comment.issue_id = issue.id
+ AND comment.workspace_id = issue.workspace_id
+ WHERE comment.id = $1 AND comment.workspace_id = $2
+ FOR UPDATE OF issue
+), issue_fence AS MATERIALIZED (
+ -- The consumed locked_count below is the ordering fence: the issue lock is
+ -- acquired before the comment lock. MATERIALIZED only prevents
+ -- folding/re-evaluation and is not, by itself, a lock-order guarantee.
+ SELECT count(*) AS locked_count FROM locked_issue
+)
+SELECT comment.id, comment.issue_id, comment.author_type, comment.author_id, comment.content, comment.type, comment.created_at, comment.updated_at, comment.parent_id, comment.workspace_id, comment.resolved_at, comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id, comment.quick_action_id, comment.via_plugin_id, comment.revision, comment.recovery_settled_at, comment.deleted_at
+FROM comment
+CROSS JOIN issue_fence
+WHERE comment.id = $1 AND comment.workspace_id = $2
+ AND comment.deleted_at IS NULL
+ AND issue_fence.locked_count >= 0
+FOR UPDATE OF comment
+`
+
+type LockCommentForDeleteParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// First statement of the comment delete transaction (#8296). Defense-in-depth:
+// workspace_id is a SQL-layer tenant guard. See DeleteIssue.
+//
+// It takes the aggregate owner's lock before the comment's, so deleting cannot
+// deadlock with issue teardown (which takes the same issue -> comment order).
+// The issue lock is also what freezes the thread: every comment insert goes
+// through CreateComment, whose first step updates this issue row, so no reply
+// can be added to the issue until the delete transaction ends. The caller's
+// later statements start from a fresh snapshot taken after the locks, which is
+// what makes their reply check exact.
+//
+// A tombstone is excluded: deleting an already-deleted comment finds nothing.
+func (q *Queries) LockCommentForDelete(ctx context.Context, arg LockCommentForDeleteParams) (Comment, error) {
+ row := q.db.QueryRow(ctx, lockCommentForDelete, arg.ID, arg.WorkspaceID)
+ var i Comment
+ err := row.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,
+ &i.SourceTaskID,
+ &i.QuickActionID,
+ &i.ViaPluginID,
+ &i.Revision,
+ &i.RecoverySettledAt,
+ &i.DeletedAt,
+ )
+ return i, err
+}
+
+const lockLiveComment = `-- name: LockLiveComment :one
+WITH locked_issue AS MATERIALIZED (
+ SELECT issue.id
+ FROM issue
+ JOIN comment ON comment.issue_id = issue.id
+ AND comment.workspace_id = issue.workspace_id
+ WHERE comment.id = $1 AND comment.workspace_id = $2
+ FOR NO KEY UPDATE OF issue
+), issue_fence AS MATERIALIZED (
+ SELECT count(*) AS locked_count FROM locked_issue
+)
+SELECT comment.id, comment.issue_id, comment.author_type, comment.author_id, comment.content, comment.type, comment.created_at, comment.updated_at, comment.parent_id, comment.workspace_id, comment.resolved_at, comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id, comment.quick_action_id, comment.via_plugin_id, comment.revision, comment.recovery_settled_at, comment.deleted_at
+FROM comment
+CROSS JOIN issue_fence
+WHERE comment.id = $1 AND comment.workspace_id = $2
+ AND comment.deleted_at IS NULL
+ AND issue_fence.locked_count >= 0
+FOR NO KEY UPDATE OF comment
+`
+
+type LockLiveCommentParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Locks a live comment ahead of a write to one of its children — reactions and
+// attachments — in the order every comment mutation shares: issue, then
+// comment, then child. A comment deleted before or while this waits reads as
+// absent (the row lock re-checks deleted_at), so no child can land on its
+// tombstone. FOR NO KEY UPDATE conflicts with the delete transaction's FOR
+// UPDATE but not with a reply's FOR KEY SHARE, so it never blocks replies.
+func (q *Queries) LockLiveComment(ctx context.Context, arg LockLiveCommentParams) (Comment, error) {
+ row := q.db.QueryRow(ctx, lockLiveComment, arg.ID, arg.WorkspaceID)
+ var i Comment
+ err := row.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,
+ &i.SourceTaskID,
+ &i.QuickActionID,
+ &i.ViaPluginID,
+ &i.Revision,
+ &i.RecoverySettledAt,
+ &i.DeletedAt,
+ )
+ return i, err
+}
+
const resolveComment = `-- name: ResolveComment :one
UPDATE comment SET
resolved_at = COALESCE(resolved_at, now()),
@@ -1832,7 +2011,8 @@ UPDATE comment SET
revision = revision + CASE WHEN resolved_at IS NULL THEN 1 ELSE 0 END,
updated_at = CASE WHEN resolved_at IS NULL THEN now() ELSE updated_at END
WHERE id = $1
-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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at
+ AND deleted_at IS 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at
`
type ResolveCommentParams struct {
@@ -1842,7 +2022,8 @@ type ResolveCommentParams struct {
}
// Idempotent: re-resolving keeps the original resolved_at + resolver. Always
-// returns the row so the handler can surface the canonical state.
+// returns the row so the handler can surface the canonical state — unless the
+// comment has been deleted, whose tombstone cannot be a resolution.
func (q *Queries) ResolveComment(ctx context.Context, arg ResolveCommentParams) (Comment, error) {
row := q.db.QueryRow(ctx, resolveComment, arg.ID, arg.ResolvedByType, arg.ResolvedByID)
var i Comment
@@ -1865,10 +2046,85 @@ func (q *Queries) ResolveComment(ctx context.Context, arg ResolveCommentParams)
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
+ )
+ return i, err
+}
+
+const tombstoneComment = `-- name: TombstoneComment :one
+UPDATE comment SET
+ content = '',
+ deleted_at = now(),
+ resolved_at = NULL,
+ resolved_by_type = NULL,
+ resolved_by_id = NULL,
+ revision = revision + 1,
+ updated_at = now()
+WHERE id = $1 AND workspace_id = $2
+ AND deleted_at IS 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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at
+`
+
+type TombstoneCommentParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Deletes a comment that still has replies by clearing it in place. The row,
+// its id and its parent_id stay so every reply keeps its direct parent; the
+// body goes, and so does any resolution, since a deleted comment cannot be a
+// thread's conclusion. The caller removes attachments and reactions in the
+// same transaction.
+func (q *Queries) TombstoneComment(ctx context.Context, arg TombstoneCommentParams) (Comment, error) {
+ row := q.db.QueryRow(ctx, tombstoneComment, arg.ID, arg.WorkspaceID)
+ var i Comment
+ err := row.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,
+ &i.SourceTaskID,
+ &i.QuickActionID,
+ &i.ViaPluginID,
+ &i.Revision,
+ &i.RecoverySettledAt,
+ &i.DeletedAt,
)
return i, err
}
+const touchIssueForCommentDelete = `-- name: TouchIssueForCommentDelete :one
+UPDATE issue
+SET revision = revision + 1,
+ last_activity_at = GREATEST(COALESCE(last_activity_at, updated_at), now())
+WHERE id = $1 AND workspace_id = $2
+RETURNING revision
+`
+
+type TouchIssueForCommentDeleteParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// A delete counts as activity on its issue, like CreateComment and
+// UpdateComment. Runs inside the delete transaction after the comment rows
+// changed, so a delete that lost its race never touches the issue.
+func (q *Queries) TouchIssueForCommentDelete(ctx context.Context, arg TouchIssueForCommentDeleteParams) (int64, error) {
+ row := q.db.QueryRow(ctx, touchIssueForCommentDelete, arg.IssueID, arg.WorkspaceID)
+ var revision int64
+ err := row.Scan(&revision)
+ return revision, err
+}
+
const unresolveComment = `-- name: UnresolveComment :one
UPDATE comment SET
resolved_at = NULL,
@@ -1877,7 +2133,7 @@ UPDATE comment SET
revision = revision + CASE WHEN resolved_at IS NOT NULL THEN 1 ELSE 0 END,
updated_at = CASE WHEN resolved_at IS NOT NULL THEN now() ELSE updated_at END
WHERE id = $1
-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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at
+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, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at
`
// Idempotent: a no-op clear (already unresolved) just returns the row.
@@ -1903,6 +2159,7 @@ func (q *Queries) UnresolveComment(ctx context.Context, id pgtype.UUID) (Comment
&i.ViaPluginID,
&i.Revision,
&i.RecoverySettledAt,
+ &i.DeletedAt,
)
return i, err
}
@@ -1925,13 +2182,15 @@ WITH locked_issue AS MATERIALIZED (
-- prevents folding/re-evaluation; it does not itself establish lock order.
SELECT count(*) AS locked_count FROM locked_issue
), target AS MATERIALIZED (
- SELECT comment.id, comment.issue_id, comment.author_type, comment.author_id, comment.content, comment.type, comment.created_at, comment.updated_at, comment.parent_id, comment.workspace_id, comment.resolved_at, comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id, comment.quick_action_id, comment.via_plugin_id, comment.revision, comment.recovery_settled_at,
+ SELECT comment.id, comment.issue_id, comment.author_type, comment.author_id, comment.content, comment.type, comment.created_at, comment.updated_at, comment.parent_id, comment.workspace_id, comment.resolved_at, comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id, comment.quick_action_id, comment.via_plugin_id, comment.revision, comment.recovery_settled_at, comment.deleted_at,
ROW(comment.content, comment.source_task_id) IS DISTINCT FROM
ROW($2, $3::uuid) AS did_change
FROM comment
CROSS JOIN issue_fence
WHERE comment.id = $1
AND issue_fence.locked_count >= 0
+ -- A deleted comment's tombstone is not editable.
+ AND comment.deleted_at IS NULL
AND ($4::bigint IS NULL OR revision = $4::bigint)
AND (
$5::text IS NULL
@@ -1952,7 +2211,7 @@ WITH locked_issue AS MATERIALIZED (
comment.parent_id, comment.workspace_id, comment.resolved_at,
comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id,
comment.quick_action_id, comment.via_plugin_id, comment.revision,
- target.did_change
+ comment.deleted_at, target.did_change
), touched_issue AS (
UPDATE issue
SET revision = issue.revision + 1,
@@ -1970,6 +2229,7 @@ SELECT updated_comment.id, updated_comment.issue_id, updated_comment.author_type
updated_comment.resolved_by_type, updated_comment.resolved_by_id,
updated_comment.source_task_id, updated_comment.quick_action_id,
updated_comment.via_plugin_id, updated_comment.revision,
+ updated_comment.deleted_at,
COALESCE((SELECT revision FROM touched_issue), 0)::bigint AS issue_revision
FROM updated_comment
`
@@ -2000,6 +2260,7 @@ type UpdateCommentRow struct {
QuickActionID pgtype.UUID `json:"quick_action_id"`
ViaPluginID pgtype.UUID `json:"via_plugin_id"`
Revision int64 `json:"revision"`
+ DeletedAt pgtype.Timestamptz `json:"deleted_at"`
IssueRevision int64 `json:"issue_revision"`
}
@@ -2030,6 +2291,7 @@ func (q *Queries) UpdateComment(ctx context.Context, arg UpdateCommentParams) (U
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.DeletedAt,
&i.IssueRevision,
)
return i, err
diff --git a/server/pkg/db/generated/comment_row.go b/server/pkg/db/generated/comment_row.go
index d534143643..1037b591d5 100644
--- a/server/pkg/db/generated/comment_row.go
+++ b/server/pkg/db/generated/comment_row.go
@@ -22,6 +22,7 @@ func (r CreateCommentRow) Comment() Comment {
QuickActionID: r.QuickActionID,
ViaPluginID: r.ViaPluginID,
Revision: r.Revision,
+ DeletedAt: r.DeletedAt,
}
}
@@ -47,5 +48,6 @@ func (r UpdateCommentRow) Comment() Comment {
QuickActionID: r.QuickActionID,
ViaPluginID: r.ViaPluginID,
Revision: r.Revision,
+ DeletedAt: r.DeletedAt,
}
}
diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.go
index 171f8275f0..d505d27b5a 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -1426,6 +1426,35 @@ func (q *Queries) LockIssueDuplicateKey(ctx context.Context, dollar_1 string) er
return err
}
+const lockIssueForAttachmentWrite = `-- name: LockIssueForAttachmentWrite :one
+SELECT id FROM issue
+WHERE id = $1 AND workspace_id = $2
+FOR NO KEY UPDATE
+`
+
+type LockIssueForAttachmentWriteParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Owner-first guard for a write to one of an issue's attachments: take the
+// issue before the attachment row, so a writer that reaches the same row
+// through the issue — teardown's issue_id cascade, or the revision bump this
+// write itself performs — either waits for this transaction or is waited on,
+// never both.
+//
+// FOR NO KEY UPDATE, the mode of that revision bump, is the weakest mode that
+// actually serializes issue writers. FOR KEY SHARE is NOT enough: it is
+// compatible with FOR NO KEY UPDATE (see LockLiveComment), so a concurrent
+// CreateComment would take the issue anyway, wait on the attachment this
+// transaction holds, and deadlock with its bump.
+func (q *Queries) LockIssueForAttachmentWrite(ctx context.Context, arg LockIssueForAttachmentWriteParams) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, lockIssueForAttachmentWrite, arg.ID, arg.WorkspaceID)
+ var id pgtype.UUID
+ err := row.Scan(&id)
+ return id, err
+}
+
const lockIssueForChannelMediaBind = `-- name: LockIssueForChannelMediaBind :one
SELECT id FROM issue
WHERE id = $1 AND workspace_id = $2
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 40af69e1f2..2651a6f2bf 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -562,6 +562,7 @@ type Comment struct {
ViaPluginID pgtype.UUID `json:"via_plugin_id"`
Revision int64 `json:"revision"`
RecoverySettledAt pgtype.Timestamptz `json:"recovery_settled_at"`
+ DeletedAt pgtype.Timestamptz `json:"deleted_at"`
}
type CommentReaction struct {
diff --git a/server/pkg/db/generated/reaction.sql.go b/server/pkg/db/generated/reaction.sql.go
index 74f9d5f5db..6f1307849d 100644
--- a/server/pkg/db/generated/reaction.sql.go
+++ b/server/pkg/db/generated/reaction.sql.go
@@ -77,6 +77,22 @@ func (q *Queries) AddReaction(ctx context.Context, arg AddReactionParams) (AddRe
return i, err
}
+const deleteCommentReactions = `-- name: DeleteCommentReactions :exec
+DELETE FROM comment_reaction
+WHERE comment_id = $1 AND workspace_id = $2
+`
+
+type DeleteCommentReactionsParams struct {
+ CommentID pgtype.UUID `json:"comment_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Part of the comment delete transaction: reactions go with the comment.
+func (q *Queries) DeleteCommentReactions(ctx context.Context, arg DeleteCommentReactionsParams) error {
+ _, err := q.db.Exec(ctx, deleteCommentReactions, arg.CommentID, arg.WorkspaceID)
+ return err
+}
+
const listReactionsByCommentIDs = `-- name: ListReactionsByCommentIDs :many
SELECT id, comment_id, workspace_id, actor_type, actor_id, emoji, created_at FROM comment_reaction
WHERE comment_id = ANY($1::uuid[])
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 8d0c0e6307..2ff6594ece 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -2113,6 +2113,8 @@ WHERE recovery.author_type = 'system'
AND recovery.type = 'progress_update'
AND recovery.source_task_id IS NOT NULL
AND recovery.recovery_settled_at IS NULL
+ -- A deleted recovery signal is withdrawn, even when replies keep its row.
+ AND recovery.deleted_at IS NULL
AND recovery.issue_id = source_issue.id
AND recovery.workspace_id = source_issue.workspace_id
AND failed.status = 'failed'
diff --git a/server/pkg/db/queries/attachment.sql b/server/pkg/db/queries/attachment.sql
index a9d79404a7..6dc6492794 100644
--- a/server/pkg/db/queries/attachment.sql
+++ b/server/pkg/db/queries/attachment.sql
@@ -84,6 +84,13 @@ WHERE a.issue_id = $1
SELECT url FROM attachment
WHERE comment_id = $1;
+-- name: DeleteCommentAttachments :many
+-- Part of the comment delete transaction: removes the deleted comment's
+-- attachments and returns their storage URLs for cleanup after commit.
+DELETE FROM attachment
+WHERE comment_id = @comment_id AND workspace_id = @workspace_id
+RETURNING url;
+
-- name: LinkAttachmentsToComment :exec
UPDATE attachment
SET comment_id = $1
@@ -174,9 +181,12 @@ WHERE chat_message_id = ANY($1::uuid[]) AND workspace_id = $2
ORDER BY created_at ASC;
-- name: LockAttachmentsForIssueLink :many
--- Issue updates bind attachments and then touch the owner row. Lock eligible
--- attachment rows first so every attachment -> issue mutation uses the same
--- lock order as DeleteAttachment and cannot deadlock with it.
+-- Issue updates bind attachments and then touch the owner row. Only rows that
+-- belong to no issue yet are eligible, and nothing reaches those through an
+-- issue — not teardown's cascade, not DeleteAttachment, which takes the owning
+-- issue first — so locking them before the owner cannot deadlock.
+-- Attachments that DO belong to the issue are locked after it; see
+-- LockAttachmentsForCommentLink.
SELECT id FROM attachment
WHERE workspace_id = sqlc.arg(workspace_id)
AND issue_id IS NULL
@@ -185,6 +195,31 @@ WHERE workspace_id = sqlc.arg(workspace_id)
ORDER BY id
FOR UPDATE;
+-- name: LockAttachmentsForCommentLink :many
+-- CreateComment binds attachments in the transaction that created the comment,
+-- after the CreateComment statement has taken the issue row: issue -> comment
+-- -> child, the order every owner-first mutation here uses. This pins the
+-- requested set under that lock and returns the ids still eligible, so the
+-- caller can refuse before the comment is committed when a requested
+-- attachment was deleted while the issue lock was contended.
+SELECT id FROM attachment
+WHERE workspace_id = sqlc.arg(workspace_id)
+ AND issue_id = sqlc.arg(issue_id)
+ AND comment_id IS NULL
+ AND source_context_id IS NULL
+ AND id = ANY(sqlc.arg(attachment_ids)::uuid[])
+ORDER BY id
+FOR UPDATE;
+
+-- name: LockAttachmentRow :one
+-- Locks an attachment that has no owner to lock instead — a chat, avatar or
+-- still-unbound upload. Reading it under its own lock is what keeps it from
+-- gaining an owner between the read and the write, which would put the write
+-- back in the attachment -> issue order issue teardown deadlocks with.
+SELECT * FROM attachment
+WHERE id = $1 AND workspace_id = $2
+FOR UPDATE;
+
-- name: LinkAttachmentsToIssue :one
WITH linked AS (
UPDATE attachment
diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sql
index e0749ccdac..8d5131b531 100644
--- a/server/pkg/db/queries/comment.sql
+++ b/server/pkg/db/queries/comment.sql
@@ -108,7 +108,7 @@ thread_stats AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
- c.source_task_id, c.quick_action_id, c.revision,
+ c.source_task_id, c.quick_action_id, c.revision, c.deleted_at,
ts.reply_count AS reply_count,
ts.last_activity_at AS last_activity_at
FROM selected_roots sr
@@ -154,7 +154,7 @@ thread_stats AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
- c.source_task_id, c.quick_action_id, c.revision,
+ c.source_task_id, c.quick_action_id, c.revision, c.deleted_at,
ts.reply_count AS reply_count,
ts.last_activity_at AS last_activity_at
FROM selected_roots sr
@@ -195,14 +195,14 @@ descendants AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
- c.source_task_id, c.quick_action_id, c.revision
+ c.source_task_id, c.quick_action_id, c.revision, c.deleted_at
FROM comment c
JOIN thread_root tr ON c.id = tr.id
UNION
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
- c.source_task_id, c.quick_action_id, c.revision
+ c.source_task_id, c.quick_action_id, c.revision, c.deleted_at
FROM comment c
JOIN descendants d ON c.parent_id = d.id
WHERE c.issue_id = @issue_id AND c.workspace_id = @workspace_id
@@ -211,7 +211,7 @@ reply_page AS (
SELECT d.id, d.issue_id, d.author_type, d.author_id, d.content, d.type,
d.created_at, d.updated_at, d.parent_id, d.workspace_id,
d.resolved_at, d.resolved_by_type, d.resolved_by_id,
- d.source_task_id, d.quick_action_id, d.revision
+ d.source_task_id, d.quick_action_id, d.revision, d.deleted_at
FROM descendants d
WHERE d.id NOT IN (SELECT id FROM thread_root)
AND (
@@ -224,19 +224,19 @@ reply_page AS (
SELECT 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,
- source_task_id, quick_action_id, revision
+ source_task_id, quick_action_id, revision, deleted_at
FROM (
SELECT d.id, d.issue_id, d.author_type, d.author_id, d.content, d.type,
d.created_at, d.updated_at, d.parent_id, d.workspace_id,
d.resolved_at, d.resolved_by_type, d.resolved_by_id,
- d.source_task_id, d.quick_action_id, d.revision
+ d.source_task_id, d.quick_action_id, d.revision, d.deleted_at
FROM descendants d
JOIN thread_root tr ON d.id = tr.id
UNION ALL
SELECT 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,
- source_task_id, quick_action_id, revision
+ source_task_id, quick_action_id, revision, deleted_at
FROM reply_page
) combined
ORDER BY created_at ASC, id ASC;
@@ -301,7 +301,7 @@ picked AS (
SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,
c.created_at, c.updated_at, c.parent_id, c.workspace_id,
c.resolved_at, c.resolved_by_type, c.resolved_by_id,
- c.source_task_id, c.quick_action_id, c.revision,
+ c.source_task_id, c.quick_action_id, c.revision, c.deleted_at,
p.root_id AS thread_root_id,
p.last_activity_at AS thread_last_activity_at
FROM picked p
@@ -327,6 +327,7 @@ WHERE issue_id = @issue_id
AND workspace_id = @workspace_id
AND created_at > @since
AND id <> @anchor_id
+ AND deleted_at IS NULL
AND NOT (author_type = 'agent' AND author_id = @author_id);
-- name: GetLatestMemberCommentForIssueSince :one
@@ -343,6 +344,7 @@ SELECT * FROM comment
WHERE issue_id = @issue_id
AND author_type = 'member'
AND created_at > @since
+ AND deleted_at IS NULL
ORDER BY created_at DESC
LIMIT 1;
@@ -377,6 +379,8 @@ SELECT * FROM comment
WHERE issue_id = @issue_id
AND (id = ANY(@planned_comment_ids::uuid[])
OR comment_thread_root_id(id) = sqlc.narg('comment_thread_id')::uuid)
+ -- A deleted comment is no longer input, even when replies keep its row.
+ AND deleted_at IS NULL
AND (
(
author_type IN ('member', 'agent')
@@ -503,6 +507,8 @@ WITH locked_issue AS MATERIALIZED (
CROSS JOIN issue_fence
WHERE comment.id = $1
AND issue_fence.locked_count >= 0
+ -- A deleted comment's tombstone is not editable.
+ AND comment.deleted_at IS NULL
AND (sqlc.narg('expected_revision')::bigint IS NULL OR revision = sqlc.narg('expected_revision')::bigint)
AND (
sqlc.narg('content_base')::text IS NULL
@@ -523,7 +529,7 @@ WITH locked_issue AS MATERIALIZED (
comment.parent_id, comment.workspace_id, comment.resolved_at,
comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id,
comment.quick_action_id, comment.via_plugin_id, comment.revision,
- target.did_change
+ comment.deleted_at, target.did_change
), touched_issue AS (
UPDATE issue
SET revision = issue.revision + 1,
@@ -541,6 +547,7 @@ SELECT updated_comment.id, updated_comment.issue_id, updated_comment.author_type
updated_comment.resolved_by_type, updated_comment.resolved_by_id,
updated_comment.source_task_id, updated_comment.quick_action_id,
updated_comment.via_plugin_id, updated_comment.revision,
+ updated_comment.deleted_at,
COALESCE((SELECT revision FROM touched_issue), 0)::bigint AS issue_revision
FROM updated_comment;
@@ -559,6 +566,7 @@ SELECT EXISTS (
AND author_type = 'agent'
AND author_id = @author_id
AND created_at >= @since
+ AND deleted_at IS NULL
) AS commented;
-- name: HasAgentRepliedInThread :one
@@ -568,43 +576,122 @@ SELECT EXISTS (
SELECT count(*) > 0 AS has_replied FROM comment
WHERE parent_id = @parent_id AND author_type = 'agent' AND author_id = @agent_id;
--- name: DeleteComment :one
--- Defense-in-depth: workspace_id is a SQL-layer tenant guard. See DeleteIssue.
+-- name: LockCommentForDelete :one
+-- First statement of the comment delete transaction (#8296). Defense-in-depth:
+-- workspace_id is a SQL-layer tenant guard. See DeleteIssue.
+--
+-- It takes the aggregate owner's lock before the comment's, so deleting cannot
+-- deadlock with issue teardown (which takes the same issue -> comment order).
+-- The issue lock is also what freezes the thread: every comment insert goes
+-- through CreateComment, whose first step updates this issue row, so no reply
+-- can be added to the issue until the delete transaction ends. The caller's
+-- later statements start from a fresh snapshot taken after the locks, which is
+-- what makes their reply check exact.
+--
+-- A tombstone is excluded: deleting an already-deleted comment finds nothing.
WITH locked_issue AS MATERIALIZED (
- -- Lock the aggregate owner before its child so this cannot deadlock with
- -- issue teardown (which takes the same issue -> comment order).
SELECT issue.id
FROM issue
JOIN comment ON comment.issue_id = issue.id
AND comment.workspace_id = issue.workspace_id
- WHERE comment.id = $1 AND comment.workspace_id = $2
+ WHERE comment.id = @id AND comment.workspace_id = @workspace_id
FOR UPDATE OF issue
), issue_fence AS MATERIALIZED (
-- The consumed locked_count below is the ordering fence: the issue lock is
- -- acquired before DELETE can lock the comment. MATERIALIZED only prevents
+ -- acquired before the comment lock. MATERIALIZED only prevents
-- folding/re-evaluation and is not, by itself, a lock-order guarantee.
SELECT count(*) AS locked_count FROM locked_issue
-), deleted_comment AS (
- DELETE FROM comment
- USING issue_fence
- WHERE comment.id = $1 AND comment.workspace_id = $2
- AND issue_fence.locked_count >= 0
- RETURNING issue_id, workspace_id
-), touched_issue AS (
- UPDATE issue
- SET revision = issue.revision + 1,
- last_activity_at = GREATEST(COALESCE(issue.last_activity_at, issue.updated_at), now())
- FROM deleted_comment
- WHERE issue.id = deleted_comment.issue_id
- AND issue.workspace_id = deleted_comment.workspace_id
- RETURNING issue.id, issue.revision
)
-SELECT EXISTS(SELECT 1 FROM deleted_comment) AS changed,
- COALESCE((SELECT revision FROM touched_issue), 0)::bigint AS issue_revision;
+SELECT comment.*
+FROM comment
+CROSS JOIN issue_fence
+WHERE comment.id = @id AND comment.workspace_id = @workspace_id
+ AND comment.deleted_at IS NULL
+ AND issue_fence.locked_count >= 0
+FOR UPDATE OF comment;
+
+-- name: LockLiveComment :one
+-- Locks a live comment ahead of a write to one of its children — reactions and
+-- attachments — in the order every comment mutation shares: issue, then
+-- comment, then child. A comment deleted before or while this waits reads as
+-- absent (the row lock re-checks deleted_at), so no child can land on its
+-- tombstone. FOR NO KEY UPDATE conflicts with the delete transaction's FOR
+-- UPDATE but not with a reply's FOR KEY SHARE, so it never blocks replies.
+WITH locked_issue AS MATERIALIZED (
+ SELECT issue.id
+ FROM issue
+ JOIN comment ON comment.issue_id = issue.id
+ AND comment.workspace_id = issue.workspace_id
+ WHERE comment.id = @id AND comment.workspace_id = @workspace_id
+ FOR NO KEY UPDATE OF issue
+), issue_fence AS MATERIALIZED (
+ SELECT count(*) AS locked_count FROM locked_issue
+)
+SELECT comment.*
+FROM comment
+CROSS JOIN issue_fence
+WHERE comment.id = @id AND comment.workspace_id = @workspace_id
+ AND comment.deleted_at IS NULL
+ AND issue_fence.locked_count >= 0
+FOR NO KEY UPDATE OF comment;
+
+-- name: CommentHasReplies :one
+SELECT EXISTS (
+ SELECT 1 FROM comment
+ WHERE parent_id = @id AND workspace_id = @workspace_id
+) AS has_replies;
+
+-- name: TombstoneComment :one
+-- Deletes a comment that still has replies by clearing it in place. The row,
+-- its id and its parent_id stay so every reply keeps its direct parent; the
+-- body goes, and so does any resolution, since a deleted comment cannot be a
+-- thread's conclusion. The caller removes attachments and reactions in the
+-- same transaction.
+UPDATE comment SET
+ content = '',
+ deleted_at = now(),
+ resolved_at = NULL,
+ resolved_by_type = NULL,
+ resolved_by_id = NULL,
+ revision = revision + 1,
+ updated_at = now()
+WHERE id = @id AND workspace_id = @workspace_id
+ AND deleted_at IS NULL
+RETURNING *;
+
+-- name: DeleteLeafComment :one
+-- Removes a comment that has no replies. The NOT EXISTS guard keeps this
+-- statement from ever reaching the legacy parent_id cascade: a comment with a
+-- reply is tombstoned instead, never deleted with its replies.
+DELETE FROM comment
+WHERE comment.id = @id AND comment.workspace_id = @workspace_id
+ AND NOT EXISTS (SELECT 1 FROM comment child WHERE child.parent_id = comment.id)
+RETURNING comment.id, comment.parent_id;
+
+-- name: DeleteReplylessCommentTombstone :one
+-- Removes a tombstone whose last reply is gone. The delete transaction calls
+-- this for each ancestor in turn, so a chain of placeholders never outlives
+-- the replies it kept attached.
+DELETE FROM comment
+WHERE comment.id = @id AND comment.workspace_id = @workspace_id
+ AND comment.deleted_at IS NOT NULL
+ AND NOT EXISTS (SELECT 1 FROM comment child WHERE child.parent_id = comment.id)
+RETURNING comment.id, comment.parent_id;
+
+-- name: TouchIssueForCommentDelete :one
+-- A delete counts as activity on its issue, like CreateComment and
+-- UpdateComment. Runs inside the delete transaction after the comment rows
+-- changed, so a delete that lost its race never touches the issue.
+UPDATE issue
+SET revision = revision + 1,
+ last_activity_at = GREATEST(COALESCE(last_activity_at, updated_at), now())
+WHERE id = @issue_id AND workspace_id = @workspace_id
+RETURNING revision;
-- name: ResolveComment :one
-- Idempotent: re-resolving keeps the original resolved_at + resolver. Always
--- returns the row so the handler can surface the canonical state.
+-- returns the row so the handler can surface the canonical state — unless the
+-- comment has been deleted, whose tombstone cannot be a resolution.
UPDATE comment SET
resolved_at = COALESCE(resolved_at, now()),
resolved_by_type = COALESCE(resolved_by_type, $2),
@@ -612,6 +699,7 @@ UPDATE comment SET
revision = revision + CASE WHEN resolved_at IS NULL THEN 1 ELSE 0 END,
updated_at = CASE WHEN resolved_at IS NULL THEN now() ELSE updated_at END
WHERE id = $1
+ AND deleted_at IS NULL
RETURNING *;
-- name: ClearOtherThreadResolutions :many
@@ -695,7 +783,7 @@ WITH RECURSIVE ancestor_path AS (
SELECT id, issue_id, author_type, author_id, content, type, created_at,
updated_at, workspace_id, parent_id, resolved_at, resolved_by_type,
resolved_by_id, source_task_id, revision, quick_action_id, via_plugin_id,
- depth, cycle
+ deleted_at, depth, cycle
FROM ancestor_path
ORDER BY depth DESC;
diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sql
index e868abcbed..08d7c62112 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -95,6 +95,22 @@ SELECT id FROM issue
WHERE id = $1 AND workspace_id = $2
FOR KEY SHARE;
+-- name: LockIssueForAttachmentWrite :one
+-- Owner-first guard for a write to one of an issue's attachments: take the
+-- issue before the attachment row, so a writer that reaches the same row
+-- through the issue — teardown's issue_id cascade, or the revision bump this
+-- write itself performs — either waits for this transaction or is waited on,
+-- never both.
+--
+-- FOR NO KEY UPDATE, the mode of that revision bump, is the weakest mode that
+-- actually serializes issue writers. FOR KEY SHARE is NOT enough: it is
+-- compatible with FOR NO KEY UPDATE (see LockLiveComment), so a concurrent
+-- CreateComment would take the issue anyway, wait on the attachment this
+-- transaction holds, and deadlock with its bump.
+SELECT id FROM issue
+WHERE id = $1 AND workspace_id = $2
+FOR NO KEY UPDATE;
+
-- name: LockIssueForDescriptionUpdate :one
-- Serialize field-baseline checks and combined attachment binding on the
-- owner row. The handler merges channel media that landed after the editor's
diff --git a/server/pkg/db/queries/reaction.sql b/server/pkg/db/queries/reaction.sql
index b6b4716658..1c060c67dc 100644
--- a/server/pkg/db/queries/reaction.sql
+++ b/server/pkg/db/queries/reaction.sql
@@ -40,3 +40,8 @@ SELECT EXISTS(SELECT 1 FROM deleted) AS changed,
SELECT * FROM comment_reaction
WHERE comment_id = ANY($1::uuid[])
ORDER BY created_at ASC;
+
+-- name: DeleteCommentReactions :exec
+-- Part of the comment delete transaction: reactions go with the comment.
+DELETE FROM comment_reaction
+WHERE comment_id = @comment_id AND workspace_id = @workspace_id;
diff --git a/server/pkg/publicapi/v1/openapi.yaml b/server/pkg/publicapi/v1/openapi.yaml
index 0ebcbceffd..856fa1fc76 100644
--- a/server/pkg/publicapi/v1/openapi.yaml
+++ b/server/pkg/publicapi/v1/openapi.yaml
@@ -363,6 +363,10 @@ components:
type: { type: string }
parent_id: { type: string }
created_at: { type: string, format: date-time }
+ deleted_at:
+ type: string
+ format: date-time
+ description: Set only on a deleted comment kept as an empty placeholder because it still has replies.
CommentListResponse:
type: object
required: [comments]
diff --git a/server/pkg/publicapi/v1/types.go b/server/pkg/publicapi/v1/types.go
index 5894bfb1bd..6d24e7b010 100644
--- a/server/pkg/publicapi/v1/types.go
+++ b/server/pkg/publicapi/v1/types.go
@@ -73,6 +73,9 @@ type Comment struct {
Type string `json:"type"`
ParentID string `json:"parent_id,omitempty"`
CreatedAt string `json:"created_at"`
+ // DeletedAt is set only on a tombstone: a comment deleted while it still
+ // had replies, kept with empty content so those replies keep their parent.
+ DeletedAt string `json:"deleted_at,omitempty"`
}
type CommentListResponse struct {