Skip to content

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

Go

feat(issues): add revision-aware concurrency guards (#7038)

YYClaw4b8873df3ac2
diff --git a/apps/mobile/app/(app)/[workspace]/issue/[id]/edit.tsx b/apps/mobile/app/(app)/[workspace]/issue/[id]/edit.tsx
index 1890f86936..c803c9b465 100644
--- a/apps/mobile/app/(app)/[workspace]/issue/[id]/edit.tsx
+++ b/apps/mobile/app/(app)/[workspace]/issue/[id]/edit.tsx
@@ -37,6 +37,7 @@ import { MentionSuggestionBar } from "@/components/issue/mention-suggestion-bar"
import { MOBILE_PLACEHOLDER_COLOR } from "@/components/ui/input-tokens";
import { issueDetailOptions } from "@/data/queries/issues";
import { useUpdateIssue } from "@/data/mutations/issues";
+import { buildIssueTextUpdate } from "@/data/issue-edit";
import { useWorkspaceStore } from "@/data/workspace-store";
import { useMentionInput } from "@/lib/use-mention-input";
@@ -47,7 +48,8 @@ export default function EditIssue() {
const update = useUpdateIssue(id);
const [title, setTitle] = useState("");
- const [descriptionBase, setDescriptionBase] = useState("");
+ const [initialTitle, setInitialTitle] = useState("");
+ const [initialDescription, setInitialDescription] = useState("");
const description = useMentionInput();
const [seeded, setSeeded] = useState(false);
// `useMentionInput` returns `setText` from `useState`, which is a stable
@@ -60,9 +62,10 @@ export default function EditIssue() {
useEffect(() => {
if (!detail.data || seeded) return;
setTitle(detail.data.title);
+ setInitialTitle(detail.data.title);
const initial = detail.data.description ?? "";
setDescriptionText(stripChannelMediaMarkers(initial));
- setDescriptionBase(initial);
+ setInitialDescription(initial);
setSeeded(true);
}, [detail.data, seeded, setDescriptionText]);
@@ -71,11 +74,11 @@ export default function EditIssue() {
const dirty = useMemo(() => {
if (!detail.data || !seeded) return false;
return (
- title.trim() !== detail.data.title ||
+ title.trim() !== initialTitle ||
currentDescription.trim() !==
- stripChannelMediaMarkers(descriptionBase).trim()
+ stripChannelMediaMarkers(initialDescription).trim()
);
- }, [detail.data, seeded, title, currentDescription, descriptionBase]);
+ }, [detail.data, seeded, title, initialTitle, currentDescription, initialDescription]);
const canSave =
seeded && title.trim().length > 0 && dirty && !update.isPending;
@@ -103,12 +106,11 @@ export default function EditIssue() {
if (!canSave) return;
// `UpdateIssueRequest.description` is `string | undefined` — server
// treats empty string as "clear the description", which is what we
- // want when the user wipes the field.
- const patch = {
- title: title.trim(),
- description: currentDescription.trim(),
- description_base: descriptionBase,
- };
+ // want when the user wipes the field. Mobile deliberately omits strict
+ // text baselines until this screen has a conflict reconciliation flow;
+ // otherwise a real 409 would leave the draft in an unrecoverable retry
+ // loop. Web/desktop keep baseline protection with their compare UI.
+ const patch = buildIssueTextUpdate(title, currentDescription);
update.mutate(patch, {
onSuccess: () => router.back(),
onError: (err) => {
@@ -118,7 +120,7 @@ export default function EditIssue() {
);
},
});
- }, [canSave, title, currentDescription, descriptionBase, update]);
+ }, [canSave, title, currentDescription, update]);
const headerLeft = useCallback(
() => (
diff --git a/apps/mobile/data/api.ts b/apps/mobile/data/api.ts
index 50e1843dcc..3a8e6d9fda 100644
--- a/apps/mobile/data/api.ts
+++ b/apps/mobile/data/api.ts
@@ -121,6 +121,7 @@ import type { ZodType } from "zod";
import { getCurrentSlug } from "./workspace-store";
import { parseWithFallback } from "@/lib/parse-response";
import { createRequestId } from "@/lib/request-id";
+import { buildCommentUpdateBody } from "./revision";
const API_URL = process.env.EXPO_PUBLIC_API_URL;
@@ -718,6 +719,7 @@ class ApiClient {
commentId: string,
content: string,
attachmentIds?: string[],
+ contentBase?: string,
): Promise<Comment> {
return this.fetchValidatedWith(
`/api/comments/${commentId}`,
@@ -725,10 +727,9 @@ class ApiClient {
EMPTY_COMMENT,
{
method: "PUT",
- body: JSON.stringify({
- content,
- ...(attachmentIds ? { attachment_ids: attachmentIds } : {}),
- }),
+ body: JSON.stringify(
+ buildCommentUpdateBody(content, attachmentIds, contentBase),
+ ),
},
{ endpoint: "updateComment" },
);
diff --git a/apps/mobile/data/issue-edit.test.ts b/apps/mobile/data/issue-edit.test.ts
new file mode 100644
index 0000000000..958fe279e5
--- /dev/null
+++ b/apps/mobile/data/issue-edit.test.ts
@@ -0,0 +1,12 @@
+import { describe, expect, it } from "vitest";
+
+import { buildIssueTextUpdate } from "./issue-edit";
+
+describe("buildIssueTextUpdate", () => {
+ it("keeps mobile text saves last-write-wins until conflict reconciliation exists", () => {
+ expect(buildIssueTextUpdate(" Updated title ", " Updated body ")).toEqual({
+ title: "Updated title",
+ description: "Updated body",
+ });
+ });
+});
diff --git a/apps/mobile/data/issue-edit.ts b/apps/mobile/data/issue-edit.ts
new file mode 100644
index 0000000000..8e746aa9c2
--- /dev/null
+++ b/apps/mobile/data/issue-edit.ts
@@ -0,0 +1,16 @@
+import type { UpdateIssueRequest } from "@multica/core/types";
+
+/**
+ * Mobile keeps text edits last-write-wins until it has a conflict comparison
+ * flow. Sending title_base/description_base without that recovery UI would
+ * turn a real 409 into an unrecoverable retry loop for the in-memory draft.
+ */
+export function buildIssueTextUpdate(
+ title: string,
+ description: string,
+): UpdateIssueRequest {
+ return {
+ title: title.trim(),
+ description: description.trim(),
+ };
+}
diff --git a/apps/mobile/data/mutations/issues.ts b/apps/mobile/data/mutations/issues.ts
index 208b1fd270..50d4f42aca 100644
--- a/apps/mobile/data/mutations/issues.ts
+++ b/apps/mobile/data/mutations/issues.ts
@@ -30,6 +30,18 @@ import { inboxKeys } from "@/data/queries/inbox";
import { useAuthStore } from "@/data/auth-store";
import { useWorkspaceStore } from "@/data/workspace-store";
import { useFailedCommentsStore } from "@/data/stores/failed-comments-store";
+import {
+ commentContentFromTimeline,
+ shouldAcceptServerRevision,
+} from "@/data/revision";
+import {
+ advanceCommentRevision,
+ onIssueAuxiliaryRevision,
+ reconcileIssueFullSnapshotRevision,
+ commentToTimelineEntry,
+ patchIssueLabels,
+ replaceCommentTimelineEntry,
+} from "@/data/realtime/issue-ws-updaters";
export type ToggleCommentReactionVars = {
commentId: string;
@@ -116,7 +128,10 @@ export function useCreateComment(issueId: string) {
// to keep its optimistic entry so the inline retry UI has something to
// render against. The success refetch replaces the synthetic id with
// the server-issued one (same ASC bottom position).
- onSuccess: () => {
+ onSuccess: (comment) => {
+ if (wsId) {
+ onIssueAuxiliaryRevision(qc, wsId, issueId, comment.issue_revision);
+ }
qc.invalidateQueries({
queryKey: issueKeys.timeline(wsId, issueId),
});
@@ -208,6 +223,17 @@ export function useToggleCommentReaction(issueId: string) {
qc.setQueryData(ctx.key, ctx.prev);
}
},
+ onSuccess: (reaction, vars) => {
+ if (reaction && wsId) {
+ advanceCommentRevision(
+ qc,
+ wsId,
+ issueId,
+ vars.commentId,
+ reaction.comment_revision,
+ );
+ }
+ },
onSettled: () => {
qc.invalidateQueries({ queryKey: issueKeys.timeline(wsId, issueId) });
},
@@ -235,7 +261,17 @@ export function useEditComment(issueId: string) {
commentId: string;
content: string;
attachmentIds?: string[];
- }) => api.updateComment(commentId, content, attachmentIds),
+ }) => {
+ const timeline = qc.getQueryData<TimelineEntry[]>(
+ issueKeys.timeline(wsId, issueId),
+ );
+ return api.updateComment(
+ commentId,
+ content,
+ attachmentIds,
+ commentContentFromTimeline(timeline, commentId),
+ );
+ },
onMutate: async ({ commentId, content }) => {
const key = issueKeys.timeline(wsId, issueId);
await qc.cancelQueries({ queryKey: key });
@@ -258,6 +294,16 @@ export function useEditComment(issueId: string) {
qc.setQueryData(ctx.key, ctx.prev);
}
},
+ onSuccess: (comment) => {
+ if (wsId) {
+ replaceCommentTimelineEntry(
+ qc,
+ wsId,
+ issueId,
+ commentToTimelineEntry(comment),
+ );
+ }
+ },
onSettled: () => {
qc.invalidateQueries({ queryKey: issueKeys.timeline(wsId, issueId) });
},
@@ -345,6 +391,16 @@ export function useResolveComment(issueId: string) {
qc.setQueryData(ctx.key, ctx.prev);
}
},
+ onSuccess: (comment) => {
+ if (wsId) {
+ replaceCommentTimelineEntry(
+ qc,
+ wsId,
+ issueId,
+ commentToTimelineEntry(comment),
+ );
+ }
+ },
onSettled: () => {
qc.invalidateQueries({ queryKey: issueKeys.timeline(wsId, issueId) });
},
@@ -402,6 +458,17 @@ export function useToggleIssueReaction(issueId: string) {
qc.setQueryData(ctx.key, ctx.prev);
}
},
+ onSuccess: (reaction) => {
+ if (reaction && wsId) {
+ onIssueAuxiliaryRevision(
+ qc,
+ wsId,
+ issueId,
+ reaction.issue_revision,
+ "issue_reactions",
+ );
+ }
+ },
onSettled: () => {
qc.invalidateQueries({ queryKey: issueKeys.detail(wsId, issueId) });
},
@@ -435,6 +502,8 @@ export function useUpdateIssue(issueId: string) {
const {
description: _description,
description_base: _descriptionBase,
+ title_base: _titleBase,
+ expected_revision: _expectedRevision,
...optimisticPatch
} = patch;
qc.setQueryData<Issue>(key, { ...prev, ...optimisticPatch });
@@ -447,7 +516,19 @@ export function useUpdateIssue(issueId: string) {
}
},
onSuccess: (server) => {
- qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), server);
+ qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), (current) =>
+ !current || shouldAcceptServerRevision(current.revision, server.revision)
+ ? server
+ : current,
+ );
+ if (wsId) {
+ reconcileIssueFullSnapshotRevision(
+ qc,
+ wsId,
+ issueId,
+ server.revision,
+ );
+ }
},
onSettled: () => {
qc.invalidateQueries({ queryKey: issueKeys.detail(wsId, issueId) });
@@ -494,10 +575,8 @@ export function useAttachLabel(issueId: string) {
}
},
onSuccess: (server) => {
- const key = issueKeys.detail(wsId, issueId);
- const current = qc.getQueryData<Issue>(key);
- if (current) {
- qc.setQueryData<Issue>(key, { ...current, labels: server.labels });
+ if (wsId) {
+ patchIssueLabels(qc, wsId, issueId, server.labels, server.issue_revision);
}
},
onSettled: () => {
@@ -534,10 +613,8 @@ export function useDetachLabel(issueId: string) {
}
},
onSuccess: (server) => {
- const key = issueKeys.detail(wsId, issueId);
- const current = qc.getQueryData<Issue>(key);
- if (current) {
- qc.setQueryData<Issue>(key, { ...current, labels: server.labels });
+ if (wsId) {
+ patchIssueLabels(qc, wsId, issueId, server.labels, server.issue_revision);
}
},
onSettled: () => {
diff --git a/apps/mobile/data/realtime/issue-ws-updaters.test.ts b/apps/mobile/data/realtime/issue-ws-updaters.test.ts
index 08071fa1d5..a2acf90de7 100644
--- a/apps/mobile/data/realtime/issue-ws-updaters.test.ts
+++ b/apps/mobile/data/realtime/issue-ws-updaters.test.ts
@@ -1,8 +1,18 @@
import { QueryClient } from "@tanstack/react-query";
+import type { Issue, IssueReaction, TimelineEntry } from "@multica/core/types";
import { describe, expect, it, vi } from "vitest";
import { issueKeys } from "@/data/queries/issue-keys";
-import { invalidateIssueAfterReconnect } from "./issue-ws-updaters";
+import {
+ addCommentReaction,
+ addIssueReaction,
+ onIssueAuxiliaryRevision,
+ invalidateIssueAfterReconnect,
+ patchIssueDetail,
+ patchIssueLabels,
+ removeIssueReaction,
+ replaceCommentTimelineEntry,
+} from "./issue-ws-updaters";
describe("invalidateIssueAfterReconnect", () => {
it("invalidates attachments together with the issue and task caches", () => {
@@ -22,3 +32,227 @@ describe("invalidateIssueAfterReconnect", () => {
]);
});
});
+
+describe("mobile issue revision gates", () => {
+ const wsId = "workspace-1";
+ const issueId = "issue-1";
+
+ it("rejects stale issue snapshots and accepts a newer one", () => {
+ const qc = new QueryClient();
+ qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), {
+ id: issueId,
+ title: "revision 5",
+ revision: 5,
+ } as Issue);
+
+ patchIssueDetail(qc, wsId, { id: issueId, title: "stale", revision: 4 });
+ expect(qc.getQueryData<Issue>(issueKeys.detail(wsId, issueId))?.title).toBe("revision 5");
+
+ patchIssueDetail(qc, wsId, { id: issueId, title: "revision 6", revision: 6 });
+ expect(qc.getQueryData<Issue>(issueKeys.detail(wsId, issueId))).toMatchObject({
+ title: "revision 6",
+ revision: 6,
+ });
+ });
+
+ it("invalidates instead of blind-merging an unversioned event over versioned state", () => {
+ const qc = new QueryClient();
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+ qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), {
+ id: issueId,
+ title: "known",
+ revision: 5,
+ } as Issue);
+
+ patchIssueDetail(qc, wsId, { id: issueId, title: "unknown order" });
+
+ expect(qc.getQueryData<Issue>(issueKeys.detail(wsId, issueId))?.title).toBe("known");
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: issueKeys.detail(wsId, issueId) });
+ });
+
+ it("keeps comment content and reactions monotonic", () => {
+ const qc = new QueryClient();
+ const key = issueKeys.timeline(wsId, issueId);
+ const current = {
+ type: "comment",
+ id: "comment-1",
+ actor_type: "member",
+ actor_id: "member-1",
+ created_at: "2026-01-01T00:00:00Z",
+ content: "revision 5",
+ revision: 5,
+ reactions: [],
+ } as TimelineEntry;
+ qc.setQueryData<TimelineEntry[]>(key, [current]);
+
+ replaceCommentTimelineEntry(qc, wsId, issueId, {
+ ...current,
+ content: "stale",
+ revision: 4,
+ });
+ addCommentReaction(qc, wsId, issueId, "comment-1", {
+ id: "reaction-1",
+ comment_id: "comment-1",
+ actor_type: "member",
+ actor_id: "member-1",
+ emoji: "👍",
+ created_at: "2026-01-01T00:00:00Z",
+ }, 4);
+ expect(qc.getQueryData<TimelineEntry[]>(key)?.[0]).toMatchObject({
+ content: "revision 5",
+ revision: 5,
+ reactions: [],
+ });
+
+ replaceCommentTimelineEntry(qc, wsId, issueId, {
+ ...current,
+ content: "revision 6",
+ revision: 6,
+ });
+ expect(qc.getQueryData<TimelineEntry[]>(key)?.[0]).toMatchObject({
+ content: "revision 6",
+ revision: 6,
+ });
+ });
+
+ it("invalidates after a partial owner event without replacing the full snapshot revision", () => {
+ const qc = new QueryClient();
+ qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), {
+ id: issueId,
+ revision: 2,
+ } as Issue);
+ onIssueAuxiliaryRevision(qc, wsId, issueId, 7);
+ expect(qc.getQueryData<Issue>(issueKeys.detail(wsId, issueId))?.revision).toBe(2);
+ expect(qc.getQueryState(issueKeys.detail(wsId, issueId))?.isInvalidated).toBe(true);
+ });
+
+ it("accepts a full r2 snapshot after a revision-only r3 event", () => {
+ const qc = new QueryClient();
+ const key = issueKeys.detail(wsId, issueId);
+ qc.setQueryData<Issue>(key, {
+ id: issueId,
+ title: "A",
+ revision: 1,
+ } as Issue);
+
+ onIssueAuxiliaryRevision(qc, wsId, issueId, 3);
+ patchIssueDetail(qc, wsId, { id: issueId, title: "B", revision: 2 });
+
+ expect(qc.getQueryData<Issue>(key)).toMatchObject({
+ title: "B",
+ revision: 2,
+ });
+ expect(qc.getQueryState(key)?.isInvalidated).toBe(true);
+ });
+
+ it("applies auxiliary labels without claiming they are a full issue snapshot", () => {
+ const qc = new QueryClient();
+ const key = issueKeys.detail(wsId, issueId);
+ qc.setQueryData<Issue>(key, {
+ id: issueId,
+ labels: [],
+ revision: 1,
+ } as unknown as Issue);
+
+ patchIssueLabels(qc, wsId, issueId, [{
+ id: "label-1",
+ workspace_id: wsId,
+ name: "Latest",
+ color: "#000000",
+ created_at: "2026-08-17T00:00:00Z",
+ updated_at: "2026-08-17T00:00:00Z",
+ }], 3);
+
+ expect(qc.getQueryData<Issue>(key)).toMatchObject({
+ revision: 1,
+ labels: [{ id: "label-1" }],
+ });
+ expect(qc.getQueryState(key)?.isInvalidated).toBe(true);
+ });
+
+ it("rejects a delayed labels event after a newer labels projection", () => {
+ const qc = new QueryClient();
+ const key = issueKeys.detail(wsId, issueId);
+ qc.setQueryData<Issue>(key, {
+ id: issueId,
+ labels: [],
+ revision: 1,
+ } as unknown as Issue);
+
+ patchIssueLabels(qc, wsId, issueId, [{
+ id: "label-latest",
+ workspace_id: wsId,
+ name: "Latest",
+ color: "#000000",
+ created_at: "2026-08-18T00:00:00Z",
+ updated_at: "2026-08-18T00:00:00Z",
+ }], 3);
+ patchIssueLabels(qc, wsId, issueId, [{
+ id: "label-stale",
+ workspace_id: wsId,
+ name: "Stale",
+ color: "#000000",
+ created_at: "2026-08-17T00:00:00Z",
+ updated_at: "2026-08-17T00:00:00Z",
+ }], 2);
+
+ expect(qc.getQueryData<Issue>(key)?.labels).toMatchObject([
+ { id: "label-latest" },
+ ]);
+ });
+
+ it("does not let a newer generic event block the first labels projection", () => {
+ const qc = new QueryClient();
+ const key = issueKeys.detail(wsId, issueId);
+ qc.setQueryData<Issue>(key, {
+ id: issueId,
+ labels: [],
+ revision: 1,
+ } as unknown as Issue);
+
+ onIssueAuxiliaryRevision(qc, wsId, issueId, 4);
+ patchIssueLabels(
+ qc,
+ wsId,
+ issueId,
+ [
+ {
+ id: "label-3",
+ workspace_id: wsId,
+ name: "Independent",
+ color: "#000000",
+ created_at: "2026-08-18T00:00:00Z",
+ updated_at: "2026-08-18T00:00:00Z",
+ },
+ ],
+ 3,
+ );
+
+ expect(qc.getQueryData<Issue>(key)?.labels).toMatchObject([
+ { id: "label-3" },
+ ]);
+ });
+
+ it("rejects a delayed issue-reaction add after a newer removal", () => {
+ const qc = new QueryClient();
+ const key = issueKeys.detail(wsId, issueId);
+ const reaction: IssueReaction = {
+ id: "reaction-1",
+ issue_id: issueId,
+ actor_type: "member",
+ actor_id: "member-1",
+ emoji: "👍",
+ created_at: "2026-08-17T00:00:00Z",
+ };
+ qc.setQueryData<Issue>(key, {
+ id: issueId,
+ reactions: [reaction],
+ revision: 1,
+ } as unknown as Issue);
+
+ removeIssueReaction(qc, wsId, issueId, reaction.emoji, reaction.actor_id, 3);
+ addIssueReaction(qc, wsId, issueId, reaction, 2);
+
+ expect(qc.getQueryData<Issue>(key)?.reactions).toEqual([]);
+ });
+});
diff --git a/apps/mobile/data/realtime/issue-ws-updaters.ts b/apps/mobile/data/realtime/issue-ws-updaters.ts
index d5b846151f..7a21bb4d13 100644
--- a/apps/mobile/data/realtime/issue-ws-updaters.ts
+++ b/apps/mobile/data/realtime/issue-ws-updaters.ts
@@ -39,6 +39,89 @@ import { issueKeys } from "@/data/queries/issue-keys";
type TimelinePredicate = (entry: TimelineEntry) => boolean;
type TimelineMutate = (entry: TimelineEntry) => TimelineEntry;
+const auxiliaryIssueRevisions = new WeakMap<QueryClient, Map<string, number>>();
+
+type AuxiliaryIssueProjection = "generic" | "labels" | "issue_reactions";
+
+function auxiliaryIssueRevisionPrefix(wsId: string, issueId: string) {
+ return `${wsId}:${issueId}:`;
+}
+
+function auxiliaryIssueRevisionKey(
+ wsId: string,
+ issueId: string,
+ projection: AuxiliaryIssueProjection,
+) {
+ return `${auxiliaryIssueRevisionPrefix(wsId, issueId)}${projection}`;
+}
+
+function recordAuxiliaryIssueRevision(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ revision: number,
+ projection: AuxiliaryIssueProjection,
+) {
+ let revisions = auxiliaryIssueRevisions.get(qc);
+ if (!revisions) {
+ revisions = new Map();
+ auxiliaryIssueRevisions.set(qc, revisions);
+ }
+ const key = auxiliaryIssueRevisionKey(wsId, issueId, projection);
+ if ((revisions.get(key) ?? 0) < revision) revisions.set(key, revision);
+}
+
+function isOlderThanRecordedAuxiliaryProjection(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ revision: number | undefined,
+ projection: AuxiliaryIssueProjection,
+) {
+ if (revision === undefined) return false;
+ const recorded = auxiliaryIssueRevisions
+ .get(qc)
+ ?.get(auxiliaryIssueRevisionKey(wsId, issueId, projection));
+ return recorded !== undefined && revision < recorded;
+}
+
+export function reconcileIssueFullSnapshotRevision(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ fullRevision: number | undefined,
+) {
+ if (fullRevision === undefined) return;
+ const revisions = auxiliaryIssueRevisions.get(qc);
+ if (!revisions) return;
+ const prefix = auxiliaryIssueRevisionPrefix(wsId, issueId);
+ let newestAuxiliaryRevision: number | undefined;
+ for (const [key, revision] of revisions) {
+ if (!key.startsWith(prefix)) continue;
+ if (fullRevision >= revision) {
+ revisions.delete(key);
+ } else if (
+ newestAuxiliaryRevision === undefined ||
+ revision > newestAuxiliaryRevision
+ ) {
+ newestAuxiliaryRevision = revision;
+ }
+ }
+ if (newestAuxiliaryRevision !== undefined) {
+ invalidateStaleIssueOwnerProjections(
+ qc,
+ wsId,
+ issueId,
+ newestAuxiliaryRevision,
+ );
+ }
+}
+
+function acceptsRevision(current: number | undefined, incoming: number | undefined) {
+ if (current === undefined) return true;
+ return incoming !== undefined && incoming >= current;
+}
+
// =====================================================
// Issue detail cache (single Issue per id)
// =====================================================
@@ -48,9 +131,55 @@ export function patchIssueDetail(
wsId: string,
partial: Partial<Issue> & { id: string },
) {
+ if (partial.revision === undefined) {
+ qc.invalidateQueries({ queryKey: issueKeys.detail(wsId, partial.id) });
+ }
qc.setQueryData<Issue>(issueKeys.detail(wsId, partial.id), (old) =>
- old ? { ...old, ...partial } : old,
+ old && acceptsRevision(old.revision, partial.revision)
+ ? { ...old, ...partial }
+ : old,
);
+ reconcileIssueFullSnapshotRevision(qc, wsId, partial.id, partial.revision);
+}
+
+export function onIssueAuxiliaryRevision(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ revision: number | undefined,
+ projection: AuxiliaryIssueProjection = "generic",
+) {
+ if (revision === undefined) return;
+ recordAuxiliaryIssueRevision(qc, wsId, issueId, revision, projection);
+ invalidateStaleIssueOwnerProjections(qc, wsId, issueId, revision);
+}
+
+function invalidateStaleIssueOwnerProjections(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ revision: number,
+) {
+ 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))) {
+ 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))) {
+ qc.invalidateQueries({ queryKey: key, exact: true });
+ }
+ }
+ const listKey = issueKeys.list(wsId);
+ if (qc.getQueryData<Issue[]>(listKey)?.some(
+ (issue) => issue.id === issueId && isStale(issue),
+ )) {
+ qc.invalidateQueries({ queryKey: listKey, exact: true });
+ }
}
export function clearIssueDetail(
@@ -116,6 +245,43 @@ export function patchTimelineEntry(
);
}
+export function replaceCommentTimelineEntry(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ entry: TimelineEntry,
+) {
+ if (entry.revision === undefined) {
+ qc.invalidateQueries({ queryKey: issueKeys.timeline(wsId, issueId) });
+ }
+ patchTimelineEntry(
+ qc,
+ wsId,
+ issueId,
+ (current) => current.type === "comment" && current.id === entry.id,
+ (current) => acceptsRevision(current.revision, entry.revision) ? entry : current,
+ );
+}
+
+export function advanceCommentRevision(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ commentId: string,
+ revision: number | undefined,
+) {
+ if (revision === undefined) return;
+ patchTimelineEntry(
+ qc,
+ wsId,
+ issueId,
+ (entry) => entry.type === "comment" && entry.id === commentId,
+ (entry) => entry.revision === undefined || revision > entry.revision
+ ? { ...entry, revision }
+ : entry,
+ );
+}
+
export function removeTimelineEntry(
qc: QueryClient,
wsId: string,
@@ -188,12 +354,20 @@ export function patchMyIssuesList(
wsId: string,
partial: Partial<Issue> & { id: string },
) {
+ if (partial.revision === undefined) {
+ qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });
+ }
// myList is keyed by (wsId, scope, filter); we don't know which entries
// the issue belongs to, so update every cached one. Any not-yet-loaded
// list will fetch fresh on mount.
qc.setQueriesData<Issue[]>({ queryKey: issueKeys.myAll(wsId) }, (old) =>
- old ? old.map((i) => (i.id === partial.id ? { ...i, ...partial } : i)) : old,
+ old ? old.map((i) =>
+ i.id === partial.id && acceptsRevision(i.revision, partial.revision)
+ ? { ...i, ...partial }
+ : i,
+ ) : old,
);
+ reconcileIssueFullSnapshotRevision(qc, wsId, partial.id, partial.revision);
}
export function removeFromMyIssuesList(
@@ -215,9 +389,17 @@ export function patchIssuesList(
wsId: string,
partial: Partial<Issue> & { id: string },
) {
+ if (partial.revision === undefined) {
+ qc.invalidateQueries({ queryKey: issueKeys.list(wsId) });
+ }
qc.setQueryData<Issue[]>(issueKeys.list(wsId), (old) =>
- old ? old.map((i) => (i.id === partial.id ? { ...i, ...partial } : i)) : old,
+ old ? old.map((i) =>
+ i.id === partial.id && acceptsRevision(i.revision, partial.revision)
+ ? { ...i, ...partial }
+ : i,
+ ) : old,
);
+ reconcileIssueFullSnapshotRevision(qc, wsId, partial.id, partial.revision);
}
export function prependToIssuesList(
@@ -252,19 +434,21 @@ export function addCommentReaction(
issueId: string,
commentId: string,
reaction: Reaction,
+ commentRevision?: number,
) {
+ if (commentRevision === undefined) {
+ qc.invalidateQueries({ queryKey: issueKeys.timeline(wsId, issueId) });
+ }
patchTimelineEntry(
qc,
wsId,
issueId,
(e) => e.type === "comment" && e.id === commentId,
- (e) => ({
+ (e) => acceptsRevision(e.revision, commentRevision) ? ({
...e,
- reactions: [
- ...(e.reactions ?? []).filter((r) => r.id !== reaction.id),
- reaction,
- ],
- }),
+ revision: commentRevision ?? e.revision,
+ reactions: [...(e.reactions ?? []).filter((r) => r.id !== reaction.id), reaction],
+ }) : e,
);
}
@@ -275,18 +459,23 @@ export function removeCommentReaction(
commentId: string,
emoji: string,
actorId: string,
+ commentRevision?: number,
) {
+ if (commentRevision === undefined) {
+ qc.invalidateQueries({ queryKey: issueKeys.timeline(wsId, issueId) });
+ }
patchTimelineEntry(
qc,
wsId,
issueId,
(e) => e.type === "comment" && e.id === commentId,
- (e) => ({
+ (e) => acceptsRevision(e.revision, commentRevision) ? ({
...e,
+ revision: commentRevision ?? e.revision,
reactions: (e.reactions ?? []).filter(
(r) => !(r.emoji === emoji && r.actor_id === actorId),
),
- }),
+ }) : e,
);
}
@@ -295,13 +484,38 @@ export function addIssueReaction(
wsId: string,
issueId: string,
reaction: IssueReaction,
+ issueRevision?: number,
) {
+ if (
+ isOlderThanRecordedAuxiliaryProjection(
+ qc,
+ wsId,
+ issueId,
+ issueRevision,
+ "issue_reactions",
+ )
+ ) {
+ return;
+ }
+ if (issueRevision === undefined) {
+ qc.invalidateQueries({ queryKey: issueKeys.detail(wsId, issueId) });
+ }
qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), (old) => {
if (!old) return old;
+ if (!acceptsRevision(old.revision, issueRevision)) return old;
const existing = old.reactions ?? [];
- if (existing.some((r) => r.id === reaction.id)) return old;
+ if (existing.some((r) => r.id === reaction.id)) {
+ return old;
+ }
return { ...old, reactions: [...existing, reaction] };
});
+ onIssueAuxiliaryRevision(
+ qc,
+ wsId,
+ issueId,
+ issueRevision,
+ "issue_reactions",
+ );
}
export function removeIssueReaction(
@@ -310,9 +524,24 @@ export function removeIssueReaction(
issueId: string,
emoji: string,
actorId: string,
+ issueRevision?: number,
) {
+ if (
+ isOlderThanRecordedAuxiliaryProjection(
+ qc,
+ wsId,
+ issueId,
+ issueRevision,
+ "issue_reactions",
+ )
+ ) {
+ return;
+ }
+ if (issueRevision === undefined) {
+ qc.invalidateQueries({ queryKey: issueKeys.detail(wsId, issueId) });
+ }
qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), (old) =>
- old
+ old && acceptsRevision(old.revision, issueRevision)
? {
...old,
reactions: (old.reactions ?? []).filter(
@@ -321,6 +550,13 @@ export function removeIssueReaction(
}
: old,
);
+ onIssueAuxiliaryRevision(
+ qc,
+ wsId,
+ issueId,
+ issueRevision,
+ "issue_reactions",
+ );
}
// =====================================================
@@ -332,20 +568,33 @@ export function patchIssueLabels(
wsId: string,
issueId: string,
labels: Label[],
+ issueRevision?: number,
) {
+ if (
+ isOlderThanRecordedAuxiliaryProjection(
+ qc,
+ wsId,
+ issueId,
+ issueRevision,
+ "labels",
+ )
+ ) {
+ return;
+ }
+ const applyLabels = (issue: Issue) =>
+ issue.id === issueId && acceptsRevision(issue.revision, issueRevision)
+ ? { ...issue, labels }
+ : issue;
qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), (old) =>
- old ? { ...old, labels } : old,
+ old ? applyLabels(old) : old,
);
qc.setQueriesData<Issue[]>({ queryKey: issueKeys.myAll(wsId) }, (old) =>
- old
- ? old.map((i) => (i.id === issueId ? { ...i, labels } : i))
- : old,
+ old?.map(applyLabels),
);
qc.setQueryData<Issue[]>(issueKeys.list(wsId), (old) =>
- old
- ? old.map((i) => (i.id === issueId ? { ...i, labels } : i))
- : old,
+ old?.map(applyLabels),
);
+ onIssueAuxiliaryRevision(qc, wsId, issueId, issueRevision, "labels");
}
// =====================================================
@@ -379,5 +628,6 @@ export function commentToTimelineEntry(comment: Comment): TimelineEntry {
resolved_by_type: comment.resolved_by_type,
resolved_by_id: comment.resolved_by_id,
source_task_id: comment.source_task_id,
+ revision: comment.revision,
};
}
diff --git a/apps/mobile/data/realtime/use-issue-realtime.ts b/apps/mobile/data/realtime/use-issue-realtime.ts
index 898becdcce..fb857cdc68 100644
--- a/apps/mobile/data/realtime/use-issue-realtime.ts
+++ b/apps/mobile/data/realtime/use-issue-realtime.ts
@@ -19,8 +19,8 @@
* Mobile pattern (per the realtime plan, see
* /Users/qingnaiyuan/.claude/plans/plan-api-indexed-waffle.md):
* - Patch over invalidate where the payload contains the full object
- * - Event always wins on optimistic-update conflicts; brief flicker
- * is acceptable, correctness wins.
+ * - Versioned events win only when their owner revision is not older than
+ * cached state; an unversioned event over versioned state triggers refetch.
* - All handlers self-gate on `issue_id === issueId` so we only react
* to events for the currently-viewed issue.
*/
@@ -38,14 +38,16 @@ import { useWSSubscriptions } from "@/lib/use-ws-subscriptions";
import {
addCommentReaction,
addIssueReaction,
+ onIssueAuxiliaryRevision,
appendTimelineEntry,
clearIssueDetail,
commentToTimelineEntry,
invalidateIssueAfterReconnect,
patchIssueDetail,
patchIssueLabels,
+ patchIssuesList,
patchMyIssuesList,
- patchTimelineEntry,
+ replaceCommentTimelineEntry,
removeCommentCascade,
removeCommentReaction,
removeFromMyIssuesList,
@@ -104,6 +106,7 @@ export function useIssueRealtime(
if (payload.issue.id !== issueId) return;
patchIssueDetail(qc, wsId, payload.issue);
patchMyIssuesList(qc, wsId, payload.issue);
+ patchIssuesList(qc, wsId, payload.issue);
}),
ws.on("issue:deleted", (payload) => {
if (payload.issue_id !== issueId) return;
@@ -113,10 +116,11 @@ export function useIssueRealtime(
}),
ws.on("issue_labels:changed", (payload) => {
if (payload.issue_id !== issueId) return;
- patchIssueLabels(qc, wsId, issueId, payload.labels);
+ patchIssueLabels(qc, wsId, issueId, payload.labels, payload.issue_revision);
}),
ws.on("issue_attachments:changed", (payload) => {
if (payload.issue_id !== issueId) return;
+ onIssueAuxiliaryRevision(qc, wsId, issueId, payload.issue_revision);
qc.invalidateQueries({
queryKey: issueKeys.attachments(wsId, issueId),
});
@@ -131,17 +135,12 @@ export function useIssueRealtime(
issueId,
commentToTimelineEntry(payload.comment),
);
+ onIssueAuxiliaryRevision(qc, wsId, issueId, payload.issue_revision);
}),
ws.on("comment:updated", (payload) => {
if (payload.comment.issue_id !== issueId) return;
const entry = commentToTimelineEntry(payload.comment);
- patchTimelineEntry(
- qc,
- wsId,
- issueId,
- (e) => e.type === "comment" && e.id === payload.comment.id,
- () => entry,
- );
+ replaceCommentTimelineEntry(qc, wsId, issueId, entry);
}),
// Resolve / unresolve broadcast from any client. Payload carries the
// full Comment with the new resolved_at/resolved_by_* fields, so we
@@ -152,24 +151,12 @@ export function useIssueRealtime(
ws.on("comment:resolved", (payload) => {
if (payload.comment.issue_id !== issueId) return;
const entry = commentToTimelineEntry(payload.comment);
- patchTimelineEntry(
- qc,
- wsId,
- issueId,
- (e) => e.type === "comment" && e.id === payload.comment.id,
- () => entry,
- );
+ replaceCommentTimelineEntry(qc, wsId, issueId, entry);
}),
ws.on("comment:unresolved", (payload) => {
if (payload.comment.issue_id !== issueId) return;
const entry = commentToTimelineEntry(payload.comment);
- patchTimelineEntry(
- qc,
- wsId,
- issueId,
- (e) => e.type === "comment" && e.id === payload.comment.id,
- () => entry,
- );
+ replaceCommentTimelineEntry(qc, wsId, issueId, entry);
}),
ws.on("comment:deleted", (payload) => {
if (payload.issue_id !== issueId) return;
@@ -193,6 +180,7 @@ export function useIssueRealtime(
issueId,
payload.reaction.comment_id,
payload.reaction,
+ payload.comment_revision,
);
}),
ws.on("reaction:removed", (payload) => {
@@ -204,13 +192,14 @@ export function useIssueRealtime(
payload.comment_id,
payload.emoji,
payload.actor_id,
+ payload.comment_revision,
);
}),
// ----- Issue-level reactions -----
ws.on("issue_reaction:added", (payload) => {
if (payload.issue_id !== issueId) return;
- addIssueReaction(qc, wsId, issueId, payload.reaction);
+ addIssueReaction(qc, wsId, issueId, payload.reaction, payload.issue_revision);
}),
ws.on("issue_reaction:removed", (payload) => {
if (payload.issue_id !== issueId) return;
@@ -220,6 +209,7 @@ export function useIssueRealtime(
issueId,
payload.emoji,
payload.actor_id,
+ payload.issue_revision,
);
}),
diff --git a/apps/mobile/data/realtime/use-my-issues-realtime.ts b/apps/mobile/data/realtime/use-my-issues-realtime.ts
index d0b3c9ef26..60a18da70b 100644
--- a/apps/mobile/data/realtime/use-my-issues-realtime.ts
+++ b/apps/mobile/data/realtime/use-my-issues-realtime.ts
@@ -48,7 +48,13 @@ export function useMyIssuesRealtime() {
removeFromMyIssuesList(qc, wsId, payload.issue_id);
}),
ws.on("issue_labels:changed", (payload) => {
- patchIssueLabels(qc, wsId, payload.issue_id, payload.labels);
+ patchIssueLabels(
+ qc,
+ wsId,
+ payload.issue_id,
+ payload.labels,
+ payload.issue_revision,
+ );
}),
ws.onReconnect(invalidateMyAll),
];
diff --git a/apps/mobile/data/revision.test.ts b/apps/mobile/data/revision.test.ts
new file mode 100644
index 0000000000..3a05636db2
--- /dev/null
+++ b/apps/mobile/data/revision.test.ts
@@ -0,0 +1,34 @@
+import type { TimelineEntry } from "@multica/core/types";
+import { describe, expect, it } from "vitest";
+
+import {
+ buildCommentUpdateBody,
+ commentContentFromTimeline,
+ shouldAcceptServerRevision,
+} from "./revision";
+
+describe("mobile revision requests", () => {
+ it("reads the edited comment content and serializes it as the field baseline", () => {
+ const timeline = [
+ {
+ type: "comment",
+ id: "comment-1",
+ content: "Original",
+ } as TimelineEntry,
+ ];
+
+ expect(commentContentFromTimeline(timeline, "comment-1")).toBe("Original");
+ expect(buildCommentUpdateBody("Latest", ["attachment-1"], "Original")).toEqual({
+ content: "Latest",
+ attachment_ids: ["attachment-1"],
+ content_base: "Original",
+ });
+ });
+
+ it("does not let an older HTTP response overwrite a newer cache revision", () => {
+ expect(shouldAcceptServerRevision(5, 4)).toBe(false);
+ expect(shouldAcceptServerRevision(5, 5)).toBe(false);
+ expect(shouldAcceptServerRevision(5, 6)).toBe(true);
+ expect(shouldAcceptServerRevision(undefined, undefined)).toBe(true);
+ });
+});
diff --git a/apps/mobile/data/revision.ts b/apps/mobile/data/revision.ts
new file mode 100644
index 0000000000..77f3472dd4
--- /dev/null
+++ b/apps/mobile/data/revision.ts
@@ -0,0 +1,32 @@
+import type { TimelineEntry } from "@multica/core/types";
+
+export function commentContentFromTimeline(
+ timeline: TimelineEntry[] | undefined,
+ commentId: string,
+): string | undefined {
+ return timeline?.find(
+ (entry) => entry.type === "comment" && entry.id === commentId,
+ )?.content;
+}
+
+export function buildCommentUpdateBody(
+ content: string,
+ attachmentIds: string[] | undefined,
+ contentBase: string | undefined,
+) {
+ return {
+ content,
+ ...(attachmentIds ? { attachment_ids: attachmentIds } : {}),
+ ...(contentBase !== undefined ? { content_base: contentBase } : {}),
+ };
+}
+
+export function shouldAcceptServerRevision(
+ currentRevision: number | undefined,
+ incomingRevision: number | undefined,
+): boolean {
+ return (
+ currentRevision === undefined ||
+ (incomingRevision !== undefined && incomingRevision > currentRevision)
+ );
+}
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index ec82d5a7a9..153f8cbc1d 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -6,6 +6,75 @@ afterEach(() => {
vi.unstubAllGlobals();
});
+describe("ApiClient edit guards", () => {
+ it("serializes field baselines for issue and comment writes", async () => {
+ const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(
+ new Response("{}", {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ ));
+ vi.stubGlobal("fetch", fetchMock);
+ const client = new ApiClient("https://api.example.test");
+
+ await client.updateIssue("issue-1", { title: "Latest", title_base: "Original" });
+ await client.updateComment("comment-1", "Latest", [], undefined, "Original");
+
+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({
+ title: "Latest",
+ title_base: "Original",
+ });
+ expect(JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({
+ content: "Latest",
+ content_base: "Original",
+ });
+ });
+
+ it("accepts an older issue response without revision and rejects a malformed revision", async () => {
+ const legacyIssue = {
+ id: "issue-1",
+ workspace_id: "ws-1",
+ number: 1,
+ identifier: "MUL-1",
+ title: "Legacy issue",
+ description: null,
+ status: "todo",
+ priority: "none",
+ assignee_type: null,
+ assignee_id: null,
+ creator_type: "member",
+ creator_id: "user-1",
+ parent_issue_id: null,
+ project_id: null,
+ position: 0,
+ start_date: null,
+ due_date: null,
+ created_at: "2026-08-16T00:00:00Z",
+ updated_at: "2026-08-16T00:00:00Z",
+ };
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(new Response(JSON.stringify({ issues: [legacyIssue], total: 1 }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }))
+ .mockResolvedValueOnce(new Response(JSON.stringify({
+ issues: [{ ...legacyIssue, revision: "invalid" }],
+ total: 1,
+ }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }));
+ vi.stubGlobal("fetch", fetchMock);
+ const client = new ApiClient("https://api.example.test");
+
+ const parsedLegacy = await client.listIssues();
+ expect(parsedLegacy).toMatchObject({ issues: [{ id: "issue-1" }], total: 1 });
+ expect(parsedLegacy.issues[0]).not.toHaveProperty("revision");
+ await expect(client.listIssues()).resolves.toEqual({ issues: [], total: 0 });
+ });
+});
+
describe("ApiClient pull-request response schema", () => {
const validPR = {
id: "pr-1",
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 6a5f4dcf25..99f5d18849 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -1156,13 +1156,15 @@ export class ApiClient {
return this.fetch("/api/assignee-frequency");
}
- async updateComment(commentId: string, content: string, attachmentIds?: string[], suppressAgentIds?: string[]): Promise<Comment> {
+ async updateComment(commentId: string, content: string, attachmentIds?: string[], suppressAgentIds?: string[], contentBase?: string, expectedRevision?: number): Promise<Comment> {
return this.fetch(`/api/comments/${commentId}`, {
method: "PUT",
body: JSON.stringify({
content,
attachment_ids: attachmentIds,
...(suppressAgentIds?.length ? { suppress_agent_ids: suppressAgentIds } : {}),
+ ...(contentBase !== undefined ? { content_base: contentBase } : {}),
+ ...(expectedRevision !== undefined ? { expected_revision: expectedRevision } : {}),
}),
});
}
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 888a124508..f1b0459bc9 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -376,6 +376,7 @@ export const EMPTY_LIST_ISSUE_STATUSES_RESPONSE: ListIssueStatusesResponse = {
export const ResourceLabelsResponseSchema = z.object({
labels: z.array(LabelSchema).default([]),
+ issue_revision: z.number().int().positive().optional(),
}).loose();
export const EMPTY_RESOURCE_LABELS_RESPONSE: ResourceLabelsResponse = {
@@ -568,6 +569,7 @@ export const IssuePropertyValuesSchema = z.preprocess(
export const IssuePropertiesResponseSchema = z.object({
properties: IssuePropertyValuesSchema,
+ issue_revision: z.number().int().positive().optional(),
}).loose();
export const EMPTY_ISSUE_PROPERTIES_RESPONSE: IssuePropertiesResponse = {
@@ -750,6 +752,7 @@ const TimelineEntrySchema = z.object({
content: z.string().optional(),
parent_id: z.string().nullable().optional(),
updated_at: z.string().optional(),
+ revision: z.number().int().positive().optional(),
comment_type: z.string().optional(),
reactions: z.array(ReactionSchema).optional(),
attachments: z.array(AttachmentSchema).optional(),
@@ -849,6 +852,7 @@ export const CommentSchema = z.object({
attachments: z.array(AttachmentSchema).default([]),
created_at: z.string(),
updated_at: z.string(),
+ revision: z.number().int().positive().optional(),
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(),
@@ -963,6 +967,7 @@ export const IssueSchema = z.object({
labels: z.array(z.unknown()).optional(),
created_at: z.string(),
updated_at: z.string(),
+ revision: z.number().int().positive().optional(),
}).loose();
export const ListIssuesResponseSchema = z.object({
diff --git a/packages/core/issues/cache-coordinator.ts b/packages/core/issues/cache-coordinator.ts
index 6e97300357..3ae1a4f1bf 100644
--- a/packages/core/issues/cache-coordinator.ts
+++ b/packages/core/issues/cache-coordinator.ts
@@ -274,9 +274,13 @@ export function applyIssueChange(
* where the card is not loaded. Omitting it degrades those judgments to
* "unknown" → a deferred refetch, never a wrong patch. */
baseIssue?: Issue;
+ /** Optional per-cache admission guard. Realtime uses this to reject a
+ * non-increasing revision in a fresh cache while still healing another
+ * loaded projection that holds an older revision of the same issue. */
+ acceptCurrent?: (current: Issue) => boolean;
},
): IssueCacheChangeResult {
- const { changed, baseIssue } = opts;
+ const { changed, baseIssue, acceptCurrent = () => true } = opts;
// Normalize ONCE, at the door. Every write below is a `{...entity, ...patch}`
// spread, and an optimistic `{status}` patch would otherwise leave the stale
// status_category on the entity while the card moves buckets. (MUL-6243)
@@ -290,6 +294,7 @@ export function applyIssueChange(
for (const [key, data] of bucketedListEntries(qc, wsId)) {
const { scope, filter, sort } = listContractFromKey(key);
const loc = findIssueLocation(data, id);
+ if (loc && !acceptCurrent(loc.issue)) continue;
const filterTouched = listFilterDependsOn(scope, filter, changed);
// "Updated date" sort: every persisted edit advances updated_at, but the
@@ -418,6 +423,7 @@ export function applyIssueChange(
...page,
issues: page.issues.map((issue) => {
if (issue.id !== id) return issue;
+ if (!acceptCurrent(issue)) return issue;
found = issue;
return { ...issue, ...patch };
}),
@@ -441,6 +447,7 @@ export function applyIssueChange(
let found: Issue | undefined;
const rows = data.rows.map((row) => {
if (row.issue.id !== id) return row;
+ if (!acceptCurrent(row.issue)) return row;
found = row.issue;
return { ...row, issue: { ...row.issue, ...patch } };
});
@@ -451,7 +458,7 @@ export function applyIssueChange(
}
const prevDetail = qc.getQueryData<Issue>(issueKeys.detail(wsId, id));
- if (prevDetail) {
+ if (prevDetail && acceptCurrent(prevDetail)) {
qc.setQueryData<Issue>(issueKeys.detail(wsId, id), {
...prevDetail,
...patch,
diff --git a/packages/core/issues/mutations.test.tsx b/packages/core/issues/mutations.test.tsx
index 212647b492..d7ddf9a87a 100644
--- a/packages/core/issues/mutations.test.tsx
+++ b/packages/core/issues/mutations.test.tsx
@@ -17,6 +17,7 @@ import {
issueKeys,
type IssueSortParam,
} from "./queries";
+import { onIssueUpdated, onIssueAuxiliaryRevision } from "./ws-updaters";
import { inboxKeys } from "../inbox/queries";
import type {
InboxItem,
@@ -183,6 +184,88 @@ describe("useUpdateIssue — optimistic move keeps every bucketed board in sync"
}
});
+ it("does not couple a field update to the cached aggregate revision", async () => {
+ qc.setQueryData(
+ issueKeys.detail(WS_ID, "issue-1"),
+ makeIssue(1, { revision: 6 }),
+ );
+ updateIssue.mockResolvedValue(makeIssue(1, { title: "Renamed", revision: 7 }));
+ const { result } = renderHook(() => useUpdateIssue(), {
+ wrapper: createWrapper(qc),
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync({ id: "issue-1", title: "Renamed" });
+ });
+
+ expect(updateIssue).toHaveBeenCalledWith("issue-1", {
+ title: "Renamed",
+ });
+ });
+
+ it("does not let an older successful response overwrite a newer WS revision", async () => {
+ let resolve!: (issue: Issue) => void;
+ updateIssue.mockReturnValue(
+ new Promise<Issue>((done) => {
+ resolve = done;
+ }),
+ );
+ const detailKey = issueKeys.detail(WS_ID, "issue-1");
+ qc.setQueryData<Issue>(detailKey, makeIssue(1, { revision: 1 }));
+ const { result } = renderHook(() => useUpdateIssue(), {
+ wrapper: createWrapper(qc),
+ });
+
+ act(() => {
+ result.current.mutate({ id: "issue-1", title: "local" });
+ });
+ await waitFor(() => expect(updateIssue).toHaveBeenCalled());
+ onIssueUpdated(
+ qc,
+ WS_ID,
+ makeIssue(1, { title: "newer remote", revision: 3 }),
+ );
+
+ await act(async () => {
+ resolve(makeIssue(1, { title: "older success", revision: 2 }));
+ });
+
+ expect(qc.getQueryData<Issue>(detailKey)).toMatchObject({
+ title: "newer remote",
+ revision: 3,
+ });
+ });
+
+ it("keeps a full response admissible after a newer revision-only response", async () => {
+ let resolve!: (issue: Issue) => void;
+ updateIssue.mockReturnValue(
+ new Promise<Issue>((done) => {
+ resolve = done;
+ }),
+ );
+ const detailKey = issueKeys.detail(WS_ID, "issue-1");
+ qc.setQueryData<Issue>(detailKey, makeIssue(1, { title: "A", revision: 1 }));
+ const { result } = renderHook(() => useUpdateIssue(), {
+ wrapper: createWrapper(qc),
+ });
+
+ act(() => {
+ result.current.mutate({ id: "issue-1", title: "local" });
+ });
+ await waitFor(() => expect(updateIssue).toHaveBeenCalled());
+ onIssueAuxiliaryRevision(qc, WS_ID, "issue-1", 3);
+
+ await act(async () => {
+ resolve(makeIssue(1, { title: "B", revision: 2 }));
+ });
+
+ expect(qc.getQueryData<Issue>(detailKey)).toMatchObject({
+ title: "B",
+ revision: 2,
+ });
+ expect(qc.getQueryState(detailKey)?.isInvalidated).toBe(true);
+ });
+
it("keeps the authoritative description base while a description update is pending", async () => {
let resolve!: (issue: Issue) => void;
updateIssue.mockReturnValue(
@@ -282,6 +365,7 @@ describe("useUpdateIssue — optimistic move keeps every bucketed board in sync"
it("rolls both caches back when the request fails", async () => {
updateIssue.mockRejectedValue(new Error("boom"));
+ const invalidateSpy = vi.spyOn(qc, "invalidateQueries");
const { result } = renderHook(() => useUpdateIssue(), {
wrapper: createWrapper(qc),
@@ -297,6 +381,12 @@ describe("useUpdateIssue — optimistic move keeps every bucketed board in sync"
expect(bucketIds(key, "todo")).toEqual(["issue-1"]);
expect(bucketIds(key, "in_progress")).toEqual([]);
}
+ const invalidatedKeys = invalidateSpy.mock.calls.map((c) => c[0]?.queryKey);
+ expect(invalidatedKeys).toContainEqual(issueKeys.detail(WS_ID, "issue-1"));
+ expect(invalidatedKeys).toContainEqual(issueKeys.list(WS_ID));
+ expect(invalidatedKeys).toContainEqual(issueKeys.myAll(WS_ID));
+ expect(invalidatedKeys).toContainEqual(issueKeys.flatAll(WS_ID));
+ expect(invalidatedKeys).toContainEqual(issueKeys.tableAll(WS_ID));
});
it("rolls the linked inbox row status back when the request fails", async () => {
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index 84eda60ba5..8e3c583bf0 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -35,6 +35,10 @@ import type {
} from "../types";
import type { TimelineEntry, IssueSubscriber, Reaction } from "../types";
import { sortTimelineEntriesAsc } from "./timeline-sort";
+import {
+ onIssueAuxiliaryRevision,
+ reconcileIssueFullSnapshotRevision,
+} from "./ws-updaters";
// ---------------------------------------------------------------------------
// Shared mutation variable types — used by both mutation hooks and
@@ -120,6 +124,8 @@ export function useUpdateIssue() {
handoff_note: _handoffNote,
description: _description,
description_base: _descriptionBase,
+ title_base: _titleBase,
+ expected_revision: _expectedRevision,
...patch
} = data;
// Fire-and-forget cancelQueries — keeps onMutate synchronous so the
@@ -190,7 +196,7 @@ export function useUpdateIssue() {
}
return { change, prevChildren, parentId, id };
},
- onError: (_err, _vars, ctx) => {
+ onError: (_err, vars, ctx) => {
if (ctx) {
rollbackIssueChange(qc, wsId, ctx.id, ctx.change);
}
@@ -200,6 +206,16 @@ export function useUpdateIssue() {
ctx.prevChildren,
);
}
+ // A remote revision may have landed through WS after onMutate captured
+ // its rollback snapshot. Restoring that snapshot on any failed request
+ // can therefore transiently put an older entity back into cache; refresh
+ // every loaded owner projection after rollback. A revision conflict is
+ // the common case, but transport/5xx failures have the same interleave.
+ qc.invalidateQueries({ queryKey: issueKeys.detail(wsId, vars.id) });
+ qc.invalidateQueries({ queryKey: issueKeys.list(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.flatAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
},
onSuccess: (serverIssue, vars) => {
// Reconcile with the authoritative server entity by patching the one card
@@ -231,7 +247,21 @@ export function useUpdateIssue() {
const reconcile = applyIssueChange(qc, wsId, serverIssue.id, reconcilable as typeof serverIssue, {
changed: issueChangedDims(intent, serverIssue),
baseIssue: serverIssue,
+ // The HTTP response can arrive after a newer WS event. Reconcile the
+ // committed snapshot only into projections that have not already
+ // advanced beyond it; otherwise an older successful response would
+ // undo a later remote write in cache.
+ acceptCurrent: (current) =>
+ current.revision === undefined ||
+ (serverIssue.revision !== undefined &&
+ serverIssue.revision > current.revision),
});
+ reconcileIssueFullSnapshotRevision(
+ qc,
+ wsId,
+ serverIssue.id,
+ serverIssue.revision,
+ );
// The server has committed — safe to flush any drift it reported now.
invalidateStaleListKeys(qc, reconcile.staleKeys);
},
@@ -685,6 +715,7 @@ type TimelineCache = TimelineEntry[];
export function useCreateComment(issueId: string) {
const qc = useQueryClient();
+ const wsId = useWorkspaceId();
return useMutation({
mutationFn: ({
content,
@@ -700,6 +731,7 @@ export function useCreateComment(issueId: string) {
suppressAgentIds?: string[];
}) => api.createComment(issueId, content, type, parentId, attachmentIds, suppressAgentIds),
onSuccess: (comment) => {
+ onIssueAuxiliaryRevision(qc, wsId, issueId, comment.issue_revision);
const entry: TimelineEntry = {
type: "comment",
id: comment.id,
@@ -744,12 +776,16 @@ export function useUpdateComment(issueId: string) {
content,
attachmentIds,
suppressAgentIds,
+ contentBase,
+ expectedRevision,
}: {
commentId: string;
content: string;
attachmentIds: string[];
suppressAgentIds?: string[];
- }) => api.updateComment(commentId, content, attachmentIds, suppressAgentIds),
+ contentBase?: string;
+ expectedRevision?: number;
+ }) => api.updateComment(commentId, content, attachmentIds, suppressAgentIds, contentBase, expectedRevision),
onMutate: async ({ commentId, content, attachmentIds }) => {
await qc.cancelQueries({ queryKey: issueKeys.timeline(issueId) });
const prev = qc.getQueryData<TimelineCache>(issueKeys.timeline(issueId));
@@ -933,6 +969,7 @@ export function useToggleCommentReaction(issueId: string) {
export function useToggleIssueReaction(issueId: string) {
const qc = useQueryClient();
+ const wsId = useWorkspaceId();
return useMutation({
mutationKey: ["toggleIssueReaction", issueId] as const,
mutationFn: async ({
@@ -945,6 +982,9 @@ export function useToggleIssueReaction(issueId: string) {
}
return api.addIssueReaction(issueId, emoji);
},
+ onSuccess: (reaction) => {
+ onIssueAuxiliaryRevision(qc, wsId, issueId, reaction?.issue_revision);
+ },
onSettled: () => {
qc.invalidateQueries({ queryKey: issueKeys.reactions(issueId) });
},
diff --git a/packages/core/issues/revision-realtime.test.ts b/packages/core/issues/revision-realtime.test.ts
new file mode 100644
index 0000000000..db238917f0
--- /dev/null
+++ b/packages/core/issues/revision-realtime.test.ts
@@ -0,0 +1,222 @@
+import { QueryClient } from "@tanstack/react-query";
+import { describe, expect, it } from "vitest";
+import type { Issue } from "../types";
+import { issueKeys } from "./queries";
+import {
+ onIssueLabelsChanged,
+ onIssueMetadataChanged,
+ onIssuePropertiesChanged,
+ onIssueUpdated,
+ onIssueAuxiliaryRevision,
+} from "./ws-updaters";
+
+function issue(revision: number, title: string): Issue {
+ return {
+ id: "issue-1",
+ workspace_id: "ws-1",
+ identifier: "MUL-1",
+ number: 1,
+ title,
+ description: null,
+ status: "todo",
+ priority: "none",
+ assignee_type: null,
+ assignee_id: null,
+ creator_type: "member",
+ creator_id: "member-1",
+ parent_issue_id: "parent-1",
+ project_id: null,
+ position: 1,
+ stage: null,
+ start_date: null,
+ due_date: null,
+ created_at: "2026-08-16T00:00:00Z",
+ updated_at: "2026-08-16T00:00:00Z",
+ revision,
+ metadata: {},
+ properties: {},
+ };
+}
+
+describe("issue realtime revision admission", () => {
+ it("heals an older projection without replacing an equal-revision detail", () => {
+ const qc = new QueryClient();
+ qc.setQueryData(issueKeys.detail("ws-1", "issue-1"), issue(3, "latest"));
+ qc.setQueryData(issueKeys.children("ws-1", "parent-1"), [
+ issue(2, "stale child"),
+ ]);
+
+ onIssueUpdated(qc, "ws-1", issue(3, "latest"));
+
+ expect(
+ qc.getQueryData<Issue>(issueKeys.detail("ws-1", "issue-1"))?.title,
+ ).toBe("latest");
+ expect(
+ qc.getQueryData<Issue[]>(issueKeys.children("ws-1", "parent-1"))?.[0],
+ ).toMatchObject({ revision: 3, title: "latest" });
+ });
+
+ it("rejects an event older than the freshest cached revision", () => {
+ const qc = new QueryClient();
+ qc.setQueryData(issueKeys.detail("ws-1", "issue-1"), issue(3, "latest"));
+ qc.setQueryData(issueKeys.children("ws-1", "parent-1"), [
+ issue(3, "latest"),
+ ]);
+
+ onIssueUpdated(qc, "ws-1", issue(2, "stale event"));
+
+ expect(
+ qc.getQueryData<Issue>(issueKeys.detail("ws-1", "issue-1"))?.title,
+ ).toBe("latest");
+ expect(
+ qc.getQueryData<Issue[]>(issueKeys.children("ws-1", "parent-1"))?.[0]
+ ?.title,
+ ).toBe("latest");
+ });
+
+ it("refetches rather than applying an unversioned event over versioned state", () => {
+ const qc = new QueryClient();
+ const detailKey = issueKeys.detail("ws-1", "issue-1");
+ qc.setQueryData(detailKey, issue(3, "latest"));
+
+ onIssueUpdated(qc, "ws-1", { ...issue(1, "unversioned"), revision: undefined });
+
+ expect(qc.getQueryData<Issue>(detailKey)?.title).toBe("latest");
+ expect(qc.getQueryState(detailKey)?.isInvalidated).toBe(true);
+ });
+
+ it("invalidates stale owner projections without claiming a partial event is a full snapshot", () => {
+ const qc = new QueryClient();
+ qc.setQueryData(issueKeys.detail("ws-1", "issue-1"), issue(5, "detail"));
+ qc.setQueryData(issueKeys.children("ws-1", "parent-1"), [
+ issue(3, "child"),
+ ]);
+
+ onIssueAuxiliaryRevision(qc, "ws-1", "issue-1", 4);
+
+ expect(
+ qc.getQueryData<Issue>(issueKeys.detail("ws-1", "issue-1"))?.revision,
+ ).toBe(5);
+ expect(
+ qc.getQueryData<Issue[]>(issueKeys.children("ws-1", "parent-1"))?.[0]
+ ?.revision,
+ ).toBe(3);
+ expect(
+ qc.getQueryState(issueKeys.detail("ws-1", "issue-1"))?.isInvalidated,
+ ).toBe(false);
+ expect(
+ qc.getQueryState(issueKeys.children("ws-1", "parent-1"))?.isInvalidated,
+ ).toBe(true);
+ });
+
+ it("admits a fuller snapshot after a newer revision-only event", () => {
+ const qc = new QueryClient();
+ const detailKey = issueKeys.detail("ws-1", "issue-1");
+ qc.setQueryData(detailKey, issue(1, "A"));
+
+ onIssueAuxiliaryRevision(qc, "ws-1", "issue-1", 3);
+ expect(qc.getQueryData<Issue>(detailKey)).toMatchObject({
+ revision: 1,
+ title: "A",
+ });
+ expect(qc.getQueryState(detailKey)?.isInvalidated).toBe(true);
+
+ onIssueUpdated(qc, "ws-1", issue(2, "B"));
+ expect(qc.getQueryData<Issue>(detailKey)).toMatchObject({
+ revision: 2,
+ title: "B",
+ });
+ expect(qc.getQueryState(detailKey)?.isInvalidated).toBe(true);
+ });
+
+ it("rejects stale auxiliary snapshots as a whole, not only their revision", () => {
+ const qc = new QueryClient();
+ const latestLabel = {
+ id: "label-latest",
+ workspace_id: "ws-1",
+ name: "latest",
+ color: "#000000",
+ created_at: "2026-08-16T00:00:00Z",
+ updated_at: "2026-08-16T00:00:00Z",
+ };
+ qc.setQueryData(issueKeys.detail("ws-1", "issue-1"), {
+ ...issue(3, "latest"),
+ metadata: { state: "latest" },
+ properties: { state: "latest" },
+ labels: [latestLabel],
+ });
+
+ onIssueMetadataChanged(qc, "ws-1", "issue-1", { state: "stale" }, 2);
+ onIssuePropertiesChanged(qc, "ws-1", "issue-1", { state: "stale" }, 2);
+ onIssueLabelsChanged(qc, "ws-1", "issue-1", [{
+ ...latestLabel,
+ id: "label-stale",
+ name: "stale",
+ }], 2);
+
+ expect(qc.getQueryData<Issue>(issueKeys.detail("ws-1", "issue-1"))).toMatchObject({
+ revision: 3,
+ metadata: { state: "latest" },
+ properties: { state: "latest" },
+ labels: [{ id: "label-latest" }],
+ });
+ });
+
+ it("does not apply an unversioned auxiliary snapshot over versioned state", () => {
+ const qc = new QueryClient();
+ const detailKey = issueKeys.detail("ws-1", "issue-1");
+ qc.setQueryData(detailKey, {
+ ...issue(3, "latest"),
+ metadata: { state: "latest" },
+ });
+
+ onIssueMetadataChanged(qc, "ws-1", "issue-1", { state: "unversioned" });
+
+ expect(qc.getQueryData<Issue>(detailKey)?.metadata).toEqual({ state: "latest" });
+ expect(qc.getQueryState(detailKey)?.isInvalidated).toBe(true);
+ });
+
+ it("orders each auxiliary projection independently", () => {
+ const qc = new QueryClient();
+ const detailKey = issueKeys.detail("ws-1", "issue-1");
+ qc.setQueryData(detailKey, {
+ ...issue(1, "base"),
+ metadata: { state: "base" },
+ properties: { estimate: 1 },
+ });
+
+ onIssueMetadataChanged(qc, "ws-1", "issue-1", { state: "latest" }, 3);
+ onIssueMetadataChanged(qc, "ws-1", "issue-1", { state: "stale" }, 2);
+ onIssuePropertiesChanged(qc, "ws-1", "issue-1", { estimate: 2 }, 2);
+
+ expect(qc.getQueryData<Issue>(detailKey)).toMatchObject({
+ revision: 1,
+ metadata: { state: "latest" },
+ properties: { estimate: 2 },
+ });
+ });
+
+ it("uses an equal-revision auxiliary event to heal only older projections", () => {
+ const qc = new QueryClient();
+ qc.setQueryData(issueKeys.detail("ws-1", "issue-1"), {
+ ...issue(3, "detail"),
+ metadata: { state: "latest" },
+ });
+ qc.setQueryData(issueKeys.children("ws-1", "parent-1"), [{
+ ...issue(2, "child"),
+ metadata: { state: "stale" },
+ }]);
+
+ onIssueMetadataChanged(qc, "ws-1", "issue-1", { state: "latest" }, 3);
+
+ expect(
+ qc.getQueryData<Issue>(issueKeys.detail("ws-1", "issue-1"))?.title,
+ ).toBe("detail");
+ expect(
+ qc.getQueryData<Issue[]>(issueKeys.children("ws-1", "parent-1"))?.[0],
+ ).toMatchObject({ revision: 2, metadata: { state: "latest" } });
+ expect(
+ qc.getQueryState(issueKeys.children("ws-1", "parent-1"))?.isInvalidated,
+ ).toBe(true);
+ });
+});
diff --git a/packages/core/issues/ws-updaters.test.ts b/packages/core/issues/ws-updaters.test.ts
index 8609a21804..1cdcac10e4 100644
--- a/packages/core/issues/ws-updaters.test.ts
+++ b/packages/core/issues/ws-updaters.test.ts
@@ -175,6 +175,36 @@ describe("onIssueLabelsChanged", () => {
).toEqual({ labels: [labelB] });
});
+ it("uses the picker cache revision to reject an older label snapshot", () => {
+ const labelKey = labelKeys.byIssue(WS_ID, ISSUE_ID);
+ qc.setQueryData<IssueLabelsResponse>(labelKey, {
+ labels: [labelA],
+ issue_revision: 3,
+ });
+
+ onIssueLabelsChanged(qc, WS_ID, ISSUE_ID, [labelB], 2);
+
+ expect(qc.getQueryData<IssueLabelsResponse>(labelKey)).toEqual({
+ labels: [labelA],
+ issue_revision: 3,
+ });
+ });
+
+ it("advances the picker cache labels and revision together", () => {
+ const labelKey = labelKeys.byIssue(WS_ID, ISSUE_ID);
+ qc.setQueryData<IssueLabelsResponse>(labelKey, {
+ labels: [labelA],
+ issue_revision: 3,
+ });
+
+ onIssueLabelsChanged(qc, WS_ID, ISSUE_ID, [labelB], 4);
+
+ expect(qc.getQueryData<IssueLabelsResponse>(labelKey)).toEqual({
+ labels: [labelB],
+ issue_revision: 4,
+ });
+ });
+
it("leaves the per-issue label cache untouched when the picker has not fetched", () => {
onIssueLabelsChanged(qc, WS_ID, ISSUE_ID, [labelB]);
diff --git a/packages/core/issues/ws-updaters.ts b/packages/core/issues/ws-updaters.ts
index be010370c6..0b2706d059 100644
--- a/packages/core/issues/ws-updaters.ts
+++ b/packages/core/issues/ws-updaters.ts
@@ -26,11 +26,106 @@ import type {
} from "../types";
import type { ListIssuesCache } from "../types";
+const auxiliaryIssueRevisions = new WeakMap<QueryClient, Map<string, number>>();
+
+type AuxiliaryIssueProjection = "generic" | "labels" | "metadata" | "properties";
+
+function auxiliaryIssueRevisionPrefix(wsId: string, issueId: string) {
+ return `${wsId}:${issueId}:`;
+}
+
+function auxiliaryIssueRevisionKey(
+ wsId: string,
+ issueId: string,
+ projection: AuxiliaryIssueProjection,
+) {
+ return `${auxiliaryIssueRevisionPrefix(wsId, issueId)}${projection}`;
+}
+
+function recordAuxiliaryIssueRevision(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ revision: number,
+ projection: AuxiliaryIssueProjection,
+) {
+ let revisions = auxiliaryIssueRevisions.get(qc);
+ if (!revisions) {
+ revisions = new Map();
+ auxiliaryIssueRevisions.set(qc, revisions);
+ }
+ const key = auxiliaryIssueRevisionKey(wsId, issueId, projection);
+ if ((revisions.get(key) ?? 0) < revision) revisions.set(key, revision);
+}
+
+function isOlderThanRecordedAuxiliaryProjection(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ revision: number | undefined,
+ projection: AuxiliaryIssueProjection,
+) {
+ if (revision === undefined) return false;
+ const recorded = auxiliaryIssueRevisions
+ .get(qc)
+ ?.get(auxiliaryIssueRevisionKey(wsId, issueId, projection));
+ return recorded !== undefined && revision < recorded;
+}
+
+export function reconcileIssueFullSnapshotRevision(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ fullRevision: number | undefined,
+) {
+ if (fullRevision === undefined) return;
+ const revisions = auxiliaryIssueRevisions.get(qc);
+ if (!revisions) return;
+ const prefix = auxiliaryIssueRevisionPrefix(wsId, issueId);
+ let newestAuxiliaryRevision: number | undefined;
+ for (const [key, revision] of revisions) {
+ if (!key.startsWith(prefix)) continue;
+ if (fullRevision >= revision) {
+ revisions.delete(key);
+ } else if (
+ newestAuxiliaryRevision === undefined ||
+ revision > newestAuxiliaryRevision
+ ) {
+ newestAuxiliaryRevision = revision;
+ }
+ }
+ if (newestAuxiliaryRevision === undefined) return;
+ // setQueryData clears an inactive query's stale flag. Restore it when this
+ // full snapshot is still behind an auxiliary event we already observed.
+ invalidateStaleIssueOwnerProjections(
+ qc,
+ wsId,
+ issueId,
+ newestAuxiliaryRevision,
+ );
+}
+
+function mergeIssuePatch(
+ issue: Issue,
+ patch: Partial<Issue>,
+ orderRevision?: number,
+): Issue {
+ if (
+ orderRevision !== undefined &&
+ issue.revision !== undefined &&
+ orderRevision < issue.revision
+ ) {
+ return issue;
+ }
+ return { ...issue, ...patch };
+}
+
function patchIssueInFlatCaches(
qc: QueryClient,
wsId: string,
issueId: string,
patch: Partial<Issue>,
+ orderRevision?: number,
) {
for (const [key, data] of qc.getQueriesData<IssueFlatCache>({
queryKey: issueKeys.flatAll(wsId),
@@ -41,7 +136,9 @@ function patchIssueInFlatCaches(
pages: data.pages.map((page) => ({
...page,
issues: page.issues.map((issue) =>
- issue.id === issueId ? { ...issue, ...patch } : issue,
+ issue.id === issueId
+ ? mergeIssuePatch(issue, patch, orderRevision)
+ : issue,
),
})),
});
@@ -54,6 +151,7 @@ function patchIssueInChildrenCaches(
wsId: string,
issueId: string,
patch: Partial<Issue>,
+ orderRevision?: number,
) {
for (const [key, data] of qc.getQueriesData<Issue[]>({
queryKey: issueKeys.childrenAll(wsId),
@@ -62,7 +160,9 @@ function patchIssueInChildrenCaches(
qc.setQueryData<Issue[]>(
key,
data.map((child) =>
- child.id === issueId ? { ...child, ...patch } : child,
+ child.id === issueId
+ ? mergeIssuePatch(child, patch, orderRevision)
+ : child,
),
);
}
@@ -73,6 +173,7 @@ function patchIssueInTableCaches(
wsId: string,
issueId: string,
patch: Partial<Issue>,
+ orderRevision?: number,
) {
for (const [key, data] of qc.getQueriesData<unknown>({
queryKey: issueKeys.tableAll(wsId),
@@ -90,13 +191,174 @@ function patchIssueInTableCaches(
...page,
rows: page.rows.map((row) =>
row.issue.id === issueId
- ? { ...row, issue: { ...row.issue, ...patch } }
+ ? {
+ ...row,
+ issue: mergeIssuePatch(row.issue, patch, orderRevision),
+ }
: row,
),
});
}
}
+function patchIssueSnapshot(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ patch: Partial<Issue>,
+ orderRevision?: number,
+) {
+ for (const prefix of [issueKeys.list(wsId), issueKeys.myAll(wsId)]) {
+ for (const [key, data] of qc.getQueriesData<ListIssuesCache>({ queryKey: prefix })) {
+ if (!data) continue;
+ const location = findIssueLocation(data, issueId);
+ if (
+ !location ||
+ mergeIssuePatch(location.issue, patch, orderRevision) === location.issue
+ ) {
+ continue;
+ }
+ qc.setQueryData<ListIssuesCache>(key, patchIssueInBuckets(data, issueId, patch));
+ }
+ }
+ patchIssueInFlatCaches(qc, wsId, issueId, patch, orderRevision);
+ patchIssueInTableCaches(qc, wsId, issueId, patch, orderRevision);
+ patchIssueInChildrenCaches(qc, wsId, issueId, patch, orderRevision);
+ qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), (old) =>
+ old ? mergeIssuePatch(old, patch, orderRevision) : old,
+ );
+ for (const [key, data] of qc.getQueriesData<Issue[]>({
+ queryKey: issueKeys.projectGanttAll(wsId),
+ })) {
+ if (!data) continue;
+ qc.setQueryData<Issue[]>(
+ key,
+ data.map((issue) =>
+ issue.id === issueId
+ ? mergeIssuePatch(issue, patch, orderRevision)
+ : issue,
+ ),
+ );
+ }
+}
+
+function freshestCachedIssueRevision(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+): number | undefined {
+ let freshest = qc.getQueryData<Issue>(issueKeys.detail(wsId, issueId))?.revision;
+ const consider = (issue: Issue | undefined) => {
+ if (issue?.revision !== undefined && (freshest === undefined || issue.revision > freshest)) {
+ freshest = issue.revision;
+ }
+ };
+ for (const prefix of [issueKeys.list(wsId), issueKeys.myAll(wsId)]) {
+ for (const [, data] of qc.getQueriesData<ListIssuesCache>({ queryKey: prefix })) {
+ consider(data ? findIssueLocation(data, issueId)?.issue : undefined);
+ }
+ }
+ for (const [, data] of qc.getQueriesData<IssueFlatCache>({
+ queryKey: issueKeys.flatAll(wsId),
+ })) {
+ for (const page of data?.pages ?? []) {
+ consider(page.issues.find((issue) => issue.id === issueId));
+ }
+ }
+ for (const [, data] of qc.getQueriesData<IssueTableRowsResponse>({
+ queryKey: issueKeys.tableAll(wsId),
+ })) {
+ if (!data || !Array.isArray(data.rows)) continue;
+ consider(data.rows.find((row) => row.issue.id === issueId)?.issue);
+ }
+ for (const prefix of [issueKeys.childrenAll(wsId), issueKeys.projectGanttAll(wsId)]) {
+ for (const [, data] of qc.getQueriesData<Issue[]>({ queryKey: prefix })) {
+ consider(data?.find((issue) => issue.id === issueId));
+ }
+ }
+ return freshest;
+}
+
+function refetchForUnversionedIssueEvent(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ revision: number | undefined,
+): boolean {
+ if (revision !== undefined) return false;
+ if (freshestCachedIssueRevision(qc, wsId, issueId) === undefined) return false;
+ // Mixed-version rollout: once any projection has an ordered revision, an
+ // older server's unversioned snapshot can no longer be applied safely.
+ qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });
+ return true;
+}
+
+function invalidateStaleIssueOwnerProjections(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ revision: number,
+) {
+ const isStale = (issue: Issue | undefined) =>
+ issue !== undefined &&
+ (issue.revision === undefined || issue.revision < revision);
+ const invalidateExact = (queryKey: readonly unknown[]) => {
+ qc.invalidateQueries({ queryKey, exact: true });
+ };
+
+ const detailKey = issueKeys.detail(wsId, issueId);
+ if (isStale(qc.getQueryData<Issue>(detailKey))) invalidateExact(detailKey);
+
+ for (const prefix of [issueKeys.list(wsId), issueKeys.myAll(wsId)]) {
+ for (const [key, data] of qc.getQueriesData<ListIssuesCache>({ queryKey: prefix })) {
+ if (isStale(data ? findIssueLocation(data, issueId)?.issue : undefined)) {
+ invalidateExact(key);
+ }
+ }
+ }
+ for (const [key, data] of qc.getQueriesData<IssueFlatCache>({
+ queryKey: issueKeys.flatAll(wsId),
+ })) {
+ if (data?.pages.some((page) => isStale(page.issues.find((issue) => issue.id === issueId)))) {
+ invalidateExact(key);
+ }
+ }
+ for (const [key, data] of qc.getQueriesData<IssueTableRowsResponse>({
+ queryKey: issueKeys.tableAll(wsId),
+ })) {
+ if (data?.rows.some((row) => row.issue.id === issueId && isStale(row.issue))) {
+ invalidateExact(key);
+ }
+ }
+ for (const prefix of [issueKeys.childrenAll(wsId), issueKeys.projectGanttAll(wsId)]) {
+ for (const [key, data] of qc.getQueriesData<Issue[]>({ queryKey: prefix })) {
+ if (data?.some((issue) => issue.id === issueId && isStale(issue))) {
+ invalidateExact(key);
+ }
+ }
+ }
+}
+
+/**
+ * An auxiliary event proves that a newer aggregate owner revision exists, but
+ * it does not carry the full Issue snapshot for that revision. Advancing the
+ * cached Issue.revision here would make an older-but-newer-full snapshot look
+ * stale and could strand fields such as title forever. Keep Issue.revision as
+ * the ordering of the full snapshot actually present in that cache, and mark
+ * only stale projections for an authoritative refetch.
+ */
+export function onIssueAuxiliaryRevision(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ revision: number | undefined,
+ projection: AuxiliaryIssueProjection = "generic",
+) {
+ if (!revision || revision <= 0) return;
+ recordAuxiliaryIssueRevision(qc, wsId, issueId, revision, projection);
+ invalidateStaleIssueOwnerProjections(qc, wsId, issueId, revision);
+}
+
function findIssueInFlatCaches(
qc: QueryClient,
wsId: string,
@@ -175,6 +437,16 @@ export function onIssueUpdated(
detailData ??
(firstListData ? findIssueLocation(firstListData, issue.id)?.issue : undefined) ??
findIssueInFlatCaches(qc, wsId, issue.id);
+ if (refetchForUnversionedIssueEvent(qc, wsId, issue.id, issue.revision)) {
+ return;
+ }
+ if (
+ issue.revision !== undefined &&
+ cachedIssue?.revision !== undefined &&
+ issue.revision < cachedIssue.revision
+ ) {
+ return;
+ }
const oldParentId =
detailData?.parent_issue_id ?? cachedIssue?.parent_issue_id ?? null;
// The NEW parent comes from the WS payload when parent_issue_id changed
@@ -217,6 +489,10 @@ export function onIssueUpdated(
const change = applyIssueChange(qc, wsId, issue.id, issue, {
changed,
baseIssue: cachedIssue,
+ acceptCurrent: (current) =>
+ issue.revision === undefined ||
+ current.revision === undefined ||
+ issue.revision > current.revision,
});
invalidateStaleListKeys(qc, change.staleKeys);
invalidateIssueDerivatives(qc, wsId, {
@@ -233,7 +509,14 @@ export function onIssueUpdated(
qc.invalidateQueries({ queryKey: issueKeys.children(wsId, oldParentId) });
} else {
qc.setQueryData<Issue[]>(issueKeys.children(wsId, oldParentId), (old) =>
- old?.map((c) => (c.id === issue.id ? { ...c, ...issue } : c)),
+ old?.map((c) =>
+ c.id === issue.id &&
+ (issue.revision === undefined ||
+ c.revision === undefined ||
+ issue.revision > c.revision)
+ ? { ...c, ...issue }
+ : c,
+ ),
);
}
}
@@ -247,6 +530,7 @@ export function onIssueUpdated(
}
qc.invalidateQueries({ queryKey: issueKeys.childrenByParentsAll(wsId) });
}
+ reconcileIssueFullSnapshotRevision(qc, wsId, issue.id, issue.revision);
}
/**
@@ -265,8 +549,13 @@ export function onIssueLabelsChanged(
wsId: string,
issueId: string,
labels: Label[],
+ revision?: number,
) {
- patchIssueLabels(qc, wsId, issueId, labels);
+ if (refetchForUnversionedIssueEvent(qc, wsId, issueId, revision)) {
+ qc.invalidateQueries({ queryKey: labelKeys.byIssue(wsId, issueId) });
+ return;
+ }
+ patchIssueLabels(qc, wsId, issueId, labels, revision);
invalidateIssueLabelDerivatives(qc, wsId);
}
@@ -276,34 +565,35 @@ export function patchIssueLabels(
wsId: string,
issueId: string,
labels: Label[],
+ revision?: number,
) {
- for (const [key, data] of qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) })) {
- if (data) qc.setQueryData<ListIssuesCache>(key, patchIssueInBuckets(data, issueId, { labels }));
+ if (
+ isOlderThanRecordedAuxiliaryProjection(
+ qc,
+ wsId,
+ issueId,
+ revision,
+ "labels",
+ )
+ ) {
+ return;
}
- patchIssueInFlatCaches(qc, wsId, issueId, { labels });
- patchIssueInTableCaches(qc, wsId, issueId, { labels });
- qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), (old) =>
- old ? { ...old, labels } : old,
- );
+ patchIssueSnapshot(qc, wsId, issueId, { labels }, revision);
qc.setQueryData<IssueLabelsResponse>(labelKeys.byIssue(wsId, issueId), (old) =>
- old ? { ...old, labels } : old,
+ old &&
+ !(
+ revision !== undefined &&
+ old.issue_revision !== undefined &&
+ revision <= old.issue_revision
+ )
+ ? {
+ ...old,
+ labels,
+ ...(revision !== undefined ? { issue_revision: revision } : {}),
+ }
+ : old,
);
- // The sub-issues panel renders label chips from these denormalized rows.
- patchIssueInChildrenCaches(qc, wsId, issueId, { labels });
- // Patch the Project Gantt caches in-place: the Gantt view applies
- // `labelFilters` to the row data, so a stale `labels` array would silently
- // hide or surface bars after another tab/agent attached or detached a
- // label. Mutating in place (instead of invalidating) avoids a refetch of
- // the entire scheduled set on every label toggle.
- for (const [key, data] of qc.getQueriesData<Issue[]>({
- queryKey: issueKeys.projectGanttAll(wsId),
- })) {
- if (!data) continue;
- const next = data.map((issue) =>
- issue.id === issueId ? { ...issue, labels } : issue,
- );
- qc.setQueryData<Issue[]>(key, next);
- }
+ onIssueAuxiliaryRevision(qc, wsId, issueId, revision, "labels");
}
/** Reconcile server-filtered label windows only after the write commits. */
@@ -344,15 +634,22 @@ export function onIssueMetadataChanged(
wsId: string,
issueId: string,
metadata: IssueMetadata,
+ revision?: number,
) {
- for (const [key, data] of qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) })) {
- if (data) qc.setQueryData<ListIssuesCache>(key, patchIssueInBuckets(data, issueId, { metadata }));
+ if (refetchForUnversionedIssueEvent(qc, wsId, issueId, revision)) return;
+ if (
+ isOlderThanRecordedAuxiliaryProjection(
+ qc,
+ wsId,
+ issueId,
+ revision,
+ "metadata",
+ )
+ ) {
+ return;
}
- patchIssueInFlatCaches(qc, wsId, issueId, { metadata });
- patchIssueInTableCaches(qc, wsId, issueId, { metadata });
- qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), (old) =>
- old ? { ...old, metadata } : old,
- );
+ patchIssueSnapshot(qc, wsId, issueId, { metadata }, revision);
+ onIssueAuxiliaryRevision(qc, wsId, issueId, revision, "metadata");
qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });
// A metadata write bumps issue.updated_at server-side (SetIssueMetadataKey /
// DeleteIssueMetadataKey), but the patches above keep each card's slot, so a
@@ -375,8 +672,10 @@ export function onIssuePropertiesChanged(
wsId: string,
issueId: string,
properties: IssuePropertyValues,
+ revision?: number,
) {
- patchIssueProperties(qc, wsId, issueId, properties);
+ if (refetchForUnversionedIssueEvent(qc, wsId, issueId, revision)) return;
+ patchIssueProperties(qc, wsId, issueId, properties, revision);
// Per-parent rows are patched for immediate UI feedback, then all children
// projections are marked stale so older fetches cannot win after commit.
qc.invalidateQueries({ queryKey: issueKeys.childrenAll(wsId) });
@@ -406,16 +705,21 @@ export function patchIssueProperties(
wsId: string,
issueId: string,
properties: IssuePropertyValues,
+ revision?: number,
) {
- for (const [key, data] of qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) })) {
- if (data) qc.setQueryData<ListIssuesCache>(key, patchIssueInBuckets(data, issueId, { properties }));
+ if (
+ isOlderThanRecordedAuxiliaryProjection(
+ qc,
+ wsId,
+ issueId,
+ revision,
+ "properties",
+ )
+ ) {
+ return;
}
- patchIssueInFlatCaches(qc, wsId, issueId, { properties });
- patchIssueInTableCaches(qc, wsId, issueId, { properties });
- qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), (old) =>
- old ? { ...old, properties } : old,
- );
- patchIssueInChildrenCaches(qc, wsId, issueId, { properties });
+ patchIssueSnapshot(qc, wsId, issueId, { properties }, revision);
+ onIssueAuxiliaryRevision(qc, wsId, issueId, revision, "properties");
}
/**
diff --git a/packages/core/labels/mutations.test.tsx b/packages/core/labels/mutations.test.tsx
index 8d26f37393..36a26496ad 100644
--- a/packages/core/labels/mutations.test.tsx
+++ b/packages/core/labels/mutations.test.tsx
@@ -179,4 +179,35 @@ describe("issue label mutations", () => {
await waitFor(() => expect(result.current.isSuccess).toBe(true));
qc.clear();
});
+
+ it("does not drop a known revision when an older backend returns an unversioned attach response", async () => {
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const labelKey = labelKeys.byIssue("ws-1", issue.id);
+ qc.setQueryData<IssueLabelsResponse>(labelKey, {
+ labels: [labelA],
+ issue_revision: 3,
+ });
+ qc.setQueryData<ListLabelsResponse>(labelKeys.list("ws-1"), {
+ labels: [labelA, labelB],
+ total: 2,
+ });
+ setApiInstance({
+ attachLabel: vi.fn().mockResolvedValue({ labels: [labelA, labelB] }),
+ } as unknown as ApiClient);
+ const { result } = renderHook(() => useAttachLabel(issue.id), {
+ wrapper: wrapper(qc),
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync(labelB.id);
+ });
+
+ expect(qc.getQueryData<IssueLabelsResponse>(labelKey)?.issue_revision).toBe(
+ 3,
+ );
+ expect(qc.getQueryState(labelKey)?.isInvalidated).toBe(true);
+ qc.clear();
+ });
});
diff --git a/packages/core/labels/mutations.ts b/packages/core/labels/mutations.ts
index 0cafcacfef..6f87255d5f 100644
--- a/packages/core/labels/mutations.ts
+++ b/packages/core/labels/mutations.ts
@@ -204,8 +204,7 @@ export function useAttachLabel(issueId: string) {
// when the backend gave us one — otherwise the optimistic patch from
// onMutate stands until onSettled's invalidation refetches.
if (data && Array.isArray(data.labels)) {
- qc.setQueryData<IssueLabelsResponse>(labelKeys.byIssue(wsId, issueId), data);
- onIssueLabelsChanged(qc, wsId, issueId, data.labels);
+ onIssueLabelsChanged(qc, wsId, issueId, data.labels, data.issue_revision);
}
},
onSettled: () => {
@@ -262,6 +261,11 @@ export function useDetachLabel(issueId: string) {
patchIssueLabels(qc, wsId, issueId, ctx.prev.labels);
}
},
+ onSuccess: (data: IssueLabelsResponse) => {
+ if (data && Array.isArray(data.labels)) {
+ onIssueLabelsChanged(qc, wsId, issueId, data.labels, data.issue_revision);
+ }
+ },
onSettled: () => {
qc.invalidateQueries({ queryKey: labelKeys.byIssue(wsId, issueId) });
invalidateIssueLabelDerivatives(qc, wsId);
diff --git a/packages/core/properties/mutations.ts b/packages/core/properties/mutations.ts
index a294d6a11a..cc7afbbfb0 100644
--- a/packages/core/properties/mutations.ts
+++ b/packages/core/properties/mutations.ts
@@ -133,7 +133,7 @@ export function useSetIssueProperty() {
rollbackSingleKey(qc, wsId, ctx);
},
onSuccess: (data, { issueId }) => {
- onIssuePropertiesChanged(qc, wsId, issueId, data.properties ?? {});
+ onIssuePropertiesChanged(qc, wsId, issueId, data.properties ?? {}, data.issue_revision);
},
onSettled: (_data, _err, { issueId }) => {
settleIssuePropertyCaches(qc, wsId, issueId);
@@ -164,7 +164,7 @@ export function useUnsetIssueProperty() {
rollbackSingleKey(qc, wsId, ctx);
},
onSuccess: (data, { issueId }) => {
- onIssuePropertiesChanged(qc, wsId, issueId, data.properties ?? {});
+ onIssuePropertiesChanged(qc, wsId, issueId, data.properties ?? {}, data.issue_revision);
},
onSettled: (_data, _err, { issueId }) => {
settleIssuePropertyCaches(qc, wsId, issueId);
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 4623d9cbcd..b61f18ca60 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -35,6 +35,7 @@ import {
onIssueLabelsChanged,
onIssuePropertiesChanged,
onIssueMetadataChanged,
+ onIssueAuxiliaryRevision,
} from "../issues/ws-updaters";
import { invalidateUpdatedAtSortedIssueLists } from "../issues/cache-coordinator";
import { onInboxNew, onInboxInvalidate, onInboxIssueStatusChanged, onInboxIssueDeleted, onInboxSummaryInvalidate } from "../inbox/ws-updaters";
@@ -986,31 +987,33 @@ export function useRealtimeSync(
});
const unsubIssueLabelsChanged = ws.on("issue_labels:changed", (p) => {
- const { issue_id, labels } = p as IssueLabelsChangedPayload;
+ const { issue_id, labels, issue_revision } = p as IssueLabelsChangedPayload;
if (!issue_id) return;
const wsId = getCurrentWsId();
- if (wsId) onIssueLabelsChanged(qc, wsId, issue_id, labels ?? []);
+ if (wsId) onIssueLabelsChanged(qc, wsId, issue_id, labels ?? [], issue_revision);
});
const unsubIssueAttachmentsChanged = ws.on("issue_attachments:changed", (p) => {
- const { issue_id } = p as IssueAttachmentsChangedPayload;
+ const { issue_id, issue_revision } = p as IssueAttachmentsChangedPayload;
if (!issue_id) return;
qc.invalidateQueries({ queryKey: issueKeys.attachments(issue_id) });
+ const wsId = getCurrentWsId();
+ if (wsId) onIssueAuxiliaryRevision(qc, wsId, issue_id, issue_revision);
});
const unsubIssueMetadataChanged = ws.on("issue_metadata:changed", (p) => {
- const { issue_id, metadata } = p as IssueMetadataChangedPayload;
+ const { issue_id, metadata, issue_revision } = p as IssueMetadataChangedPayload;
if (!issue_id) return;
const wsId = getCurrentWsId();
- if (wsId) onIssueMetadataChanged(qc, wsId, issue_id, metadata ?? {});
+ if (wsId) onIssueMetadataChanged(qc, wsId, issue_id, metadata ?? {}, issue_revision);
});
const unsubIssuePropertiesChanged = ws.on("issue_properties:changed", (p) => {
- const { issue_id, properties } = p as IssuePropertiesChangedPayload;
+ const { issue_id, properties, issue_revision } = p as IssuePropertiesChangedPayload;
if (!issue_id) return;
const wsId = getCurrentWsId();
if (wsId) {
- onIssuePropertiesChanged(qc, wsId, issue_id, properties ?? {});
+ onIssuePropertiesChanged(qc, wsId, issue_id, properties ?? {}, issue_revision);
// The catalog embeds per-definition usage counts; every value
// set/unset shifts them. The list is tiny, so a refetch beats
// trying to patch counts client-side.
@@ -1062,7 +1065,7 @@ export function useRealtimeSync(
};
const unsubCommentCreated = ws.on("comment:created", (p) => {
- const { comment } = p as CommentCreatedPayload;
+ const { comment, issue_revision: issueRevision } = p as CommentCreatedPayload;
if (!comment?.issue_id) return;
invalidateTimeline(comment.issue_id);
// A new comment bumps the parent issue's updated_at server-side
@@ -1071,7 +1074,13 @@ export function useRealtimeSync(
// place; every other sort is untouched. Only comment:created bumps
// updated_at, so the other comment events below deliberately do not.
const wsId = getCurrentWsId();
- if (wsId) invalidateUpdatedAtSortedIssueLists(qc, wsId);
+ if (wsId) {
+ invalidateUpdatedAtSortedIssueLists(qc, wsId);
+ // A comment carries only the aggregate owner revision, not a full
+ // Issue snapshot. Mark stale projections for an authoritative fetch
+ // without making a later full snapshot look older than the cache.
+ onIssueAuxiliaryRevision(qc, wsId, comment.issue_id, issueRevision);
+ }
});
const unsubCommentUpdated = ws.on("comment:updated", (p) => {
@@ -1112,13 +1121,21 @@ export function useRealtimeSync(
// --- Issue-level reactions & subscribers (global fallback) ---
const unsubIssueReactionAdded = ws.on("issue_reaction:added", (p) => {
- const { issue_id } = p as IssueReactionAddedPayload;
- if (issue_id) qc.invalidateQueries({ queryKey: issueKeys.reactions(issue_id) });
+ const { issue_id, issue_revision } = p as IssueReactionAddedPayload;
+ if (issue_id) {
+ qc.invalidateQueries({ queryKey: issueKeys.reactions(issue_id) });
+ const wsId = getCurrentWsId();
+ if (wsId) onIssueAuxiliaryRevision(qc, wsId, issue_id, issue_revision);
+ }
});
const unsubIssueReactionRemoved = ws.on("issue_reaction:removed", (p) => {
- const { issue_id } = p as IssueReactionRemovedPayload;
- if (issue_id) qc.invalidateQueries({ queryKey: issueKeys.reactions(issue_id) });
+ const { issue_id, issue_revision } = p as IssueReactionRemovedPayload;
+ if (issue_id) {
+ qc.invalidateQueries({ queryKey: issueKeys.reactions(issue_id) });
+ const wsId = getCurrentWsId();
+ if (wsId) onIssueAuxiliaryRevision(qc, wsId, issue_id, issue_revision);
+ }
});
const unsubSubscriberAdded = ws.on("subscriber:added", (p) => {
diff --git a/packages/core/types/activity.ts b/packages/core/types/activity.ts
index 11b666d68c..b5e653af53 100644
--- a/packages/core/types/activity.ts
+++ b/packages/core/types/activity.ts
@@ -20,6 +20,7 @@ export interface TimelineEntry {
content?: string;
parent_id?: string | null;
updated_at?: string;
+ revision?: number;
comment_type?: string;
/** Set only on comments a quick action produced (MUL-5465). Unforgeable. */
quick_action_id?: string | null;
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index 9749980d66..8694b32a48 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -23,7 +23,12 @@ export interface CreateIssueRequest {
}
export interface UpdateIssueRequest {
+ /** Legacy aggregate compare-and-swap token. New text editors use field
+ * baselines so unrelated issue activity does not reject their edits. */
+ expected_revision?: number;
title?: string;
+ /** Authoritative title the editor adopted before producing this update. */
+ title_base?: string;
description?: string;
/** Authoritative description the editor had adopted before producing this
* update. The server uses it to merge channel media that landed meanwhile. */
diff --git a/packages/core/types/comment.ts b/packages/core/types/comment.ts
index ddc0b7cbe8..5ec762dfd2 100644
--- a/packages/core/types/comment.ts
+++ b/packages/core/types/comment.ts
@@ -12,6 +12,7 @@ export interface Reaction {
actor_id: string;
emoji: string;
created_at: string;
+ comment_revision?: number;
}
export interface Comment {
@@ -26,6 +27,10 @@ export interface Comment {
attachments: import("./attachment").Attachment[];
created_at: string;
updated_at: string;
+ /** Monotonic server revision; absent when connected to an older backend. */
+ revision?: number;
+ /** Parent issue revision after this comment creation; create responses only. */
+ issue_revision?: number;
resolved_at: string | null;
resolved_by_type: CommentAuthorType | null;
resolved_by_id: string | null;
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index 5d0c4bb114..571130bd05 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -124,20 +124,24 @@ export interface IssueDeletedPayload {
export interface IssueLabelsChangedPayload {
issue_id: string;
labels: Label[];
+ issue_revision?: number;
}
export interface IssueAttachmentsChangedPayload {
issue_id: string;
+ issue_revision?: number;
}
export interface IssueMetadataChangedPayload {
issue_id: string;
metadata: IssueMetadata;
+ issue_revision?: number;
}
export interface IssuePropertiesChangedPayload {
issue_id: string;
properties: IssuePropertyValues;
+ issue_revision?: number;
}
export interface PropertyChangedPayload {
@@ -198,6 +202,7 @@ export interface InboxBatchArchivedPayload {
export interface CommentCreatedPayload {
comment: Comment;
+ issue_revision?: number;
}
export interface CommentUpdatedPayload {
@@ -339,6 +344,7 @@ export interface TaskCancelledPayload {
export interface ReactionAddedPayload {
reaction: Reaction;
issue_id: string;
+ comment_revision?: number;
}
export interface ReactionRemovedPayload {
@@ -347,11 +353,13 @@ export interface ReactionRemovedPayload {
emoji: string;
actor_type: string;
actor_id: string;
+ comment_revision?: number;
}
export interface IssueReactionAddedPayload {
reaction: IssueReaction;
issue_id: string;
+ issue_revision?: number;
}
export interface IssueReactionRemovedPayload {
@@ -359,6 +367,7 @@ export interface IssueReactionRemovedPayload {
emoji: string;
actor_type: string;
actor_id: string;
+ issue_revision?: number;
}
export interface ChatMessageEventPayload {
diff --git a/packages/core/types/issue.ts b/packages/core/types/issue.ts
index 2681184ae4..2f15c0a543 100644
--- a/packages/core/types/issue.ts
+++ b/packages/core/types/issue.ts
@@ -41,6 +41,7 @@ export interface IssueReaction {
actor_id: string;
emoji: string;
created_at: string;
+ issue_revision?: number;
}
/**
@@ -93,4 +94,6 @@ export interface Issue {
labels?: Label[];
created_at: string;
updated_at: string;
+ /** Monotonic server revision; absent when connected to an older backend. */
+ revision?: number;
}
diff --git a/packages/core/types/label.ts b/packages/core/types/label.ts
index daa9fa1d8e..f6a58f7714 100644
--- a/packages/core/types/label.ts
+++ b/packages/core/types/label.ts
@@ -40,6 +40,7 @@ export interface ListLabelsResponse {
export interface IssueLabelsResponse {
labels: Label[];
+ issue_revision?: number;
}
export type ResourceLabelsResponse = IssueLabelsResponse;
diff --git a/packages/core/types/property.ts b/packages/core/types/property.ts
index c97f41e3fc..aed9b462a3 100644
--- a/packages/core/types/property.ts
+++ b/packages/core/types/property.ts
@@ -181,4 +181,5 @@ export interface ListPropertiesResponse {
/** Response of PUT/DELETE /api/issues/{id}/properties/{propertyId}: the full post-mutation bag. */
export interface IssuePropertiesResponse {
properties: IssuePropertyValues;
+ issue_revision?: number;
}
diff --git a/packages/views/issues/actions/use-issue-actions.ts b/packages/views/issues/actions/use-issue-actions.ts
index 9aaa92a63f..f6ced57a5e 100644
--- a/packages/views/issues/actions/use-issue-actions.ts
+++ b/packages/views/issues/actions/use-issue-actions.ts
@@ -9,15 +9,20 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import { useModalStore } from "@multica/core/modals";
import { useUpdateIssue } from "@multica/core/issues/mutations";
+import { errorCode } from "@multica/core/api";
import { pinListOptions, useCreatePin, useDeletePin } from "@multica/core/pins";
import { copyText } from "@multica/ui/lib/clipboard";
import { useNavigation } from "../../navigation";
import { useT } from "../../i18n";
import { useIssueSurfaceActionsOptional } from "../surface/actions-context";
+import type { IssueSurfaceMutationOptions } from "../surface/actions-context";
export interface UseIssueActionsResult {
isPinned: boolean;
- updateField: (updates: Partial<UpdateIssueRequest>) => void;
+ updateField: (
+ updates: Partial<UpdateIssueRequest>,
+ options?: IssueSurfaceMutationOptions,
+ ) => void;
openInNewTab: () => void;
togglePin: () => void;
copyLink: () => Promise<void>;
@@ -64,9 +69,11 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {
const issueAssigneeType = issue?.assignee_type ?? null;
const issueAssigneeId = issue?.assignee_id ?? null;
const issueStatus = issue?.status ?? null;
-
const updateField = useCallback(
- (updates: Partial<UpdateIssueRequest>) => {
+ (
+ updates: Partial<UpdateIssueRequest>,
+ options?: IssueSurfaceMutationOptions,
+ ) => {
if (!issueId) return;
// Assigning to an agent/squad may start a run. Route through the
// pre-trigger confirm modal (preview + optional handoff note + "暂不开始"),
@@ -94,17 +101,24 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {
if (surfaceActions) {
surfaceActions.updateIssue(issueId, updates, {
errorMessage: t(($) => $.detail.update_failed),
+ ...options,
});
} else {
updateIssue.mutate(
{ id: issueId, ...updates },
{
- onError: (err) =>
+ onSuccess: options?.onSuccess,
+ onError: (err) => {
toast.error(
- err instanceof Error && err.message
+ errorCode(err) === "revision_conflict"
+ ? t(($) => $.revision.conflict)
+ : err instanceof Error && err.message
? err.message
: t(($) => $.detail.update_failed),
- ),
+ );
+ options?.onError?.(err);
+ },
+ onSettled: () => options?.onSettled?.(),
},
);
}
@@ -205,7 +219,10 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {
if (surfaceActions) {
surfaceActions.updateIssue(
issueId,
- { parent_issue_id: null, stage: null },
+ {
+ parent_issue_id: null,
+ stage: null,
+ },
{
onSuccess: () =>
toast.success(t(($) => $.actions.remove_parent_issue_success)),
@@ -214,7 +231,11 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {
);
} else {
updateIssue.mutate(
- { id: issueId, parent_issue_id: null, stage: null },
+ {
+ id: issueId,
+ parent_issue_id: null,
+ stage: null,
+ },
{
onSuccess: () =>
toast.success(t(($) => $.actions.remove_parent_issue_success)),
diff --git a/packages/views/issues/components/comment-card-edit-gate.test.tsx b/packages/views/issues/components/comment-card-edit-gate.test.tsx
index 9fdf42c976..872f753838 100644
--- a/packages/views/issues/components/comment-card-edit-gate.test.tsx
+++ b/packages/views/issues/components/comment-card-edit-gate.test.tsx
@@ -22,6 +22,10 @@ vi.mock("@multica/core/api", () => ({
// Uploads flow through the coordinator, which calls api.uploadFile (MUL-5181).
api: { uploadFile: apiUploadFile },
dispatchReasonCode: () => undefined,
+ errorCode: (error: unknown) =>
+ typeof error === "object" && error !== null && "body" in error
+ ? (error as { body?: { code?: string } }).body?.code
+ : undefined,
}));
vi.mock("../../navigation", () => ({
@@ -150,6 +154,7 @@ const entry: TimelineEntry = {
type: "comment",
created_at: "2026-07-01T00:00:00Z",
updated_at: "2026-07-01T00:00:00Z",
+ revision: 7,
attachments: [],
reactions: [],
} as unknown as TimelineEntry;
@@ -212,6 +217,37 @@ describe("comment edit — draft snapshot", () => {
});
});
+describe("comment edit — content conflict", () => {
+ it("keeps the local draft visible and resubmits with the captured content", async () => {
+ const onEdit = vi.fn().mockRejectedValue({
+ body: { code: "revision_conflict" },
+ });
+ renderCard(onEdit);
+ await startEditing();
+
+ fireEvent.change(screen.getByTestId("editor"), {
+ target: { value: "My local edit" },
+ });
+ fireEvent.click(getSaveButton());
+
+ await waitFor(() =>
+ expect(onEdit).toHaveBeenCalledWith(
+ "comment-1",
+ "My local edit",
+ [],
+ undefined,
+ "Original body",
+ ),
+ );
+ expect(await screen.findByText("The comment was changed concurrently. Compare both versions.")).toBeVisible();
+ expect(screen.getByText("My local edit")).toBeVisible();
+ expect(screen.getByTestId("editor")).toBeVisible();
+ expect(
+ useCommentDraftStore.getState().getDraft("edit:issue-1:comment-1"),
+ ).toBe("My local edit");
+ });
+});
+
// MUL-4808 — comment edit had no upload gate: saving mid-upload persisted the
// edit with the pending image stripped out of the body and its id unbound.
describe("comment edit — upload submit gate", () => {
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 3c5f9f06eb..6daf916009 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -32,7 +32,7 @@ import { useTimeAgo } from "../../i18n";
import { ContentEditor, type ContentEditorRef, ReadonlyContent, useFileDropZone, FileDropOverlay, Attachment as AttachmentRenderer, AttachmentDownloadProvider, useUploadGate, useComposerSubmit } from "../../editor";
import { useCommentUploads } from "./use-comment-uploads";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
-import { api, dispatchReasonCode } from "@multica/core/api";
+import { api, dispatchReasonCode, errorCode } from "@multica/core/api";
import { ReplyInput } from "./reply-input";
import { CommentTriggerChips } from "./comment-trigger-chips";
import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";
@@ -43,6 +43,7 @@ import { useCommentCollapseStore, useCommentDraftStore } from "@multica/core/iss
import { useT } from "../../i18n";
import { CommentsFoldBar } from "./resolved-thread-bar";
import { deriveThreadResolution } from "./thread-utils";
+import { RevisionConflictCompare } from "./revision-conflict-compare";
const highlightedCommentBackgroundClass =
"bg-[color-mix(in_srgb,var(--card)_95%,var(--brand)_5%)]";
@@ -108,7 +109,7 @@ interface CommentCardProps {
canModerate?: boolean;
onReply: (parentId: string, content: string, attachmentIds?: string[], suppressAgentIds?: string[]) => Promise<string | boolean>;
onReplyAccepted?: (commentId: string) => void;
- onEdit: (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[]) => Promise<void>;
+ onEdit: (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[], contentBase?: string) => Promise<void>;
onDelete: (commentId: string) => void;
onToggleReaction: (commentId: string, emoji: string) => void;
/** Resolve/unresolve any comment in this thread (commentId = the target row). */
@@ -304,12 +305,14 @@ function TaskCommentRetryButton({
function useEditAttachmentState(
issueId: string,
entry: TimelineEntry,
- onEdit: (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[]) => Promise<void>,
+ onEdit: (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[], contentBase?: string) => Promise<void>,
) {
const { t } = useT("issues");
const { t: tEditor } = useT("editor");
const [editing, setEditing] = useState(false);
const [initialValue, setInitialValue] = useState(entry.content ?? "");
+ const [initialContentBase, setInitialContentBase] = useState(entry.content ?? "");
+ const [revisionConflict, setRevisionConflict] = useState(false);
const editorRef = useRef<ContentEditorRef>(null);
// Saving mid-upload would persist the edit without the file the user just
// pasted in — same failure as posting a new comment.
@@ -340,6 +343,9 @@ function useEditAttachmentState(
useEffect(() => {
setSuppressedAgentIds(new Set());
}, [issueId, entry.id, entry.parent_id]);
+ useEffect(() => {
+ if (revisionConflict) setInitialContentBase(entry.content ?? "");
+ }, [entry.content, revisionConflict]);
const { isDragOver, dropZoneProps } = useFileDropZone({
onDrop: (files) => files.forEach((f) => editorRef.current?.uploadFile(f)),
@@ -373,6 +379,7 @@ function useEditAttachmentState(
const resetState = () => {
setEditing(false);
+ setRevisionConflict(false);
setContent(entry.content ?? "");
setSuppressedAgentIds(new Set());
setRetainedStandaloneIds(null);
@@ -384,6 +391,7 @@ function useEditAttachmentState(
cancelledRef.current = false;
const draft = getDraft(draftKey) ?? entry.content ?? "";
setInitialValue(draft);
+ setInitialContentBase(entry.content ?? "");
setContent(draft);
setRetainedStandaloneIds(initialStandaloneAttachmentIds(entry));
setEditing(true);
@@ -442,11 +450,18 @@ function useEditAttachmentState(
trimmed,
activeIds,
suppressAgentIds.length > 0 ? suppressAgentIds : undefined,
+ initialContentBase,
);
+ setRevisionConflict(false);
return true;
} catch (err) {
+ if (errorCode(err) === "revision_conflict") {
+ setRevisionConflict(true);
+ }
toast.error(
- err instanceof Error && err.message
+ errorCode(err) === "revision_conflict"
+ ? t(($) => $.revision.conflict)
+ : err instanceof Error && err.message
? err.message
: t(($) => $.comment.update_failed),
);
@@ -498,9 +513,31 @@ function useEditAttachmentState(
startEdit,
cancelEdit,
saveEdit,
+ revisionConflict,
};
}
+function CommentRevisionConflict({
+ serverContent,
+ localContent,
+}: {
+ serverContent: string;
+ localContent: string;
+}) {
+ const { t } = useT("issues");
+ return (
+ <RevisionConflictCompare
+ className="mt-2"
+ title={t(($) => $.revision.compare_comment)}
+ serverLabel={t(($) => $.revision.server_version)}
+ localLabel={t(($) => $.revision.local_version)}
+ serverValue={serverContent}
+ localValue={localContent}
+ footer={t(($) => $.revision.save_again)}
+ />
+ );
+}
+
// ---------------------------------------------------------------------------
// Single comment row (used for both parent and replies within the same Card)
// ---------------------------------------------------------------------------
@@ -525,7 +562,7 @@ function CommentRow({
isResolution?: boolean;
/** True when this row is the deep-link target currently being highlighted. */
isHighlighted?: boolean;
- onEdit: (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[]) => Promise<void>;
+ onEdit: (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[], contentBase?: string) => Promise<void>;
onDelete: (commentId: string) => void;
onToggleReaction: (commentId: string, emoji: string) => void;
onResolveToggle?: (commentId: string, resolved: boolean) => void;
@@ -663,6 +700,12 @@ function CommentRow({
attachments={edit.editorAttachments}
/>
</div>
+ {edit.revisionConflict ? (
+ <CommentRevisionConflict
+ serverContent={entry.content ?? ""}
+ localContent={edit.content}
+ />
+ ) : null}
{edit.standaloneEditAttachments.length > 0 && (
<AttachmentList
attachments={edit.standaloneEditAttachments}
@@ -980,6 +1023,12 @@ function CommentCardImpl({
attachments={edit.editorAttachments}
/>
</div>
+ {edit.revisionConflict ? (
+ <CommentRevisionConflict
+ serverContent={entry.content ?? ""}
+ localContent={edit.content}
+ />
+ ) : null}
<div className="flex items-center justify-between mt-2">
<div className="flex min-w-0 flex-1 flex-col gap-1">
{edit.standaloneEditAttachments.length > 0 && (
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 909fd48b5c..3312b122ec 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -1,6 +1,6 @@
import { forwardRef, useEffect, useRef, useState, useImperativeHandle } from "react";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Issue, Label, TimelineEntry } from "@multica/core/types";
import { I18nProvider } from "@multica/core/i18n/react";
@@ -309,6 +309,10 @@ vi.mock("@multica/core/api", () => ({
api: mockApiObj,
getApi: () => mockApiObj,
setApiInstance: vi.fn(),
+ errorCode: (error: unknown) =>
+ typeof error === "object" && error !== null && "body" in error
+ ? (error as { body?: { code?: string } }).body?.code
+ : undefined,
}));
// Mock issue config
@@ -536,6 +540,7 @@ const mockIssue: Issue = {
properties: {},
created_at: "2026-01-15T00:00:00Z",
updated_at: "2026-01-20T00:00:00Z",
+ revision: 3,
};
const mockTimeline: TimelineEntry[] = [
@@ -1636,6 +1641,182 @@ describe("IssueDetail (shared)", () => {
});
});
+ it("keeps a description draft visible when its captured content conflicts", async () => {
+ mockApiObj.updateIssue.mockRejectedValueOnce({
+ body: { code: "revision_conflict" },
+ });
+ renderIssueDetail();
+
+ const editor = await screen.findByDisplayValue("Add JWT auth to the backend");
+ fireEvent.focus(editor);
+ fireEvent.change(editor, { target: { value: "My local description" } });
+
+ await waitFor(() =>
+ expect(mockApiObj.updateIssue).toHaveBeenCalledWith(
+ "issue-1",
+ expect.objectContaining({
+ description: "My local description",
+ description_base: "Add JWT auth to the backend",
+ }),
+ ),
+ );
+ expect(
+ await screen.findByText("The description was changed concurrently. Compare both versions."),
+ ).toBeVisible();
+ expect(screen.getAllByText("My local description").length).toBeGreaterThan(0);
+ expect(screen.getByDisplayValue("My local description")).toBeVisible();
+ });
+
+ it("serializes description saves and rebases the queued draft on submitted content", async () => {
+ let resolveFirst!: (issue: Issue) => void;
+ const firstSave = new Promise<Issue>((resolve) => {
+ resolveFirst = resolve;
+ });
+ mockApiObj.updateIssue
+ .mockReturnValueOnce(firstSave)
+ .mockResolvedValueOnce({
+ ...mockIssue,
+ description: "Second local description",
+ revision: 5,
+ });
+ renderIssueDetail();
+
+ const editor = await screen.findByDisplayValue("Add JWT auth to the backend");
+ fireEvent.focus(editor);
+ fireEvent.change(editor, { target: { value: "First local description" } });
+ await waitFor(() => expect(mockApiObj.updateIssue).toHaveBeenCalledTimes(1));
+ fireEvent.change(editor, { target: { value: "Second local description" } });
+ expect(mockApiObj.updateIssue).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ resolveFirst({ ...mockIssue, description: "First local description", revision: 4 });
+ await firstSave;
+ });
+
+ await waitFor(() => expect(mockApiObj.updateIssue).toHaveBeenCalledTimes(2));
+ expect(mockApiObj.updateIssue).toHaveBeenNthCalledWith(
+ 2,
+ "issue-1",
+ expect.objectContaining({
+ description: "Second local description",
+ description_base: "First local description",
+ }),
+ );
+ });
+
+ it("keeps the newest queued description when the in-flight save conflicts", async () => {
+ let rejectFirst!: (error: unknown) => void;
+ const firstSave = new Promise<Issue>((_resolve, reject) => {
+ rejectFirst = reject;
+ });
+ mockApiObj.updateIssue.mockReturnValueOnce(firstSave);
+ renderIssueDetail();
+
+ const editor = await screen.findByDisplayValue("Add JWT auth to the backend");
+ fireEvent.focus(editor);
+ fireEvent.change(editor, { target: { value: "First local description" } });
+ await waitFor(() => expect(mockApiObj.updateIssue).toHaveBeenCalledTimes(1));
+ fireEvent.change(editor, { target: { value: "Newest local description" } });
+
+ await act(async () => {
+ rejectFirst({ body: { code: "revision_conflict" } });
+ await firstSave.catch(() => undefined);
+ });
+
+ expect(mockApiObj.updateIssue).toHaveBeenCalledTimes(1);
+ expect(
+ await screen.findByText("The description was changed concurrently. Compare both versions."),
+ ).toBeVisible();
+ expect(screen.getByDisplayValue("Newest local description")).toBeVisible();
+ });
+
+ it("ignores a late description callback after switching issues", async () => {
+ const queryClient = createTestQueryClient();
+ const issue2: Issue = {
+ ...mockIssue,
+ id: "issue-2",
+ identifier: "TES-2",
+ description: "Second issue description",
+ revision: 8,
+ };
+ queryClient.setQueryData(["issues", "ws-1", "detail", "issue-2"], issue2);
+ mockApiObj.getIssue.mockImplementation((issueId: string) =>
+ Promise.resolve(issueId === "issue-2" ? issue2 : mockIssue),
+ );
+
+ let resolveFirst!: (issue: Issue) => void;
+ const firstSave = new Promise<Issue>((resolve) => {
+ resolveFirst = resolve;
+ });
+ mockApiObj.updateIssue
+ .mockReturnValueOnce(firstSave)
+ .mockResolvedValueOnce({ ...issue2, description: "Issue two draft", revision: 9 });
+
+ const ui = (issueId: string) => (
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={queryClient}>
+ <IssueDetail issueId={issueId} />
+ </QueryClientProvider>
+ </I18nProvider>
+ );
+ const { rerender } = render(ui("issue-1"));
+
+ const issueOneEditor = await screen.findByDisplayValue("Add JWT auth to the backend");
+ fireEvent.focus(issueOneEditor);
+ fireEvent.change(issueOneEditor, {
+ target: { value: "Issue one draft" },
+ });
+ await waitFor(() => expect(mockApiObj.updateIssue).toHaveBeenCalledTimes(1));
+
+ rerender(ui("issue-2"));
+ const issueTwoEditor = await screen.findByDisplayValue("Second issue description");
+ fireEvent.focus(issueTwoEditor);
+ fireEvent.change(issueTwoEditor, {
+ target: { value: "Issue two draft" },
+ });
+ await waitFor(() => expect(mockApiObj.updateIssue).toHaveBeenCalledTimes(2));
+ expect(mockApiObj.updateIssue).toHaveBeenNthCalledWith(
+ 2,
+ "issue-2",
+ expect.objectContaining({ description_base: "Second issue description" }),
+ );
+
+ await act(async () => {
+ resolveFirst({ ...mockIssue, description: "Issue one draft", revision: 4 });
+ await firstSave;
+ });
+
+ expect(mockApiObj.updateIssue).toHaveBeenCalledTimes(2);
+ expect(screen.getByDisplayValue("Issue two draft")).toBeVisible();
+ });
+
+ it("keeps a title draft visible when its captured content conflicts", async () => {
+ mockApiObj.updateIssue.mockRejectedValueOnce({
+ body: { code: "revision_conflict" },
+ });
+ renderIssueDetail();
+
+ fireEvent.click(await screen.findByRole("button", { name: "Implement authentication" }));
+ const editor = await screen.findByTestId("title-editor");
+ fireEvent.change(editor, { target: { value: "My local title" } });
+ fireEvent.blur(editor);
+
+ await waitFor(() =>
+ expect(mockApiObj.updateIssue).toHaveBeenCalledWith(
+ "issue-1",
+ expect.objectContaining({
+ title: "My local title",
+ title_base: "Implement authentication",
+ }),
+ ),
+ );
+ expect(
+ await screen.findByText("The title was changed concurrently. Compare both versions."),
+ ).toBeVisible();
+ expect(screen.getAllByText("My local title").length).toBeGreaterThan(0);
+ expect(screen.getByDisplayValue("My local title")).toBeVisible();
+ });
+
describe("sub-issues list", () => {
beforeEach(() => {
useSubIssueDisplayStore.setState({
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index cc8851248e..aeab67a79f 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -66,6 +66,7 @@ import { STATUS_CONFIG, PRIORITY_CONFIG } from "@multica/core/issues/config";
import { formatDateOnly, isPastDateOnly } from "@multica/core/issues/date";
import { useUpdateIssue } from "@multica/core/issues/mutations";
import { toast } from "sonner";
+import { errorCode } from "@multica/core/api";
import { StatusIcon, PriorityIcon, StatusPicker, PriorityPicker, StagePicker, StartDatePicker, DueDatePicker, AssigneePicker, LabelPicker } from ".";
import { maxSiblingStage } from "./pickers/stage-picker";
import { CustomPropertyValueEditor, CustomPropertyValueDisplay } from "./pickers/custom-property-picker";
@@ -77,6 +78,7 @@ import { SubIssuesAgentWorkingChip } from "./sub-issues-agent-working-chip";
import { ProjectPicker } from "../../projects/components/project-picker";
import { LocalDirectoryHint } from "../../projects/components/local-directory-hint";
import { CommentCard } from "./comment-card";
+import { RevisionConflictCompare } from "./revision-conflict-compare";
import { CommentInput } from "./comment-input";
import { CurrentIssueRenderContextProvider } from "../current-issue-render-context";
import { ResolvedThreadBar } from "./resolved-thread-bar";
@@ -693,7 +695,10 @@ function SubIssueRow({
const handleUpdate = useCallback(
(updates: Partial<UpdateIssueRequest>) => {
updateIssue.mutate(
- { id: child.id, ...updates },
+ {
+ id: child.id,
+ ...updates,
+ },
{
onError: (err) =>
toast.error(
@@ -1950,12 +1955,33 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
}, [highlightCommentId, highlightRequestToken, id, writeViewState, items, targetIdx, scrollContainerEl, replyToRoot, expandedResolved, timelineView, toggleResolvedExpand]);
const descEditorRef = useRef<ContentEditorRef>(null);
+ const descriptionEditingRef = useRef(false);
+ const [descriptionConflictDraft, setDescriptionConflictDraft] = useState<string | null>(null);
+ const descriptionAttachmentIdsRef = useRef<string[]>([]);
+ const descriptionSaveInFlightRef = useRef(false);
+ const descriptionSaveIssueIdRef = useRef(id);
+ const pendingDescriptionSaveRef = useRef<{
+ markdown: string;
+ baseMarkdown: string;
+ attachmentIds: string[];
+ } | null>(null);
// Keep the description editor mounted from the start. Unlike the empty
// composer shells, a long rendered description cannot swap between
// react-markdown and ProseMirror without small per-block height differences
// accumulating into a visible scroll/layout jump. The chunked Markdown path
// keeps this single eager editor affordable; title and composers stay lazy.
const titleEditorRef = useRef<TitleEditorRef>(null);
+ const titleBaseRef = useRef<string | undefined>(issue?.title);
+ const [titleConflictDraft, setTitleConflictDraft] = useState<string | null>(null);
+ useEffect(() => {
+ setTitleConflictDraft(null);
+ setDescriptionConflictDraft(null);
+ titleBaseRef.current = undefined;
+ descriptionAttachmentIdsRef.current = [];
+ descriptionSaveInFlightRef.current = false;
+ descriptionSaveIssueIdRef.current = id;
+ pendingDescriptionSaveRef.current = null;
+ }, [id]);
const titleLazy = useLazyEditor({ editorRef: titleEditorRef, resetKey: id });
const { isDragOver: descDragOver, dropZoneProps: descDropZoneProps } = useFileDropZone({
onDrop: (files) => files.forEach((file) => descEditorRef.current?.uploadFile(file)),
@@ -2188,6 +2214,61 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
return <IssueNotFound showBackLink={!onDelete} leading={leadingAction} />;
}
+ const persistDescriptionSave = (
+ draft: { markdown: string; baseMarkdown: string; attachmentIds: string[] },
+ ) => {
+ descriptionSaveInFlightRef.current = true;
+ handleUpdateField(
+ {
+ description: draft.markdown,
+ description_base: draft.baseMarkdown,
+ attachment_ids:
+ draft.attachmentIds.length > 0 ? draft.attachmentIds : undefined,
+ },
+ {
+ onSuccess: (serverIssue) => {
+ if (descriptionSaveIssueIdRef.current !== id) return;
+ setDescriptionConflictDraft(null);
+ descriptionSaveInFlightRef.current = false;
+ const pending = pendingDescriptionSaveRef.current;
+ pendingDescriptionSaveRef.current = null;
+ if (pending) {
+ // Usually the accepted document is exactly what we submitted. If
+ // the server appended late channel media, keep the submitted body
+ // as the next editor baseline: the server can recognize that the
+ // only delta is media the editor never saw and preserve it again.
+ const nextBase = serverIssue.description === draft.markdown
+ ? serverIssue.description
+ : draft.markdown;
+ persistDescriptionSave({ ...pending, baseMarkdown: nextBase });
+ }
+ },
+ onError: (error) => {
+ if (descriptionSaveIssueIdRef.current !== id) return;
+ descriptionSaveInFlightRef.current = false;
+ const pending = pendingDescriptionSaveRef.current;
+ pendingDescriptionSaveRef.current = null;
+ if (errorCode(error) === "revision_conflict") {
+ const latest = pending ?? draft;
+ descriptionAttachmentIdsRef.current = latest.attachmentIds;
+ setDescriptionConflictDraft(latest.markdown);
+ }
+ },
+ },
+ );
+ };
+
+ const queueDescriptionSave = (
+ draft: { markdown: string; baseMarkdown: string; attachmentIds: string[] },
+ ) => {
+ descriptionAttachmentIdsRef.current = draft.attachmentIds;
+ if (descriptionSaveInFlightRef.current) {
+ pendingDescriptionSaveRef.current = draft;
+ return;
+ }
+ persistDescriptionSave(draft);
+ };
+
const sidebarContent = (
<div className="space-y-5">
{/* Properties */}
@@ -2769,13 +2850,28 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
<TitleEditor
key={`title-${id}`}
ref={titleEditorRef}
- defaultValue={issue.title}
+ defaultValue={titleConflictDraft ?? issue.title}
placeholder={t(($) => $.detail.title_placeholder)}
className="w-full text-display-sm font-bold leading-snug tracking-tight"
onReady={titleLazy.onReady}
onBlur={(value) => {
const trimmed = value.trim();
- if (trimmed && trimmed !== issue.title) handleUpdateField({ title: trimmed });
+ if (trimmed && trimmed !== issue.title) {
+ handleUpdateField({
+ title: trimmed,
+ title_base: titleBaseRef.current,
+ }, {
+ onSuccess: (serverIssue) => {
+ setTitleConflictDraft(null);
+ titleBaseRef.current = serverIssue.title;
+ },
+ onError: (error) => {
+ if (errorCode(error) === "revision_conflict") {
+ setTitleConflictDraft(trimmed);
+ }
+ },
+ });
+ }
}}
/>
</div>
@@ -2789,11 +2885,13 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
// A drag-selection (copying the title) must not summon the editor.
const sel = window.getSelection();
if (sel && !sel.isCollapsed) return;
+ titleBaseRef.current = issue.title;
titleLazy.activate({ x: e.clientX, y: e.clientY });
}}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
+ titleBaseRef.current = issue.title;
titleLazy.activate();
}
}}
@@ -2801,6 +2899,38 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
{issue.title}
</div>
)}
+ {titleConflictDraft !== null ? (
+ <RevisionConflictCompare
+ className="mt-2"
+ title={t(($) => $.revision.compare_title)}
+ serverLabel={t(($) => $.revision.server_version)}
+ localLabel={t(($) => $.revision.local_version)}
+ serverValue={issue.title}
+ localValue={titleConflictDraft}
+ actions={(
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={() => {
+ const draft = titleConflictDraft.trim();
+ if (!draft) return;
+ handleUpdateField(
+ { title: draft, title_base: issue.title },
+ {
+ onSuccess: (serverIssue) => {
+ setTitleConflictDraft(null);
+ titleBaseRef.current = serverIssue.title;
+ },
+ },
+ );
+ }}
+ >
+ {t(($) => $.revision.keep_local)}
+ </Button>
+ )}
+ />
+ ) : null}
{parentIssue && (
<AppLink
@@ -2831,11 +2961,24 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
</AppLink>
)}
- <div {...descDropZoneProps} className="relative mt-5 rounded-lg">
+ <div
+ {...descDropZoneProps}
+ className="relative mt-5 rounded-lg"
+ onFocusCapture={() => {
+ if (!descriptionEditingRef.current) {
+ descriptionEditingRef.current = true;
+ }
+ }}
+ onBlurCapture={(event) => {
+ if (!event.currentTarget.contains(event.relatedTarget)) {
+ descriptionEditingRef.current = false;
+ }
+ }}
+ >
<ContentEditor
ref={descEditorRef}
key={id}
- value={issue.description || ""}
+ value={descriptionConflictDraft ?? issue.description ?? ""}
placeholder={t(($) => $.detail.desc_placeholder)}
onUpdate={(md, baseMarkdown) => {
// Bind any pending uploads still referenced in the markdown
@@ -2858,10 +3001,10 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
const ids = descPendingAttachmentsRef.current
.filter((a) => contentReferencesAttachment(md, a))
.map((a) => a.id);
- handleUpdateField({
- description: md,
- description_base: baseMarkdown,
- attachment_ids: ids.length > 0 ? ids : undefined,
+ queueDescriptionSave({
+ markdown: md,
+ baseMarkdown,
+ attachmentIds: ids,
});
}}
onUploadFile={handleDescriptionUpload}
@@ -2874,6 +3017,43 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
attachments={descEditorAttachments}
/>
+ {descriptionConflictDraft !== null ? (
+ <RevisionConflictCompare
+ className="mt-3"
+ title={t(($) => $.revision.compare_description)}
+ serverLabel={t(($) => $.revision.server_version)}
+ localLabel={t(($) => $.revision.local_version)}
+ serverValue={issue.description || ""}
+ localValue={descriptionConflictDraft}
+ actions={(
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={() => {
+ handleUpdateField(
+ {
+ description: descriptionConflictDraft,
+ description_base: issue.description || "",
+ attachment_ids:
+ descriptionAttachmentIdsRef.current.length > 0
+ ? descriptionAttachmentIdsRef.current
+ : undefined,
+ },
+ {
+ onSuccess: () => {
+ setDescriptionConflictDraft(null);
+ },
+ },
+ );
+ }}
+ >
+ {t(($) => $.revision.keep_local)}
+ </Button>
+ )}
+ />
+ ) : null}
+
<div className="flex items-center gap-1 mt-3">
<ReactionBar
reactions={issueReactions}
diff --git a/packages/views/issues/components/revision-conflict-compare.test.tsx b/packages/views/issues/components/revision-conflict-compare.test.tsx
new file mode 100644
index 0000000000..13e1910df5
--- /dev/null
+++ b/packages/views/issues/components/revision-conflict-compare.test.tsx
@@ -0,0 +1,65 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import {
+ RevisionConflictCompare,
+ revisionConflictRows,
+} from "./revision-conflict-compare";
+
+describe("RevisionConflictCompare", () => {
+ it("aligns replacements and keeps every line in the comparison", () => {
+ expect(
+ revisionConflictRows(
+ "same\nserver only\ntail",
+ "same\nlocal only\ntail\nextra",
+ ),
+ ).toEqual([
+ {
+ server: { text: "same", changed: false },
+ local: { text: "same", changed: false },
+ },
+ {
+ server: { text: "server only", changed: true },
+ local: { text: "local only", changed: true },
+ },
+ {
+ server: { text: "tail", changed: false },
+ local: { text: "tail", changed: false },
+ },
+ { server: undefined, local: { text: "extra", changed: true } },
+ ]);
+ });
+
+ it("renders a scrollable full diff with explicit additions and removals", () => {
+ const serverValue = Array.from(
+ { length: 12 },
+ (_, index) => `server line ${index + 1}`,
+ ).join("\n");
+ const localValue = `${serverValue.replace(
+ "server line 6",
+ "local line 6",
+ )}\nlocal line 13`;
+ const { container } = render(
+ <RevisionConflictCompare
+ title="Compare both versions"
+ serverLabel="Latest server version"
+ localLabel="Your local version"
+ serverValue={serverValue}
+ localValue={localValue}
+ />,
+ );
+
+ expect(screen.getAllByText("server line 12")).toHaveLength(2);
+ expect(screen.getByText("local line 13")).toBeVisible();
+ expect(
+ container.querySelector('[data-diff-kind="remove"]'),
+ ).toHaveTextContent("server line 6");
+ expect(
+ container.querySelectorAll('[data-diff-kind="add"]')[0],
+ ).toHaveTextContent("local line 6");
+ expect(container.querySelector("[data-revision-diff-scroll]")).toHaveClass(
+ "max-h-80",
+ "overflow-y-auto",
+ );
+ expect(container.querySelector("[class*='line-clamp']")).toBeNull();
+ });
+});
diff --git a/packages/views/issues/components/revision-conflict-compare.tsx b/packages/views/issues/components/revision-conflict-compare.tsx
new file mode 100644
index 0000000000..29f6b08a39
--- /dev/null
+++ b/packages/views/issues/components/revision-conflict-compare.tsx
@@ -0,0 +1,145 @@
+import type { ReactNode } from "react";
+import { cn } from "@multica/ui/lib/utils";
+import { diffTraceLines } from "../../common/task-transcript/trace-event-presenter";
+
+interface RevisionConflictCompareProps {
+ title: string;
+ serverLabel: string;
+ localLabel: string;
+ serverValue: string;
+ localValue: string;
+ footer?: ReactNode;
+ actions?: ReactNode;
+ className?: string;
+}
+
+interface RevisionConflictRow {
+ server?: { text: string; changed: boolean };
+ local?: { text: string; changed: boolean };
+}
+
+const textLines = (value: string): string[] =>
+ value.length > 0 ? value.split("\n") : [""];
+
+export function revisionConflictRows(
+ serverValue: string,
+ localValue: string,
+): RevisionConflictRow[] {
+ const diff = diffTraceLines(textLines(serverValue), textLines(localValue));
+ const rows: RevisionConflictRow[] = [];
+ let removed: string[] = [];
+ let added: string[] = [];
+
+ const flushChanges = () => {
+ const count = Math.max(removed.length, added.length);
+ for (let index = 0; index < count; index++) {
+ const server = removed[index];
+ const local = added[index];
+ rows.push({
+ server:
+ server === undefined ? undefined : { text: server, changed: true },
+ local:
+ local === undefined ? undefined : { text: local, changed: true },
+ });
+ }
+ removed = [];
+ added = [];
+ };
+
+ for (const line of diff) {
+ if (line.kind === "remove") {
+ removed.push(line.text);
+ } else if (line.kind === "add") {
+ added.push(line.text);
+ } else if (line.kind === "context") {
+ flushChanges();
+ rows.push({
+ server: { text: line.text, changed: false },
+ local: { text: line.text, changed: false },
+ });
+ }
+ }
+ flushChanges();
+ return rows;
+}
+
+function DiffCell({
+ side,
+ line,
+}: {
+ side: "server" | "local";
+ line?: { text: string; changed: boolean };
+}) {
+ const changed = line?.changed === true;
+ const marker = changed ? (side === "server" ? "−" : "+") : "";
+ return (
+ <div
+ data-diff-kind={
+ changed ? (side === "server" ? "remove" : "add") : "context"
+ }
+ className={cn(
+ "grid min-w-0 grid-cols-[1.25rem_minmax(0,1fr)] px-2 py-1 font-mono text-micro leading-relaxed",
+ !line && "bg-muted/20",
+ changed && side === "server" && "bg-destructive/10 text-destructive",
+ changed && side === "local" && "bg-success/10 text-success",
+ )}
+ >
+ <span className="select-none text-center opacity-70">
+ {marker}
+ </span>
+ <span className="min-w-0 whitespace-pre-wrap break-words">
+ {line ? line.text || " " : ""}
+ </span>
+ </div>
+ );
+}
+
+export function RevisionConflictCompare({
+ title,
+ serverLabel,
+ localLabel,
+ serverValue,
+ localValue,
+ footer,
+ actions,
+ className,
+}: RevisionConflictCompareProps) {
+ const rows = revisionConflictRows(serverValue, localValue);
+ return (
+ <div
+ role="alert"
+ className={cn(
+ "rounded-md border border-warning/40 bg-warning/5 p-3 text-caption",
+ className,
+ )}
+ >
+ <div className="font-medium">{title}</div>
+ <div className="mt-2 overflow-hidden rounded-md border bg-background/70">
+ <div className="grid grid-cols-2 border-b bg-muted/40 font-medium text-muted-foreground">
+ <div className="min-w-0 px-3 py-1.5">{serverLabel}</div>
+ <div className="min-w-0 border-l px-3 py-1.5">{localLabel}</div>
+ </div>
+ <div
+ data-revision-diff-scroll
+ className="max-h-80 overflow-y-auto overscroll-contain"
+ >
+ {rows.map((row, index) => (
+ <div
+ key={index}
+ className="grid grid-cols-2 border-b last:border-b-0"
+ >
+ <DiffCell side="server" line={row.server} />
+ <div className="min-w-0 border-l">
+ <DiffCell side="local" line={row.local} />
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ {footer ? (
+ <div className="mt-2 text-muted-foreground">{footer}</div>
+ ) : null}
+ {actions ? <div className="mt-2">{actions}</div> : null}
+ </div>
+ );
+}
diff --git a/packages/views/issues/hooks/use-issue-timeline.test.tsx b/packages/views/issues/hooks/use-issue-timeline.test.tsx
index c5132e39b4..4f8c2baf5a 100644
--- a/packages/views/issues/hooks/use-issue-timeline.test.tsx
+++ b/packages/views/issues/hooks/use-issue-timeline.test.tsx
@@ -68,6 +68,7 @@ const queryState = vi.hoisted(() => ({
// can assert what would have been written.
const cacheUpdates = vi.hoisted(() => ({
last: null as unknown,
+ invalidations: 0,
}));
vi.mock("@tanstack/react-query", async () => {
@@ -81,7 +82,9 @@ vi.mock("@tanstack/react-query", async () => {
isLoading: queryState.isLoading,
}),
useQueryClient: () => ({
- invalidateQueries: vi.fn(),
+ invalidateQueries: vi.fn(() => {
+ cacheUpdates.invalidations += 1;
+ }),
setQueryData: vi.fn((_key: unknown, updater: unknown) => {
cacheUpdates.last = typeof updater === "function"
? (updater as (old: unknown) => unknown)(queryState.data)
@@ -118,6 +121,7 @@ describe("useIssueTimeline", () => {
queryState.data = [];
queryState.isLoading = false;
cacheUpdates.last = null;
+ cacheUpdates.invalidations = 0;
});
// CommentCard is wrapped in React.memo (perf fix for long timelines, see
@@ -172,6 +176,28 @@ describe("useIssueTimeline", () => {
});
});
+ it("passes the captured comment content through editComment", async () => {
+ const { result } = renderHook(() => useIssueTimeline("issue-1", "user-1"));
+
+ await act(async () => {
+ await result.current.editComment(
+ "comment-1",
+ "updated",
+ [],
+ undefined,
+ "original",
+ );
+ });
+
+ expect(stableHandles.updateMutateAsync).toHaveBeenCalledWith({
+ commentId: "comment-1",
+ content: "updated",
+ attachmentIds: [],
+ suppressAgentIds: undefined,
+ contentBase: "original",
+ });
+ });
+
it("comment:created appends the new entry to the cache", () => {
queryState.data = [];
renderHook(() => useIssueTimeline("issue-1", "user-1"));
@@ -278,6 +304,82 @@ describe("useIssueTimeline", () => {
expect(cacheUpdates.last).toBeNull();
});
+ it("rejects a delayed comment update older than the cached revision", () => {
+ queryState.data = [{
+ type: "comment",
+ id: "c1",
+ actor_type: "member",
+ actor_id: "u",
+ content: "latest",
+ parent_id: null,
+ created_at: "2026-05-06T01:00:00Z",
+ updated_at: "2026-05-06T03:00:00Z",
+ revision: 3,
+ reactions: [],
+ attachments: [],
+ }];
+ renderHook(() => useIssueTimeline("issue-1", "user-1"));
+
+ act(() => {
+ wsHandlers.get("comment:updated")!({
+ comment: {
+ id: "c1",
+ issue_id: "issue-1",
+ author_type: "member",
+ author_id: "u",
+ content: "stale",
+ parent_id: null,
+ created_at: "2026-05-06T01:00:00Z",
+ updated_at: "2026-05-06T02:00:00Z",
+ revision: 2,
+ type: "comment",
+ reactions: [],
+ attachments: [],
+ },
+ });
+ });
+
+ expect(cacheUpdates.last).toEqual(queryState.data);
+ });
+
+ it("refetches instead of applying an unversioned event over versioned cache state", () => {
+ queryState.data = [{
+ type: "comment",
+ id: "c1",
+ actor_type: "member",
+ actor_id: "u",
+ content: "versioned",
+ parent_id: null,
+ created_at: "2026-05-06T01:00:00Z",
+ updated_at: "2026-05-06T03:00:00Z",
+ revision: 3,
+ reactions: [],
+ attachments: [],
+ }];
+ renderHook(() => useIssueTimeline("issue-1", "user-1"));
+
+ act(() => {
+ wsHandlers.get("comment:updated")!({
+ comment: {
+ id: "c1",
+ issue_id: "issue-1",
+ author_type: "member",
+ author_id: "u",
+ content: "unversioned",
+ parent_id: null,
+ created_at: "2026-05-06T01:00:00Z",
+ updated_at: "2026-05-06T04:00:00Z",
+ type: "comment",
+ reactions: [],
+ attachments: [],
+ },
+ });
+ });
+
+ expect(cacheUpdates.last).toEqual(queryState.data);
+ expect(cacheUpdates.invalidations).toBeGreaterThan(0);
+ });
+
// The global useRealtimeSync handler now uses refetchType: "none" for
// timeline events, which means useIssueTimeline must own the granular
// cache update for every event that mutates the timeline — including
diff --git a/packages/views/issues/hooks/use-issue-timeline.ts b/packages/views/issues/hooks/use-issue-timeline.ts
index 0704986bab..149db08cba 100644
--- a/packages/views/issues/hooks/use-issue-timeline.ts
+++ b/packages/views/issues/hooks/use-issue-timeline.ts
@@ -6,6 +6,7 @@ import {
useQueryClient,
useMutationState,
} from "@tanstack/react-query";
+import type { QueryClient } from "@tanstack/react-query";
import type {
Comment,
TimelineEntry,
@@ -55,6 +56,7 @@ function commentToTimelineEntry(c: Comment): TimelineEntry {
parent_id: c.parent_id,
created_at: c.created_at,
updated_at: c.updated_at,
+ revision: c.revision,
comment_type: c.type,
reactions: c.reactions ?? [],
attachments: c.attachments ?? [],
@@ -65,6 +67,42 @@ function commentToTimelineEntry(c: Comment): TimelineEntry {
};
}
+function acceptsCommentRevision(
+ current: TimelineEntry,
+ incoming: Comment,
+): boolean {
+ return (
+ current.revision === undefined ||
+ (incoming.revision !== undefined && incoming.revision >= current.revision)
+ );
+}
+
+function applyCommentSnapshot(
+ qc: QueryClient,
+ issueId: string,
+ comment: Comment,
+) {
+ let missingRevision = false;
+ qc.setQueryData<TLCache>(issueKeys.timeline(issueId), (old) =>
+ old?.map((entry) => {
+ if (entry.id !== comment.id) return entry;
+ if (entry.revision !== undefined && comment.revision === undefined) {
+ missingRevision = true;
+ return entry;
+ }
+ return acceptsCommentRevision(entry, comment)
+ ? commentToTimelineEntry(comment)
+ : entry;
+ }),
+ );
+ if (missingRevision) {
+ // During a rolling deployment, an old server may emit an unversioned
+ // snapshot after this cache has already observed a versioned one. Never
+ // overwrite the ordered value; refetch from the authoritative API instead.
+ qc.invalidateQueries({ queryKey: issueKeys.timeline(issueId) });
+ }
+}
+
export function useIssueTimeline(issueId: string, userId?: string) {
const { t } = useT("issues");
const qc = useQueryClient();
@@ -118,11 +156,7 @@ export function useIssueTimeline(issueId: string, userId?: string) {
(payload: unknown) => {
const { comment } = payload as CommentUpdatedPayload;
if (comment.issue_id !== issueId) return;
- qc.setQueryData<TLCache>(issueKeys.timeline(issueId), (old) =>
- old?.map((e) =>
- e.id === comment.id ? commentToTimelineEntry(comment) : e,
- ),
- );
+ applyCommentSnapshot(qc, issueId, comment);
},
[qc, issueId],
),
@@ -140,11 +174,7 @@ export function useIssueTimeline(issueId: string, userId?: string) {
(payload: unknown) => {
const { comment } = payload as CommentResolvedPayload;
if (comment.issue_id !== issueId) return;
- qc.setQueryData<TLCache>(issueKeys.timeline(issueId), (old) =>
- old?.map((e) =>
- e.id === comment.id ? commentToTimelineEntry(comment) : e,
- ),
- );
+ applyCommentSnapshot(qc, issueId, comment);
},
[qc, issueId],
),
@@ -156,11 +186,7 @@ export function useIssueTimeline(issueId: string, userId?: string) {
(payload: unknown) => {
const { comment } = payload as CommentUnresolvedPayload;
if (comment.issue_id !== issueId) return;
- qc.setQueryData<TLCache>(issueKeys.timeline(issueId), (old) =>
- old?.map((e) =>
- e.id === comment.id ? commentToTimelineEntry(comment) : e,
- ),
- );
+ applyCommentSnapshot(qc, issueId, comment);
},
[qc, issueId],
),
@@ -220,16 +246,33 @@ export function useIssueTimeline(issueId: string, userId?: string) {
"reaction:added",
useCallback(
(payload: unknown) => {
- const { reaction, issue_id } = payload as ReactionAddedPayload;
+ const { reaction, issue_id, comment_revision } = payload as ReactionAddedPayload;
if (issue_id !== issueId) return;
+ let missingRevision = false;
qc.setQueryData<TLCache>(issueKeys.timeline(issueId), (old) =>
old?.map((e) => {
if (e.id !== reaction.comment_id) return e;
+ if (comment_revision === undefined && e.revision !== undefined) {
+ missingRevision = true;
+ return e;
+ }
+ if (
+ comment_revision !== undefined &&
+ e.revision !== undefined &&
+ comment_revision < e.revision
+ ) return e;
const existing = e.reactions ?? [];
if (existing.some((r) => r.id === reaction.id)) return e;
- return { ...e, reactions: [...existing, reaction] };
+ return {
+ ...e,
+ revision: comment_revision ?? e.revision,
+ reactions: [...existing, reaction],
+ };
}),
);
+ if (missingRevision) {
+ qc.invalidateQueries({ queryKey: issueKeys.timeline(issueId) });
+ }
},
[qc, issueId],
),
@@ -241,11 +284,22 @@ export function useIssueTimeline(issueId: string, userId?: string) {
(payload: unknown) => {
const p = payload as ReactionRemovedPayload;
if (p.issue_id !== issueId) return;
+ let missingRevision = false;
qc.setQueryData<TLCache>(issueKeys.timeline(issueId), (old) =>
old?.map((e) => {
if (e.id !== p.comment_id) return e;
+ if (p.comment_revision === undefined && e.revision !== undefined) {
+ missingRevision = true;
+ return e;
+ }
+ if (
+ p.comment_revision !== undefined &&
+ e.revision !== undefined &&
+ p.comment_revision < e.revision
+ ) return e;
return {
...e,
+ revision: p.comment_revision ?? e.revision,
reactions: (e.reactions ?? []).filter(
(r) =>
!(
@@ -257,6 +311,9 @@ export function useIssueTimeline(issueId: string, userId?: string) {
};
}),
);
+ if (missingRevision) {
+ qc.invalidateQueries({ queryKey: issueKeys.timeline(issueId) });
+ }
},
[qc, issueId],
),
@@ -346,19 +403,17 @@ export function useIssueTimeline(issueId: string, userId?: string) {
);
const editComment = useCallback(
- async (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[]) => {
- try {
- const comment = await updateComment({ commentId, content, attachmentIds, suppressAgentIds });
- warnUnhandledTriggers(comment?.trigger_outcomes, comment?.content);
- } catch (err) {
- toast.error(
- err instanceof Error && err.message
- ? err.message
- : t(($) => $.comment.update_failed),
- );
- }
+ async (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[], contentBase?: string) => {
+ const comment = await updateComment({
+ commentId,
+ content,
+ attachmentIds,
+ suppressAgentIds,
+ contentBase,
+ });
+ warnUnhandledTriggers(comment?.trigger_outcomes, comment?.content);
},
- [updateComment, warnUnhandledTriggers, t],
+ [updateComment, warnUnhandledTriggers],
);
const deleteComment = useCallback(
diff --git a/packages/views/issues/surface/actions-context.tsx b/packages/views/issues/surface/actions-context.tsx
index 928d6916e7..c5318a1031 100644
--- a/packages/views/issues/surface/actions-context.tsx
+++ b/packages/views/issues/surface/actions-context.tsx
@@ -1,12 +1,12 @@
"use client";
import { createContext, useContext, type ReactNode } from "react";
-import type { UpdateIssueRequest } from "@multica/core/types";
+import type { Issue, UpdateIssueRequest } from "@multica/core/types";
import type { IssueCreateDefaults } from "./types";
export type IssueSurfaceMutationOptions = {
errorMessage?: string;
- onSuccess?: () => void;
+ onSuccess?: (issue: Issue) => void;
onError?: (err: unknown) => void;
onSettled?: () => void;
};
diff --git a/packages/views/issues/surface/use-issue-surface-actions.ts b/packages/views/issues/surface/use-issue-surface-actions.ts
index 194c286601..794b6e10a1 100644
--- a/packages/views/issues/surface/use-issue-surface-actions.ts
+++ b/packages/views/issues/surface/use-issue-surface-actions.ts
@@ -8,6 +8,7 @@ import {
useBatchUpdateIssues,
useUpdateIssue,
} from "@multica/core/issues/mutations";
+import { errorCode } from "@multica/core/api";
import { useModalStore } from "@multica/core/modals";
import {
type IssueSurfaceActions,
@@ -45,6 +46,7 @@ export function useIssueSurfaceActions({
createDefaults: IssueCreateDefaults;
}): IssueSurfaceActionController {
const { t } = useT("projects");
+ const { t: tIssues } = useT("issues");
const updateIssueMutation = useUpdateIssue();
const batchUpdateMutation = useBatchUpdateIssues();
const batchDeleteMutation = useBatchDeleteIssues();
@@ -58,10 +60,12 @@ export function useIssueSurfaceActions({
updateIssueMutation.mutate(
{ id: issueId, ...updates },
{
- onSuccess: () => options?.onSuccess?.(),
+ onSuccess: (issue) => options?.onSuccess?.(issue),
onError: (err) => {
toast.error(
- err instanceof Error && err.message
+ errorCode(err) === "revision_conflict"
+ ? tIssues(($) => $.revision.conflict)
+ : err instanceof Error && err.message
? err.message
: (options?.errorMessage ??
t(($) => $.detail.toast_move_issue_failed)),
@@ -72,7 +76,7 @@ export function useIssueSurfaceActions({
},
);
},
- [t, updateIssueMutation],
+ [t, tIssues, updateIssueMutation],
);
const moveIssue = useCallback(
@@ -91,7 +95,9 @@ export function useIssueSurfaceActions({
{
onError: (err) => {
toast.error(
- err instanceof Error && err.message
+ errorCode(err) === "revision_conflict"
+ ? tIssues(($) => $.revision.conflict)
+ : err instanceof Error && err.message
? err.message
: t(($) => $.detail.toast_move_issue_failed),
);
@@ -100,7 +106,7 @@ export function useIssueSurfaceActions({
},
);
},
- [t, updateIssueMutation],
+ [t, tIssues, updateIssueMutation],
);
const openCreateIssue = useCallback(
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 5ceb0bf7c4..6736cad7a7 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -4,6 +4,16 @@
"hint": "Issues are hidden until it loads, because a status filter can't be applied without it.",
"retry": "Try again"
},
+ "revision": {
+ "conflict": "The issue or comment changed. The latest version was refreshed; compare it before saving again.",
+ "compare_title": "The title was changed concurrently. Compare both versions.",
+ "compare_description": "The description was changed concurrently. Compare both versions.",
+ "compare_comment": "The comment was changed concurrently. Compare both versions.",
+ "server_version": "Latest server version",
+ "local_version": "Your local version",
+ "keep_local": "Use local version and save",
+ "save_again": "After reviewing both versions, click Save again to use your local version."
+ },
"page": {
"breadcrumb_title": "Issues",
"breadcrumb_workspace_fallback": "Workspace",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index e208fab2cc..942ebb2676 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -4,6 +4,16 @@
"hint": "これがないとステータスの絞り込みを適用できないため、イシューは表示されません。",
"retry": "再試行"
},
+ "revision": {
+ "conflict": "タスクまたはコメントが変更されました。最新版に更新したので、比較してからもう一度保存してください。",
+ "compare_title": "タイトルが同時に変更されました。両方の内容を比較してください。",
+ "compare_description": "説明が同時に変更されました。両方の内容を比較してください。",
+ "compare_comment": "コメントが同時に変更されました。両方の内容を比較してください。",
+ "server_version": "サーバー上の最新版",
+ "local_version": "ローカル版",
+ "keep_local": "ローカル版を使用して保存",
+ "save_again": "両方の内容を確認した後、もう一度「保存」をクリックするとローカル版を使用できます。"
+ },
"page": {
"breadcrumb_title": "タスク",
"breadcrumb_workspace_fallback": "ワークスペース",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 7babc3647f..e219af3bc9 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -4,6 +4,16 @@
"hint": "이것 없이는 상태 필터를 적용할 수 없어 이슈를 표시하지 않습니다.",
"retry": "다시 시도"
},
+ "revision": {
+ "conflict": "태스크 또는 댓글이 변경되었습니다. 최신 버전으로 새로 고쳤으니 비교한 후 다시 저장하세요.",
+ "compare_title": "제목이 동시에 변경되었습니다. 두 버전을 비교하세요.",
+ "compare_description": "설명이 동시에 변경되었습니다. 두 버전을 비교하세요.",
+ "compare_comment": "댓글이 동시에 변경되었습니다. 두 버전을 비교하세요.",
+ "server_version": "서버의 최신 버전",
+ "local_version": "내 로컬 버전",
+ "keep_local": "로컬 버전으로 저장",
+ "save_again": "두 버전을 확인한 후 저장을 다시 클릭하면 로컬 버전을 사용할 수 있습니다."
+ },
"page": {
"breadcrumb_title": "태스크",
"breadcrumb_workspace_fallback": "워크스페이스",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 4f1a77aba6..8a8cd5f10b 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -4,6 +4,16 @@
"hint": "没有它就无法应用状态筛选,因此暂时不显示议题。",
"retry": "重试"
},
+ "revision": {
+ "conflict": "任务或评论已发生变化。已刷新到最新版本,请比较后重新保存。",
+ "compare_title": "标题存在并发修改,请比较两个版本。",
+ "compare_description": "描述存在并发修改,请比较两个版本。",
+ "compare_comment": "评论存在并发修改,请比较两个版本。",
+ "server_version": "服务端最新版本",
+ "local_version": "你的本地版本",
+ "keep_local": "采用本地版本并保存",
+ "save_again": "确认后再次点击“保存”即可采用本地版本。"
+ },
"page": {
"breadcrumb_title": "任务",
"breadcrumb_workspace_fallback": "工作区",
diff --git a/packages/views/modals/add-child-issue.tsx b/packages/views/modals/add-child-issue.tsx
index 9a2ee736de..3ba3561919 100644
--- a/packages/views/modals/add-child-issue.tsx
+++ b/packages/views/modals/add-child-issue.tsx
@@ -49,8 +49,17 @@ export function AddChildIssueModal({
excludeIds={excludeIds}
onSelect={(selected) => {
updateIssue.mutate(
- { id: selected.id, parent_issue_id: issueId },
{
+ id: selected.id,
+ parent_issue_id: issueId,
+ },
+ {
+ onSuccess: () =>
+ toast.success(
+ t(($) => $.add_child.toast_success, {
+ identifier: selected.identifier,
+ }),
+ ),
onError: (err) =>
toast.error(
err instanceof Error && err.message
@@ -59,7 +68,6 @@ export function AddChildIssueModal({
),
},
);
- toast.success(t(($) => $.add_child.toast_success, { identifier: selected.identifier }));
}}
/>
);
diff --git a/packages/views/modals/issue-parent-modals.test.tsx b/packages/views/modals/issue-parent-modals.test.tsx
new file mode 100644
index 0000000000..c5a6ffadf4
--- /dev/null
+++ b/packages/views/modals/issue-parent-modals.test.tsx
@@ -0,0 +1,121 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { AddChildIssueModal } from "./add-child-issue";
+import { SetParentIssueModal } from "./set-parent-issue";
+
+const mocks = vi.hoisted(() => ({
+ mutate: vi.fn(),
+ toast: { success: vi.fn(), error: vi.fn() },
+}));
+
+vi.mock("sonner", () => ({ toast: mocks.toast }));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@multica/core/issues/mutations", () => ({
+ useUpdateIssue: () => ({ mutate: mocks.mutate }),
+}));
+vi.mock("@multica/core/issues/queries", () => ({
+ issueDetailOptions: (_wsId: string, issueId: string) => ({
+ queryKey: ["issues", "detail", issueId],
+ }),
+ childIssuesOptions: (_wsId: string, issueId: string) => ({
+ queryKey: ["issues", "children", issueId],
+ }),
+}));
+vi.mock("@tanstack/react-query", () => ({
+ useQuery: ({ queryKey }: { queryKey: string[] }) =>
+ queryKey[1] === "detail"
+ ? { data: { id: queryKey[2], revision: 7, parent_issue_id: null } }
+ : { data: [] },
+}));
+vi.mock("./issue-picker-modal", () => ({
+ IssuePickerModal: ({
+ onSelect,
+ }: {
+ onSelect: (issue: { id: string; identifier: string; revision: number }) => void;
+ }) => (
+ <button
+ type="button"
+ onClick={() =>
+ onSelect({ id: "selected-1", identifier: "MUL-2", revision: 5 })
+ }
+ >
+ Select issue
+ </button>
+ ),
+}));
+vi.mock("../i18n", () => ({
+ useT: () => ({
+ t: (
+ selector: (labels: Record<string, Record<string, string>>) => string,
+ vars?: Record<string, unknown>,
+ ) =>
+ selector({
+ add_child: {
+ title: "Add child",
+ description: "Choose child",
+ toast_success: `Added ${String(vars?.identifier ?? "")}`,
+ toast_failed: "Add failed",
+ },
+ set_parent: {
+ title: "Set parent",
+ description: "Choose parent",
+ toast_success: `Set ${String(vars?.identifier ?? "")}`,
+ toast_failed: "Set failed",
+ },
+ }),
+ }),
+}));
+
+describe.each([
+ {
+ name: "AddChildIssueModal",
+ Component: AddChildIssueModal,
+ expectedMutation: {
+ id: "selected-1",
+ parent_issue_id: "issue-1",
+ },
+ },
+ {
+ name: "SetParentIssueModal",
+ Component: SetParentIssueModal,
+ expectedMutation: {
+ id: "issue-1",
+ parent_issue_id: "selected-1",
+ },
+ },
+])("$name", ({ Component, expectedMutation }) => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("shows success only after the mutation succeeds", () => {
+ mocks.mutate.mockImplementation((_variables, callbacks) => {
+ callbacks.onSuccess();
+ });
+
+ render(<Component onClose={vi.fn()} data={{ issueId: "issue-1" }} />);
+ fireEvent.click(screen.getByRole("button", { name: "Select issue" }));
+
+ expect(mocks.mutate).toHaveBeenCalledWith(
+ expectedMutation,
+ expect.objectContaining({
+ onSuccess: expect.any(Function),
+ onError: expect.any(Function),
+ }),
+ );
+ expect(mocks.toast.success).toHaveBeenCalledTimes(1);
+ expect(mocks.toast.error).not.toHaveBeenCalled();
+ });
+
+ it("does not report success when the mutation fails", () => {
+ mocks.mutate.mockImplementation((_variables, callbacks) => {
+ callbacks.onError(new Error("revision conflict"));
+ });
+
+ render(<Component onClose={vi.fn()} data={{ issueId: "issue-1" }} />);
+ fireEvent.click(screen.getByRole("button", { name: "Select issue" }));
+
+ expect(mocks.toast.success).not.toHaveBeenCalled();
+ expect(mocks.toast.error).toHaveBeenCalledWith("revision conflict");
+ });
+});
diff --git a/packages/views/modals/run-confirm.tsx b/packages/views/modals/run-confirm.tsx
index aafd2498d1..cc8a555454 100644
--- a/packages/views/modals/run-confirm.tsx
+++ b/packages/views/modals/run-confirm.tsx
@@ -16,6 +16,7 @@ import { Textarea } from "@multica/ui/components/ui/textarea";
import { Spinner } from "@multica/ui/components/ui/spinner";
import type { IssueAssigneeType, UpdateIssueRequest } from "@multica/core/types";
import { useUpdateIssue, useBatchUpdateIssues } from "@multica/core/issues/mutations";
+import { errorCode } from "@multica/core/api";
import { useActorName } from "@multica/core/workspace/hooks";
import { useWorkspaceId } from "@multica/core/hooks";
import { agentListOptions, squadListOptions } from "@multica/core/workspace/queries";
@@ -54,6 +55,7 @@ interface RunConfirmData {
assigneeType?: IssueAssigneeType;
assigneeId?: string;
assigneeName?: string;
+ issueRevision?: number;
}
/**
@@ -81,6 +83,7 @@ export function RunConfirmModal({
data: Record<string, unknown> | null;
}) {
const { t } = useT("modals");
+ const { t: tIssues } = useT("issues");
const { getActorName } = useActorName();
const sendShortcut = useShortcut("send");
const d = (data ?? {}) as RunConfirmData;
@@ -157,13 +160,22 @@ export function RunConfirmModal({
// no result toast to add here. Whether a run started is the server's
// existing decision at write time, not something this dialog reports.
if (issueIds.length === 1) {
- await updateIssue.mutateAsync({ id: issueIds[0]!, ...payload });
+ await updateIssue.mutateAsync({
+ id: issueIds[0]!,
+ ...payload,
+ });
} else {
await batchUpdate.mutateAsync({ ids: issueIds, updates: payload });
}
onClose();
} catch (err) {
- toast.error(err instanceof Error && err.message ? err.message : t(($) => $.run_confirm.toast_failed));
+ toast.error(
+ errorCode(err) === "revision_conflict"
+ ? tIssues(($) => $.revision.conflict)
+ : err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.run_confirm.toast_failed),
+ );
setPendingAction(null);
}
};
diff --git a/packages/views/modals/set-parent-issue.tsx b/packages/views/modals/set-parent-issue.tsx
index d6a392cee7..873606c551 100644
--- a/packages/views/modals/set-parent-issue.tsx
+++ b/packages/views/modals/set-parent-issue.tsx
@@ -3,7 +3,9 @@
import { useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { useWorkspaceId } from "@multica/core/hooks";
-import { childIssuesOptions } from "@multica/core/issues/queries";
+import {
+ childIssuesOptions,
+} from "@multica/core/issues/queries";
import { useUpdateIssue } from "@multica/core/issues/mutations";
import { IssuePickerModal } from "./issue-picker-modal";
import { useT } from "../i18n";
@@ -38,8 +40,17 @@ export function SetParentIssueModal({
excludeIds={excludeIds}
onSelect={(selected) => {
updateIssue.mutate(
- { id: issueId, parent_issue_id: selected.id },
{
+ id: issueId,
+ parent_issue_id: selected.id,
+ },
+ {
+ onSuccess: () =>
+ toast.success(
+ t(($) => $.set_parent.toast_success, {
+ identifier: selected.identifier,
+ }),
+ ),
onError: (err) =>
toast.error(
err instanceof Error && err.message
@@ -48,7 +59,6 @@ export function SetParentIssueModal({
),
},
);
- toast.success(t(($) => $.set_parent.toast_success, { identifier: selected.identifier }));
}}
/>
);
diff --git a/server/internal/handler/activity.go b/server/internal/handler/activity.go
index 71f623b669..08faa165e5 100644
--- a/server/internal/handler/activity.go
+++ b/server/internal/handler/activity.go
@@ -28,6 +28,7 @@ type TimelineEntry struct {
Content *string `json:"content,omitempty"`
ParentID *string `json:"parent_id,omitempty"`
UpdatedAt *string `json:"updated_at,omitempty"`
+ Revision int64 `json:"revision,omitempty"`
CommentType *string `json:"comment_type,omitempty"`
// Set only on comments produced by a quick action run. Unforgeable: there
// is no request field for it on the generic comment endpoint.
@@ -288,6 +289,7 @@ func (h *Handler) commentsToEntries(r *http.Request, comments []db.Comment) []Ti
ParentID: uuidToPtr(c.ParentID),
CreatedAt: timestampToString(c.CreatedAt),
UpdatedAt: &updatedAt,
+ Revision: c.Revision,
Reactions: reactions[cid],
Attachments: attachments[cid],
ResolvedAt: timestampToPtr(c.ResolvedAt),
diff --git a/server/internal/handler/activity_test.go b/server/internal/handler/activity_test.go
index e2556fb9df..8b6c2bc911 100644
--- a/server/internal/handler/activity_test.go
+++ b/server/internal/handler/activity_test.go
@@ -112,6 +112,28 @@ func TestListTimeline_ReturnsAllEntriesAscending(t *testing.T) {
}
}
+func TestListTimeline_CommentIncludesRevision(t *testing.T) {
+ issueID := createIssueForTimeline(t, "Comment revision projection")
+ commentIDs, _ := seedTimelineEntries(t, issueID, 1, 0)
+ if _, err := testPool.Exec(context.Background(), `UPDATE comment SET revision = 7 WHERE id = $1`, commentIDs[0]); err != nil {
+ t.Fatalf("set comment revision: %v", err)
+ }
+
+ entries, status := fetchTimeline(t, issueID)
+ if status != http.StatusOK {
+ t.Fatalf("status = %d, want 200", status)
+ }
+ for _, entry := range entries {
+ if entry.ID == commentIDs[0] {
+ if entry.Revision != 7 {
+ t.Fatalf("comment revision = %d, want 7", entry.Revision)
+ }
+ return
+ }
+ }
+ t.Fatalf("comment %s missing from timeline", commentIDs[0])
+}
+
func TestListTimeline_MergesCommentsAndActivities(t *testing.T) {
issueID := createIssueForTimeline(t, "Merged entries test")
seedTimelineEntries(t, issueID, 3, 2)
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index d781494b32..76ade30f9d 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -14,6 +14,7 @@ import (
"unicode"
"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"
"github.com/multica-ai/multica/server/internal/service"
@@ -32,6 +33,8 @@ type CommentResponse struct {
ParentID *string `json:"parent_id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
+ Revision int64 `json:"revision"`
+ IssueRevision int64 `json:"issue_revision,omitempty"`
ResolvedAt *string `json:"resolved_at"`
ResolvedByType *string `json:"resolved_by_type"`
ResolvedByID *string `json:"resolved_by_id"`
@@ -104,6 +107,7 @@ func commentToResponse(c db.Comment, reactions []ReactionResponse, attachments [
ParentID: uuidToPtr(c.ParentID),
CreatedAt: timestampToString(c.CreatedAt),
UpdatedAt: timestampToString(c.UpdatedAt),
+ Revision: c.Revision,
ResolvedAt: timestampToPtr(c.ResolvedAt),
ResolvedByType: textToPtr(c.ResolvedByType),
ResolvedByID: uuidToPtr(c.ResolvedByID),
@@ -797,6 +801,7 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
ResolvedByID: r.ResolvedByID,
SourceTaskID: r.SourceTaskID,
QuickActionID: r.QuickActionID,
+ Revision: r.Revision,
}
if !r.ParentID.Valid {
root := c
@@ -890,6 +895,7 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
ResolvedByID: r.ResolvedByID,
SourceTaskID: r.SourceTaskID,
QuickActionID: r.QuickActionID,
+ Revision: r.Revision,
}
if !r.ParentID.Valid {
root := c
@@ -977,6 +983,7 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
ResolvedByID: r.ResolvedByID,
SourceTaskID: r.SourceTaskID,
QuickActionID: r.QuickActionID,
+ Revision: r.Revision,
})
}
@@ -1035,7 +1042,7 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
Content: r.Content, Type: r.Type, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt,
ParentID: r.ParentID, WorkspaceID: r.WorkspaceID, ResolvedAt: r.ResolvedAt,
ResolvedByType: r.ResolvedByType, ResolvedByID: r.ResolvedByID,
- SourceTaskID: r.SourceTaskID, QuickActionID: r.QuickActionID,
+ SourceTaskID: r.SourceTaskID, QuickActionID: r.QuickActionID, Revision: r.Revision,
}
stats[uuidToString(r.ID)] = rootStat{ReplyCount: int(r.ReplyCount), LastActivityAt: r.LastActivityAt}
}
@@ -1065,7 +1072,7 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
Content: r.Content, Type: r.Type, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt,
ParentID: r.ParentID, WorkspaceID: r.WorkspaceID, ResolvedAt: r.ResolvedAt,
ResolvedByType: r.ResolvedByType, ResolvedByID: r.ResolvedByID,
- SourceTaskID: r.SourceTaskID, QuickActionID: r.QuickActionID,
+ SourceTaskID: r.SourceTaskID, QuickActionID: r.QuickActionID, Revision: r.Revision,
}
stats[uuidToString(r.ID)] = rootStat{ReplyCount: int(r.ReplyCount), LastActivityAt: r.LastActivityAt}
}
@@ -1861,7 +1868,7 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
}
}
- comment, err := h.Queries.CreateComment(r.Context(), db.CreateCommentParams{
+ created, err := h.Queries.CreateComment(r.Context(), db.CreateCommentParams{
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
AuthorType: authorType,
@@ -1876,6 +1883,7 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to create comment: "+err.Error())
return
}
+ comment := created.Comment()
// Link uploaded attachments to this comment.
if len(attachmentIDs) > 0 {
@@ -1885,6 +1893,7 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
// Fetch linked attachments so the response includes them.
groupedAtt := h.groupAttachments(r, []pgtype.UUID{comment.ID})
resp := commentToResponse(comment, nil, groupedAtt[uuidToString(comment.ID)])
+ resp.IssueRevision = created.IssueRevision
slog.Info("comment created", append(logger.RequestAttrs(r), "comment_id", uuidToString(comment.ID), "issue_id", issueID)...)
h.publish(protocol.EventCommentCreated, uuidToString(issue.WorkspaceID), authorType, authorID, map[string]any{
"comment": resp,
@@ -1892,6 +1901,7 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
"issue_assignee_type": textToPtr(issue.AssigneeType),
"issue_assignee_id": uuidToPtr(issue.AssigneeID),
"issue_status": issue.Status,
+ "issue_revision": created.IssueRevision,
})
// A reply in a resolved thread re-opens it. Done after CreateComment commits
@@ -3224,8 +3234,10 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
var req struct {
Content string `json:"content"`
+ ContentBase *string `json:"content_base,omitempty"`
AttachmentIDs *[]string `json:"attachment_ids"`
SuppressAgentIDs []string `json:"suppress_agent_ids"`
+ ExpectedRevision *int64 `json:"expected_revision,omitempty"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
@@ -3235,10 +3247,25 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
// rejects before the empty check, so an edit that introduces such a byte
// can't 500 (GH #5388).
req.Content = sanitizeNullBytes(req.Content)
+ if req.ContentBase != nil {
+ sanitized := sanitizeNullBytes(*req.ContentBase)
+ req.ContentBase = &sanitized
+ }
if req.Content == "" {
writeError(w, http.StatusBadRequest, "content is required")
return
}
+ if req.ExpectedRevision != nil {
+ if *req.ExpectedRevision < 1 {
+ writeError(w, http.StatusBadRequest, "expected_revision must be a positive integer")
+ return
+ }
+ if existing.Revision != *req.ExpectedRevision {
+ writeRevisionConflict(w, "comment", existing.ID, *req.ExpectedRevision, existing.Revision)
+ return
+ }
+ }
+ strictContentEdit := req.ContentBase != nil || req.ExpectedRevision != nil
var attachmentIDs []pgtype.UUID
replaceAttachments := req.AttachmentIDs != nil
@@ -3287,26 +3314,90 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
} else {
sourceTaskID = pgtype.UUID{}
}
- cancelled, err = h.TaskService.CancelTasksByTriggerComment(r.Context(), existing.ID)
- if err != nil {
- slog.Warn("cancel tasks for edited comment failed", "comment_id", uuidToString(existing.ID), "error", err)
- writeError(w, http.StatusInternalServerError, "failed to prepare comment edit")
- return
+ // Legacy clients keep the existing cancel-before-update behavior. Strict
+ // revision writes defer cancellation until the conditional UPDATE wins,
+ // so a race that returns 409 cannot mutate the task queue.
+ if !strictContentEdit {
+ cancelled, err = h.TaskService.CancelTasksByTriggerComment(r.Context(), existing.ID)
+ if err != nil {
+ slog.Warn("cancel tasks for edited comment failed", "comment_id", uuidToString(existing.ID), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to prepare comment edit")
+ return
+ }
}
}
- comment, err := h.Queries.UpdateComment(r.Context(), db.UpdateCommentParams{
+ updateParams := db.UpdateCommentParams{
ID: commentUUID,
Content: req.Content,
SourceTaskID: sourceTaskID,
- })
+ }
+ if req.ContentBase != nil {
+ updateParams.ContentBase = pgtype.Text{String: *req.ContentBase, Valid: true}
+ }
+ if req.ExpectedRevision != nil {
+ updateParams.ExpectedRevision = pgtype.Int8{Int64: *req.ExpectedRevision, Valid: true}
+ }
+ var comment db.Comment
+ transactionalEdit := replaceAttachments || (oldContent != req.Content && strictContentEdit)
+ if transactionalEdit {
+ // Strict body edits, attachment-set edits, and cancellation of tasks built
+ // from the old body are one database outcome. UpdateComment takes the row
+ // lock before the attachment replacement, so two modern editors cannot
+ // interleave their CAS check and attachment selection. A body + attachment
+ // edit is one visible mutation and therefore bumps revision exactly once.
+ tx, beginErr := h.TxStarter.Begin(r.Context())
+ if beginErr != nil {
+ writeError(w, http.StatusInternalServerError, "failed to prepare comment edit")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+ comment, err = qtx.UpdateComment(r.Context(), updateParams)
+ if err == nil && oldContent != req.Content && strictContentEdit {
+ cancelled, err = qtx.CancelAgentTasksByTriggerComment(r.Context(), existing.ID)
+ }
+ if err == nil && replaceAttachments {
+ var changed int64
+ changed, err = qtx.ReplaceCommentAttachments(r.Context(), db.ReplaceCommentAttachmentsParams{
+ CommentID: comment.ID,
+ IssueID: existing.IssueID,
+ AttachmentIds: attachmentIDs,
+ })
+ if err == nil && changed > 0 && oldContent == req.Content {
+ comment, err = qtx.BumpCommentRevision(r.Context(), db.BumpCommentRevisionParams{
+ ID: comment.ID,
+ WorkspaceID: existing.WorkspaceID,
+ })
+ }
+ }
+ if err == nil {
+ err = tx.Commit(r.Context())
+ }
+ if err == nil {
+ h.TaskService.BroadcastCancelledTasks(r.Context(), uuidToString(existing.WorkspaceID), cancelled)
+ }
+ } else {
+ comment, err = h.Queries.UpdateComment(r.Context(), updateParams)
+ }
if err != nil {
slog.Warn("update comment failed", append(logger.RequestAttrs(r), "error", err, "comment_id", commentId)...)
- if triggerIssue != nil {
+ if triggerIssue != nil && !strictContentEdit {
// Cancellation committed but the edit did not. Restore the complete
// original batch, including the still-valid unchanged comment.
h.retriggerCancelledTaskSurvivors(r.Context(), *triggerIssue, cancelled, pgtype.UUID{})
}
+ if errors.Is(err, pgx.ErrNoRows) && strictContentEdit {
+ current, reloadErr := h.Queries.GetCommentInWorkspace(r.Context(), db.GetCommentInWorkspaceParams{ID: commentUUID, WorkspaceID: wsUUID})
+ if reloadErr == nil {
+ if req.ExpectedRevision != nil {
+ writeRevisionConflict(w, "comment", current.ID, *req.ExpectedRevision, current.Revision)
+ } else {
+ writeEditConflict(w, "comment", current.ID)
+ }
+ return
+ }
+ }
writeError(w, http.StatusInternalServerError, "failed to update comment")
return
}
@@ -3335,25 +3426,6 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
return h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), delegationAuthority, suppressAgentIDs)
}
- // Replace the comment attachment set when a modern client sends
- // attachment_ids. Older clients omit the field; in that case preserve the
- // existing attachment links rather than unlinking everything.
- if replaceAttachments {
- if err := h.Queries.ReplaceCommentAttachments(r.Context(), db.ReplaceCommentAttachmentsParams{
- CommentID: comment.ID,
- IssueID: existing.IssueID,
- AttachmentIds: attachmentIDs,
- }); err != nil {
- slog.Error("failed to replace comment attachments", "error", err)
- // UpdateComment already committed the new body. Even though attachment
- // replacement failed, repair task routing for that persisted edit so a
- // dispatched run cannot permanently keep the old comment version.
- retriggerEditedComment()
- writeError(w, http.StatusInternalServerError, "failed to update attachments")
- return
- }
- }
-
// Fetch reactions and attachments for the updated comment.
grouped := h.groupReactions(r, []pgtype.UUID{comment.ID})
groupedAtt := h.groupAttachments(r, []pgtype.UUID{comment.ID})
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index b6e1f4d31a..2d95a21003 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -18,6 +18,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/storage"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
)
// extContentTypes overrides http.DetectContentType for extensions it gets wrong.
@@ -570,7 +571,26 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
// S3 upload succeeded but DB record failed — still return the link
// so the file is usable. Log the error for investigation.
} else {
- writeJSON(w, http.StatusOK, h.attachmentToResponse(att, attachmentURLModeFromRequest(r)))
+ if att.IssueRevision > 0 && att.IssueID.Valid {
+ h.publish(protocol.EventIssueAttachmentsChanged, workspaceID, uploaderType, uploaderID, map[string]any{
+ "issue_id": uuidToString(att.IssueID),
+ "issue_revision": att.IssueRevision,
+ })
+ }
+ if att.CommentRevision > 0 && att.CommentID.Valid {
+ if comment, loadErr := h.Queries.GetCommentInWorkspace(r.Context(), db.GetCommentInWorkspaceParams{
+ ID: att.CommentID,
+ WorkspaceID: att.WorkspaceID,
+ }); loadErr == nil {
+ commentID := uuidToString(comment.ID)
+ reactions := h.groupReactions(r, []pgtype.UUID{comment.ID})
+ attachments := h.groupAttachments(r, []pgtype.UUID{comment.ID})
+ h.publish(protocol.EventCommentUpdated, workspaceID, uploaderType, uploaderID, map[string]any{
+ "comment": commentToResponse(comment, reactions[commentID], attachments[commentID]),
+ })
+ }
+ }
+ writeJSON(w, http.StatusOK, h.attachmentToResponse(att.Attachment(), attachmentURLModeFromRequest(r)))
return
}
@@ -1413,14 +1433,34 @@ func (h *Handler) DeleteAttachment(w http.ResponseWriter, r *http.Request) {
return
}
- if err := h.Queries.DeleteAttachment(r.Context(), db.DeleteAttachmentParams{
+ deleted, err := h.Queries.DeleteAttachment(r.Context(), db.DeleteAttachmentParams{
ID: att.ID,
WorkspaceID: att.WorkspaceID,
- }); err != nil {
+ })
+ if err != nil {
slog.Error("failed to delete attachment", "error", err)
writeError(w, http.StatusInternalServerError, "failed to delete attachment")
return
}
+ if deleted.Changed && att.IssueID.Valid {
+ h.publish(protocol.EventIssueAttachmentsChanged, workspaceID, "member", userID, map[string]any{
+ "issue_id": uuidToString(att.IssueID),
+ "issue_revision": deleted.IssueRevision,
+ })
+ }
+ if deleted.Changed && att.CommentID.Valid {
+ if comment, loadErr := h.Queries.GetCommentInWorkspace(r.Context(), db.GetCommentInWorkspaceParams{
+ ID: att.CommentID,
+ WorkspaceID: att.WorkspaceID,
+ }); loadErr == nil {
+ commentID := uuidToString(comment.ID)
+ reactions := h.groupReactions(r, []pgtype.UUID{comment.ID})
+ attachments := h.groupAttachments(r, []pgtype.UUID{comment.ID})
+ h.publish(protocol.EventCommentUpdated, workspaceID, "member", userID, map[string]any{
+ "comment": commentToResponse(comment, reactions[commentID], attachments[commentID]),
+ })
+ }
+ }
h.deleteS3Object(r.Context(), att.Url)
w.WriteHeader(http.StatusNoContent)
@@ -1430,16 +1470,16 @@ func (h *Handler) DeleteAttachment(w http.ResponseWriter, r *http.Request) {
// Attachment linking
// ---------------------------------------------------------------------------
-// linkAttachmentsByIssueIDs links the given attachment IDs to an issue.
-// Only updates attachments that have no issue_id yet.
-func (h *Handler) linkAttachmentsByIssueIDs(ctx context.Context, issueID, workspaceID pgtype.UUID, ids []pgtype.UUID) {
- if err := h.Queries.LinkAttachmentsToIssue(ctx, db.LinkAttachmentsToIssueParams{
- IssueID: issueID,
- WorkspaceID: workspaceID,
- Column3: ids,
- }); err != nil {
- slog.Error("failed to link attachments to issue", "error", err)
- }
+// linkAttachmentsByIssueIDs links unbound attachments to an issue. A caller
+// that did not already advance the issue revision can ask this visible change
+// to advance it exactly once.
+func (h *Handler) linkAttachmentsByIssueIDs(ctx context.Context, issueID, workspaceID pgtype.UUID, ids []pgtype.UUID, bumpRevision bool) (db.LinkAttachmentsToIssueRow, error) {
+ return h.Queries.LinkAttachmentsToIssue(ctx, db.LinkAttachmentsToIssueParams{
+ IssueID: issueID,
+ WorkspaceID: workspaceID,
+ AttachmentIds: ids,
+ BumpRevision: bumpRevision,
+ })
}
// linkAttachmentsByIDs links the given attachment IDs to a comment.
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 1f65994624..45dc5fecdd 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -487,6 +487,26 @@ func writeErrorCode(w http.ResponseWriter, status int, code, msg string) {
writeJSON(w, status, map[string]string{"error": msg, "code": code})
}
+func writeRevisionConflict(w http.ResponseWriter, resourceType string, resourceID pgtype.UUID, expected, actual int64) {
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": "resource changed since it was loaded",
+ "code": "revision_conflict",
+ "resource_type": resourceType,
+ "resource_id": uuidToString(resourceID),
+ "expected_revision": expected,
+ "actual_revision": actual,
+ })
+}
+
+func writeEditConflict(w http.ResponseWriter, resourceType string, resourceID pgtype.UUID) {
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": "resource field changed since it was loaded",
+ "code": "revision_conflict",
+ "resource_type": resourceType,
+ "resource_id": uuidToString(resourceID),
+ })
+}
+
// Thin wrappers around util functions.
//
// parseUUID is intentionally the panicking variant: any handler call site
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 3389880623..d0becf1fcd 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -62,6 +62,7 @@ type IssueResponse struct {
DueDate *string `json:"due_date"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
+ Revision int64 `json:"revision"`
// Metadata is the per-issue KV map (see issue_metadata.go). Always emitted
// (empty object when unset) so frontend code can `issue.metadata[key]`
// without nil-guarding the parent field.
@@ -151,12 +152,12 @@ var errIssueStatusArchivedRace = errors.New("issue status was archived while the
// 400 — but an archive can commit between that pre-flight check and the write.
// Re-checking here, under the lock, means the status is provably active at the
// moment the row is written. ArchiveIssueStatus holds the EXCLUSIVE side around
-// its in-use census, so the two orderings are both covered:
+// retirement, so the two orderings are both covered:
//
// - archive first: it commits, this re-resolve then fails and the write is
-// rejected, so no issue is stranded on an archived status;
-// - writer first: the census blocks until this transaction commits, then sees
-// the issue and refuses the archive with a conflict.
+// rejected, so no new assignment lands on an archived status;
+// - writer first: archive blocks until this transaction commits, then retires
+// the status from future use while the issue keeps its existing assignment.
//
// A built-in status is a no-op: it can never be archived (enforced by
// issue_status_system_not_archivable), so the common path takes no lock and
@@ -293,6 +294,7 @@ func issueToResponse(i db.Issue, issuePrefix string) IssueResponse {
DueDate: dateToPtr(i.DueDate),
CreatedAt: timestampToString(i.CreatedAt),
UpdatedAt: timestampToString(i.UpdatedAt),
+ Revision: i.Revision,
Metadata: parseIssueMetadata(i.Metadata),
Properties: parseIssueProperties(i.Properties),
}
@@ -328,6 +330,7 @@ func issueListRowToResponse(i db.ListIssuesRow, issuePrefix string) IssueRespons
DueDate: dateToPtr(i.DueDate),
CreatedAt: timestampToString(i.CreatedAt),
UpdatedAt: timestampToString(i.UpdatedAt),
+ Revision: i.Revision,
Metadata: parseIssueMetadata(i.Metadata),
Properties: parseIssueProperties(i.Properties),
}
@@ -395,6 +398,7 @@ func openIssueRowToResponse(i db.ListOpenIssuesRow, issuePrefix string) IssueRes
DueDate: dateToPtr(i.DueDate),
CreatedAt: timestampToString(i.CreatedAt),
UpdatedAt: timestampToString(i.UpdatedAt),
+ Revision: i.Revision,
Metadata: parseIssueMetadata(i.Metadata),
Properties: parseIssueProperties(i.Properties),
}
@@ -822,6 +826,7 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position,
i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id,
+ i.revision,
COUNT(*) OVER() AS total_count,
%s AS match_source,
%s AS matched_comment_content
@@ -909,6 +914,7 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {
&sr.issue.UpdatedAt,
&sr.issue.Number,
&sr.issue.ProjectID,
+ &sr.issue.Revision,
&sr.totalCount,
&sr.matchSource,
&sr.matchedCommentContent,
@@ -1435,7 +1441,8 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
query := fmt.Sprintf(`SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
+ i.revision
FROM issue i
WHERE %s
ORDER BY %s
@@ -1474,6 +1481,7 @@ LIMIT %s OFFSET %s`, whereSql, orderBy, limitRef, offsetRef)
&row.Metadata,
&row.Stage,
&row.Properties,
+ &row.Revision,
); err != nil {
slog.Warn("ListIssues scan failed", "error", err)
writeError(w, http.StatusInternalServerError, "failed to list issues")
@@ -2984,7 +2992,11 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
}
type UpdateIssueRequest struct {
- Title *string `json:"title"`
+ ExpectedRevision *int64 `json:"expected_revision,omitempty"`
+ Title *string `json:"title"`
+ // TitleBase is the title adopted by the editor before producing Title. It
+ // protects title edits without coupling them to unrelated issue mutations.
+ TitleBase *string `json:"title_base,omitempty"`
Description *string `json:"description"`
// DescriptionBase is the authoritative Markdown the editor had adopted
// before producing Description. It lets the server preserve channel media
@@ -3097,60 +3109,102 @@ func refreshUntouchedNullableIssueParams(params *db.UpdateIssueParams, current d
}
}
-func (h *Handler) updateIssueWithDescriptionMerge(ctx context.Context, workspaceID pgtype.UUID, params db.UpdateIssueParams, rawFields map[string]json.RawMessage, base *string, statusKey string) (db.Issue, db.Issue, error) {
+var errIssueFieldConflict = errors.New("issue text field conflict")
+
+func (h *Handler) updateIssueAtomically(ctx context.Context, workspaceID pgtype.UUID, params db.UpdateIssueParams, rawFields map[string]json.RawMessage, titleBase, descriptionBase *string, attachmentIDs []pgtype.UUID, statusKey string) (db.Issue, db.Issue, bool, error) {
if h.TxStarter == nil {
- return db.Issue{}, db.Issue{}, errors.New("issue description update requires transaction starter")
+ return db.Issue{}, db.Issue{}, false, errors.New("atomic issue update requires transaction starter")
}
tx, err := h.TxStarter.Begin(ctx)
if err != nil {
- return db.Issue{}, db.Issue{}, fmt.Errorf("begin issue description update: %w", err)
+ return db.Issue{}, db.Issue{}, false, fmt.Errorf("begin atomic issue update: %w", err)
}
defer tx.Rollback(ctx)
qtx := h.Queries.WithTx(tx)
// This path opens its own transaction, so it carries the archive-race guard
- // itself rather than going through runWithIssueStatusGuard. Taken before the
- // row lock below to keep the global catalog-then-row lock order. (MUL-6243)
+ // itself rather than going through runWithIssueStatusGuard. The catalog lock
+ // must precede both attachment and issue row locks everywhere. (MUL-6243)
if err := assertIssueStatusStillActive(ctx, qtx, workspaceID, statusKey); err != nil {
- return db.Issue{}, db.Issue{}, err
+ return db.Issue{}, db.Issue{}, false, err
+ }
+ if len(attachmentIDs) > 0 {
+ if _, err := qtx.LockAttachmentsForIssueLink(ctx, db.LockAttachmentsForIssueLinkParams{
+ WorkspaceID: workspaceID,
+ AttachmentIds: attachmentIDs,
+ }); err != nil {
+ return db.Issue{}, db.Issue{}, false, fmt.Errorf("lock issue attachments: %w", err)
+ }
}
current, err := qtx.LockIssueForDescriptionUpdate(ctx, db.LockIssueForDescriptionUpdateParams{
ID: params.ID,
WorkspaceID: workspaceID,
})
if err != nil {
- return db.Issue{}, db.Issue{}, fmt.Errorf("lock issue description: %w", err)
- }
- attachments, err := qtx.ListAttachmentsByIssue(ctx, db.ListAttachmentsByIssueParams{
- IssueID: current.ID,
- WorkspaceID: current.WorkspaceID,
- })
- if err != nil {
- return db.Issue{}, db.Issue{}, fmt.Errorf("list issue attachments for description merge: %w", err)
+ return db.Issue{}, db.Issue{}, false, fmt.Errorf("lock issue for update: %w", err)
}
- currentDescription := ""
- if current.Description.Valid {
- currentDescription = current.Description.String
+ if params.Title.Valid && titleBase != nil && current.Title != *titleBase && current.Title != params.Title.String {
+ return db.Issue{}, current, false, errIssueFieldConflict
}
- incomingDescription := ""
+
if params.Description.Valid {
- incomingDescription = params.Description.String
- }
- params.Description = pgtype.Text{
- String: mergeIssueChannelMediaDescription(currentDescription, incomingDescription, base, attachments),
- Valid: true,
+ attachments, listErr := qtx.ListAttachmentsByIssue(ctx, db.ListAttachmentsByIssueParams{
+ IssueID: current.ID,
+ WorkspaceID: current.WorkspaceID,
+ })
+ if listErr != nil {
+ return db.Issue{}, current, false, fmt.Errorf("list issue attachments for description merge: %w", listErr)
+ }
+ currentDescription := ""
+ if current.Description.Valid {
+ currentDescription = current.Description.String
+ }
+ incomingDescription := params.Description.String
+ if descriptionBase != nil && currentDescription != *descriptionBase && currentDescription != incomingDescription {
+ baseWithLateMedia := mergeIssueChannelMediaDescription(currentDescription, *descriptionBase, descriptionBase, attachments)
+ if currentDescription != baseWithLateMedia {
+ return db.Issue{}, current, false, errIssueFieldConflict
+ }
+ }
+ params.Description = pgtype.Text{
+ String: mergeIssueChannelMediaDescription(currentDescription, incomingDescription, descriptionBase, attachments),
+ Valid: true,
+ }
}
refreshUntouchedNullableIssueParams(&params, current, rawFields)
issue, err := qtx.UpdateIssue(ctx, params)
if err != nil {
- return db.Issue{}, db.Issue{}, fmt.Errorf("update locked issue description: %w", err)
+ return db.Issue{}, current, false, fmt.Errorf("update locked issue: %w", err)
+ }
+
+ attachmentsChanged := false
+ if len(attachmentIDs) > 0 {
+ linked, linkErr := qtx.LinkAttachmentsToIssue(ctx, db.LinkAttachmentsToIssueParams{
+ IssueID: issue.ID,
+ WorkspaceID: issue.WorkspaceID,
+ AttachmentIds: attachmentIDs,
+ BumpRevision: issue.Revision == current.Revision,
+ })
+ if linkErr != nil {
+ return db.Issue{}, current, false, fmt.Errorf("link issue attachments: %w", linkErr)
+ }
+ attachmentsChanged = linked.LinkedCount > 0
+ if linked.IssueRevision > 0 {
+ issue, err = qtx.GetIssueInWorkspace(ctx, db.GetIssueInWorkspaceParams{
+ ID: issue.ID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil {
+ return db.Issue{}, current, false, fmt.Errorf("reload issue after attachment link: %w", err)
+ }
+ }
}
if err := tx.Commit(ctx); err != nil {
- return db.Issue{}, db.Issue{}, fmt.Errorf("commit issue description update: %w", err)
+ return db.Issue{}, current, false, fmt.Errorf("commit atomic issue update: %w", err)
}
- return issue, current, nil
+ return issue, current, attachmentsChanged, nil
}
func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
@@ -3190,6 +3244,17 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
ProjectID: prevIssue.ProjectID,
Stage: prevIssue.Stage,
}
+ if req.ExpectedRevision != nil {
+ if *req.ExpectedRevision < 1 {
+ writeError(w, http.StatusBadRequest, "expected_revision must be a positive integer")
+ return
+ }
+ if prevIssue.Revision != *req.ExpectedRevision {
+ writeRevisionConflict(w, "issue", prevIssue.ID, *req.ExpectedRevision, prevIssue.Revision)
+ return
+ }
+ params.ExpectedRevision = pgtype.Int8{Int64: *req.ExpectedRevision, Valid: true}
+ }
// COALESCE fields — only set when explicitly provided
if req.Title != nil {
@@ -3355,12 +3420,13 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
}
var issue db.Issue
- if req.Description != nil {
+ attachmentsChanged := false
+ if req.Description != nil || req.TitleBase != nil || req.DescriptionBase != nil || len(attachmentIDs) > 0 {
var lockedPrev db.Issue
- issue, lockedPrev, err = h.updateIssueWithDescriptionMerge(
- r.Context(), prevIssue.WorkspaceID, params, rawFields, req.DescriptionBase, statusKeyForGuard,
+ issue, lockedPrev, attachmentsChanged, err = h.updateIssueAtomically(
+ r.Context(), prevIssue.WorkspaceID, params, rawFields, req.TitleBase, req.DescriptionBase, attachmentIDs, statusKeyForGuard,
)
- if err == nil {
+ if lockedPrev.ID.Valid {
prevIssue = lockedPrev
}
} else {
@@ -3374,14 +3440,24 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
if writeIssueStatusRaceError(w, err) {
return
}
+ if errors.Is(err, errIssueFieldConflict) {
+ writeEditConflict(w, "issue", prevIssue.ID)
+ return
+ }
+ if errors.Is(err, pgx.ErrNoRows) && req.ExpectedRevision != nil {
+ current, reloadErr := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{ID: prevIssue.ID, WorkspaceID: prevIssue.WorkspaceID})
+ if reloadErr == nil {
+ writeRevisionConflict(w, "issue", current.ID, *req.ExpectedRevision, current.Revision)
+ return
+ }
+ }
slog.Warn("update issue failed", append(logger.RequestAttrs(r), "error", err, "issue_id", id, "workspace_id", workspaceID)...)
writeError(w, http.StatusInternalServerError, "failed to update issue: "+err.Error())
return
}
- if len(attachmentIDs) > 0 {
- h.linkAttachmentsByIssueIDs(r.Context(), issue.ID, issue.WorkspaceID, attachmentIDs)
- }
+ // Determine actor identity: agent (via X-Agent-ID header) or member.
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)
resp := issueToResponse(issue, prefix)
@@ -3406,9 +3482,6 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
dueDateChanged := prevDueDate != resp.DueDate && (prevDueDate == nil) != (resp.DueDate == nil) ||
(prevDueDate != nil && resp.DueDate != nil && *prevDueDate != *resp.DueDate)
- // Determine actor identity: agent (via X-Agent-ID header) or member.
- actorType, actorID := h.resolveActor(r, userID, workspaceID)
-
h.publish(protocol.EventIssueUpdated, workspaceID, actorType, actorID, map[string]any{
"issue": resp,
"assignee_changed": assigneeChanged,
@@ -3430,6 +3503,15 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
"creator_type": prevIssue.CreatorType,
"creator_id": uuidToString(prevIssue.CreatorID),
})
+ if attachmentsChanged {
+ // The full owner snapshot must be admitted before an auxiliary event at
+ // the same revision. Otherwise clients advance only the revision here and
+ // reject issue:updated as non-increasing, stranding the old issue fields.
+ h.publish(protocol.EventIssueAttachmentsChanged, workspaceID, actorType, actorID, map[string]any{
+ "issue_id": uuidToString(issue.ID),
+ "issue_revision": issue.Revision,
+ })
+ }
// Reconcile the task queue. Whether this write starts an agent run — and
// for whom (agent assignee or squad leader) — is decided by the single
@@ -3992,8 +4074,8 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
// Preserve every marked channel-media block conservatively, matching
// legacy single-update clients that omit description_base.
var lockedPrev db.Issue
- issue, lockedPrev, err = h.updateIssueWithDescriptionMerge(
- r.Context(), prevIssue.WorkspaceID, params, rawUpdates, nil, batchStatusKey,
+ issue, lockedPrev, _, err = h.updateIssueAtomically(
+ r.Context(), prevIssue.WorkspaceID, params, rawUpdates, nil, nil, nil, batchStatusKey,
)
if err == nil {
prevIssue = lockedPrev
diff --git a/server/internal/handler/issue_child_done.go b/server/internal/handler/issue_child_done.go
index b072187d68..be16f75599 100644
--- a/server/internal/handler/issue_child_done.go
+++ b/server/internal/handler/issue_child_done.go
@@ -312,7 +312,7 @@ func (h *Handler) postChildDoneComment(ctx context.Context, parent, completed db
// author_type='system', author_id=zero UUID. The zero UUID is a valid 16
// byte value and the column is NOT NULL; frontend code should branch on
// author_type === 'system' rather than on the UUID value.
- comment, err := h.Queries.CreateComment(ctx, db.CreateCommentParams{
+ created, err := h.Queries.CreateComment(ctx, db.CreateCommentParams{
IssueID: parent.ID,
WorkspaceID: parent.WorkspaceID,
AuthorType: "system",
@@ -328,6 +328,7 @@ func (h *Handler) postChildDoneComment(ctx context.Context, parent, completed db
"parent_id", uuidToString(parent.ID))
return
}
+ comment := created.Comment()
h.publish(protocol.EventCommentCreated, uuidToString(parent.WorkspaceID), "system", "", map[string]any{
"comment": commentToResponse(comment, nil, nil),
@@ -335,6 +336,7 @@ func (h *Handler) postChildDoneComment(ctx context.Context, parent, completed db
"issue_assignee_type": textToPtr(parent.AssigneeType),
"issue_assignee_id": uuidToPtr(parent.AssigneeID),
"issue_status": parent.Status,
+ "issue_revision": created.IssueRevision,
})
// Dispatch the explicit trigger / inbox row for the parent assignee.
diff --git a/server/internal/handler/issue_collection_revision_test.go b/server/internal/handler/issue_collection_revision_test.go
new file mode 100644
index 0000000000..34ce5c37f0
--- /dev/null
+++ b/server/internal/handler/issue_collection_revision_test.go
@@ -0,0 +1,115 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "testing"
+ "time"
+)
+
+func TestIssueCollectionProjectionsIncludePositiveRevision(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ suffix := time.Now().UnixNano()
+ var projectID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO project (workspace_id, title)
+ VALUES ($1, $2)
+ RETURNING id
+ `, testWorkspaceID, fmt.Sprintf("Revision projection %d", suffix)).Scan(&projectID); err != nil {
+ t.Fatalf("create project: %v", err)
+ }
+
+ var issueNumber int
+ if err := testPool.QueryRow(ctx, `
+ UPDATE workspace
+ SET issue_counter = GREATEST(
+ issue_counter,
+ (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)
+ ) + 1
+ WHERE id = $1
+ RETURNING issue_counter
+ `, testWorkspaceID).Scan(&issueNumber); err != nil {
+ t.Fatalf("reserve issue number: %v", err)
+ }
+
+ title := fmt.Sprintf("revision-projection-%d", suffix)
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (
+ workspace_id, title, status, priority, creator_type, creator_id,
+ position, number, project_id, revision
+ )
+ VALUES ($1, $2, 'in_review', 'none', 'member', $3, 1, $4, $5, 7)
+ RETURNING id
+ `, testWorkspaceID, title, testUserID, issueNumber, projectID).Scan(&issueID); err != nil {
+ t.Fatalf("seed issue: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID)
+ })
+
+ groupKey := "status:in_review"
+ tableRecorder := httptest.NewRecorder()
+ testHandler.ListIssueTableRows(tableRecorder, newRequest(http.MethodPost, "/api/issues/table/rows", issueTableRowsRequest{
+ Query: issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "project", ProjectID: projectID},
+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},
+ },
+ Group: issueTableGroupSpec{Kind: "status"},
+ GroupKey: &groupKey,
+ Hierarchy: issueTableHierarchyRequest{Enabled: false},
+ Page: issueTablePageRequest{Limit: 10},
+ }))
+ if tableRecorder.Code != http.StatusOK {
+ t.Fatalf("table rows status = %d: %s", tableRecorder.Code, tableRecorder.Body.String())
+ }
+ var tableResponse issueTableRowsResponse
+ if err := json.NewDecoder(tableRecorder.Body).Decode(&tableResponse); err != nil {
+ t.Fatalf("decode table rows: %v", err)
+ }
+ if len(tableResponse.Rows) != 1 || tableResponse.Rows[0].Issue.ID != issueID {
+ t.Fatalf("table rows = %+v, want issue %s", tableResponse.Rows, issueID)
+ }
+ if tableResponse.Rows[0].Issue.Revision != 7 {
+ t.Fatalf("table row revision = %d, want 7", tableResponse.Rows[0].Issue.Revision)
+ }
+
+ listRecorder := httptest.NewRecorder()
+ testHandler.ListIssues(listRecorder, newRequest(http.MethodGet, "/api/issues?project_id="+url.QueryEscape(projectID), nil))
+ if listRecorder.Code != http.StatusOK {
+ t.Fatalf("list issues status = %d: %s", listRecorder.Code, listRecorder.Body.String())
+ }
+ var listResponse struct {
+ Issues []IssueResponse `json:"issues"`
+ }
+ if err := json.NewDecoder(listRecorder.Body).Decode(&listResponse); err != nil {
+ t.Fatalf("decode issue list: %v", err)
+ }
+ if len(listResponse.Issues) != 1 || listResponse.Issues[0].ID != issueID || listResponse.Issues[0].Revision != 7 {
+ t.Fatalf("list projection = %+v, want issue %s at revision 7", listResponse.Issues, issueID)
+ }
+
+ searchRecorder := httptest.NewRecorder()
+ testHandler.SearchIssues(searchRecorder, newRequest(http.MethodGet, "/api/issues/search?q="+url.QueryEscape(title), nil))
+ if searchRecorder.Code != http.StatusOK {
+ t.Fatalf("search issues status = %d: %s", searchRecorder.Code, searchRecorder.Body.String())
+ }
+ var searchResponse struct {
+ Issues []IssueResponse `json:"issues"`
+ }
+ if err := json.NewDecoder(searchRecorder.Body).Decode(&searchResponse); err != nil {
+ t.Fatalf("decode issue search: %v", err)
+ }
+ if len(searchResponse.Issues) != 1 || searchResponse.Issues[0].ID != issueID || searchResponse.Issues[0].Revision != 7 {
+ t.Fatalf("search projection = %+v, want issue %s at revision 7", searchResponse.Issues, issueID)
+ }
+}
diff --git a/server/internal/handler/issue_metadata.go b/server/internal/handler/issue_metadata.go
index e723567cb2..222fae639e 100644
--- a/server/internal/handler/issue_metadata.go
+++ b/server/internal/handler/issue_metadata.go
@@ -188,10 +188,11 @@ func (h *Handler) SetIssueMetadataKey(w http.ResponseWriter, r *http.Request) {
actorType, actorID := h.resolveActor(r, userID, workspaceID)
metadata := parseIssueMetadata(updated.Metadata)
h.publish(protocol.EventIssueMetadataChanged, workspaceID, actorType, actorID, map[string]any{
- "issue_id": uuidToString(updated.ID),
- "metadata": metadata,
+ "issue_id": uuidToString(updated.ID),
+ "metadata": metadata,
+ "issue_revision": updated.Revision,
})
- writeJSON(w, http.StatusOK, map[string]any{"metadata": metadata})
+ writeJSON(w, http.StatusOK, map[string]any{"metadata": metadata, "issue_revision": updated.Revision})
}
func (h *Handler) DeleteIssueMetadataKey(w http.ResponseWriter, r *http.Request) {
@@ -230,8 +231,9 @@ func (h *Handler) DeleteIssueMetadataKey(w http.ResponseWriter, r *http.Request)
actorType, actorID := h.resolveActor(r, userID, workspaceID)
metadata := parseIssueMetadata(updated.Metadata)
h.publish(protocol.EventIssueMetadataChanged, workspaceID, actorType, actorID, map[string]any{
- "issue_id": uuidToString(updated.ID),
- "metadata": metadata,
+ "issue_id": uuidToString(updated.ID),
+ "metadata": metadata,
+ "issue_revision": updated.Revision,
})
- writeJSON(w, http.StatusOK, map[string]any{"metadata": metadata})
+ writeJSON(w, http.StatusOK, map[string]any{"metadata": metadata, "issue_revision": updated.Revision})
}
diff --git a/server/internal/handler/issue_move.go b/server/internal/handler/issue_move.go
index 2a9739115d..7f47c3a146 100644
--- a/server/internal/handler/issue_move.go
+++ b/server/internal/handler/issue_move.go
@@ -15,13 +15,14 @@ import (
)
var issueMoveFields = map[string]struct{}{
- "status": {},
- "assignee_type": {},
- "assignee_id": {},
- "parent_issue_id": {},
- "project_id": {},
- "before_id": {},
- "after_id": {},
+ "status": {},
+ "assignee_type": {},
+ "assignee_id": {},
+ "parent_issue_id": {},
+ "project_id": {},
+ "before_id": {},
+ "after_id": {},
+ "expected_revision": {},
}
// MoveIssue accepts relative neighbors instead of a client-authored canonical
diff --git a/server/internal/handler/issue_reaction.go b/server/internal/handler/issue_reaction.go
index b4e0a077f0..96339b379b 100644
--- a/server/internal/handler/issue_reaction.go
+++ b/server/internal/handler/issue_reaction.go
@@ -12,12 +12,13 @@ import (
)
type IssueReactionResponse struct {
- ID string `json:"id"`
- IssueID string `json:"issue_id"`
- ActorType string `json:"actor_type"`
- ActorID string `json:"actor_id"`
- Emoji string `json:"emoji"`
- CreatedAt string `json:"created_at"`
+ ID string `json:"id"`
+ IssueID string `json:"issue_id"`
+ ActorType string `json:"actor_type"`
+ ActorID string `json:"actor_id"`
+ Emoji string `json:"emoji"`
+ CreatedAt string `json:"created_at"`
+ IssueRevision *int64 `json:"issue_revision,omitempty"`
}
func issueReactionToResponse(r db.IssueReaction) IssueReactionResponse {
@@ -31,6 +32,21 @@ func issueReactionToResponse(r db.IssueReaction) IssueReactionResponse {
}
}
+func addedIssueReactionToResponse(r db.AddIssueReactionRow) IssueReactionResponse {
+ response := IssueReactionResponse{
+ ID: uuidToString(r.ID),
+ IssueID: uuidToString(r.IssueID),
+ ActorType: r.ActorType,
+ ActorID: uuidToString(r.ActorID),
+ Emoji: r.Emoji,
+ CreatedAt: timestampToString(r.CreatedAt),
+ }
+ if r.IssueRevision > 0 {
+ response.IssueRevision = &r.IssueRevision
+ }
+ return response
+}
+
func (h *Handler) AddIssueReaction(w http.ResponseWriter, r *http.Request) {
issueID := chi.URLParam(r, "id")
issue, ok := h.loadIssueForUser(w, r, issueID)
@@ -71,15 +87,18 @@ func (h *Handler) AddIssueReaction(w http.ResponseWriter, r *http.Request) {
return
}
- resp := issueReactionToResponse(reaction)
- h.publish(protocol.EventIssueReactionAdded, workspaceID, actorType, actorID, map[string]any{
- "reaction": resp,
- "issue_id": uuidToString(issue.ID),
- "issue_title": issue.Title,
- "issue_status": issue.Status,
- "creator_type": issue.CreatorType,
- "creator_id": uuidToString(issue.CreatorID),
- })
+ resp := addedIssueReactionToResponse(reaction)
+ if reaction.IssueRevision > 0 {
+ h.publish(protocol.EventIssueReactionAdded, workspaceID, actorType, actorID, map[string]any{
+ "reaction": resp,
+ "issue_id": uuidToString(issue.ID),
+ "issue_title": issue.Title,
+ "issue_status": issue.Status,
+ "creator_type": issue.CreatorType,
+ "creator_id": uuidToString(issue.CreatorID),
+ "issue_revision": reaction.IssueRevision,
+ })
+ }
writeJSON(w, http.StatusCreated, resp)
}
@@ -110,22 +129,26 @@ func (h *Handler) RemoveIssueReaction(w http.ResponseWriter, r *http.Request) {
workspaceID := uuidToString(issue.WorkspaceID)
actorType, actorID := h.resolveActor(r, userID, workspaceID)
- if err := h.Queries.RemoveIssueReaction(r.Context(), db.RemoveIssueReactionParams{
+ removed, err := h.Queries.RemoveIssueReaction(r.Context(), db.RemoveIssueReactionParams{
IssueID: issue.ID,
ActorType: actorType,
ActorID: parseUUID(actorID),
Emoji: req.Emoji,
- }); err != nil {
+ })
+ if err != nil {
slog.Warn("remove issue reaction failed", append(logger.RequestAttrs(r), "error", err, "issue_id", issueID)...)
writeError(w, http.StatusInternalServerError, "failed to remove reaction")
return
}
- h.publish(protocol.EventIssueReactionRemoved, workspaceID, actorType, actorID, map[string]any{
- "issue_id": uuidToString(issue.ID),
- "emoji": req.Emoji,
- "actor_type": actorType,
- "actor_id": actorID,
- })
+ if removed.Changed {
+ h.publish(protocol.EventIssueReactionRemoved, workspaceID, actorType, actorID, map[string]any{
+ "issue_id": uuidToString(issue.ID),
+ "emoji": req.Emoji,
+ "actor_type": actorType,
+ "actor_id": actorID,
+ "issue_revision": removed.IssueRevision,
+ })
+ }
w.WriteHeader(http.StatusNoContent)
}
diff --git a/server/internal/handler/issue_revision_test.go b/server/internal/handler/issue_revision_test.go
new file mode 100644
index 0000000000..75224a369b
--- /dev/null
+++ b/server/internal/handler/issue_revision_test.go
@@ -0,0 +1,940 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "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/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+var errInjectedIssueAttachmentLink = errors.New("injected issue attachment link failure")
+
+type failIssueAttachmentLinkTxStarter struct {
+ inner txStarter
+}
+
+func (s failIssueAttachmentLinkTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.inner.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return &failIssueAttachmentLinkTx{Tx: tx}, nil
+}
+
+type failIssueAttachmentLinkTx struct {
+ pgx.Tx
+}
+
+func (tx *failIssueAttachmentLinkTx) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {
+ if strings.Contains(sql, "LinkAttachmentsToIssue") {
+ return failingIssueAttachmentLinkRow{}
+ }
+ return tx.Tx.QueryRow(ctx, sql, args...)
+}
+
+type failingIssueAttachmentLinkRow struct{}
+
+func (failingIssueAttachmentLinkRow) Scan(...any) error {
+ return errInjectedIssueAttachmentLink
+}
+
+type pauseIssueAttachmentLinkTxStarter struct {
+ inner txStarter
+ reached chan<- struct{}
+ release <-chan struct{}
+}
+
+func (s pauseIssueAttachmentLinkTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.inner.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return &pauseIssueAttachmentLinkTx{
+ Tx: tx,
+ reached: s.reached,
+ release: s.release,
+ }, nil
+}
+
+type pauseIssueAttachmentLinkTx struct {
+ pgx.Tx
+ reached chan<- struct{}
+ release <-chan struct{}
+}
+
+func (tx *pauseIssueAttachmentLinkTx) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {
+ if strings.Contains(sql, "LinkAttachmentsToIssue") {
+ tx.reached <- struct{}{}
+ select {
+ case <-tx.release:
+ case <-ctx.Done():
+ return failingIssueAttachmentLinkRow{}
+ }
+ }
+ return tx.Tx.QueryRow(ctx, sql, args...)
+}
+
+func insertWorkflowTestIssue(t *testing.T, title string, number int) string {
+ t.Helper()
+ var id string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO issue (workspace_id, title, creator_type, creator_id, number)
+ VALUES ($1, $2, 'member', $3, $4)
+ RETURNING id
+ `, testWorkspaceID, title, testUserID, number).Scan(&id); err != nil {
+ t.Fatalf("insert workflow issue: %v", err)
+ }
+ return id
+}
+
+func TestRevisionConflictsPreserveLatestIssueAndComment(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ issueID := insertWorkflowTestIssue(t, "revision original", int(time.Now().UnixNano()%100000)+8_750_000)
+ var commentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)
+ VALUES ($1, $2, 'member', $3, 'comment original')
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID).Scan(&commentID); err != nil {
+ t.Fatalf("insert revision comment: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM comment WHERE id = $1`, commentID)
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+
+ updateIssue := func(title, base string) *httptest.ResponseRecorder {
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequest(http.MethodPut, "/api/issues/"+issueID, map[string]any{
+ "title": title, "title_base": base,
+ }), "id", issueID)
+ testHandler.UpdateIssue(w, req)
+ return w
+ }
+ if w := updateIssue("revision latest", "revision original"); w.Code != http.StatusOK {
+ t.Fatalf("first issue update = %d: %s", w.Code, w.Body.String())
+ }
+ if w := updateIssue("revision latest", "revision latest"); w.Code != http.StatusOK {
+ t.Fatalf("no-op issue update = %d: %s", w.Code, w.Body.String())
+ }
+ if w := updateIssue("revision stale overwrite", "revision original"); w.Code != http.StatusConflict {
+ t.Fatalf("stale issue update = %d, want 409: %s", w.Code, w.Body.String())
+ }
+ var title string
+ var issueRevision int64
+ if err := testPool.QueryRow(ctx, `SELECT title, revision FROM issue WHERE id = $1`, issueID).Scan(&title, &issueRevision); err != nil {
+ t.Fatalf("reload revision issue: %v", err)
+ }
+ if title != "revision latest" || issueRevision != 2 {
+ t.Fatalf("issue after stale write = (%q, %d), want latest/2", title, issueRevision)
+ }
+ legacyIssue := httptest.NewRecorder()
+ testHandler.UpdateIssue(legacyIssue, withURLParam(newRequest(http.MethodPut, "/api/issues/"+issueID, map[string]any{
+ "title": "legacy issue update",
+ }), "id", issueID))
+ if legacyIssue.Code != http.StatusOK {
+ t.Fatalf("legacy issue update = %d: %s", legacyIssue.Code, legacyIssue.Body.String())
+ }
+ if err := testPool.QueryRow(ctx, `SELECT title, revision FROM issue WHERE id = $1`, issueID).Scan(&title, &issueRevision); err != nil {
+ t.Fatalf("reload legacy issue update: %v", err)
+ }
+ if title != "legacy issue update" || issueRevision != 3 {
+ t.Fatalf("legacy issue update = (%q, %d), want legacy issue update/3", title, issueRevision)
+ }
+
+ updateComment := func(content, base string) *httptest.ResponseRecorder {
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequest(http.MethodPut, "/api/comments/"+commentID, map[string]any{
+ "content": content, "content_base": base,
+ }), "commentId", commentID)
+ testHandler.UpdateComment(w, req)
+ return w
+ }
+ if w := updateComment("comment latest", "comment original"); w.Code != http.StatusOK {
+ t.Fatalf("first comment update = %d: %s", w.Code, w.Body.String())
+ }
+ if w := updateComment("comment latest", "comment latest"); w.Code != http.StatusOK {
+ t.Fatalf("no-op comment update = %d: %s", w.Code, w.Body.String())
+ }
+ if w := updateComment("comment stale overwrite", "comment original"); w.Code != http.StatusConflict {
+ t.Fatalf("stale comment update = %d, want 409: %s", w.Code, w.Body.String())
+ }
+ var content string
+ var commentRevision int64
+ if err := testPool.QueryRow(ctx, `SELECT content, revision FROM comment WHERE id = $1`, commentID).Scan(&content, &commentRevision); err != nil {
+ t.Fatalf("reload revision comment: %v", err)
+ }
+ if content != "comment latest" || commentRevision != 2 {
+ t.Fatalf("comment after stale write = (%q, %d), want latest/2", content, commentRevision)
+ }
+
+ var attachmentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO attachment (
+ workspace_id, issue_id, uploader_type, uploader_id,
+ filename, url, content_type, size_bytes
+ )
+ VALUES ($1, $2, 'member', $3, 'revision.txt', '/revision.txt', 'text/plain', 1)
+ RETURNING id
+ `, testWorkspaceID, issueID, testUserID).Scan(&attachmentID); err != nil {
+ t.Fatalf("insert revision attachment: %v", err)
+ }
+ updateAttachments := func() *httptest.ResponseRecorder {
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequest(http.MethodPut, "/api/comments/"+commentID, map[string]any{
+ "content": "comment latest",
+ "attachment_ids": []string{attachmentID},
+ "content_base": "comment latest",
+ }), "commentId", commentID)
+ testHandler.UpdateComment(w, req)
+ return w
+ }
+ if w := updateAttachments(); w.Code != http.StatusOK {
+ t.Fatalf("attachment-only comment update = %d: %s", w.Code, w.Body.String())
+ }
+ if w := updateAttachments(); w.Code != http.StatusOK {
+ t.Fatalf("attachment no-op comment update = %d: %s", w.Code, w.Body.String())
+ }
+ if err := testPool.QueryRow(ctx, `SELECT revision FROM comment WHERE id = $1`, commentID).Scan(&commentRevision); err != nil {
+ t.Fatalf("reload attachment comment revision: %v", err)
+ }
+ if commentRevision != 3 {
+ t.Fatalf("comment revision after attachment update = %d, want 3", commentRevision)
+ }
+ legacyComment := httptest.NewRecorder()
+ testHandler.UpdateComment(legacyComment, withURLParam(newRequest(http.MethodPut, "/api/comments/"+commentID, map[string]any{
+ "content": "legacy comment update",
+ }), "commentId", commentID))
+ if legacyComment.Code != http.StatusOK {
+ t.Fatalf("legacy comment update = %d: %s", legacyComment.Code, legacyComment.Body.String())
+ }
+ if err := testPool.QueryRow(ctx, `SELECT content, revision FROM comment WHERE id = $1`, commentID).Scan(&content, &commentRevision); err != nil {
+ t.Fatalf("reload legacy comment update: %v", err)
+ }
+ if content != "legacy comment update" || commentRevision != 4 {
+ t.Fatalf("legacy comment update = (%q, %d), want legacy comment update/4", content, commentRevision)
+ }
+}
+
+func TestTextBaselinesIgnoreUnrelatedAggregateRevisionChanges(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ issueID := insertWorkflowTestIssue(t, "baseline title", int(time.Now().UnixNano()%100000)+8_755_000)
+ if _, err := testPool.Exec(ctx, `UPDATE issue SET description = 'baseline description' WHERE id = $1`, issueID); err != nil {
+ t.Fatalf("seed issue description: %v", err)
+ }
+ var commentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)
+ VALUES ($1, $2, 'member', $3, 'baseline comment')
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID).Scan(&commentID); err != nil {
+ t.Fatalf("insert baseline comment: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM comment WHERE id = $1`, commentID)
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+
+ // An unrelated priority write advances the aggregate owner revision.
+ priority := httptest.NewRecorder()
+ testHandler.UpdateIssue(priority, withURLParam(newRequest(http.MethodPut, "/api/issues/"+issueID, map[string]any{
+ "priority": "high",
+ }), "id", issueID))
+ if priority.Code != http.StatusOK {
+ t.Fatalf("unrelated issue update = %d: %s", priority.Code, priority.Body.String())
+ }
+
+ text := httptest.NewRecorder()
+ testHandler.UpdateIssue(text, withURLParam(newRequest(http.MethodPut, "/api/issues/"+issueID, map[string]any{
+ "title": "edited title",
+ "title_base": "baseline title",
+ "description": "edited description",
+ "description_base": "baseline description",
+ }), "id", issueID))
+ if text.Code != http.StatusOK {
+ t.Fatalf("text update after unrelated revision = %d: %s", text.Code, text.Body.String())
+ }
+ staleDescription := httptest.NewRecorder()
+ testHandler.UpdateIssue(staleDescription, withURLParam(newRequest(http.MethodPut, "/api/issues/"+issueID, map[string]any{
+ "description": "stale description overwrite",
+ "description_base": "baseline description",
+ }), "id", issueID))
+ if staleDescription.Code != http.StatusConflict {
+ t.Fatalf("true issue description conflict = %d, want 409: %s", staleDescription.Code, staleDescription.Body.String())
+ }
+
+ // A reaction/resolve-style aggregate bump on the comment must likewise not
+ // reject a body edit whose content baseline is still current.
+ if _, err := testPool.Exec(ctx, `UPDATE comment SET revision = revision + 1 WHERE id = $1`, commentID); err != nil {
+ t.Fatalf("bump comment revision: %v", err)
+ }
+ comment := httptest.NewRecorder()
+ testHandler.UpdateComment(comment, withURLParam(newRequest(http.MethodPut, "/api/comments/"+commentID, map[string]any{
+ "content": "edited comment",
+ "content_base": "baseline comment",
+ }), "commentId", commentID))
+ if comment.Code != http.StatusOK {
+ t.Fatalf("comment edit after unrelated revision = %d: %s", comment.Code, comment.Body.String())
+ }
+
+ stale := httptest.NewRecorder()
+ testHandler.UpdateComment(stale, withURLParam(newRequest(http.MethodPut, "/api/comments/"+commentID, map[string]any{
+ "content": "stale overwrite",
+ "content_base": "baseline comment",
+ }), "commentId", commentID))
+ if stale.Code != http.StatusConflict {
+ t.Fatalf("true comment content conflict = %d, want 409: %s", stale.Code, stale.Body.String())
+ }
+}
+
+func TestConcurrentRevisionWritesHaveExactlyOneWinner(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ issueID := insertWorkflowTestIssue(t, "concurrent revision", int(time.Now().UnixNano()%100000)+8_760_000)
+ var commentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)
+ VALUES ($1, $2, 'member', $3, 'concurrent original')
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID).Scan(&commentID); err != nil {
+ t.Fatalf("insert concurrent comment: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM comment WHERE id = $1`, commentID)
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+
+ assertOneWinner := func(run func(value string) int) {
+ t.Helper()
+ start := make(chan struct{})
+ results := make(chan int, 2)
+ for _, value := range []string{"writer-a", "writer-b"} {
+ go func() {
+ <-start
+ results <- run(value)
+ }()
+ }
+ close(start)
+ okCount, conflictCount := 0, 0
+ for range 2 {
+ switch <-results {
+ case http.StatusOK:
+ okCount++
+ case http.StatusConflict:
+ conflictCount++
+ }
+ }
+ if okCount != 1 || conflictCount != 1 {
+ t.Fatalf("concurrent outcomes = ok:%d conflict:%d, want 1/1", okCount, conflictCount)
+ }
+ }
+
+ assertOneWinner(func(title string) int {
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequest(http.MethodPut, "/api/issues/"+issueID, map[string]any{
+ "title": title, "title_base": "concurrent revision",
+ }), "id", issueID)
+ testHandler.UpdateIssue(w, req)
+ return w.Code
+ })
+
+ assertOneWinner(func(content string) int {
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequest(http.MethodPut, "/api/comments/"+commentID, map[string]any{
+ "content": content, "content_base": "concurrent original",
+ }), "commentId", commentID)
+ testHandler.UpdateComment(w, req)
+ return w.Code
+ })
+
+ var issueRevision, commentRevision int64
+ if err := testPool.QueryRow(ctx, `SELECT revision FROM issue WHERE id = $1`, issueID).Scan(&issueRevision); err != nil {
+ t.Fatalf("reload concurrent issue: %v", err)
+ }
+ if err := testPool.QueryRow(ctx, `SELECT revision FROM comment WHERE id = $1`, commentID).Scan(&commentRevision); err != nil {
+ t.Fatalf("reload concurrent comment: %v", err)
+ }
+ if issueRevision != 2 || commentRevision != 2 {
+ t.Fatalf("concurrent revisions = issue:%d comment:%d, want 2/2", issueRevision, commentRevision)
+ }
+}
+
+func TestConcurrentCommentRevisionConflictCancelsTaskBatchOnce(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ fixture := createCommentDeliveryFixture(t, "revision task side effects")
+ if _, err := testPool.Exec(ctx, `
+ UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1
+ `, fixture.issueID, fixture.agentID); err != nil {
+ t.Fatalf("assign revision test issue: %v", err)
+ }
+
+ cancelEvents := make(chan events.Event, 4)
+ testHandler.Bus.Subscribe(protocol.EventTaskCancelled, func(event events.Event) {
+ payload, ok := event.Payload.(map[string]any)
+ if ok && payload["issue_id"] == fixture.issueID {
+ cancelEvents <- event
+ }
+ })
+
+ start := make(chan struct{})
+ results := make(chan int, 2)
+ for _, content := range []string{"concurrent edit a", "concurrent edit b"} {
+ go func() {
+ <-start
+ w := httptest.NewRecorder()
+ req := withURLParam(newRequest(http.MethodPut, "/api/comments/"+fixture.commentID[2], map[string]any{
+ "content": content,
+ "content_base": fixture.content[2],
+ }), "commentId", fixture.commentID[2])
+ testHandler.UpdateComment(w, req)
+ results <- w.Code
+ }()
+ }
+ close(start)
+ okCount, conflictCount := 0, 0
+ for range 2 {
+ switch <-results {
+ case http.StatusOK:
+ okCount++
+ case http.StatusConflict:
+ conflictCount++
+ }
+ }
+ if okCount != 1 || conflictCount != 1 {
+ t.Fatalf("concurrent comment outcomes = ok:%d conflict:%d, want 1/1", okCount, conflictCount)
+ }
+
+ var originalStatus string
+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, fixture.taskID).Scan(&originalStatus); err != nil {
+ t.Fatalf("load original task: %v", err)
+ }
+ if originalStatus != "cancelled" {
+ t.Fatalf("original task status = %q, want cancelled", originalStatus)
+ }
+ if got := len(cancelEvents); got != 1 {
+ t.Fatalf("task cancellation events = %d, want exactly one winning edit side effect", got)
+ }
+ var activeCount int
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM agent_task_queue
+ WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+ `, fixture.issueID).Scan(&activeCount); err != nil {
+ t.Fatalf("count active replacement tasks: %v", err)
+ }
+ if activeCount != 1 {
+ t.Fatalf("active replacement tasks = %d, want one batch from the winning edit", activeCount)
+ }
+}
+
+func TestNoOpIssueUpdateDoesNotAdvanceRevisionOrUpdatedAt(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ issueID := insertWorkflowTestIssue(t, "no-op issue update", int(time.Now().UnixNano()%100000)+8_768_000)
+ oldUpdatedAt := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
+ if _, err := testPool.Exec(ctx, `UPDATE issue SET updated_at = $2 WHERE id = $1`, issueID, oldUpdatedAt); err != nil {
+ t.Fatalf("seed old issue timestamp: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+
+ w := httptest.NewRecorder()
+ testHandler.UpdateIssue(w, withURLParam(newRequest(http.MethodPut, "/api/issues/"+issueID, map[string]any{
+ "title": "no-op issue update",
+ "expected_revision": 1,
+ }), "id", issueID))
+ if w.Code != http.StatusOK {
+ t.Fatalf("no-op update = %d: %s", w.Code, w.Body.String())
+ }
+ var revision int64
+ var updatedAt time.Time
+ if err := testPool.QueryRow(ctx, `SELECT revision, updated_at FROM issue WHERE id = $1`, issueID).Scan(&revision, &updatedAt); err != nil {
+ t.Fatalf("load no-op issue: %v", err)
+ }
+ if revision != 1 || !updatedAt.Equal(oldUpdatedAt) {
+ t.Fatalf("no-op issue = revision %d, updated_at %s; want 1 and %s", revision, updatedAt, oldUpdatedAt)
+ }
+}
+
+func TestNoOpIssueWithAttachmentPublishesFreshOwnerBeforeAttachmentEvent(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ issueID := insertWorkflowTestIssue(t, "ordered attachment events", int(time.Now().UnixNano()%100000)+8_770_000)
+ if _, err := testPool.Exec(ctx, `UPDATE issue SET updated_at = '2000-01-01T00:00:00Z' WHERE id = $1`, issueID); err != nil {
+ t.Fatalf("seed old issue timestamp: %v", err)
+ }
+ var attachmentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO attachment (
+ workspace_id, uploader_type, uploader_id,
+ filename, url, content_type, size_bytes
+ )
+ VALUES ($1, 'member', $2, 'ordered.txt', '/ordered.txt', 'text/plain', 1)
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&attachmentID); err != nil {
+ t.Fatalf("insert unbound attachment: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM attachment WHERE id = $1`, attachmentID)
+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+
+ h := *testHandler
+ h.Bus = events.New()
+ var ordered []events.Event
+ h.Bus.SubscribeAll(func(event events.Event) {
+ if event.Type == protocol.EventIssueUpdated || event.Type == protocol.EventIssueAttachmentsChanged {
+ ordered = append(ordered, event)
+ }
+ })
+
+ w := httptest.NewRecorder()
+ h.UpdateIssue(w, withURLParam(newRequest(http.MethodPut, "/api/issues/"+issueID, map[string]any{
+ "title": "ordered attachment events",
+ "attachment_ids": []string{attachmentID},
+ "expected_revision": 1,
+ }), "id", issueID))
+ if w.Code != http.StatusOK {
+ t.Fatalf("combined update = %d: %s", w.Code, w.Body.String())
+ }
+ if len(ordered) != 2 || ordered[0].Type != protocol.EventIssueUpdated || ordered[1].Type != protocol.EventIssueAttachmentsChanged {
+ t.Fatalf("event order = %#v, want issue:updated then issue_attachments:changed", ordered)
+ }
+ updatedPayload, ok := ordered[0].Payload.(map[string]any)
+ if !ok {
+ t.Fatalf("updated payload = %#v", ordered[0].Payload)
+ }
+ updatedIssue, ok := updatedPayload["issue"].(IssueResponse)
+ if !ok {
+ t.Fatalf("updated issue = %#v", updatedPayload["issue"])
+ }
+ if updatedIssue.Revision != 2 {
+ t.Fatalf("no-op owner revision = %d, want 2", updatedIssue.Revision)
+ }
+ responseUpdatedAt, err := time.Parse(time.RFC3339Nano, updatedIssue.UpdatedAt)
+ if err != nil {
+ t.Fatalf("parse response updated_at %q: %v", updatedIssue.UpdatedAt, err)
+ }
+ if !responseUpdatedAt.After(time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)) {
+ t.Fatalf("response updated_at = %s, want refreshed timestamp", responseUpdatedAt)
+ }
+ var updatedAt time.Time
+ if err := testPool.QueryRow(ctx, `SELECT updated_at FROM issue WHERE id = $1`, issueID).Scan(&updatedAt); err != nil {
+ t.Fatalf("load no-op updated_at: %v", err)
+ }
+ if !updatedAt.After(time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)) {
+ t.Fatalf("no-op updated_at = %s, want refreshed timestamp", updatedAt)
+ }
+ attachmentPayload, ok := ordered[1].Payload.(map[string]any)
+ if !ok || attachmentPayload["issue_revision"] != updatedIssue.Revision {
+ t.Fatalf("event revisions = updated:%#v attachment:%#v", updatedIssue.Revision, attachmentPayload["issue_revision"])
+ }
+}
+
+func TestIssueUpdateAndAttachmentBindingExcludeInterleavingMutation(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ issueID := insertWorkflowTestIssue(t, "atomic attachment binding", int(time.Now().UnixNano()%100000)+8_772_000)
+ var attachmentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO attachment (
+ workspace_id, uploader_type, uploader_id,
+ filename, url, content_type, size_bytes
+ )
+ VALUES ($1, 'member', $2, 'atomic.txt', '/atomic.txt', 'text/plain', 1)
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&attachmentID); err != nil {
+ t.Fatalf("insert atomic attachment: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, attachmentID)
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+
+ reachedLink := make(chan struct{}, 1)
+ releaseLink := make(chan struct{})
+ defer func() {
+ select {
+ case <-releaseLink:
+ default:
+ close(releaseLink)
+ }
+ }()
+ h := *testHandler
+ h.TxStarter = pauseIssueAttachmentLinkTxStarter{
+ inner: testHandler.TxStarter,
+ reached: reachedLink,
+ release: releaseLink,
+ }
+ handlerDone := make(chan *httptest.ResponseRecorder, 1)
+ go func() {
+ w := httptest.NewRecorder()
+ h.UpdateIssue(w, withURLParam(newRequest(http.MethodPut, "/api/issues/"+issueID, map[string]any{
+ "title": "atomic attachment binding",
+ "attachment_ids": []string{attachmentID},
+ "expected_revision": 1,
+ }), "id", issueID))
+ handlerDone <- w
+ }()
+
+ select {
+ case <-reachedLink:
+ case <-time.After(5 * time.Second):
+ t.Fatal("issue update did not reach the attachment link")
+ }
+
+ concurrentDone := make(chan error, 1)
+ go func() {
+ _, execErr := testPool.Exec(ctx, `
+ /* issue_revision_interleaving */
+ UPDATE issue
+ SET priority = 'high', revision = revision + 1
+ WHERE id = $1
+ `, issueID)
+ concurrentDone <- execErr
+ }()
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ var waiting bool
+ if err := testPool.QueryRow(ctx, `
+ SELECT EXISTS (
+ SELECT 1
+ FROM pg_stat_activity
+ WHERE datname = current_database()
+ AND wait_event_type = 'Lock'
+ AND query LIKE '%issue_revision_interleaving%'
+ )
+ `).Scan(&waiting); err != nil {
+ t.Fatalf("observe blocked concurrent mutation: %v", err)
+ }
+ if waiting {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("concurrent mutation was not blocked by the issue update transaction")
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+
+ close(releaseLink)
+ response := <-handlerDone
+ if response.Code != http.StatusOK {
+ t.Fatalf("combined update = %d: %s", response.Code, response.Body.String())
+ }
+ var updated IssueResponse
+ if err := json.NewDecoder(response.Body).Decode(&updated); err != nil {
+ t.Fatalf("decode combined update: %v", err)
+ }
+ if updated.Revision != 2 {
+ t.Fatalf("combined update revision = %d, want 2", updated.Revision)
+ }
+ if err := <-concurrentDone; err != nil {
+ t.Fatalf("concurrent mutation after commit: %v", err)
+ }
+
+ var linkedIssueID, priority string
+ var revision int64
+ if err := testPool.QueryRow(ctx, `
+ SELECT a.issue_id, i.priority, i.revision
+ FROM attachment AS a
+ JOIN issue AS i ON i.id = a.issue_id
+ WHERE a.id = $1
+ `, attachmentID).Scan(&linkedIssueID, &priority, &revision); err != nil {
+ t.Fatalf("load atomic result: %v", err)
+ }
+ if linkedIssueID != issueID || priority != "high" || revision != 3 {
+ t.Fatalf("atomic result = issue %s, priority %s, revision %d; want %s/high/3", linkedIssueID, priority, revision, issueID)
+ }
+}
+
+func TestIssueUpdateRollsBackWhenAttachmentBindingFails(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ issueID := insertWorkflowTestIssue(t, "attachment rollback original", int(time.Now().UnixNano()%100000)+8_774_000)
+ var attachmentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO attachment (
+ workspace_id, uploader_type, uploader_id,
+ filename, url, content_type, size_bytes
+ )
+ VALUES ($1, 'member', $2, 'rollback.txt', '/rollback.txt', 'text/plain', 1)
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&attachmentID); err != nil {
+ t.Fatalf("insert rollback attachment: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, attachmentID)
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+
+ h := *testHandler
+ h.TxStarter = failIssueAttachmentLinkTxStarter{inner: testHandler.TxStarter}
+ w := httptest.NewRecorder()
+ h.UpdateIssue(w, withURLParam(newRequest(http.MethodPut, "/api/issues/"+issueID, map[string]any{
+ "title": "attachment rollback changed",
+ "attachment_ids": []string{attachmentID},
+ }), "id", issueID))
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("injected link failure = %d, want 500: %s", w.Code, w.Body.String())
+ }
+
+ var title string
+ var revision int64
+ if err := testPool.QueryRow(ctx, `SELECT title, revision FROM issue WHERE id = $1`, issueID).Scan(&title, &revision); err != nil {
+ t.Fatalf("load rolled-back issue: %v", err)
+ }
+ var linked bool
+ if err := testPool.QueryRow(ctx, `SELECT issue_id IS NOT NULL FROM attachment WHERE id = $1`, attachmentID).Scan(&linked); err != nil {
+ t.Fatalf("load rolled-back attachment: %v", err)
+ }
+ if title != "attachment rollback original" || revision != 1 || linked {
+ t.Fatalf("rollback result = title %q, revision %d, linked %t", title, revision, linked)
+ }
+}
+
+func TestAuxiliaryVisibleMutationsAdvanceOwnerRevisionExactlyOnce(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ issueID := insertWorkflowTestIssue(t, "revision auxiliary projections", int(time.Now().UnixNano()%100000)+8_775_000)
+ issueUUID, _ := util.ParseUUID(issueID)
+ workspaceUUID, _ := util.ParseUUID(testWorkspaceID)
+ userUUID, _ := util.ParseUUID(testUserID)
+ var commentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)
+ VALUES ($1, $2, 'member', $3, 'auxiliary revision comment')
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID).Scan(&commentID); err != nil {
+ t.Fatalf("insert auxiliary comment: %v", err)
+ }
+ commentUUID, _ := util.ParseUUID(commentID)
+ labelID := uuid.New()
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO issue_label (id, workspace_id, resource_type, name, color)
+ VALUES ($1, $2, 'issue', $3, '#3b82f6')
+ `, labelID, testWorkspaceID, "workflow-aux-"+labelID.String()); err != nil {
+ t.Fatalf("insert auxiliary label: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM attachment WHERE issue_id = $1 OR comment_id = $2`, issueID, commentID)
+ testPool.Exec(ctx, `DELETE FROM comment_reaction WHERE comment_id = $1`, commentID)
+ testPool.Exec(ctx, `DELETE FROM issue_reaction WHERE issue_id = $1`, issueID)
+ testPool.Exec(ctx, `DELETE FROM issue_to_label WHERE issue_id = $1`, issueID)
+ testPool.Exec(ctx, `DELETE FROM issue_label WHERE id = $1`, labelID)
+ testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, commentID)
+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+
+ labelParams := db.AttachLabelToIssueParams{IssueID: issueUUID, LabelID: pgtype.UUID{Bytes: labelID, Valid: true}, WorkspaceID: workspaceUUID}
+ attached, err := testHandler.Queries.AttachLabelToIssue(ctx, labelParams)
+ if err != nil || !attached.Changed || attached.IssueRevision != 2 {
+ t.Fatalf("attach label = (%+v, %v), want changed revision 2", attached, err)
+ }
+ attached, err = testHandler.Queries.AttachLabelToIssue(ctx, labelParams)
+ if err != nil || attached.Changed || attached.IssueRevision != 0 {
+ t.Fatalf("duplicate label attach = (%+v, %v), want no-op", attached, err)
+ }
+ labelsResponse := httptest.NewRecorder()
+ testHandler.ListLabelsForIssue(labelsResponse, withURLParam(newRequest(http.MethodGet, "/api/issues/"+issueID+"/labels", nil), "id", issueID))
+ if labelsResponse.Code != http.StatusOK {
+ t.Fatalf("list issue labels = %d: %s", labelsResponse.Code, labelsResponse.Body.String())
+ }
+ var labelPayload struct {
+ IssueRevision int64 `json:"issue_revision"`
+ }
+ if err := json.Unmarshal(labelsResponse.Body.Bytes(), &labelPayload); err != nil || labelPayload.IssueRevision != 2 {
+ t.Fatalf("list issue labels revision = (%d, %v), want 2", labelPayload.IssueRevision, err)
+ }
+ detached, err := testHandler.Queries.DetachLabelFromIssue(ctx, db.DetachLabelFromIssueParams(labelParams))
+ if err != nil || !detached.Changed || detached.IssueRevision != 3 {
+ t.Fatalf("detach label = (%+v, %v), want changed revision 3", detached, err)
+ }
+ detached, err = testHandler.Queries.DetachLabelFromIssue(ctx, db.DetachLabelFromIssueParams(labelParams))
+ if err != nil || detached.Changed || detached.IssueRevision != 0 {
+ t.Fatalf("duplicate label detach = (%+v, %v), want no-op", detached, err)
+ }
+
+ issueReaction := db.AddIssueReactionParams{IssueID: issueUUID, WorkspaceID: workspaceUUID, ActorType: "member", ActorID: userUUID, Emoji: "eyes"}
+ addedIssueReaction, err := testHandler.Queries.AddIssueReaction(ctx, issueReaction)
+ if err != nil || addedIssueReaction.IssueRevision != 4 {
+ t.Fatalf("add issue reaction = (%+v, %v), want revision 4", addedIssueReaction, err)
+ }
+ addedIssueReaction, err = testHandler.Queries.AddIssueReaction(ctx, issueReaction)
+ if err != nil || addedIssueReaction.IssueRevision != 0 {
+ t.Fatalf("duplicate issue reaction = (%+v, %v), want no-op", addedIssueReaction, err)
+ }
+ removedIssueReaction, err := testHandler.Queries.RemoveIssueReaction(ctx, db.RemoveIssueReactionParams{
+ IssueID: issueUUID, ActorType: "member", ActorID: userUUID, Emoji: "eyes",
+ })
+ if err != nil || !removedIssueReaction.Changed || removedIssueReaction.IssueRevision != 5 {
+ t.Fatalf("remove issue reaction = (%+v, %v), want revision 5", removedIssueReaction, err)
+ }
+ removedIssueReaction, err = testHandler.Queries.RemoveIssueReaction(ctx, db.RemoveIssueReactionParams{
+ IssueID: issueUUID, ActorType: "member", ActorID: userUUID, Emoji: "eyes",
+ })
+ if err != nil || removedIssueReaction.Changed || removedIssueReaction.IssueRevision != 0 {
+ t.Fatalf("duplicate issue reaction removal = (%+v, %v), want no-op", removedIssueReaction, err)
+ }
+
+ commentReaction := db.AddReactionParams{CommentID: commentUUID, WorkspaceID: workspaceUUID, ActorType: "member", ActorID: userUUID, Emoji: "thumbs_up"}
+ addedCommentReaction, err := testHandler.Queries.AddReaction(ctx, commentReaction)
+ if err != nil || addedCommentReaction.CommentRevision != 2 {
+ t.Fatalf("add comment reaction = (%+v, %v), want revision 2", addedCommentReaction, err)
+ }
+ addedCommentReaction, err = testHandler.Queries.AddReaction(ctx, commentReaction)
+ if err != nil || addedCommentReaction.CommentRevision != 0 {
+ t.Fatalf("duplicate comment reaction = (%+v, %v), want no-op", addedCommentReaction, err)
+ }
+ removedCommentReaction, err := testHandler.Queries.RemoveReaction(ctx, db.RemoveReactionParams{
+ CommentID: commentUUID, ActorType: "member", ActorID: userUUID, Emoji: "thumbs_up",
+ })
+ if err != nil || !removedCommentReaction.Changed || removedCommentReaction.CommentRevision != 3 {
+ t.Fatalf("remove comment reaction = (%+v, %v), want revision 3", removedCommentReaction, err)
+ }
+ removedCommentReaction, err = testHandler.Queries.RemoveReaction(ctx, db.RemoveReactionParams{
+ CommentID: commentUUID, ActorType: "member", ActorID: userUUID, Emoji: "thumbs_up",
+ })
+ if err != nil || removedCommentReaction.Changed || removedCommentReaction.CommentRevision != 0 {
+ t.Fatalf("duplicate comment reaction removal = (%+v, %v), want no-op", removedCommentReaction, err)
+ }
+
+ attachmentID := uuid.New()
+ createdAttachment, err := testHandler.Queries.CreateAttachment(ctx, db.CreateAttachmentParams{
+ ID: pgtype.UUID{Bytes: attachmentID, Valid: true}, WorkspaceID: workspaceUUID,
+ IssueID: issueUUID, CommentID: commentUUID, UploaderType: "member", UploaderID: userUUID,
+ Filename: "aux.txt", Url: "/aux.txt", ContentType: "text/plain", SizeBytes: 1,
+ })
+ if err != nil || createdAttachment.IssueRevision != 6 || createdAttachment.CommentRevision != 4 {
+ t.Fatalf("create attachment = (%+v, %v), want issue/comment revisions 6/4", createdAttachment, err)
+ }
+ deletedAttachment, err := testHandler.Queries.DeleteAttachment(ctx, db.DeleteAttachmentParams{
+ ID: pgtype.UUID{Bytes: attachmentID, Valid: true}, WorkspaceID: workspaceUUID,
+ })
+ if err != nil || !deletedAttachment.Changed || deletedAttachment.IssueRevision != 7 || deletedAttachment.CommentRevision != 5 {
+ t.Fatalf("delete attachment = (%+v, %v), want issue/comment revisions 7/5", deletedAttachment, err)
+ }
+
+ unboundAttachmentID := pgtype.UUID{Bytes: uuid.New(), Valid: true}
+ if _, err := testHandler.Queries.CreateAttachment(ctx, db.CreateAttachmentParams{
+ ID: unboundAttachmentID, WorkspaceID: workspaceUUID,
+ UploaderType: "member", UploaderID: userUUID,
+ Filename: "linked.txt", Url: "/linked.txt", ContentType: "text/plain", SizeBytes: 1,
+ }); err != nil {
+ t.Fatalf("create unbound attachment: %v", err)
+ }
+ linkedAttachment, err := testHandler.Queries.LinkAttachmentsToIssue(ctx, db.LinkAttachmentsToIssueParams{
+ IssueID: issueUUID, WorkspaceID: workspaceUUID, AttachmentIds: []pgtype.UUID{unboundAttachmentID}, BumpRevision: true,
+ })
+ if err != nil || linkedAttachment.LinkedCount != 1 || linkedAttachment.IssueRevision != 8 {
+ t.Fatalf("link attachment = (%+v, %v), want one link and issue revision 8", linkedAttachment, err)
+ }
+ linkedAttachment, err = testHandler.Queries.LinkAttachmentsToIssue(ctx, db.LinkAttachmentsToIssueParams{
+ IssueID: issueUUID, WorkspaceID: workspaceUUID, AttachmentIds: []pgtype.UUID{unboundAttachmentID}, BumpRevision: true,
+ })
+ if err != nil || linkedAttachment.LinkedCount != 0 || linkedAttachment.IssueRevision != 0 {
+ t.Fatalf("duplicate attachment link = (%+v, %v), want no-op", linkedAttachment, err)
+ }
+
+ metadataParams := db.SetIssueMetadataKeyParams{
+ Key: "revision-test", Value: []byte(`"value"`), ID: issueUUID, WorkspaceID: workspaceUUID,
+ }
+ metadataIssue, err := testHandler.Queries.SetIssueMetadataKey(ctx, metadataParams)
+ if err != nil || metadataIssue.Revision != 9 {
+ t.Fatalf("set metadata = (%+v, %v), want revision 9", metadataIssue, err)
+ }
+ metadataIssue, err = testHandler.Queries.SetIssueMetadataKey(ctx, metadataParams)
+ if err != nil || metadataIssue.Revision != 9 {
+ t.Fatalf("duplicate metadata set = (%+v, %v), want unchanged revision 9", metadataIssue, err)
+ }
+ metadataIssue, err = testHandler.Queries.DeleteIssueMetadataKey(ctx, db.DeleteIssueMetadataKeyParams{
+ Key: metadataParams.Key, ID: issueUUID, WorkspaceID: workspaceUUID,
+ })
+ if err != nil || metadataIssue.Revision != 10 {
+ t.Fatalf("delete metadata = (%+v, %v), want revision 10", metadataIssue, err)
+ }
+
+ propertyParams := db.SetIssuePropertyValueParams{
+ Key: "revision-test", Value: []byte(`42`), ID: issueUUID, WorkspaceID: workspaceUUID,
+ }
+ propertyIssue, err := testHandler.Queries.SetIssuePropertyValue(ctx, propertyParams)
+ if err != nil || propertyIssue.Revision != 11 {
+ t.Fatalf("set property = (%+v, %v), want revision 11", propertyIssue, err)
+ }
+ propertyIssue, err = testHandler.Queries.SetIssuePropertyValue(ctx, propertyParams)
+ if err != nil || propertyIssue.Revision != 11 {
+ t.Fatalf("duplicate property set = (%+v, %v), want unchanged revision 11", propertyIssue, err)
+ }
+ propertyIssue, err = testHandler.Queries.DeleteIssuePropertyValue(ctx, db.DeleteIssuePropertyValueParams{
+ Key: propertyParams.Key, ID: issueUUID, WorkspaceID: workspaceUUID,
+ })
+ if err != nil || propertyIssue.Revision != 12 {
+ t.Fatalf("delete property = (%+v, %v), want revision 12", propertyIssue, err)
+ }
+
+ resolved, err := testHandler.Queries.ResolveComment(ctx, db.ResolveCommentParams{
+ ID: commentUUID, ResolvedByType: pgtype.Text{String: "member", Valid: true}, ResolvedByID: userUUID,
+ })
+ if err != nil || resolved.Revision != 6 {
+ t.Fatalf("resolve comment = (%+v, %v), want revision 6", resolved, err)
+ }
+ resolved, err = testHandler.Queries.ResolveComment(ctx, db.ResolveCommentParams{
+ ID: commentUUID, ResolvedByType: pgtype.Text{String: "member", Valid: true}, ResolvedByID: userUUID,
+ })
+ if err != nil || resolved.Revision != 6 {
+ t.Fatalf("duplicate resolve = (%+v, %v), want unchanged revision 6", resolved, err)
+ }
+ unresolved, err := testHandler.Queries.UnresolveComment(ctx, commentUUID)
+ if err != nil || unresolved.Revision != 7 {
+ t.Fatalf("unresolve comment = (%+v, %v), want revision 7", unresolved, err)
+ }
+ unresolved, err = testHandler.Queries.UnresolveComment(ctx, commentUUID)
+ if err != nil || unresolved.Revision != 7 {
+ t.Fatalf("duplicate unresolve = (%+v, %v), want unchanged revision 7", unresolved, err)
+ }
+
+ statusIssue, err := testHandler.Queries.UpdateIssueStatus(ctx, db.UpdateIssueStatusParams{
+ ID: issueUUID, Status: "in_progress", WorkspaceID: workspaceUUID,
+ })
+ if err != nil || statusIssue.Revision != 13 {
+ t.Fatalf("update status = (%+v, %v), want revision 13", statusIssue, err)
+ }
+ statusIssue, err = testHandler.Queries.UpdateIssueStatus(ctx, db.UpdateIssueStatusParams{
+ ID: issueUUID, Status: "in_progress", WorkspaceID: workspaceUUID,
+ })
+ if err != nil || statusIssue.Revision != 13 {
+ t.Fatalf("duplicate status update = (%+v, %v), want unchanged revision 13", statusIssue, err)
+ }
+}
diff --git a/server/internal/handler/issue_table_rows.go b/server/internal/handler/issue_table_rows.go
index f22ea5834b..db7b22a0d3 100644
--- a/server/internal/handler/issue_table_rows.go
+++ b/server/internal/handler/issue_table_rows.go
@@ -350,6 +350,7 @@ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at,
i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
+ i.revision,
%s AS direct_child_count, i.table_sort_key
FROM page i
ORDER BY %s`, cte, childCountExpr, resolvedSort.orderBy())
@@ -392,6 +393,7 @@ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
&row.issue.Metadata,
&row.issue.Stage,
&row.issue.Properties,
+ &row.issue.Revision,
&row.childCount,
&row.sortKey,
); err != nil {
diff --git a/server/internal/handler/label.go b/server/internal/handler/label.go
index 703870b2ca..324254579e 100644
--- a/server/internal/handler/label.go
+++ b/server/internal/handler/label.go
@@ -408,7 +408,10 @@ func (h *Handler) ListLabelsForIssue(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to list labels")
return
}
- writeJSON(w, http.StatusOK, map[string]any{"labels": labelsToResponse(labels)})
+ writeJSON(w, http.StatusOK, map[string]any{
+ "labels": labelsToResponse(labels),
+ "issue_revision": issue.Revision,
+ })
}
// AttachLabel attaches a label to an issue.
@@ -455,11 +458,12 @@ func (h *Handler) AttachLabel(w http.ResponseWriter, r *http.Request) {
return
}
- if err := h.Queries.AttachLabelToIssue(r.Context(), db.AttachLabelToIssueParams{
+ attached, err := h.Queries.AttachLabelToIssue(r.Context(), db.AttachLabelToIssueParams{
IssueID: issue.ID,
LabelID: labelID,
WorkspaceID: issue.WorkspaceID,
- }); err != nil {
+ })
+ if err != nil {
slog.Warn("AttachLabelToIssue failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to attach label")
return
@@ -475,11 +479,18 @@ func (h *Handler) AttachLabel(w http.ResponseWriter, r *http.Request) {
return
}
resp := labelsToResponse(labels)
- h.publish(protocol.EventIssueLabelsChanged, uuidToString(issue.WorkspaceID), "member", userID, map[string]any{
- "issue_id": uuidToString(issue.ID),
- "labels": resp,
- })
- writeJSON(w, http.StatusOK, map[string]any{"labels": resp})
+ if attached.Changed {
+ h.publish(protocol.EventIssueLabelsChanged, uuidToString(issue.WorkspaceID), "member", userID, map[string]any{
+ "issue_id": uuidToString(issue.ID),
+ "labels": resp,
+ "issue_revision": attached.IssueRevision,
+ })
+ }
+ payload := map[string]any{"labels": resp}
+ if attached.IssueRevision > 0 {
+ payload["issue_revision"] = attached.IssueRevision
+ }
+ writeJSON(w, http.StatusOK, payload)
}
// DetachLabel removes a label from an issue.
@@ -520,11 +531,12 @@ func (h *Handler) DetachLabel(w http.ResponseWriter, r *http.Request) {
return
}
- if err := h.Queries.DetachLabelFromIssue(r.Context(), db.DetachLabelFromIssueParams{
+ detached, err := h.Queries.DetachLabelFromIssue(r.Context(), db.DetachLabelFromIssueParams{
IssueID: issue.ID,
LabelID: labelUUID,
WorkspaceID: issue.WorkspaceID,
- }); err != nil {
+ })
+ if err != nil {
slog.Warn("DetachLabelFromIssue failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to detach label")
return
@@ -536,11 +548,18 @@ func (h *Handler) DetachLabel(w http.ResponseWriter, r *http.Request) {
return
}
resp := labelsToResponse(labels)
- h.publish(protocol.EventIssueLabelsChanged, uuidToString(issue.WorkspaceID), "member", userID, map[string]any{
- "issue_id": uuidToString(issue.ID),
- "labels": resp,
- })
- writeJSON(w, http.StatusOK, map[string]any{"labels": resp})
+ if detached.Changed {
+ h.publish(protocol.EventIssueLabelsChanged, uuidToString(issue.WorkspaceID), "member", userID, map[string]any{
+ "issue_id": uuidToString(issue.ID),
+ "labels": resp,
+ "issue_revision": detached.IssueRevision,
+ })
+ }
+ payload := map[string]any{"labels": resp}
+ if detached.IssueRevision > 0 {
+ payload["issue_revision"] = detached.IssueRevision
+ }
+ writeJSON(w, http.StatusOK, payload)
}
// ---------------------------------------------------------------------------
diff --git a/server/internal/handler/plugin_action.go b/server/internal/handler/plugin_action.go
index 11036e6091..02bf054d0b 100644
--- a/server/internal/handler/plugin_action.go
+++ b/server/internal/handler/plugin_action.go
@@ -313,7 +313,7 @@ func (h *Handler) CreatePluginComment(w http.ResponseWriter, r *http.Request) {
rootComment = &parent
}
- comment, err := h.Queries.CreateComment(r.Context(), db.CreateCommentParams{
+ createdComment, err := h.Queries.CreateComment(r.Context(), db.CreateCommentParams{
IssueID: issue.ID,
WorkspaceID: caller.WorkspaceID,
AuthorType: "member",
@@ -327,6 +327,7 @@ func (h *Handler) CreatePluginComment(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to create the comment")
return
}
+ comment := createdComment.Comment()
// The same two follow-ups every other comment path performs. Skipping them
// made a plugin-posted comment invisible until the next refetch, and left a
diff --git a/server/internal/handler/property.go b/server/internal/handler/property.go
index 2dfae49806..1802a5a2f2 100644
--- a/server/internal/handler/property.go
+++ b/server/internal/handler/property.go
@@ -982,10 +982,11 @@ func (h *Handler) SetIssueProperty(w http.ResponseWriter, r *http.Request) {
actorType, actorID := h.resolveActor(r, userID, workspaceID)
properties := parseIssueProperties(updated.Properties)
h.publish(protocol.EventIssuePropertiesChanged, workspaceID, actorType, actorID, map[string]any{
- "issue_id": uuidToString(updated.ID),
- "properties": properties,
+ "issue_id": uuidToString(updated.ID),
+ "properties": properties,
+ "issue_revision": updated.Revision,
})
- writeJSON(w, http.StatusOK, map[string]any{"properties": properties})
+ writeJSON(w, http.StatusOK, map[string]any{"properties": properties, "issue_revision": updated.Revision})
}
func (h *Handler) DeleteIssueProperty(w http.ResponseWriter, r *http.Request) {
@@ -1032,10 +1033,11 @@ func (h *Handler) DeleteIssueProperty(w http.ResponseWriter, r *http.Request) {
actorType, actorID := h.resolveActor(r, userID, workspaceID)
properties := parseIssueProperties(updated.Properties)
h.publish(protocol.EventIssuePropertiesChanged, workspaceID, actorType, actorID, map[string]any{
- "issue_id": uuidToString(updated.ID),
- "properties": properties,
+ "issue_id": uuidToString(updated.ID),
+ "properties": properties,
+ "issue_revision": updated.Revision,
})
- writeJSON(w, http.StatusOK, map[string]any{"properties": properties})
+ writeJSON(w, http.StatusOK, map[string]any{"properties": properties, "issue_revision": updated.Revision})
}
// withPropertyLock runs fn inside a transaction holding the advisory lock
diff --git a/server/internal/handler/quick_action.go b/server/internal/handler/quick_action.go
index 45e7f6bab9..8246e42e92 100644
--- a/server/internal/handler/quick_action.go
+++ b/server/internal/handler/quick_action.go
@@ -885,7 +885,7 @@ func (h *Handler) RunQuickAction(w http.ResponseWriter, r *http.Request) {
body := sanitizeNullBytes(buildQuickActionBody(qa, target))
- comment, err := h.Queries.CreateComment(r.Context(), db.CreateCommentParams{
+ created, err := h.Queries.CreateComment(r.Context(), db.CreateCommentParams{
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
AuthorType: actorType,
@@ -903,14 +903,17 @@ func (h *Handler) RunQuickAction(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to run quick action")
return
}
+ comment := created.Comment()
resp := commentToResponse(comment, nil, nil)
+ resp.IssueRevision = created.IssueRevision
h.publish(protocol.EventCommentCreated, workspaceID, actorType, actorID, map[string]any{
"comment": resp,
"issue_title": issue.Title,
"issue_assignee_type": textToPtr(issue.AssigneeType),
"issue_assignee_id": uuidToPtr(issue.AssigneeID),
"issue_status": issue.Status,
+ "issue_revision": created.IssueRevision,
})
delegationAuthority := h.autopilotDelegationAuthorityFromRequest(r, issue, actorType, actorID)
diff --git a/server/internal/handler/reaction.go b/server/internal/handler/reaction.go
index 26e23d657e..a40834e71c 100644
--- a/server/internal/handler/reaction.go
+++ b/server/internal/handler/reaction.go
@@ -13,12 +13,13 @@ import (
)
type ReactionResponse struct {
- ID string `json:"id"`
- CommentID string `json:"comment_id"`
- ActorType string `json:"actor_type"`
- ActorID string `json:"actor_id"`
- Emoji string `json:"emoji"`
- CreatedAt string `json:"created_at"`
+ ID string `json:"id"`
+ CommentID string `json:"comment_id"`
+ ActorType string `json:"actor_type"`
+ ActorID string `json:"actor_id"`
+ Emoji string `json:"emoji"`
+ CreatedAt string `json:"created_at"`
+ CommentRevision *int64 `json:"comment_revision,omitempty"`
}
func reactionToResponse(r db.CommentReaction) ReactionResponse {
@@ -32,6 +33,21 @@ func reactionToResponse(r db.CommentReaction) ReactionResponse {
}
}
+func addedReactionToResponse(r db.AddReactionRow) ReactionResponse {
+ response := ReactionResponse{
+ ID: uuidToString(r.ID),
+ CommentID: uuidToString(r.CommentID),
+ ActorType: r.ActorType,
+ ActorID: uuidToString(r.ActorID),
+ Emoji: r.Emoji,
+ CreatedAt: timestampToString(r.CreatedAt),
+ }
+ if r.CommentRevision > 0 {
+ response.CommentRevision = &r.CommentRevision
+ }
+ return response
+}
+
func (h *Handler) AddReaction(w http.ResponseWriter, r *http.Request) {
commentId := chi.URLParam(r, "commentId")
@@ -85,7 +101,7 @@ func (h *Handler) AddReaction(w http.ResponseWriter, r *http.Request) {
return
}
- resp := reactionToResponse(reaction)
+ resp := addedReactionToResponse(reaction)
// Look up issue title for inbox notifications.
issueID := uuidToString(comment.IssueID)
@@ -95,15 +111,18 @@ func (h *Handler) AddReaction(w http.ResponseWriter, r *http.Request) {
issueStatus = issue.Status
}
- h.publish(protocol.EventReactionAdded, workspaceID, actorType, actorID, map[string]any{
- "reaction": resp,
- "issue_id": issueID,
- "issue_title": issueTitle,
- "issue_status": issueStatus,
- "comment_id": uuidToString(comment.ID),
- "comment_author_type": comment.AuthorType,
- "comment_author_id": uuidToString(comment.AuthorID),
- })
+ if reaction.CommentRevision > 0 {
+ h.publish(protocol.EventReactionAdded, workspaceID, actorType, actorID, map[string]any{
+ "reaction": resp,
+ "issue_id": issueID,
+ "issue_title": issueTitle,
+ "issue_status": issueStatus,
+ "comment_id": uuidToString(comment.ID),
+ "comment_author_type": comment.AuthorType,
+ "comment_author_id": uuidToString(comment.AuthorID),
+ "comment_revision": reaction.CommentRevision,
+ })
+ }
writeJSON(w, http.StatusCreated, resp)
}
@@ -147,24 +166,28 @@ func (h *Handler) RemoveReaction(w http.ResponseWriter, r *http.Request) {
actorType, actorID := h.resolveActor(r, userID, workspaceID)
- if err := h.Queries.RemoveReaction(r.Context(), db.RemoveReactionParams{
+ removed, err := h.Queries.RemoveReaction(r.Context(), db.RemoveReactionParams{
CommentID: comment.ID,
ActorType: actorType,
ActorID: parseUUID(actorID),
Emoji: req.Emoji,
- }); err != nil {
+ })
+ 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")
return
}
- h.publish(protocol.EventReactionRemoved, workspaceID, actorType, actorID, map[string]any{
- "comment_id": uuidToString(comment.ID),
- "issue_id": uuidToString(comment.IssueID),
- "emoji": req.Emoji,
- "actor_type": actorType,
- "actor_id": actorID,
- })
+ if removed.Changed {
+ h.publish(protocol.EventReactionRemoved, workspaceID, actorType, actorID, map[string]any{
+ "comment_id": uuidToString(comment.ID),
+ "issue_id": uuidToString(comment.IssueID),
+ "emoji": req.Emoji,
+ "actor_type": actorType,
+ "actor_id": actorID,
+ "comment_revision": removed.CommentRevision,
+ })
+ }
w.WriteHeader(http.StatusNoContent)
}
diff --git a/server/internal/handler/runtime_unusable_notice.go b/server/internal/handler/runtime_unusable_notice.go
index f4fc3c78d7..f8ec291d5f 100644
--- a/server/internal/handler/runtime_unusable_notice.go
+++ b/server/internal/handler/runtime_unusable_notice.go
@@ -26,7 +26,7 @@ func (h *Handler) noteRuntimeUnusable(ctx context.Context, issue db.Issue, agent
content := service.RuntimeUnusableNotice(agent.Name, verdict)
// author_type='system', author_id=zero UUID — same shape as the sub-issue
// completion notice; clients branch on author_type, not the UUID value.
- comment, err := h.Queries.CreateComment(ctx, db.CreateCommentParams{
+ created, err := h.Queries.CreateComment(ctx, db.CreateCommentParams{
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
AuthorType: "system",
@@ -42,11 +42,13 @@ func (h *Handler) noteRuntimeUnusable(ctx context.Context, issue db.Issue, agent
"agent_id", uuidToString(agent.ID))
return
}
+ comment := created.Comment()
h.publish(protocol.EventCommentCreated, uuidToString(issue.WorkspaceID), "system", "", map[string]any{
"comment": commentToResponse(comment, nil, nil),
"issue_title": issue.Title,
"issue_assignee_type": textToPtr(issue.AssigneeType),
"issue_assignee_id": uuidToPtr(issue.AssigneeID),
"issue_status": issue.Status,
+ "issue_revision": created.IssueRevision,
})
}
diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.go
index e34d0290ff..489404de7e 100644
--- a/server/internal/integrations/channel/engine/session.go
+++ b/server/internal/integrations/channel/engine/session.go
@@ -100,7 +100,8 @@ func (a dbSessionQueries) MaterializeIssueChannelMediaMarkdown(ctx context.Conte
return a.q.MaterializeIssueChannelMediaMarkdown(ctx, arg)
}
func (a dbSessionQueries) CreateAttachment(ctx context.Context, arg db.CreateAttachmentParams) (db.Attachment, error) {
- return a.q.CreateAttachment(ctx, arg)
+ created, err := a.q.CreateAttachment(ctx, arg)
+ return created.Attachment(), err
}
func (a dbSessionQueries) LinkAttachmentsToChatMessage(ctx context.Context, arg db.LinkAttachmentsToChatMessageParams) ([]pgtype.UUID, error) {
return a.q.LinkAttachmentsToChatMessage(ctx, arg)
diff --git a/server/internal/migrations/issue_comment_revision_migration_test.go b/server/internal/migrations/issue_comment_revision_migration_test.go
new file mode 100644
index 0000000000..5259bd3521
--- /dev/null
+++ b/server/internal/migrations/issue_comment_revision_migration_test.go
@@ -0,0 +1,126 @@
+package migrations
+
+import (
+ "context"
+ "os"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+const issueCommentRevisionMigrationTestSchema = "issue_comment_revision_migration_test"
+
+func TestIssueCommentRevisionMigrationUpDownPreservesData(t *testing.T) {
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ t.Skip("integration test requires Postgres at DATABASE_URL")
+ }
+
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ t.Fatalf("connect to Postgres: %v", err)
+ }
+ defer pool.Close()
+
+ conn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire Postgres connection: %v", err)
+ }
+ defer conn.Release()
+
+ cleanup := func() {
+ _, _ = pool.Exec(context.Background(), "DROP SCHEMA IF EXISTS "+issueCommentRevisionMigrationTestSchema+" CASCADE")
+ }
+ cleanup()
+ t.Cleanup(cleanup)
+ if _, err := conn.Exec(ctx, "CREATE SCHEMA "+issueCommentRevisionMigrationTestSchema); err != nil {
+ t.Fatalf("create isolated migration schema: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `SELECT set_config('search_path', $1, false)`, issueCommentRevisionMigrationTestSchema); err != nil {
+ t.Fatalf("set isolated migration search path: %v", err)
+ }
+
+ if _, err := conn.Exec(ctx, `
+ CREATE TABLE issue (id TEXT PRIMARY KEY, title TEXT NOT NULL);
+ CREATE TABLE comment (id TEXT PRIMARY KEY, issue_id TEXT NOT NULL, content TEXT NOT NULL);
+ INSERT INTO issue (id, title) VALUES ('issue-1', 'Original title');
+ INSERT INTO comment (id, issue_id, content) VALUES ('comment-1', 'issue-1', 'Original comment');
+ `); err != nil {
+ t.Fatalf("create pre-migration fixtures: %v", err)
+ }
+
+ applyMigrationFile(t, ctx, conn.Conn(), "351_issue_comment_revision.up.sql")
+ assertRevisionColumn(t, ctx, conn.Conn(), "issue")
+ assertRevisionColumn(t, ctx, conn.Conn(), "comment")
+ assertRevisionValues(t, ctx, conn.Conn(), 1, 1)
+
+ if _, err := conn.Exec(ctx, `
+ INSERT INTO issue (id, title) VALUES ('issue-2', 'Post-migration title');
+ INSERT INTO comment (id, issue_id, content) VALUES ('comment-2', 'issue-2', 'Post-migration comment');
+ `); err != nil {
+ t.Fatalf("insert rows using revision defaults: %v", err)
+ }
+ assertRevisionValues(t, ctx, conn.Conn(), 2, 2)
+
+ applyMigrationFile(t, ctx, conn.Conn(), "351_issue_comment_revision.down.sql")
+ assertRevisionColumnMissing(t, ctx, conn.Conn(), "issue")
+ assertRevisionColumnMissing(t, ctx, conn.Conn(), "comment")
+
+ var issueCount, commentCount int
+ if err := conn.QueryRow(ctx, `SELECT (SELECT count(*) FROM issue), (SELECT count(*) FROM comment)`).Scan(&issueCount, &commentCount); err != nil {
+ t.Fatalf("count rows after down migration: %v", err)
+ }
+ if issueCount != 2 || commentCount != 2 {
+ t.Fatalf("row counts after down migration = (%d, %d), want (2, 2)", issueCount, commentCount)
+ }
+
+ applyMigrationFile(t, ctx, conn.Conn(), "351_issue_comment_revision.up.sql")
+ assertRevisionValues(t, ctx, conn.Conn(), 2, 2)
+}
+
+func assertRevisionColumn(t *testing.T, ctx context.Context, conn *pgx.Conn, table string) {
+ t.Helper()
+ var nullable, defaultValue string
+ if err := conn.QueryRow(ctx, `
+ SELECT is_nullable, column_default
+ FROM information_schema.columns
+ WHERE table_schema = $1 AND table_name = $2 AND column_name = 'revision'
+ `, issueCommentRevisionMigrationTestSchema, table).Scan(&nullable, &defaultValue); err != nil {
+ t.Fatalf("inspect %s.revision: %v", table, err)
+ }
+ if nullable != "NO" || defaultValue != "1" {
+ t.Fatalf("%s.revision metadata = (nullable %s, default %s), want (NO, 1)", table, nullable, defaultValue)
+ }
+}
+
+func assertRevisionColumnMissing(t *testing.T, ctx context.Context, conn *pgx.Conn, table string) {
+ t.Helper()
+ var count int
+ if err := conn.QueryRow(ctx, `
+ SELECT count(*)
+ FROM information_schema.columns
+ WHERE table_schema = $1 AND table_name = $2 AND column_name = 'revision'
+ `, issueCommentRevisionMigrationTestSchema, table).Scan(&count); err != nil {
+ t.Fatalf("inspect missing %s.revision: %v", table, err)
+ }
+ if count != 0 {
+ t.Fatalf("%s.revision still exists after down migration", table)
+ }
+}
+
+func assertRevisionValues(t *testing.T, ctx context.Context, conn *pgx.Conn, wantIssues, wantComments int) {
+ t.Helper()
+ var issues, comments int
+ if err := conn.QueryRow(ctx, `
+ SELECT
+ (SELECT count(*) FROM issue WHERE revision = 1),
+ (SELECT count(*) FROM comment WHERE revision = 1)
+ `).Scan(&issues, &comments); err != nil {
+ t.Fatalf("read revision values: %v", err)
+ }
+ if issues != wantIssues || comments != wantComments {
+ t.Fatalf("revision=1 counts = (%d, %d), want (%d, %d)", issues, comments, wantIssues, wantComments)
+ }
+}
diff --git a/server/internal/service/issue.go b/server/internal/service/issue.go
index 04d4eb046d..1268d4464b 100644
--- a/server/internal/service/issue.go
+++ b/server/internal/service/issue.go
@@ -347,7 +347,7 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Iss
// workspace/resource_type-guarded and ON CONFLICT DO NOTHING, and the
// ids were already validated above.
for _, label := range labels {
- if err := qtx.AttachLabelToIssue(ctx, db.AttachLabelToIssueParams{
+ if err := qtx.AttachLabelToIssueOnCreate(ctx, db.AttachLabelToIssueOnCreateParams{
IssueID: issue.ID,
LabelID: label.ID,
WorkspaceID: p.WorkspaceID,
@@ -460,10 +460,11 @@ func (s *IssueService) linkAttachments(ctx context.Context, issue db.Issue, ids
if len(ids) == 0 {
return nil
}
- if err := s.Queries.LinkAttachmentsToIssue(ctx, db.LinkAttachmentsToIssueParams{
- IssueID: issue.ID,
- WorkspaceID: issue.WorkspaceID,
- Column3: ids,
+ if _, err := s.Queries.LinkAttachmentsToIssue(ctx, db.LinkAttachmentsToIssueParams{
+ IssueID: issue.ID,
+ WorkspaceID: issue.WorkspaceID,
+ AttachmentIds: ids,
+ BumpRevision: false,
}); err != nil {
slog.Error("failed to link attachments to issue",
"issue_id", util.UUIDToString(issue.ID),
@@ -515,16 +516,8 @@ func (s *IssueService) PublishAttachmentsChanged(ctx context.Context, issue db.I
if s.Bus == nil {
return
}
- s.Bus.Publish(events.Event{
- Type: protocol.EventIssueAttachmentsChanged,
- WorkspaceID: util.UUIDToString(issue.WorkspaceID),
- ActorType: "member",
- ActorID: util.UUIDToString(actorID),
- Payload: map[string]any{
- "issue_id": util.UUIDToString(issue.ID),
- },
- })
if s.Queries == nil {
+ s.publishIssueAttachmentsChanged(issue, actorID, 0)
return
}
@@ -535,12 +528,17 @@ func (s *IssueService) PublishAttachmentsChanged(ctx context.Context, issue db.I
if err != nil {
slog.Warn("failed to load issue after channel media bind",
"issue_id", util.UUIDToString(issue.ID), "error", err)
+ s.publishIssueAttachmentsChanged(issue, actorID, 0)
return
}
workspace, err := s.Queries.GetWorkspace(ctx, issue.WorkspaceID)
if err != nil {
slog.Warn("failed to load workspace after channel media bind",
"workspace_id", util.UUIDToString(issue.WorkspaceID), "error", err)
+ // Without the workspace we cannot publish the matching owner snapshot.
+ // Keep this auxiliary event unversioned so clients invalidate instead of
+ // advancing the owner revision past a snapshot they never received.
+ s.publishIssueAttachmentsChanged(issue, actorID, 0)
return
}
s.Bus.Publish(events.Event{
@@ -555,6 +553,24 @@ func (s *IssueService) PublishAttachmentsChanged(ctx context.Context, issue db.I
"project_changed": false,
},
})
+ // Publish the auxiliary projection only after the full owner snapshot at
+ // this revision. Reversing these two events makes revision-aware clients
+ // reject the issue:updated payload as an equal-revision duplicate.
+ s.publishIssueAttachmentsChanged(current, actorID, current.Revision)
+}
+
+func (s *IssueService) publishIssueAttachmentsChanged(issue db.Issue, actorID pgtype.UUID, revision int64) {
+ payload := map[string]any{"issue_id": util.UUIDToString(issue.ID)}
+ if revision > 0 {
+ payload["issue_revision"] = revision
+ }
+ s.Bus.Publish(events.Event{
+ Type: protocol.EventIssueAttachmentsChanged,
+ WorkspaceID: util.UUIDToString(issue.WorkspaceID),
+ ActorType: "member",
+ ActorID: util.UUIDToString(actorID),
+ Payload: payload,
+ })
}
func (s *IssueService) captureCreatedAnalytics(issue db.Issue, creatorType, actorID string, opts IssueCreateOpts) {
diff --git a/server/internal/service/issue_channel_media_test.go b/server/internal/service/issue_channel_media_test.go
index 587aae36dd..7060161318 100644
--- a/server/internal/service/issue_channel_media_test.go
+++ b/server/internal/service/issue_channel_media_test.go
@@ -88,7 +88,13 @@ func TestPublishAttachmentsChangedAlsoBroadcastsUpdatedDescription(t *testing.T)
bus := events.New()
svc := &IssueService{Bus: bus, Queries: q}
var updated events.Event
+ var ordered []events.Event
bus.Subscribe(protocol.EventIssueUpdated, func(e events.Event) { updated = e })
+ bus.SubscribeAll(func(e events.Event) {
+ if e.Type == protocol.EventIssueUpdated || e.Type == protocol.EventIssueAttachmentsChanged {
+ ordered = append(ordered, e)
+ }
+ })
svc.PublishAttachmentsChanged(ctx, issue, actorID)
@@ -112,6 +118,13 @@ func TestPublishAttachmentsChangedAlsoBroadcastsUpdatedDescription(t *testing.T)
t.Fatalf("%s = %#v, want false", key, payload[key])
}
}
+ if len(ordered) != 2 || ordered[0].Type != protocol.EventIssueUpdated || ordered[1].Type != protocol.EventIssueAttachmentsChanged {
+ t.Fatalf("event order = %#v, want issue:updated then issue_attachments:changed", ordered)
+ }
+ attachmentPayload, ok := ordered[1].Payload.(map[string]any)
+ if !ok || attachmentPayload["issue_revision"] != issue.Revision {
+ t.Fatalf("attachment event payload = %#v, want revision %d", ordered[1].Payload, issue.Revision)
+ }
}
func TestCreateMediaGatedIssueCommitsDeferredTaskAtomicallyBeforeCreatedEvent(t *testing.T) {
diff --git a/server/internal/service/runtime_unusable_notice.go b/server/internal/service/runtime_unusable_notice.go
index 7a87458e57..aed1556d91 100644
--- a/server/internal/service/runtime_unusable_notice.go
+++ b/server/internal/service/runtime_unusable_notice.go
@@ -28,7 +28,7 @@ func (s *IssueService) noteRuntimeUnusable(ctx context.Context, issue db.Issue,
}
// author_type='system', author_id=zero UUID. The zero UUID is a valid 16
// byte value and the column is NOT NULL; clients branch on author_type.
- comment, err := s.Queries.CreateComment(ctx, db.CreateCommentParams{
+ created, err := s.Queries.CreateComment(ctx, db.CreateCommentParams{
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
AuthorType: "system",
@@ -42,6 +42,7 @@ func (s *IssueService) noteRuntimeUnusable(ctx context.Context, issue db.Issue,
"error", err, "issue_id", util.UUIDToString(issue.ID))
return
}
+ comment := created.Comment()
if s.Bus == nil {
return
}
@@ -57,8 +58,10 @@ func (s *IssueService) noteRuntimeUnusable(ctx context.Context, issue db.Issue,
"author_id": util.UUIDToString(comment.AuthorID),
"content": comment.Content,
"type": comment.Type,
+ "revision": comment.Revision,
},
- "issue_title": issue.Title,
+ "issue_title": issue.Title,
+ "issue_revision": created.IssueRevision,
},
})
}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index ea7d1685b1..a58545dbd9 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -5069,7 +5069,7 @@ func (s *TaskService) ensureDelegatedFailureRecoveryComment(ctx context.Context,
if !errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("find recovery comment: %w", err)
}
- comment, err = qtx.CreateComment(ctx, db.CreateCommentParams{
+ createdComment, err := qtx.CreateComment(ctx, db.CreateCommentParams{
IssueID: target.issue.ID,
WorkspaceID: target.issue.WorkspaceID,
AuthorType: "system",
@@ -5081,7 +5081,7 @@ func (s *TaskService) ensureDelegatedFailureRecoveryComment(ctx context.Context,
if err != nil {
return fmt.Errorf("create recovery comment: %w", err)
}
- target.comment = comment
+ target.comment = createdComment.Comment()
created = true
return nil
}); err != nil {
@@ -5174,7 +5174,7 @@ func (s *TaskService) exhaustDelegatedFailureRecovery(ctx context.Context, targe
return fmt.Errorf("find delegated failure exhaustion comment: %w", err)
}
- comment, err = qtx.CreateComment(ctx, db.CreateCommentParams{
+ createdComment, err := qtx.CreateComment(ctx, db.CreateCommentParams{
IssueID: target.issue.ID,
WorkspaceID: target.issue.WorkspaceID,
AuthorType: "system",
@@ -5186,7 +5186,7 @@ func (s *TaskService) exhaustDelegatedFailureRecovery(ctx context.Context, targe
if err != nil {
return fmt.Errorf("create delegated failure exhaustion comment: %w", err)
}
- exhaustedComment = comment
+ exhaustedComment = createdComment.Comment()
created = true
// Exhaustion deliberately does not @mention the coordinator agent: doing
@@ -6015,7 +6015,7 @@ func (s *TaskService) createAgentComment(ctx context.Context, issueID, agentID p
rootComment = &root
}
}
- comment, err := s.Queries.CreateComment(ctx, db.CreateCommentParams{
+ created, err := s.Queries.CreateComment(ctx, db.CreateCommentParams{
IssueID: issueID,
WorkspaceID: issue.WorkspaceID,
AuthorType: "agent",
@@ -6028,6 +6028,7 @@ func (s *TaskService) createAgentComment(ctx context.Context, issueID, agentID p
if err != nil {
return
}
+ comment := created.Comment()
s.CancelDeferredEscalationsForIssueAgent(ctx, issueID, agentID)
s.Bus.Publish(events.Event{
Type: protocol.EventCommentCreated,
@@ -6045,9 +6046,11 @@ func (s *TaskService) createAgentComment(ctx context.Context, issueID, agentID p
"parent_id": util.UUIDToPtr(comment.ParentID),
"source_task_id": util.UUIDToPtr(comment.SourceTaskID),
"created_at": comment.CreatedAt.Time.Format("2006-01-02T15:04:05Z"),
+ "revision": comment.Revision,
},
- "issue_title": issue.Title,
- "issue_status": issue.Status,
+ "issue_title": issue.Title,
+ "issue_status": issue.Status,
+ "issue_revision": created.IssueRevision,
},
})
s.AutoUnresolveThreadOnReply(ctx, rootComment, util.UUIDToString(issue.WorkspaceID), "agent", util.UUIDToString(agentID))
@@ -6087,6 +6090,7 @@ func (s *TaskService) AutoUnresolveThreadOnReply(ctx context.Context, parent *db
"resolved_at": util.TimestampToPtr(updated.ResolvedAt),
"resolved_by_type": util.TextToPtr(updated.ResolvedByType),
"resolved_by_id": util.UUIDToPtr(updated.ResolvedByID),
+ "revision": updated.Revision,
},
},
})
@@ -6152,6 +6156,7 @@ func IssueToMap(issue db.Issue, issuePrefix string) map[string]any {
"due_date": util.DateToPtr(issue.DueDate),
"created_at": util.TimestampToString(issue.CreatedAt),
"updated_at": util.TimestampToString(issue.UpdatedAt),
+ "revision": issue.Revision,
"metadata": util.JSONObjectOrEmpty(issue.Metadata),
"properties": util.JSONObjectOrEmpty(issue.Properties),
}
diff --git a/server/migrations/351_issue_comment_revision.down.sql b/server/migrations/351_issue_comment_revision.down.sql
new file mode 100644
index 0000000000..ad89c6ba1d
--- /dev/null
+++ b/server/migrations/351_issue_comment_revision.down.sql
@@ -0,0 +1,5 @@
+ALTER TABLE comment
+ DROP COLUMN IF EXISTS revision;
+
+ALTER TABLE issue
+ DROP COLUMN IF EXISTS revision;
diff --git a/server/migrations/351_issue_comment_revision.up.sql b/server/migrations/351_issue_comment_revision.up.sql
new file mode 100644
index 0000000000..bc58421142
--- /dev/null
+++ b/server/migrations/351_issue_comment_revision.up.sql
@@ -0,0 +1,5 @@
+ALTER TABLE issue
+ ADD COLUMN revision BIGINT NOT NULL DEFAULT 1;
+
+ALTER TABLE comment
+ ADD COLUMN revision BIGINT NOT NULL DEFAULT 1;
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 55b2ae616e..b17561cd13 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -5197,7 +5197,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
+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
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
@@ -5282,6 +5282,7 @@ func (q *Queries) ListPendingDelegatedFailureRecoveries(ctx context.Context, max
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/attachment.sql.go b/server/pkg/db/generated/attachment.sql.go
index fe56bb8cb4..077ab0afac 100644
--- a/server/pkg/db/generated/attachment.sql.go
+++ b/server/pkg/db/generated/attachment.sql.go
@@ -77,15 +77,31 @@ func (q *Queries) CountUnboundChatAttachmentsForTask(ctx context.Context, arg Co
}
const createAttachment = `-- name: CreateAttachment :one
-INSERT INTO attachment (
- id, workspace_id, issue_id, comment_id, chat_session_id, task_id,
- uploader_type, uploader_id, filename, url, content_type, size_bytes
-)
-VALUES (
- $1, $2, $9, $10, $11, $12,
- $3, $4, $5, $6, $7, $8
+WITH inserted AS (
+ INSERT INTO attachment (
+ id, workspace_id, issue_id, comment_id, chat_session_id, task_id,
+ uploader_type, uploader_id, filename, url, content_type, size_bytes
+ )
+ VALUES (
+ $1, $2, $9, $10, $11, $12,
+ $3, $4, $5, $6, $7, $8
+ )
+ RETURNING 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
+), bumped_issue AS (
+ UPDATE issue
+ SET revision = revision + 1
+ WHERE id IN (SELECT issue_id FROM inserted WHERE issue_id IS NOT NULL)
+ RETURNING revision
+), bumped_comment AS (
+ UPDATE comment
+ SET revision = revision + 1
+ WHERE id IN (SELECT comment_id FROM inserted WHERE comment_id IS NOT NULL)
+ RETURNING revision
)
-RETURNING 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
+SELECT inserted.id, inserted.workspace_id, inserted.issue_id, inserted.comment_id, inserted.uploader_type, inserted.uploader_id, inserted.filename, inserted.url, inserted.content_type, inserted.size_bytes, inserted.created_at, inserted.chat_session_id, inserted.chat_message_id, inserted.task_id,
+ COALESCE((SELECT revision FROM bumped_issue), 0)::bigint AS issue_revision,
+ COALESCE((SELECT revision FROM bumped_comment), 0)::bigint AS comment_revision
+FROM inserted
`
type CreateAttachmentParams struct {
@@ -103,7 +119,26 @@ type CreateAttachmentParams struct {
TaskID pgtype.UUID `json:"task_id"`
}
-func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (Attachment, error) {
+type CreateAttachmentRow struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ CommentID pgtype.UUID `json:"comment_id"`
+ UploaderType string `json:"uploader_type"`
+ UploaderID pgtype.UUID `json:"uploader_id"`
+ Filename string `json:"filename"`
+ Url string `json:"url"`
+ ContentType string `json:"content_type"`
+ SizeBytes int64 `json:"size_bytes"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ ChatMessageID pgtype.UUID `json:"chat_message_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ IssueRevision int64 `json:"issue_revision"`
+ CommentRevision int64 `json:"comment_revision"`
+}
+
+func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (CreateAttachmentRow, error) {
row := q.db.QueryRow(ctx, createAttachment,
arg.ID,
arg.WorkspaceID,
@@ -118,7 +153,7 @@ func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentPara
arg.ChatSessionID,
arg.TaskID,
)
- var i Attachment
+ var i CreateAttachmentRow
err := row.Scan(
&i.ID,
&i.WorkspaceID,
@@ -134,12 +169,31 @@ func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentPara
&i.ChatSessionID,
&i.ChatMessageID,
&i.TaskID,
+ &i.IssueRevision,
+ &i.CommentRevision,
)
return i, err
}
-const deleteAttachment = `-- name: DeleteAttachment :exec
-DELETE FROM attachment WHERE id = $1 AND workspace_id = $2
+const deleteAttachment = `-- name: DeleteAttachment :one
+WITH deleted AS (
+ DELETE FROM attachment
+ WHERE attachment.id = $1 AND attachment.workspace_id = $2
+ RETURNING issue_id, comment_id
+), bumped_issue AS (
+ UPDATE issue
+ SET revision = revision + 1
+ WHERE id IN (SELECT issue_id FROM deleted WHERE issue_id IS NOT NULL)
+ RETURNING revision
+), bumped_comment AS (
+ UPDATE comment
+ SET revision = revision + 1
+ WHERE id IN (SELECT comment_id FROM deleted WHERE comment_id IS NOT NULL)
+ RETURNING revision
+)
+SELECT EXISTS(SELECT 1 FROM deleted) AS changed,
+ COALESCE((SELECT revision FROM bumped_issue), 0)::bigint AS issue_revision,
+ COALESCE((SELECT revision FROM bumped_comment), 0)::bigint AS comment_revision
`
type DeleteAttachmentParams struct {
@@ -147,9 +201,17 @@ type DeleteAttachmentParams struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
}
-func (q *Queries) DeleteAttachment(ctx context.Context, arg DeleteAttachmentParams) error {
- _, err := q.db.Exec(ctx, deleteAttachment, arg.ID, arg.WorkspaceID)
- return err
+type DeleteAttachmentRow struct {
+ Changed bool `json:"changed"`
+ IssueRevision int64 `json:"issue_revision"`
+ CommentRevision int64 `json:"comment_revision"`
+}
+
+func (q *Queries) DeleteAttachment(ctx context.Context, arg DeleteAttachmentParams) (DeleteAttachmentRow, error) {
+ row := q.db.QueryRow(ctx, deleteAttachment, arg.ID, arg.WorkspaceID)
+ var i DeleteAttachmentRow
+ err := row.Scan(&i.Changed, &i.IssueRevision, &i.CommentRevision)
+ return i, err
}
const detachAttachmentsFromUserChatMessageByTask = `-- name: DetachAttachmentsFromUserChatMessageByTask :many
@@ -339,23 +401,50 @@ func (q *Queries) LinkAttachmentsToComment(ctx context.Context, arg LinkAttachme
return err
}
-const linkAttachmentsToIssue = `-- name: LinkAttachmentsToIssue :exec
-UPDATE attachment
-SET issue_id = $1
-WHERE workspace_id = $2
- AND issue_id IS NULL
- AND id = ANY($3::uuid[])
+const linkAttachmentsToIssue = `-- name: LinkAttachmentsToIssue :one
+WITH linked AS (
+ UPDATE attachment
+ SET issue_id = $1
+ WHERE attachment.workspace_id = $2
+ AND attachment.issue_id IS NULL
+ AND attachment.id = ANY($3::uuid[])
+ RETURNING attachment.issue_id
+), bumped_issue AS (
+ UPDATE issue
+ SET revision = revision + 1,
+ updated_at = now()
+ WHERE id = $1
+ AND $4::boolean
+ AND EXISTS (SELECT 1 FROM linked)
+ RETURNING revision
+)
+SELECT COUNT(*)::bigint AS linked_count,
+ COALESCE((SELECT revision FROM bumped_issue), 0)::bigint AS issue_revision
+FROM linked
`
type LinkAttachmentsToIssueParams struct {
- IssueID pgtype.UUID `json:"issue_id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- Column3 []pgtype.UUID `json:"column_3"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AttachmentIds []pgtype.UUID `json:"attachment_ids"`
+ BumpRevision bool `json:"bump_revision"`
}
-func (q *Queries) LinkAttachmentsToIssue(ctx context.Context, arg LinkAttachmentsToIssueParams) error {
- _, err := q.db.Exec(ctx, linkAttachmentsToIssue, arg.IssueID, arg.WorkspaceID, arg.Column3)
- return err
+type LinkAttachmentsToIssueRow struct {
+ LinkedCount int64 `json:"linked_count"`
+ IssueRevision int64 `json:"issue_revision"`
+}
+
+func (q *Queries) LinkAttachmentsToIssue(ctx context.Context, arg LinkAttachmentsToIssueParams) (LinkAttachmentsToIssueRow, error) {
+ row := q.db.QueryRow(ctx, linkAttachmentsToIssue,
+ arg.IssueID,
+ arg.WorkspaceID,
+ arg.AttachmentIds,
+ arg.BumpRevision,
+ )
+ var i LinkAttachmentsToIssueRow
+ err := row.Scan(&i.LinkedCount, &i.IssueRevision)
+ return i, err
}
const listAttachmentURLsByCommentID = `-- name: ListAttachmentURLsByCommentID :many
@@ -685,7 +774,44 @@ func (q *Queries) ListAttachmentsByIssue(ctx context.Context, arg ListAttachment
return items, nil
}
-const replaceCommentAttachments = `-- name: ReplaceCommentAttachments :exec
+const lockAttachmentsForIssueLink = `-- name: LockAttachmentsForIssueLink :many
+SELECT id FROM attachment
+WHERE workspace_id = $1
+ AND issue_id IS NULL
+ AND id = ANY($2::uuid[])
+ORDER BY id
+FOR UPDATE
+`
+
+type LockAttachmentsForIssueLinkParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ 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.
+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 {
+ 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 replaceCommentAttachments = `-- name: ReplaceCommentAttachments :execrows
UPDATE attachment
SET comment_id = CASE
WHEN id = ANY($3::uuid[]) THEN $1
@@ -693,7 +819,7 @@ SET comment_id = CASE
END
WHERE issue_id = $2
AND (
- comment_id = $1
+ (comment_id = $1 AND NOT id = ANY($3::uuid[]))
OR (comment_id IS NULL AND id = ANY($3::uuid[]))
)
`
@@ -704,7 +830,10 @@ type ReplaceCommentAttachmentsParams struct {
AttachmentIds []pgtype.UUID `json:"attachment_ids"`
}
-func (q *Queries) ReplaceCommentAttachments(ctx context.Context, arg ReplaceCommentAttachmentsParams) error {
- _, err := q.db.Exec(ctx, replaceCommentAttachments, arg.CommentID, arg.IssueID, arg.AttachmentIds)
- return err
+func (q *Queries) ReplaceCommentAttachments(ctx context.Context, arg ReplaceCommentAttachmentsParams) (int64, error) {
+ result, err := q.db.Exec(ctx, replaceCommentAttachments, arg.CommentID, arg.IssueID, arg.AttachmentIds)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
}
diff --git a/server/pkg/db/generated/attachment_row.go b/server/pkg/db/generated/attachment_row.go
new file mode 100644
index 0000000000..3a4a74c350
--- /dev/null
+++ b/server/pkg/db/generated/attachment_row.go
@@ -0,0 +1,22 @@
+package db
+
+// Attachment converts the sqlc row returned by the CTE-backed create query
+// into the canonical model used by the rest of the application.
+func (r CreateAttachmentRow) Attachment() Attachment {
+ return Attachment{
+ ID: r.ID,
+ WorkspaceID: r.WorkspaceID,
+ IssueID: r.IssueID,
+ CommentID: r.CommentID,
+ UploaderType: r.UploaderType,
+ UploaderID: r.UploaderID,
+ Filename: r.Filename,
+ Url: r.Url,
+ ContentType: r.ContentType,
+ SizeBytes: r.SizeBytes,
+ CreatedAt: r.CreatedAt,
+ ChatSessionID: r.ChatSessionID,
+ ChatMessageID: r.ChatMessageID,
+ TaskID: r.TaskID,
+ }
+}
diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.go
index c3fa131caf..f41f9f69a2 100644
--- a/server/pkg/db/generated/comment.sql.go
+++ b/server/pkg/db/generated/comment.sql.go
@@ -11,6 +11,45 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
+const bumpCommentRevision = `-- name: BumpCommentRevision :one
+UPDATE comment
+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
+`
+
+type BumpCommentRevisionParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) BumpCommentRevision(ctx context.Context, arg BumpCommentRevisionParams) (Comment, error) {
+ row := q.db.QueryRow(ctx, bumpCommentRevision, 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,
+ )
+ return i, err
+}
+
const clearOtherThreadResolutions = `-- name: ClearOtherThreadResolutions :many
WITH RECURSIVE root_of AS (
-- Walk up from the target to its thread root.
@@ -41,11 +80,12 @@ UPDATE comment SET
resolved_at = NULL,
resolved_by_type = NULL,
resolved_by_id = NULL,
+ revision = revision + 1,
updated_at = now()
WHERE comment.id IN (SELECT id FROM descendants)
AND comment.id <> $1
AND comment.resolved_at IS NOT NULL
-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id
+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
`
type ClearOtherThreadResolutionsParams struct {
@@ -90,6 +130,7 @@ func (q *Queries) ClearOtherThreadResolutions(ctx context.Context, arg ClearOthe
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
); err != nil {
return nil, err
}
@@ -158,17 +199,23 @@ func (q *Queries) CountNewCommentsSince(ctx context.Context, arg CountNewComment
const createComment = `-- name: CreateComment :one
WITH touched_issue AS (
- UPDATE issue SET updated_at = now()
- WHERE issue.id = $9 AND issue.workspace_id = $10
- RETURNING issue.id, issue.workspace_id
+ UPDATE issue SET updated_at = now(), revision = revision + 1
+ WHERE issue.id = $1 AND issue.workspace_id = $2
+ RETURNING issue.id, issue.workspace_id, issue.revision
+), inserted_comment 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)
+ SELECT ti.id, ti.workspace_id, $3, $4, $5, $6, $7, $8, $9, $10
+ 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
)
-INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id, via_plugin_id)
-SELECT ti.id, ti.workspace_id, $1, $2, $3, $4, $5, $6, $7, $8
-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
+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, touched_issue.revision AS issue_revision
+FROM inserted_comment
+JOIN touched_issue ON touched_issue.id = inserted_comment.issue_id
`
type CreateCommentParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
AuthorType string `json:"author_type"`
AuthorID pgtype.UUID `json:"author_id"`
Content string `json:"content"`
@@ -177,8 +224,27 @@ type CreateCommentParams struct {
SourceTaskID pgtype.UUID `json:"source_task_id"`
QuickActionID pgtype.UUID `json:"quick_action_id"`
ViaPluginID pgtype.UUID `json:"via_plugin_id"`
- IssueID pgtype.UUID `json:"issue_id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+type CreateCommentRow struct {
+ ID pgtype.UUID `json:"id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ AuthorType string `json:"author_type"`
+ AuthorID pgtype.UUID `json:"author_id"`
+ Content string `json:"content"`
+ Type string `json:"type"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ ParentID pgtype.UUID `json:"parent_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ResolvedAt pgtype.Timestamptz `json:"resolved_at"`
+ ResolvedByType pgtype.Text `json:"resolved_by_type"`
+ ResolvedByID pgtype.UUID `json:"resolved_by_id"`
+ SourceTaskID pgtype.UUID `json:"source_task_id"`
+ QuickActionID pgtype.UUID `json:"quick_action_id"`
+ ViaPluginID pgtype.UUID `json:"via_plugin_id"`
+ Revision int64 `json:"revision"`
+ IssueRevision int64 `json:"issue_revision"`
}
// A new comment counts as activity on its issue, so the same statement bumps
@@ -197,8 +263,10 @@ type CreateCommentParams struct {
// Centralizing this here means every comment entrypoint inherits both
// guarantees regardless of what a caller passes. The "Updated date" sort and
// the daemon GC TTL both read updated_at, so this consistency is load-bearing.
-func (q *Queries) CreateComment(ctx context.Context, arg CreateCommentParams) (Comment, error) {
+func (q *Queries) CreateComment(ctx context.Context, arg CreateCommentParams) (CreateCommentRow, error) {
row := q.db.QueryRow(ctx, createComment,
+ arg.IssueID,
+ arg.WorkspaceID,
arg.AuthorType,
arg.AuthorID,
arg.Content,
@@ -207,10 +275,8 @@ func (q *Queries) CreateComment(ctx context.Context, arg CreateCommentParams) (C
arg.SourceTaskID,
arg.QuickActionID,
arg.ViaPluginID,
- arg.IssueID,
- arg.WorkspaceID,
)
- var i Comment
+ var i CreateCommentRow
err := row.Scan(
&i.ID,
&i.IssueID,
@@ -228,6 +294,8 @@ func (q *Queries) CreateComment(ctx context.Context, arg CreateCommentParams) (C
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
+ &i.IssueRevision,
)
return i, err
}
@@ -248,7 +316,7 @@ func (q *Queries) DeleteComment(ctx context.Context, arg DeleteCommentParams) er
}
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 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 FROM comment
WHERE id = $1
`
@@ -272,12 +340,13 @@ func (q *Queries) GetComment(ctx context.Context, id pgtype.UUID) (Comment, erro
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
)
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 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 FROM comment
WHERE id = $1 AND workspace_id = $2
`
@@ -306,12 +375,13 @@ func (q *Queries) GetCommentInWorkspace(ctx context.Context, arg GetCommentInWor
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
)
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 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 FROM comment
WHERE issue_id = $1
AND workspace_id = $2
AND author_type = 'system'
@@ -351,12 +421,13 @@ func (q *Queries) GetDelegatedFailureRecoveryComment(ctx context.Context, arg Ge
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
)
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 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 FROM comment
WHERE issue_id = $1
AND workspace_id = $2
AND author_type = 'system'
@@ -396,12 +467,13 @@ func (q *Queries) GetDelegatedFailureRecoveryExhaustionComment(ctx context.Conte
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
)
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 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 FROM comment
WHERE issue_id = $1
AND author_type = 'member'
AND created_at > $2
@@ -443,6 +515,7 @@ func (q *Queries) GetLatestMemberCommentForIssueSince(ctx context.Context, arg G
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
)
return i, err
}
@@ -457,7 +530,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 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 FROM comment c
WHERE c.id = (SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1)
`
@@ -491,6 +564,7 @@ func (q *Queries) GetThreadRoot(ctx context.Context, arg GetThreadRootParams) (C
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
)
return i, err
}
@@ -539,7 +613,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 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 FROM comment
WHERE parent_id = ANY($1::uuid[])
AND issue_id = $2
AND workspace_id = $3
@@ -599,6 +673,7 @@ func (q *Queries) ListChildCommentsForParents(ctx context.Context, arg ListChild
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
); err != nil {
return nil, err
}
@@ -611,7 +686,7 @@ func (q *Queries) ListChildCommentsForParents(ctx context.Context, arg ListChild
}
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 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 FROM comment
WHERE id = ANY($1::uuid[])
AND issue_id = $2
AND workspace_id = $3
@@ -659,6 +734,7 @@ func (q *Queries) ListCommentsByIDsForIssue(ctx context.Context, arg ListComment
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
); err != nil {
return nil, err
}
@@ -671,8 +747,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 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 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 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 FROM comment
WHERE issue_id = $1 AND workspace_id = $2
ORDER BY created_at DESC, id DESC
LIMIT $3
@@ -729,6 +805,7 @@ func (q *Queries) ListCommentsForIssue(ctx context.Context, arg ListCommentsForI
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
); err != nil {
return nil, err
}
@@ -741,7 +818,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 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 FROM comment
WHERE issue_id = $1 AND workspace_id = $2 AND created_at > $3
ORDER BY created_at ASC, id ASC
LIMIT $4
@@ -787,6 +864,7 @@ func (q *Queries) ListCommentsSinceForIssue(ctx context.Context, arg ListComment
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
); err != nil {
return nil, err
}
@@ -832,7 +910,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.source_task_id, c.quick_action_id, c.revision,
p.root_id AS thread_root_id,
p.last_activity_at AS thread_last_activity_at
FROM picked p
@@ -866,6 +944,7 @@ type ListRecentThreadCommentsForIssueRow struct {
ResolvedByID pgtype.UUID `json:"resolved_by_id"`
SourceTaskID pgtype.UUID `json:"source_task_id"`
QuickActionID pgtype.UUID `json:"quick_action_id"`
+ Revision int64 `json:"revision"`
ThreadRootID pgtype.UUID `json:"thread_root_id"`
ThreadLastActivityAt pgtype.Timestamptz `json:"thread_last_activity_at"`
}
@@ -930,6 +1009,7 @@ func (q *Queries) ListRecentThreadCommentsForIssue(ctx context.Context, arg List
&i.ResolvedByID,
&i.SourceTaskID,
&i.QuickActionID,
+ &i.Revision,
&i.ThreadRootID,
&i.ThreadLastActivityAt,
); err != nil {
@@ -944,7 +1024,7 @@ 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 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 FROM comment
WHERE issue_id = $1
AND (
(
@@ -1025,6 +1105,7 @@ func (q *Queries) ListReconcilableCommentsForIssueSince(ctx context.Context, arg
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
); err != nil {
return nil, err
}
@@ -1066,7 +1147,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.source_task_id, c.quick_action_id, c.revision,
ts.reply_count AS reply_count,
ts.last_activity_at AS last_activity_at
FROM selected_roots sr
@@ -1097,6 +1178,7 @@ type ListRootCommentsForIssueRow struct {
ResolvedByID pgtype.UUID `json:"resolved_by_id"`
SourceTaskID pgtype.UUID `json:"source_task_id"`
QuickActionID pgtype.UUID `json:"quick_action_id"`
+ Revision int64 `json:"revision"`
ReplyCount int32 `json:"reply_count"`
LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`
}
@@ -1138,6 +1220,7 @@ func (q *Queries) ListRootCommentsForIssue(ctx context.Context, arg ListRootComm
&i.ResolvedByID,
&i.SourceTaskID,
&i.QuickActionID,
+ &i.Revision,
&i.ReplyCount,
&i.LastActivityAt,
); err != nil {
@@ -1182,7 +1265,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.source_task_id, c.quick_action_id, c.revision,
ts.reply_count AS reply_count,
ts.last_activity_at AS last_activity_at
FROM selected_roots sr
@@ -1214,6 +1297,7 @@ type ListRootCommentsSinceForIssueRow struct {
ResolvedByID pgtype.UUID `json:"resolved_by_id"`
SourceTaskID pgtype.UUID `json:"source_task_id"`
QuickActionID pgtype.UUID `json:"quick_action_id"`
+ Revision int64 `json:"revision"`
ReplyCount int32 `json:"reply_count"`
LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`
}
@@ -1255,6 +1339,7 @@ func (q *Queries) ListRootCommentsSinceForIssue(ctx context.Context, arg ListRoo
&i.ResolvedByID,
&i.SourceTaskID,
&i.QuickActionID,
+ &i.Revision,
&i.ReplyCount,
&i.LastActivityAt,
); err != nil {
@@ -1286,14 +1371,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.source_task_id, c.quick_action_id, c.revision
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.source_task_id, c.quick_action_id, c.revision
FROM comment c
JOIN descendants d ON c.parent_id = d.id
WHERE c.issue_id = $2 AND c.workspace_id = $3
@@ -1302,7 +1387,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.source_task_id, d.quick_action_id, d.revision
FROM descendants d
WHERE d.id NOT IN (SELECT id FROM thread_root)
AND (
@@ -1315,19 +1400,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
+ source_task_id, quick_action_id, revision
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.source_task_id, d.quick_action_id, d.revision
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
+ source_task_id, quick_action_id, revision
FROM reply_page
) combined
ORDER BY created_at ASC, id ASC
@@ -1359,6 +1444,7 @@ type ListThreadCommentsForIssuePagedRow struct {
ResolvedByID pgtype.UUID `json:"resolved_by_id"`
SourceTaskID pgtype.UUID `json:"source_task_id"`
QuickActionID pgtype.UUID `json:"quick_action_id"`
+ Revision int64 `json:"revision"`
}
// Resolves @anchor_id to its thread root, recursively expands every descendant,
@@ -1409,6 +1495,7 @@ func (q *Queries) ListThreadCommentsForIssuePaged(ctx context.Context, arg ListT
&i.ResolvedByID,
&i.SourceTaskID,
&i.QuickActionID,
+ &i.Revision,
); err != nil {
return nil, err
}
@@ -1425,9 +1512,10 @@ UPDATE comment SET
resolved_at = COALESCE(resolved_at, now()),
resolved_by_type = COALESCE(resolved_by_type, $2),
resolved_by_id = COALESCE(resolved_by_id, $3),
+ 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
+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
`
type ResolveCommentParams struct {
@@ -1458,6 +1546,7 @@ func (q *Queries) ResolveComment(ctx context.Context, arg ResolveCommentParams)
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
)
return i, err
}
@@ -1467,9 +1556,10 @@ UPDATE comment SET
resolved_at = NULL,
resolved_by_type = NULL,
resolved_by_id = NULL,
+ 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
+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
`
// Idempotent: a no-op clear (already unresolved) just returns the row.
@@ -1493,6 +1583,7 @@ func (q *Queries) UnresolveComment(ctx context.Context, id pgtype.UUID) (Comment
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
)
return i, err
}
@@ -1501,19 +1592,34 @@ const updateComment = `-- name: UpdateComment :one
UPDATE comment SET
content = $2,
source_task_id = $3,
- updated_at = now()
+ revision = revision + CASE WHEN ROW(content, source_task_id) IS DISTINCT FROM ROW($2, $3) THEN 1 ELSE 0 END,
+ updated_at = CASE WHEN ROW(content, source_task_id) IS DISTINCT FROM ROW($2, $3) 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
+ AND ($4::bigint IS NULL OR revision = $4::bigint)
+ AND (
+ $5::text IS NULL
+ OR content IS NOT DISTINCT FROM $5::text
+ OR content IS NOT DISTINCT FROM $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
`
type UpdateCommentParams struct {
- ID pgtype.UUID `json:"id"`
- Content string `json:"content"`
- SourceTaskID pgtype.UUID `json:"source_task_id"`
+ ID pgtype.UUID `json:"id"`
+ Content string `json:"content"`
+ SourceTaskID pgtype.UUID `json:"source_task_id"`
+ ExpectedRevision pgtype.Int8 `json:"expected_revision"`
+ ContentBase pgtype.Text `json:"content_base"`
}
func (q *Queries) UpdateComment(ctx context.Context, arg UpdateCommentParams) (Comment, error) {
- row := q.db.QueryRow(ctx, updateComment, arg.ID, arg.Content, arg.SourceTaskID)
+ row := q.db.QueryRow(ctx, updateComment,
+ arg.ID,
+ arg.Content,
+ arg.SourceTaskID,
+ arg.ExpectedRevision,
+ arg.ContentBase,
+ )
var i Comment
err := row.Scan(
&i.ID,
@@ -1532,6 +1638,7 @@ func (q *Queries) UpdateComment(ctx context.Context, arg UpdateCommentParams) (C
&i.SourceTaskID,
&i.QuickActionID,
&i.ViaPluginID,
+ &i.Revision,
)
return i, err
}
diff --git a/server/pkg/db/generated/comment_row.go b/server/pkg/db/generated/comment_row.go
new file mode 100644
index 0000000000..f8d0adc125
--- /dev/null
+++ b/server/pkg/db/generated/comment_row.go
@@ -0,0 +1,26 @@
+package db
+
+// Comment converts the sqlc row returned by the CTE-backed create query into
+// the canonical model used by comment rendering and task side effects. The
+// row's IssueRevision remains available separately for owner-cache coherence.
+func (r CreateCommentRow) Comment() Comment {
+ return Comment{
+ ID: r.ID,
+ IssueID: r.IssueID,
+ AuthorType: r.AuthorType,
+ AuthorID: r.AuthorID,
+ Content: r.Content,
+ Type: r.Type,
+ CreatedAt: r.CreatedAt,
+ UpdatedAt: r.UpdatedAt,
+ ParentID: r.ParentID,
+ WorkspaceID: r.WorkspaceID,
+ ResolvedAt: r.ResolvedAt,
+ ResolvedByType: r.ResolvedByType,
+ ResolvedByID: r.ResolvedByID,
+ SourceTaskID: r.SourceTaskID,
+ QuickActionID: r.QuickActionID,
+ ViaPluginID: r.ViaPluginID,
+ Revision: r.Revision,
+ }
+}
diff --git a/server/pkg/db/generated/comment_row_test.go b/server/pkg/db/generated/comment_row_test.go
new file mode 100644
index 0000000000..c54e15a640
--- /dev/null
+++ b/server/pkg/db/generated/comment_row_test.go
@@ -0,0 +1,28 @@
+package db
+
+import (
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+func TestCreateCommentRowCommentPreservesCanonicalFields(t *testing.T) {
+ viaPluginID := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}
+ row := CreateCommentRow{
+ Content: "created comment",
+ Revision: 7,
+ ViaPluginID: viaPluginID,
+ IssueRevision: 11,
+ }
+
+ comment := row.Comment()
+ if comment.Content != row.Content {
+ t.Fatalf("content = %q, want %q", comment.Content, row.Content)
+ }
+ if comment.Revision != row.Revision {
+ t.Fatalf("revision = %d, want %d", comment.Revision, row.Revision)
+ }
+ if comment.ViaPluginID != viaPluginID {
+ t.Fatalf("via_plugin_id = %#v, want %#v", comment.ViaPluginID, viaPluginID)
+ }
+}
diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.go
index 731148564d..9bd9685542 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -179,7 +179,7 @@ INSERT INTO issue (
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
$16
-) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
`
type CreateIssueParams struct {
@@ -248,6 +248,7 @@ func (q *Queries) CreateIssue(ctx context.Context, arg CreateIssueParams) (Issue
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
@@ -261,7 +262,7 @@ INSERT INTO issue (
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
$16, $17, $18
-) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
`
type CreateIssueWithOriginParams struct {
@@ -334,6 +335,7 @@ func (q *Queries) CreateIssueWithOrigin(ctx context.Context, arg CreateIssueWith
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
@@ -377,9 +379,10 @@ func (q *Queries) DeleteIssue(ctx context.Context, arg DeleteIssueParams) error
const deleteIssueMetadataKey = `-- name: DeleteIssueMetadataKey :one
UPDATE issue SET
metadata = metadata - $1::text,
+ revision = revision + CASE WHEN metadata ? $1::text THEN 1 ELSE 0 END,
updated_at = now()
WHERE id = $2 AND workspace_id = $3
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
`
type DeleteIssueMetadataKeyParams struct {
@@ -420,12 +423,13 @@ func (q *Queries) DeleteIssueMetadataKey(ctx context.Context, arg DeleteIssueMet
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
const findActiveDuplicateIssue = `-- name: FindActiveDuplicateIssue :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
WHERE workspace_id = $1
AND issue_effective_status(workspace_id, status) NOT IN ('done', 'cancelled')
AND project_id IS NOT DISTINCT FROM $2::uuid
@@ -477,12 +481,13 @@ func (q *Queries) FindActiveDuplicateIssue(ctx context.Context, arg FindActiveDu
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
const findRecentAutopilotDuplicateIssue = `-- name: FindRecentAutopilotDuplicateIssue :one
-SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties FROM issue i
+SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision FROM issue i
WHERE i.workspace_id = $1
AND issue_effective_status(i.workspace_id, i.status) NOT IN ('done', 'cancelled')
AND i.origin_type = 'autopilot'
@@ -545,12 +550,13 @@ func (q *Queries) FindRecentAutopilotDuplicateIssue(ctx context.Context, arg Fin
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
const getIssue = `-- name: GetIssue :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
WHERE id = $1
`
@@ -584,12 +590,13 @@ func (q *Queries) GetIssue(ctx context.Context, id pgtype.UUID) (Issue, error) {
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
const getIssueByNumber = `-- name: GetIssueByNumber :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
WHERE workspace_id = $1 AND number = $2
`
@@ -628,12 +635,13 @@ func (q *Queries) GetIssueByNumber(ctx context.Context, arg GetIssueByNumberPara
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
const getIssueByOrigin = `-- name: GetIssueByOrigin :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
WHERE workspace_id = $1
AND origin_type = $2
AND origin_id = $3
@@ -681,6 +689,7 @@ func (q *Queries) GetIssueByOrigin(ctx context.Context, arg GetIssueByOriginPara
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
@@ -705,7 +714,7 @@ func (q *Queries) GetIssueGCStatus(ctx context.Context, id pgtype.UUID) (GetIssu
}
const getIssueInWorkspace = `-- name: GetIssueInWorkspace :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
WHERE id = $1 AND workspace_id = $2
`
@@ -744,12 +753,13 @@ func (q *Queries) GetIssueInWorkspace(ctx context.Context, arg GetIssueInWorkspa
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
const listChildIssues = `-- name: ListChildIssues :many
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
WHERE parent_issue_id = $1
ORDER BY number ASC
`
@@ -796,6 +806,7 @@ func (q *Queries) ListChildIssues(ctx context.Context, parentIssueID pgtype.UUID
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
); err != nil {
return nil, err
}
@@ -808,7 +819,7 @@ func (q *Queries) ListChildIssues(ctx context.Context, parentIssueID pgtype.UUID
}
const listChildrenByParents = `-- name: ListChildrenByParents :many
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
WHERE workspace_id = $1
AND parent_issue_id = ANY($2::uuid[])
ORDER BY parent_issue_id, number ASC
@@ -862,6 +873,7 @@ func (q *Queries) ListChildrenByParents(ctx context.Context, arg ListChildrenByP
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
); err != nil {
return nil, err
}
@@ -914,7 +926,8 @@ func (q *Queries) ListIssueGCStatuses(ctx context.Context, arg ListIssueGCStatus
const listIssues = `-- name: ListIssues :many
SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
+ i.revision
FROM issue i
WHERE i.workspace_id = $1
AND ($4::text IS NULL OR i.status = $4)
@@ -1006,6 +1019,7 @@ type ListIssuesRow struct {
Metadata []byte `json:"metadata"`
Stage pgtype.Int4 `json:"stage"`
Properties []byte `json:"properties"`
+ Revision int64 `json:"revision"`
}
// involves_user_id widens the assignee filter to surface issues where the user
@@ -1058,6 +1072,7 @@ func (q *Queries) ListIssues(ctx context.Context, arg ListIssuesParams) ([]ListI
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
); err != nil {
return nil, err
}
@@ -1072,7 +1087,8 @@ func (q *Queries) ListIssues(ctx context.Context, arg ListIssuesParams) ([]ListI
const listOpenIssues = `-- name: ListOpenIssues :many
SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
+ i.revision
FROM issue i
WHERE i.workspace_id = $1
AND issue_effective_status(i.workspace_id, i.status) NOT IN ('done', 'cancelled')
@@ -1168,6 +1184,7 @@ type ListOpenIssuesRow struct {
Metadata []byte `json:"metadata"`
Stage pgtype.Int4 `json:"stage"`
Properties []byte `json:"properties"`
+ Revision int64 `json:"revision"`
}
// See ListIssues for the semantics of involves_user_id (mirrors the 4-branch
@@ -1213,6 +1230,7 @@ func (q *Queries) ListOpenIssues(ctx context.Context, arg ListOpenIssuesParams)
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
); err != nil {
return nil, err
}
@@ -1277,7 +1295,7 @@ func (q *Queries) LockIssueForDelete(ctx context.Context, arg LockIssueForDelete
}
const lockIssueForDescriptionUpdate = `-- name: LockIssueForDescriptionUpdate :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision FROM issue
WHERE id = $1 AND workspace_id = $2
FOR UPDATE
`
@@ -1287,9 +1305,10 @@ type LockIssueForDescriptionUpdateParams struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
}
-// Serialize user description saves with detached channel-media appends. The
-// handler merges channel media that landed after the editor's submitted base
-// while holding this lock, then performs UpdateIssue in the same transaction.
+// Serialize field-baseline checks and combined attachment binding on the
+// owner row. The handler merges channel media that landed after the editor's
+// submitted base, updates the issue, and binds this request's attachments in
+// the same transaction while holding this lock.
func (q *Queries) LockIssueForDescriptionUpdate(ctx context.Context, arg LockIssueForDescriptionUpdateParams) (Issue, error) {
row := q.db.QueryRow(ctx, lockIssueForDescriptionUpdate, arg.ID, arg.WorkspaceID)
var i Issue
@@ -1320,6 +1339,7 @@ func (q *Queries) LockIssueForDescriptionUpdate(ctx context.Context, arg LockIss
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
@@ -1365,10 +1385,11 @@ SET description = CASE
WHEN description IS NULL OR description = '' THEN $3
ELSE description || E'\n\n' || $3
END,
+ revision = revision + 1,
updated_at = now()
WHERE id = $4
AND workspace_id = $5
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
`
type MaterializeIssueChannelMediaMarkdownParams struct {
@@ -1420,6 +1441,7 @@ func (q *Queries) MaterializeIssueChannelMediaMarkdown(ctx context.Context, arg
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
@@ -1428,9 +1450,10 @@ const setIssueMetadataKey = `-- name: SetIssueMetadataKey :one
UPDATE issue SET
metadata = jsonb_set(metadata, ARRAY[$1::text], $2::jsonb),
+ revision = revision + CASE WHEN metadata -> $1::text IS DISTINCT FROM $2::jsonb THEN 1 ELSE 0 END,
updated_at = now()
WHERE id = $3 AND workspace_id = $4
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
`
type SetIssueMetadataKeyParams struct {
@@ -1479,43 +1502,78 @@ func (q *Queries) SetIssueMetadataKey(ctx context.Context, arg SetIssueMetadataK
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
const updateIssue = `-- name: UpdateIssue :one
-UPDATE issue SET
- title = COALESCE($2, title),
- description = COALESCE($3, description),
- status = COALESCE($4, status),
- priority = COALESCE($5, priority),
- assignee_type = $6,
- assignee_id = $7,
- position = COALESCE($8, position),
- start_date = $9,
- due_date = $10,
- parent_issue_id = $11,
- project_id = $12,
- stage = $13,
- updated_at = now()
-WHERE id = $1
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
+WITH candidate AS (
+ SELECT
+ i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision,
+ COALESCE($2::text, i.title) AS next_title,
+ COALESCE($3::text, i.description) AS next_description,
+ COALESCE($4::text, i.status) AS next_status,
+ COALESCE($5::text, i.priority) AS next_priority,
+ $6::text AS next_assignee_type,
+ $7::uuid AS next_assignee_id,
+ COALESCE($8::double precision, i.position) AS next_position,
+ $9::date AS next_start_date,
+ $10::date AS next_due_date,
+ $11::uuid AS next_parent_issue_id,
+ $12::uuid AS next_project_id,
+ $13::integer AS next_stage
+ FROM issue AS i
+ WHERE i.id = $1
+ AND ($14::bigint IS NULL OR i.revision = $14::bigint)
+), changed AS (
+ SELECT
+ candidate.id, candidate.workspace_id, candidate.title, candidate.description, candidate.status, candidate.priority, candidate.assignee_type, candidate.assignee_id, candidate.creator_type, candidate.creator_id, candidate.parent_issue_id, candidate.acceptance_criteria, candidate.context_refs, candidate.position, candidate.due_date, candidate.created_at, candidate.updated_at, candidate.number, candidate.project_id, candidate.origin_type, candidate.origin_id, candidate.first_executed_at, candidate.start_date, candidate.metadata, candidate.stage, candidate.properties, candidate.revision, candidate.next_title, candidate.next_description, candidate.next_status, candidate.next_priority, candidate.next_assignee_type, candidate.next_assignee_id, candidate.next_position, candidate.next_start_date, candidate.next_due_date, candidate.next_parent_issue_id, candidate.next_project_id, candidate.next_stage,
+ ROW(
+ title, description, status, priority, assignee_type, assignee_id,
+ position, start_date, due_date, parent_issue_id, project_id, stage
+ ) IS DISTINCT FROM ROW(
+ next_title, next_description, next_status, next_priority,
+ next_assignee_type, next_assignee_id, next_position, next_start_date,
+ next_due_date, next_parent_issue_id, next_project_id, next_stage
+ ) AS did_change
+ FROM candidate
+)
+UPDATE issue AS i SET
+ title = changed.next_title,
+ description = changed.next_description,
+ status = changed.next_status,
+ priority = changed.next_priority,
+ assignee_type = changed.next_assignee_type,
+ assignee_id = changed.next_assignee_id,
+ position = changed.next_position,
+ start_date = changed.next_start_date,
+ due_date = changed.next_due_date,
+ parent_issue_id = changed.next_parent_issue_id,
+ project_id = changed.next_project_id,
+ stage = changed.next_stage,
+ revision = i.revision + changed.did_change::integer,
+ updated_at = CASE WHEN changed.did_change THEN now() ELSE i.updated_at END
+FROM changed
+WHERE i.id = changed.id
+RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision
`
type UpdateIssueParams struct {
- ID pgtype.UUID `json:"id"`
- Title pgtype.Text `json:"title"`
- Description pgtype.Text `json:"description"`
- Status pgtype.Text `json:"status"`
- Priority pgtype.Text `json:"priority"`
- AssigneeType pgtype.Text `json:"assignee_type"`
- AssigneeID pgtype.UUID `json:"assignee_id"`
- Position pgtype.Float8 `json:"position"`
- StartDate pgtype.Date `json:"start_date"`
- DueDate pgtype.Date `json:"due_date"`
- ParentIssueID pgtype.UUID `json:"parent_issue_id"`
- ProjectID pgtype.UUID `json:"project_id"`
- Stage pgtype.Int4 `json:"stage"`
+ ID pgtype.UUID `json:"id"`
+ Title pgtype.Text `json:"title"`
+ Description pgtype.Text `json:"description"`
+ Status pgtype.Text `json:"status"`
+ Priority pgtype.Text `json:"priority"`
+ AssigneeType pgtype.Text `json:"assignee_type"`
+ AssigneeID pgtype.UUID `json:"assignee_id"`
+ Position pgtype.Float8 `json:"position"`
+ StartDate pgtype.Date `json:"start_date"`
+ DueDate pgtype.Date `json:"due_date"`
+ ParentIssueID pgtype.UUID `json:"parent_issue_id"`
+ ProjectID pgtype.UUID `json:"project_id"`
+ Stage pgtype.Int4 `json:"stage"`
+ ExpectedRevision pgtype.Int8 `json:"expected_revision"`
}
func (q *Queries) UpdateIssue(ctx context.Context, arg UpdateIssueParams) (Issue, error) {
@@ -1533,6 +1591,7 @@ func (q *Queries) UpdateIssue(ctx context.Context, arg UpdateIssueParams) (Issue
arg.ParentIssueID,
arg.ProjectID,
arg.Stage,
+ arg.ExpectedRevision,
)
var i Issue
err := row.Scan(
@@ -1562,6 +1621,7 @@ func (q *Queries) UpdateIssue(ctx context.Context, arg UpdateIssueParams) (Issue
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
@@ -1569,9 +1629,10 @@ func (q *Queries) UpdateIssue(ctx context.Context, arg UpdateIssueParams) (Issue
const updateIssueStatus = `-- name: UpdateIssueStatus :one
UPDATE issue SET
status = $2,
+ revision = revision + CASE WHEN status IS DISTINCT FROM $2 THEN 1 ELSE 0 END,
updated_at = now()
WHERE id = $1 AND workspace_id = $3
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
`
type UpdateIssueStatusParams struct {
@@ -1611,6 +1672,7 @@ func (q *Queries) UpdateIssueStatus(ctx context.Context, arg UpdateIssueStatusPa
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
diff --git a/server/pkg/db/generated/issue_label.sql.go b/server/pkg/db/generated/issue_label.sql.go
index ba851e20f5..d04d3d640e 100644
--- a/server/pkg/db/generated/issue_label.sql.go
+++ b/server/pkg/db/generated/issue_label.sql.go
@@ -39,7 +39,52 @@ func (q *Queries) AttachLabelToAgent(ctx context.Context, arg AttachLabelToAgent
return err
}
-const attachLabelToIssue = `-- name: AttachLabelToIssue :exec
+const attachLabelToIssue = `-- name: AttachLabelToIssue :one
+WITH inserted AS (
+ INSERT INTO issue_to_label (issue_id, label_id)
+ SELECT $1::uuid, $2::uuid
+ WHERE EXISTS (
+ SELECT 1 FROM issue i
+ WHERE i.id = $1::uuid
+ AND i.workspace_id = $3::uuid
+ )
+ AND EXISTS (
+ SELECT 1 FROM issue_label l
+ WHERE l.id = $2::uuid
+ AND l.workspace_id = $3::uuid
+ AND l.resource_type = 'issue'
+ )
+ ON CONFLICT DO NOTHING
+ RETURNING issue_id
+), bumped AS (
+ UPDATE issue
+ SET revision = revision + 1
+ WHERE id IN (SELECT issue_id FROM inserted)
+ RETURNING revision
+)
+SELECT EXISTS(SELECT 1 FROM inserted) AS changed,
+ COALESCE((SELECT revision FROM bumped), 0)::bigint AS issue_revision
+`
+
+type AttachLabelToIssueParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ LabelID pgtype.UUID `json:"label_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+type AttachLabelToIssueRow struct {
+ Changed bool `json:"changed"`
+ IssueRevision int64 `json:"issue_revision"`
+}
+
+func (q *Queries) AttachLabelToIssue(ctx context.Context, arg AttachLabelToIssueParams) (AttachLabelToIssueRow, error) {
+ row := q.db.QueryRow(ctx, attachLabelToIssue, arg.IssueID, arg.LabelID, arg.WorkspaceID)
+ var i AttachLabelToIssueRow
+ err := row.Scan(&i.Changed, &i.IssueRevision)
+ return i, err
+}
+
+const attachLabelToIssueOnCreate = `-- name: AttachLabelToIssueOnCreate :exec
INSERT INTO issue_to_label (issue_id, label_id)
SELECT $1::uuid, $2::uuid
WHERE EXISTS (
@@ -56,7 +101,7 @@ AND EXISTS (
ON CONFLICT DO NOTHING
`
-type AttachLabelToIssueParams struct {
+type AttachLabelToIssueOnCreateParams struct {
IssueID pgtype.UUID `json:"issue_id"`
LabelID pgtype.UUID `json:"label_id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
@@ -65,8 +110,8 @@ type AttachLabelToIssueParams struct {
// Workspace-guarded INSERT: the WHERE EXISTS clauses ensure both the issue
// and the label belong to the given workspace. A future caller that forgets
// handler-level prechecks still cannot attach labels across workspaces.
-func (q *Queries) AttachLabelToIssue(ctx context.Context, arg AttachLabelToIssueParams) error {
- _, err := q.db.Exec(ctx, attachLabelToIssue, arg.IssueID, arg.LabelID, arg.WorkspaceID)
+func (q *Queries) AttachLabelToIssueOnCreate(ctx context.Context, arg AttachLabelToIssueOnCreateParams) error {
+ _, err := q.db.Exec(ctx, attachLabelToIssueOnCreate, arg.IssueID, arg.LabelID, arg.WorkspaceID)
return err
}
@@ -245,15 +290,25 @@ func (q *Queries) DetachLabelFromAgent(ctx context.Context, arg DetachLabelFromA
return err
}
-const detachLabelFromIssue = `-- name: DetachLabelFromIssue :exec
-DELETE FROM issue_to_label
-WHERE issue_id = $1::uuid
- AND label_id = $2::uuid
- AND EXISTS (
- SELECT 1 FROM issue i
- WHERE i.id = $1::uuid
- AND i.workspace_id = $3::uuid
- )
+const detachLabelFromIssue = `-- name: DetachLabelFromIssue :one
+WITH deleted AS (
+ DELETE FROM issue_to_label
+ WHERE issue_id = $1::uuid
+ AND label_id = $2::uuid
+ AND EXISTS (
+ SELECT 1 FROM issue i
+ WHERE i.id = $1::uuid
+ AND i.workspace_id = $3::uuid
+ )
+ RETURNING issue_id
+), bumped AS (
+ UPDATE issue
+ SET revision = revision + 1
+ WHERE id IN (SELECT issue_id FROM deleted)
+ RETURNING revision
+)
+SELECT EXISTS(SELECT 1 FROM deleted) AS changed,
+ COALESCE((SELECT revision FROM bumped), 0)::bigint AS issue_revision
`
type DetachLabelFromIssueParams struct {
@@ -262,11 +317,18 @@ type DetachLabelFromIssueParams struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
}
+type DetachLabelFromIssueRow struct {
+ Changed bool `json:"changed"`
+ IssueRevision int64 `json:"issue_revision"`
+}
+
// Workspace-guarded DELETE: only deletes if the issue is in the given
// workspace. Mirror of the attach query.
-func (q *Queries) DetachLabelFromIssue(ctx context.Context, arg DetachLabelFromIssueParams) error {
- _, err := q.db.Exec(ctx, detachLabelFromIssue, arg.IssueID, arg.LabelID, arg.WorkspaceID)
- return err
+func (q *Queries) DetachLabelFromIssue(ctx context.Context, arg DetachLabelFromIssueParams) (DetachLabelFromIssueRow, error) {
+ row := q.db.QueryRow(ctx, detachLabelFromIssue, arg.IssueID, arg.LabelID, arg.WorkspaceID)
+ var i DetachLabelFromIssueRow
+ err := row.Scan(&i.Changed, &i.IssueRevision)
+ return i, err
}
const detachLabelFromSkill = `-- name: DetachLabelFromSkill :exec
diff --git a/server/pkg/db/generated/issue_property.sql.go b/server/pkg/db/generated/issue_property.sql.go
index 3dac7fb859..7731f99ecf 100644
--- a/server/pkg/db/generated/issue_property.sql.go
+++ b/server/pkg/db/generated/issue_property.sql.go
@@ -118,9 +118,10 @@ func (q *Queries) CreateIssueProperty(ctx context.Context, arg CreateIssueProper
const deleteIssuePropertyValue = `-- name: DeleteIssuePropertyValue :one
UPDATE issue
SET properties = properties - $1::text,
- updated_at = now()
+ revision = revision + CASE WHEN properties ? $1::text THEN 1 ELSE 0 END,
+ updated_at = CASE WHEN properties ? $1::text THEN now() ELSE updated_at END
WHERE id = $2::uuid AND workspace_id = $3::uuid
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
`
type DeleteIssuePropertyValueParams struct {
@@ -159,6 +160,7 @@ func (q *Queries) DeleteIssuePropertyValue(ctx context.Context, arg DeleteIssueP
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
@@ -264,9 +266,10 @@ func (q *Queries) ListIssueProperties(ctx context.Context, arg ListIssueProperti
const setIssuePropertyValue = `-- name: SetIssuePropertyValue :one
UPDATE issue
SET properties = jsonb_set(properties, ARRAY[$1::text], $2::jsonb, true),
- updated_at = now()
+ revision = revision + CASE WHEN properties -> $1::text IS DISTINCT FROM $2::jsonb THEN 1 ELSE 0 END,
+ updated_at = CASE WHEN properties -> $1::text IS DISTINCT FROM $2::jsonb THEN now() ELSE updated_at END
WHERE id = $3::uuid AND workspace_id = $4::uuid
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision
`
type SetIssuePropertyValueParams struct {
@@ -313,6 +316,7 @@ func (q *Queries) SetIssuePropertyValue(ctx context.Context, arg SetIssuePropert
&i.Metadata,
&i.Stage,
&i.Properties,
+ &i.Revision,
)
return i, err
}
diff --git a/server/pkg/db/generated/issue_reaction.sql.go b/server/pkg/db/generated/issue_reaction.sql.go
index c37535fbd6..8f85ea795d 100644
--- a/server/pkg/db/generated/issue_reaction.sql.go
+++ b/server/pkg/db/generated/issue_reaction.sql.go
@@ -12,10 +12,28 @@ import (
)
const addIssueReaction = `-- name: AddIssueReaction :one
-INSERT INTO issue_reaction (issue_id, workspace_id, actor_type, actor_id, emoji)
-VALUES ($1, $2, $3, $4, $5)
-ON CONFLICT (issue_id, actor_type, actor_id, emoji) DO UPDATE SET created_at = issue_reaction.created_at
-RETURNING id, issue_id, workspace_id, actor_type, actor_id, emoji, created_at
+WITH inserted AS (
+ INSERT INTO issue_reaction (issue_id, workspace_id, actor_type, actor_id, emoji)
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (issue_id, actor_type, actor_id, emoji) DO NOTHING
+ RETURNING id, issue_id, workspace_id, actor_type, actor_id, emoji, created_at
+), bumped AS (
+ UPDATE issue
+ SET revision = revision + 1
+ WHERE id IN (SELECT issue_id FROM inserted)
+ RETURNING revision
+)
+SELECT reaction.id, reaction.issue_id, reaction.workspace_id, reaction.actor_type, reaction.actor_id, reaction.emoji, reaction.created_at, COALESCE((SELECT revision FROM bumped), 0)::bigint AS issue_revision
+FROM inserted reaction
+UNION ALL
+SELECT reaction.id, reaction.issue_id, reaction.workspace_id, reaction.actor_type, reaction.actor_id, reaction.emoji, reaction.created_at, 0::bigint AS issue_revision
+FROM issue_reaction reaction
+WHERE reaction.issue_id = $1
+ AND reaction.actor_type = $3
+ AND reaction.actor_id = $4
+ AND reaction.emoji = $5
+ AND NOT EXISTS (SELECT 1 FROM inserted)
+LIMIT 1
`
type AddIssueReactionParams struct {
@@ -26,7 +44,18 @@ type AddIssueReactionParams struct {
Emoji string `json:"emoji"`
}
-func (q *Queries) AddIssueReaction(ctx context.Context, arg AddIssueReactionParams) (IssueReaction, error) {
+type AddIssueReactionRow struct {
+ ID pgtype.UUID `json:"id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ActorType string `json:"actor_type"`
+ ActorID pgtype.UUID `json:"actor_id"`
+ Emoji string `json:"emoji"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ IssueRevision int64 `json:"issue_revision"`
+}
+
+func (q *Queries) AddIssueReaction(ctx context.Context, arg AddIssueReactionParams) (AddIssueReactionRow, error) {
row := q.db.QueryRow(ctx, addIssueReaction,
arg.IssueID,
arg.WorkspaceID,
@@ -34,7 +63,7 @@ func (q *Queries) AddIssueReaction(ctx context.Context, arg AddIssueReactionPara
arg.ActorID,
arg.Emoji,
)
- var i IssueReaction
+ var i AddIssueReactionRow
err := row.Scan(
&i.ID,
&i.IssueID,
@@ -43,6 +72,7 @@ func (q *Queries) AddIssueReaction(ctx context.Context, arg AddIssueReactionPara
&i.ActorID,
&i.Emoji,
&i.CreatedAt,
+ &i.IssueRevision,
)
return i, err
}
@@ -81,9 +111,19 @@ func (q *Queries) ListIssueReactions(ctx context.Context, issueID pgtype.UUID) (
return items, nil
}
-const removeIssueReaction = `-- name: RemoveIssueReaction :exec
-DELETE FROM issue_reaction
-WHERE issue_id = $1 AND actor_type = $2 AND actor_id = $3 AND emoji = $4
+const removeIssueReaction = `-- name: RemoveIssueReaction :one
+WITH deleted AS (
+ DELETE FROM issue_reaction
+ WHERE issue_id = $1 AND actor_type = $2 AND actor_id = $3 AND emoji = $4
+ RETURNING issue_id
+), bumped AS (
+ UPDATE issue
+ SET revision = revision + 1
+ WHERE id IN (SELECT issue_id FROM deleted)
+ RETURNING revision
+)
+SELECT EXISTS(SELECT 1 FROM deleted) AS changed,
+ COALESCE((SELECT revision FROM bumped), 0)::bigint AS issue_revision
`
type RemoveIssueReactionParams struct {
@@ -93,12 +133,19 @@ type RemoveIssueReactionParams struct {
Emoji string `json:"emoji"`
}
-func (q *Queries) RemoveIssueReaction(ctx context.Context, arg RemoveIssueReactionParams) error {
- _, err := q.db.Exec(ctx, removeIssueReaction,
+type RemoveIssueReactionRow struct {
+ Changed bool `json:"changed"`
+ IssueRevision int64 `json:"issue_revision"`
+}
+
+func (q *Queries) RemoveIssueReaction(ctx context.Context, arg RemoveIssueReactionParams) (RemoveIssueReactionRow, error) {
+ row := q.db.QueryRow(ctx, removeIssueReaction,
arg.IssueID,
arg.ActorType,
arg.ActorID,
arg.Emoji,
)
- return err
+ var i RemoveIssueReactionRow
+ err := row.Scan(&i.Changed, &i.IssueRevision)
+ return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 6128db4775..50ad5fa156 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -468,6 +468,7 @@ type Comment struct {
SourceTaskID pgtype.UUID `json:"source_task_id"`
QuickActionID pgtype.UUID `json:"quick_action_id"`
ViaPluginID pgtype.UUID `json:"via_plugin_id"`
+ Revision int64 `json:"revision"`
}
type CommentReaction struct {
@@ -671,6 +672,7 @@ type Issue struct {
Metadata []byte `json:"metadata"`
Stage pgtype.Int4 `json:"stage"`
Properties []byte `json:"properties"`
+ Revision int64 `json:"revision"`
}
type IssueDependency struct {
diff --git a/server/pkg/db/generated/reaction.sql.go b/server/pkg/db/generated/reaction.sql.go
index da9cb9c233..74f9d5f5db 100644
--- a/server/pkg/db/generated/reaction.sql.go
+++ b/server/pkg/db/generated/reaction.sql.go
@@ -12,10 +12,28 @@ import (
)
const addReaction = `-- name: AddReaction :one
-INSERT INTO comment_reaction (comment_id, workspace_id, actor_type, actor_id, emoji)
-VALUES ($1, $2, $3, $4, $5)
-ON CONFLICT (comment_id, actor_type, actor_id, emoji) DO UPDATE SET created_at = comment_reaction.created_at
-RETURNING id, comment_id, workspace_id, actor_type, actor_id, emoji, created_at
+WITH inserted AS (
+ INSERT INTO comment_reaction (comment_id, workspace_id, actor_type, actor_id, emoji)
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (comment_id, actor_type, actor_id, emoji) DO NOTHING
+ RETURNING id, comment_id, workspace_id, actor_type, actor_id, emoji, created_at
+), bumped AS (
+ UPDATE comment
+ SET revision = revision + 1
+ WHERE id IN (SELECT comment_id FROM inserted)
+ RETURNING revision
+)
+SELECT reaction.id, reaction.comment_id, reaction.workspace_id, reaction.actor_type, reaction.actor_id, reaction.emoji, reaction.created_at, COALESCE((SELECT revision FROM bumped), 0)::bigint AS comment_revision
+FROM inserted reaction
+UNION ALL
+SELECT reaction.id, reaction.comment_id, reaction.workspace_id, reaction.actor_type, reaction.actor_id, reaction.emoji, reaction.created_at, 0::bigint AS comment_revision
+FROM comment_reaction reaction
+WHERE reaction.comment_id = $1
+ AND reaction.actor_type = $3
+ AND reaction.actor_id = $4
+ AND reaction.emoji = $5
+ AND NOT EXISTS (SELECT 1 FROM inserted)
+LIMIT 1
`
type AddReactionParams struct {
@@ -26,7 +44,18 @@ type AddReactionParams struct {
Emoji string `json:"emoji"`
}
-func (q *Queries) AddReaction(ctx context.Context, arg AddReactionParams) (CommentReaction, error) {
+type AddReactionRow struct {
+ ID pgtype.UUID `json:"id"`
+ CommentID pgtype.UUID `json:"comment_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ActorType string `json:"actor_type"`
+ ActorID pgtype.UUID `json:"actor_id"`
+ Emoji string `json:"emoji"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ CommentRevision int64 `json:"comment_revision"`
+}
+
+func (q *Queries) AddReaction(ctx context.Context, arg AddReactionParams) (AddReactionRow, error) {
row := q.db.QueryRow(ctx, addReaction,
arg.CommentID,
arg.WorkspaceID,
@@ -34,7 +63,7 @@ func (q *Queries) AddReaction(ctx context.Context, arg AddReactionParams) (Comme
arg.ActorID,
arg.Emoji,
)
- var i CommentReaction
+ var i AddReactionRow
err := row.Scan(
&i.ID,
&i.CommentID,
@@ -43,6 +72,7 @@ func (q *Queries) AddReaction(ctx context.Context, arg AddReactionParams) (Comme
&i.ActorID,
&i.Emoji,
&i.CreatedAt,
+ &i.CommentRevision,
)
return i, err
}
@@ -81,9 +111,19 @@ func (q *Queries) ListReactionsByCommentIDs(ctx context.Context, dollar_1 []pgty
return items, nil
}
-const removeReaction = `-- name: RemoveReaction :exec
-DELETE FROM comment_reaction
-WHERE comment_id = $1 AND actor_type = $2 AND actor_id = $3 AND emoji = $4
+const removeReaction = `-- name: RemoveReaction :one
+WITH deleted AS (
+ DELETE FROM comment_reaction
+ WHERE comment_id = $1 AND actor_type = $2 AND actor_id = $3 AND emoji = $4
+ RETURNING comment_id
+), bumped AS (
+ UPDATE comment
+ SET revision = revision + 1
+ WHERE id IN (SELECT comment_id FROM deleted)
+ RETURNING revision
+)
+SELECT EXISTS(SELECT 1 FROM deleted) AS changed,
+ COALESCE((SELECT revision FROM bumped), 0)::bigint AS comment_revision
`
type RemoveReactionParams struct {
@@ -93,12 +133,19 @@ type RemoveReactionParams struct {
Emoji string `json:"emoji"`
}
-func (q *Queries) RemoveReaction(ctx context.Context, arg RemoveReactionParams) error {
- _, err := q.db.Exec(ctx, removeReaction,
+type RemoveReactionRow struct {
+ Changed bool `json:"changed"`
+ CommentRevision int64 `json:"comment_revision"`
+}
+
+func (q *Queries) RemoveReaction(ctx context.Context, arg RemoveReactionParams) (RemoveReactionRow, error) {
+ row := q.db.QueryRow(ctx, removeReaction,
arg.CommentID,
arg.ActorType,
arg.ActorID,
arg.Emoji,
)
- return err
+ var i RemoveReactionRow
+ err := row.Scan(&i.Changed, &i.CommentRevision)
+ return i, err
}
diff --git a/server/pkg/db/generated/squad.sql.go b/server/pkg/db/generated/squad.sql.go
index 49c3feca95..6039d3445a 100644
--- a/server/pkg/db/generated/squad.sql.go
+++ b/server/pkg/db/generated/squad.sql.go
@@ -654,7 +654,7 @@ func (q *Queries) RemoveSquadMember(ctx context.Context, arg RemoveSquadMemberPa
}
const transferSquadAssignees = `-- name: TransferSquadAssignees :exec
-UPDATE issue SET assignee_type = 'agent', assignee_id = $2, updated_at = now()
+UPDATE issue SET assignee_type = 'agent', assignee_id = $2, revision = revision + 1, updated_at = now()
WHERE assignee_type = 'squad' AND assignee_id = $1
`
diff --git a/server/pkg/db/queries/attachment.sql b/server/pkg/db/queries/attachment.sql
index b92cebce42..13473ee3a6 100644
--- a/server/pkg/db/queries/attachment.sql
+++ b/server/pkg/db/queries/attachment.sql
@@ -1,13 +1,29 @@
-- name: CreateAttachment :one
-INSERT INTO attachment (
- id, workspace_id, issue_id, comment_id, chat_session_id, task_id,
- uploader_type, uploader_id, filename, url, content_type, size_bytes
-)
-VALUES (
- $1, $2, sqlc.narg(issue_id), sqlc.narg(comment_id), sqlc.narg(chat_session_id), sqlc.narg(task_id),
- $3, $4, $5, $6, $7, $8
+WITH inserted AS (
+ INSERT INTO attachment (
+ id, workspace_id, issue_id, comment_id, chat_session_id, task_id,
+ uploader_type, uploader_id, filename, url, content_type, size_bytes
+ )
+ VALUES (
+ $1, $2, sqlc.narg(issue_id), sqlc.narg(comment_id), sqlc.narg(chat_session_id), sqlc.narg(task_id),
+ $3, $4, $5, $6, $7, $8
+ )
+ RETURNING *
+), bumped_issue AS (
+ UPDATE issue
+ SET revision = revision + 1
+ WHERE id IN (SELECT issue_id FROM inserted WHERE issue_id IS NOT NULL)
+ RETURNING revision
+), bumped_comment AS (
+ UPDATE comment
+ SET revision = revision + 1
+ WHERE id IN (SELECT comment_id FROM inserted WHERE comment_id IS NOT NULL)
+ RETURNING revision
)
-RETURNING *;
+SELECT inserted.*,
+ COALESCE((SELECT revision FROM bumped_issue), 0)::bigint AS issue_revision,
+ COALESCE((SELECT revision FROM bumped_comment), 0)::bigint AS comment_revision
+FROM inserted;
-- name: ListAttachmentsByIssue :many
SELECT * FROM attachment
@@ -54,7 +70,7 @@ WHERE issue_id = $2
AND comment_id IS NULL
AND id = ANY($3::uuid[]);
--- name: ReplaceCommentAttachments :exec
+-- name: ReplaceCommentAttachments :execrows
UPDATE attachment
SET comment_id = CASE
WHEN id = ANY(sqlc.arg(attachment_ids)::uuid[]) THEN $1
@@ -62,7 +78,7 @@ SET comment_id = CASE
END
WHERE issue_id = $2
AND (
- comment_id = $1
+ (comment_id = $1 AND NOT id = ANY(sqlc.arg(attachment_ids)::uuid[]))
OR (comment_id IS NULL AND id = ANY(sqlc.arg(attachment_ids)::uuid[]))
);
@@ -131,15 +147,57 @@ SELECT * FROM attachment
WHERE chat_message_id = ANY($1::uuid[]) AND workspace_id = $2
ORDER BY created_at ASC;
--- name: LinkAttachmentsToIssue :exec
-UPDATE attachment
-SET issue_id = $1
-WHERE workspace_id = $2
+-- 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.
+SELECT id FROM attachment
+WHERE workspace_id = sqlc.arg(workspace_id)
AND issue_id IS NULL
- AND id = ANY($3::uuid[]);
-
--- name: DeleteAttachment :exec
-DELETE FROM attachment WHERE id = $1 AND workspace_id = $2;
+ AND id = ANY(sqlc.arg(attachment_ids)::uuid[])
+ORDER BY id
+FOR UPDATE;
+
+-- name: LinkAttachmentsToIssue :one
+WITH linked AS (
+ UPDATE attachment
+ SET issue_id = sqlc.arg(issue_id)
+ WHERE attachment.workspace_id = sqlc.arg(workspace_id)
+ AND attachment.issue_id IS NULL
+ AND attachment.id = ANY(sqlc.arg(attachment_ids)::uuid[])
+ RETURNING attachment.issue_id
+), bumped_issue AS (
+ UPDATE issue
+ SET revision = revision + 1,
+ updated_at = now()
+ WHERE id = sqlc.arg(issue_id)
+ AND sqlc.arg(bump_revision)::boolean
+ AND EXISTS (SELECT 1 FROM linked)
+ RETURNING revision
+)
+SELECT COUNT(*)::bigint AS linked_count,
+ COALESCE((SELECT revision FROM bumped_issue), 0)::bigint AS issue_revision
+FROM linked;
+
+-- name: DeleteAttachment :one
+WITH deleted AS (
+ DELETE FROM attachment
+ WHERE attachment.id = $1 AND attachment.workspace_id = $2
+ RETURNING issue_id, comment_id
+), bumped_issue AS (
+ UPDATE issue
+ SET revision = revision + 1
+ WHERE id IN (SELECT issue_id FROM deleted WHERE issue_id IS NOT NULL)
+ RETURNING revision
+), bumped_comment AS (
+ UPDATE comment
+ SET revision = revision + 1
+ WHERE id IN (SELECT comment_id FROM deleted WHERE comment_id IS NOT NULL)
+ RETURNING revision
+)
+SELECT EXISTS(SELECT 1 FROM deleted) AS changed,
+ COALESCE((SELECT revision FROM bumped_issue), 0)::bigint AS issue_revision,
+ COALESCE((SELECT revision FROM bumped_comment), 0)::bigint AS comment_revision;
-- name: ListAttachmentsByIDs :many
SELECT * FROM attachment
diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sql
index 0d7d07f049..efae0624e4 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.source_task_id, c.quick_action_id, c.revision,
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.source_task_id, c.quick_action_id, c.revision,
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.source_task_id, c.quick_action_id, c.revision
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.source_task_id, c.quick_action_id, c.revision
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.source_task_id, d.quick_action_id, d.revision
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
+ source_task_id, quick_action_id, revision
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.source_task_id, d.quick_action_id, d.revision
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
+ source_task_id, quick_action_id, revision
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.source_task_id, c.quick_action_id, c.revision,
p.root_id AS thread_root_id,
p.last_activity_at AS thread_last_activity_at
FROM picked p
@@ -438,14 +438,18 @@ WHERE c.id = (SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1);
-- guarantees regardless of what a caller passes. The "Updated date" sort and
-- the daemon GC TTL both read updated_at, so this consistency is load-bearing.
WITH touched_issue AS (
- UPDATE issue SET updated_at = now()
+ UPDATE issue SET updated_at = now(), revision = revision + 1
WHERE issue.id = sqlc.arg(issue_id) AND issue.workspace_id = sqlc.arg(workspace_id)
- RETURNING issue.id, issue.workspace_id
+ RETURNING issue.id, issue.workspace_id, issue.revision
+), inserted_comment 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)
+ SELECT ti.id, ti.workspace_id, sqlc.arg(author_type), sqlc.arg(author_id), sqlc.arg(content), sqlc.arg(type), sqlc.narg(parent_id), sqlc.narg(source_task_id), sqlc.narg(quick_action_id), sqlc.narg(via_plugin_id)
+ FROM touched_issue ti
+ RETURNING *
)
-INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id, via_plugin_id)
-SELECT ti.id, ti.workspace_id, sqlc.arg(author_type), sqlc.arg(author_id), sqlc.arg(content), sqlc.arg(type), sqlc.narg(parent_id), sqlc.narg(source_task_id), sqlc.narg(quick_action_id), sqlc.narg(via_plugin_id)
-FROM touched_issue ti
-RETURNING *;
+SELECT inserted_comment.*, touched_issue.revision AS issue_revision
+FROM inserted_comment
+JOIN touched_issue ON touched_issue.id = inserted_comment.issue_id;
-- name: GetDelegatedFailureRecoveryComment :one
-- The failed task row is locked by the caller before this lookup/insert pair,
@@ -479,8 +483,23 @@ LIMIT 1;
UPDATE comment SET
content = $2,
source_task_id = sqlc.narg(source_task_id),
- updated_at = now()
+ revision = revision + CASE WHEN ROW(content, source_task_id) IS DISTINCT FROM ROW($2, sqlc.narg(source_task_id)) THEN 1 ELSE 0 END,
+ updated_at = CASE WHEN ROW(content, source_task_id) IS DISTINCT FROM ROW($2, sqlc.narg(source_task_id)) THEN now() ELSE updated_at END
WHERE id = $1
+ AND (sqlc.narg('expected_revision')::bigint IS NULL OR revision = sqlc.narg('expected_revision')::bigint)
+ AND (
+ sqlc.narg('content_base')::text IS NULL
+ OR content IS NOT DISTINCT FROM sqlc.narg('content_base')::text
+ OR content IS NOT DISTINCT FROM $2
+ )
+RETURNING *;
+
+-- name: BumpCommentRevision :one
+UPDATE comment
+SET revision = revision + 1,
+ updated_at = now()
+WHERE id = @id
+ AND workspace_id = @workspace_id
RETURNING *;
-- name: HasAgentCommentedSince :one
@@ -510,6 +529,7 @@ UPDATE comment SET
resolved_at = COALESCE(resolved_at, now()),
resolved_by_type = COALESCE(resolved_by_type, $2),
resolved_by_id = COALESCE(resolved_by_id, $3),
+ 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 *;
@@ -554,6 +574,7 @@ UPDATE comment SET
resolved_at = NULL,
resolved_by_type = NULL,
resolved_by_id = NULL,
+ revision = revision + 1,
updated_at = now()
WHERE comment.id IN (SELECT id FROM descendants)
AND comment.id <> @target_id
@@ -566,6 +587,7 @@ UPDATE comment SET
resolved_at = NULL,
resolved_by_type = NULL,
resolved_by_id = NULL,
+ 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 *;
diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sql
index 290490b500..52e7a4f6ed 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -7,7 +7,8 @@
-- "Assigned to me"), and the two filters must produce disjoint result sets.
SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
+ i.revision
FROM issue i
WHERE i.workspace_id = $1
AND (sqlc.narg('status')::text IS NULL OR i.status = sqlc.narg('status'))
@@ -89,9 +90,10 @@ WHERE id = $1 AND workspace_id = $2
FOR KEY SHARE;
-- name: LockIssueForDescriptionUpdate :one
--- Serialize user description saves with detached channel-media appends. The
--- handler merges channel media that landed after the editor's submitted base
--- while holding this lock, then performs UpdateIssue in the same transaction.
+-- Serialize field-baseline checks and combined attachment binding on the
+-- owner row. The handler merges channel media that landed after the editor's
+-- submitted base, updates the issue, and binds this request's attachments in
+-- the same transaction while holding this lock.
SELECT * FROM issue
WHERE id = $1 AND workspace_id = $2
FOR UPDATE;
@@ -110,6 +112,7 @@ SET description = CASE
WHEN description IS NULL OR description = '' THEN sqlc.arg(markdown)
ELSE description || E'\n\n' || sqlc.arg(markdown)
END,
+ revision = revision + 1,
updated_at = now()
WHERE id = sqlc.arg(id)
AND workspace_id = sqlc.arg(workspace_id)
@@ -140,27 +143,61 @@ SELECT * FROM issue
WHERE workspace_id = $1 AND number = $2;
-- name: UpdateIssue :one
-UPDATE issue SET
- title = COALESCE(sqlc.narg('title'), title),
- description = COALESCE(sqlc.narg('description'), description),
- status = COALESCE(sqlc.narg('status'), status),
- priority = COALESCE(sqlc.narg('priority'), priority),
- assignee_type = sqlc.narg('assignee_type'),
- assignee_id = sqlc.narg('assignee_id'),
- position = COALESCE(sqlc.narg('position'), position),
- start_date = sqlc.narg('start_date'),
- due_date = sqlc.narg('due_date'),
- parent_issue_id = sqlc.narg('parent_issue_id'),
- project_id = sqlc.narg('project_id'),
- stage = sqlc.narg('stage'),
- updated_at = now()
-WHERE id = $1
-RETURNING *;
+WITH candidate AS (
+ SELECT
+ i.*,
+ COALESCE(sqlc.narg('title')::text, i.title) AS next_title,
+ COALESCE(sqlc.narg('description')::text, i.description) AS next_description,
+ COALESCE(sqlc.narg('status')::text, i.status) AS next_status,
+ COALESCE(sqlc.narg('priority')::text, i.priority) AS next_priority,
+ sqlc.narg('assignee_type')::text AS next_assignee_type,
+ sqlc.narg('assignee_id')::uuid AS next_assignee_id,
+ COALESCE(sqlc.narg('position')::double precision, i.position) AS next_position,
+ sqlc.narg('start_date')::date AS next_start_date,
+ sqlc.narg('due_date')::date AS next_due_date,
+ sqlc.narg('parent_issue_id')::uuid AS next_parent_issue_id,
+ sqlc.narg('project_id')::uuid AS next_project_id,
+ sqlc.narg('stage')::integer AS next_stage
+ FROM issue AS i
+ WHERE i.id = $1
+ AND (sqlc.narg('expected_revision')::bigint IS NULL OR i.revision = sqlc.narg('expected_revision')::bigint)
+), changed AS (
+ SELECT
+ candidate.*,
+ ROW(
+ title, description, status, priority, assignee_type, assignee_id,
+ position, start_date, due_date, parent_issue_id, project_id, stage
+ ) IS DISTINCT FROM ROW(
+ next_title, next_description, next_status, next_priority,
+ next_assignee_type, next_assignee_id, next_position, next_start_date,
+ next_due_date, next_parent_issue_id, next_project_id, next_stage
+ ) AS did_change
+ FROM candidate
+)
+UPDATE issue AS i SET
+ title = changed.next_title,
+ description = changed.next_description,
+ status = changed.next_status,
+ priority = changed.next_priority,
+ assignee_type = changed.next_assignee_type,
+ assignee_id = changed.next_assignee_id,
+ position = changed.next_position,
+ start_date = changed.next_start_date,
+ due_date = changed.next_due_date,
+ parent_issue_id = changed.next_parent_issue_id,
+ project_id = changed.next_project_id,
+ stage = changed.next_stage,
+ revision = i.revision + changed.did_change::integer,
+ updated_at = CASE WHEN changed.did_change THEN now() ELSE i.updated_at END
+FROM changed
+WHERE i.id = changed.id
+RETURNING i.*;
-- name: UpdateIssueStatus :one
-- Workspace_id in the WHERE clause is a SQL-layer tenant guard; see DeleteIssue.
UPDATE issue SET
status = $2,
+ revision = revision + CASE WHEN status IS DISTINCT FROM $2 THEN 1 ELSE 0 END,
updated_at = now()
WHERE id = $1 AND workspace_id = $3
RETURNING *;
@@ -238,7 +275,8 @@ DELETE FROM issue WHERE issue.id IN (SELECT target.id FROM target);
-- filter; member-direct assignment is intentionally excluded).
SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
+ i.revision
FROM issue i
WHERE i.workspace_id = $1
AND issue_effective_status(i.workspace_id, i.status) NOT IN ('done', 'cancelled')
@@ -411,6 +449,7 @@ GROUP BY parent_issue_id;
-- issue first so this is also the tenant check.
UPDATE issue SET
metadata = jsonb_set(metadata, ARRAY[sqlc.arg('key')::text], sqlc.arg('value')::jsonb),
+ revision = revision + CASE WHEN metadata -> sqlc.arg('key')::text IS DISTINCT FROM sqlc.arg('value')::jsonb THEN 1 ELSE 0 END,
updated_at = now()
WHERE id = sqlc.arg('id') AND workspace_id = sqlc.arg('workspace_id')
RETURNING *;
@@ -420,6 +459,7 @@ RETURNING *;
-- Deleting a missing key is a no-op (still returns the row).
UPDATE issue SET
metadata = metadata - sqlc.arg('key')::text,
+ revision = revision + CASE WHEN metadata ? sqlc.arg('key')::text THEN 1 ELSE 0 END,
updated_at = now()
WHERE id = sqlc.arg('id') AND workspace_id = sqlc.arg('workspace_id')
RETURNING *;
diff --git a/server/pkg/db/queries/issue_label.sql b/server/pkg/db/queries/issue_label.sql
index a69cc23130..6017a3ba84 100644
--- a/server/pkg/db/queries/issue_label.sql
+++ b/server/pkg/db/queries/issue_label.sql
@@ -69,7 +69,7 @@ DELETE FROM skill_to_label WHERE skill_id = $1;
DELETE FROM agent_to_label
WHERE agent_id IN (SELECT id FROM agent WHERE runtime_id = $1 AND kind = 'system');
--- name: AttachLabelToIssue :exec
+-- name: AttachLabelToIssueOnCreate :exec
-- Workspace-guarded INSERT: the WHERE EXISTS clauses ensure both the issue
-- and the label belong to the given workspace. A future caller that forgets
-- handler-level prechecks still cannot attach labels across workspaces.
@@ -88,17 +88,53 @@ AND EXISTS (
)
ON CONFLICT DO NOTHING;
--- name: DetachLabelFromIssue :exec
+-- name: AttachLabelToIssue :one
+WITH inserted AS (
+ INSERT INTO issue_to_label (issue_id, label_id)
+ SELECT sqlc.arg('issue_id')::uuid, sqlc.arg('label_id')::uuid
+ WHERE EXISTS (
+ SELECT 1 FROM issue i
+ WHERE i.id = sqlc.arg('issue_id')::uuid
+ AND i.workspace_id = sqlc.arg('workspace_id')::uuid
+ )
+ AND EXISTS (
+ SELECT 1 FROM issue_label l
+ WHERE l.id = sqlc.arg('label_id')::uuid
+ AND l.workspace_id = sqlc.arg('workspace_id')::uuid
+ AND l.resource_type = 'issue'
+ )
+ ON CONFLICT DO NOTHING
+ RETURNING issue_id
+), bumped AS (
+ UPDATE issue
+ SET revision = revision + 1
+ WHERE id IN (SELECT issue_id FROM inserted)
+ RETURNING revision
+)
+SELECT EXISTS(SELECT 1 FROM inserted) AS changed,
+ COALESCE((SELECT revision FROM bumped), 0)::bigint AS issue_revision;
+
+-- name: DetachLabelFromIssue :one
-- Workspace-guarded DELETE: only deletes if the issue is in the given
-- workspace. Mirror of the attach query.
-DELETE FROM issue_to_label
-WHERE issue_id = sqlc.arg('issue_id')::uuid
- AND label_id = sqlc.arg('label_id')::uuid
- AND EXISTS (
- SELECT 1 FROM issue i
- WHERE i.id = sqlc.arg('issue_id')::uuid
- AND i.workspace_id = sqlc.arg('workspace_id')::uuid
- );
+WITH deleted AS (
+ DELETE FROM issue_to_label
+ WHERE issue_id = sqlc.arg('issue_id')::uuid
+ AND label_id = sqlc.arg('label_id')::uuid
+ AND EXISTS (
+ SELECT 1 FROM issue i
+ WHERE i.id = sqlc.arg('issue_id')::uuid
+ AND i.workspace_id = sqlc.arg('workspace_id')::uuid
+ )
+ RETURNING issue_id
+), bumped AS (
+ UPDATE issue
+ SET revision = revision + 1
+ WHERE id IN (SELECT issue_id FROM deleted)
+ RETURNING revision
+)
+SELECT EXISTS(SELECT 1 FROM deleted) AS changed,
+ COALESCE((SELECT revision FROM bumped), 0)::bigint AS issue_revision;
-- name: ListLabelsByIssue :many
-- Workspace filter at the SQL layer (mirrors GetProjectInWorkspace). Any caller
diff --git a/server/pkg/db/queries/issue_property.sql b/server/pkg/db/queries/issue_property.sql
index 8afc43b1ab..1d4bc3d44f 100644
--- a/server/pkg/db/queries/issue_property.sql
+++ b/server/pkg/db/queries/issue_property.sql
@@ -52,14 +52,16 @@ RETURNING *;
-- on different property keys never clobber each other.
UPDATE issue
SET properties = jsonb_set(properties, ARRAY[sqlc.arg('key')::text], sqlc.arg('value')::jsonb, true),
- updated_at = now()
+ revision = revision + CASE WHEN properties -> sqlc.arg('key')::text IS DISTINCT FROM sqlc.arg('value')::jsonb THEN 1 ELSE 0 END,
+ updated_at = CASE WHEN properties -> sqlc.arg('key')::text IS DISTINCT FROM sqlc.arg('value')::jsonb THEN now() ELSE updated_at END
WHERE id = sqlc.arg('id')::uuid AND workspace_id = sqlc.arg('workspace_id')::uuid
RETURNING *;
-- name: DeleteIssuePropertyValue :one
UPDATE issue
SET properties = properties - sqlc.arg('key')::text,
- updated_at = now()
+ revision = revision + CASE WHEN properties ? sqlc.arg('key')::text THEN 1 ELSE 0 END,
+ updated_at = CASE WHEN properties ? sqlc.arg('key')::text THEN now() ELSE updated_at END
WHERE id = sqlc.arg('id')::uuid AND workspace_id = sqlc.arg('workspace_id')::uuid
RETURNING *;
diff --git a/server/pkg/db/queries/issue_reaction.sql b/server/pkg/db/queries/issue_reaction.sql
index 00e7c45b75..0fa830076b 100644
--- a/server/pkg/db/queries/issue_reaction.sql
+++ b/server/pkg/db/queries/issue_reaction.sql
@@ -1,12 +1,40 @@
-- name: AddIssueReaction :one
-INSERT INTO issue_reaction (issue_id, workspace_id, actor_type, actor_id, emoji)
-VALUES ($1, $2, $3, $4, $5)
-ON CONFLICT (issue_id, actor_type, actor_id, emoji) DO UPDATE SET created_at = issue_reaction.created_at
-RETURNING *;
+WITH inserted AS (
+ INSERT INTO issue_reaction (issue_id, workspace_id, actor_type, actor_id, emoji)
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (issue_id, actor_type, actor_id, emoji) DO NOTHING
+ RETURNING *
+), bumped AS (
+ UPDATE issue
+ SET revision = revision + 1
+ WHERE id IN (SELECT issue_id FROM inserted)
+ RETURNING revision
+)
+SELECT reaction.*, COALESCE((SELECT revision FROM bumped), 0)::bigint AS issue_revision
+FROM inserted reaction
+UNION ALL
+SELECT reaction.*, 0::bigint AS issue_revision
+FROM issue_reaction reaction
+WHERE reaction.issue_id = $1
+ AND reaction.actor_type = $3
+ AND reaction.actor_id = $4
+ AND reaction.emoji = $5
+ AND NOT EXISTS (SELECT 1 FROM inserted)
+LIMIT 1;
--- name: RemoveIssueReaction :exec
-DELETE FROM issue_reaction
-WHERE issue_id = $1 AND actor_type = $2 AND actor_id = $3 AND emoji = $4;
+-- name: RemoveIssueReaction :one
+WITH deleted AS (
+ DELETE FROM issue_reaction
+ WHERE issue_id = $1 AND actor_type = $2 AND actor_id = $3 AND emoji = $4
+ RETURNING issue_id
+), bumped AS (
+ UPDATE issue
+ SET revision = revision + 1
+ WHERE id IN (SELECT issue_id FROM deleted)
+ RETURNING revision
+)
+SELECT EXISTS(SELECT 1 FROM deleted) AS changed,
+ COALESCE((SELECT revision FROM bumped), 0)::bigint AS issue_revision;
-- name: ListIssueReactions :many
SELECT * FROM issue_reaction
diff --git a/server/pkg/db/queries/reaction.sql b/server/pkg/db/queries/reaction.sql
index 10afbadebe..b6b4716658 100644
--- a/server/pkg/db/queries/reaction.sql
+++ b/server/pkg/db/queries/reaction.sql
@@ -1,12 +1,40 @@
-- name: AddReaction :one
-INSERT INTO comment_reaction (comment_id, workspace_id, actor_type, actor_id, emoji)
-VALUES ($1, $2, $3, $4, $5)
-ON CONFLICT (comment_id, actor_type, actor_id, emoji) DO UPDATE SET created_at = comment_reaction.created_at
-RETURNING *;
+WITH inserted AS (
+ INSERT INTO comment_reaction (comment_id, workspace_id, actor_type, actor_id, emoji)
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (comment_id, actor_type, actor_id, emoji) DO NOTHING
+ RETURNING *
+), bumped AS (
+ UPDATE comment
+ SET revision = revision + 1
+ WHERE id IN (SELECT comment_id FROM inserted)
+ RETURNING revision
+)
+SELECT reaction.*, COALESCE((SELECT revision FROM bumped), 0)::bigint AS comment_revision
+FROM inserted reaction
+UNION ALL
+SELECT reaction.*, 0::bigint AS comment_revision
+FROM comment_reaction reaction
+WHERE reaction.comment_id = $1
+ AND reaction.actor_type = $3
+ AND reaction.actor_id = $4
+ AND reaction.emoji = $5
+ AND NOT EXISTS (SELECT 1 FROM inserted)
+LIMIT 1;
--- name: RemoveReaction :exec
-DELETE FROM comment_reaction
-WHERE comment_id = $1 AND actor_type = $2 AND actor_id = $3 AND emoji = $4;
+-- name: RemoveReaction :one
+WITH deleted AS (
+ DELETE FROM comment_reaction
+ WHERE comment_id = $1 AND actor_type = $2 AND actor_id = $3 AND emoji = $4
+ RETURNING comment_id
+), bumped AS (
+ UPDATE comment
+ SET revision = revision + 1
+ WHERE id IN (SELECT comment_id FROM deleted)
+ RETURNING revision
+)
+SELECT EXISTS(SELECT 1 FROM deleted) AS changed,
+ COALESCE((SELECT revision FROM bumped), 0)::bigint AS comment_revision;
-- name: ListReactionsByCommentIDs :many
SELECT * FROM comment_reaction
diff --git a/server/pkg/db/queries/squad.sql b/server/pkg/db/queries/squad.sql
index 567c8489ce..17300551ef 100644
--- a/server/pkg/db/queries/squad.sql
+++ b/server/pkg/db/queries/squad.sql
@@ -117,7 +117,7 @@ ORDER BY s.created_at ASC;
-- name: TransferSquadAssignees :exec
-- Transfer all issues assigned to a squad to the squad's leader agent.
-UPDATE issue SET assignee_type = 'agent', assignee_id = $2, updated_at = now()
+UPDATE issue SET assignee_type = 'agent', assignee_id = $2, revision = revision + 1, updated_at = now()
WHERE assignee_type = 'squad' AND assignee_id = $1;
-- name: TransferSquadAutopilotsToLeader :exec