Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: mark an issue as a duplicate from the status picker (MUL-7349) (#8728)
Bohan Jiang96db419c0a65
diff --git a/e2e/issue-duplicate.spec.ts b/e2e/issue-duplicate.spec.tsnew file mode 100644index 0000000000..8a2693611c--- /dev/null+++ b/e2e/issue-duplicate.spec.ts@@ -0,0 +1,56 @@+import { test, expect } from "@playwright/test";+import { loginAsDefault, createTestApi } from "./helpers";+import type { TestApiClient } from "./fixtures";++// Mark as duplicate (MUL-7349): the status picker's action cancels an issue+// and links it to its original; the original lists it; reopening removes it.+test.describe("Mark as duplicate", () => {+ let api: TestApiClient;+ let slug: string;++ test.beforeEach(async ({ page }) => {+ api = await createTestApi();+ slug = await loginAsDefault(page);+ });++ test.afterEach(async () => {+ await api.cleanup();+ });++ test("marks, links both sides, and unmarks", async ({ page }) => {+ const run = Date.now().toString(36);+ const originalTitle = `Tap targets too small ${run}`;+ const original = await api.createIssue(originalTitle, { status: "in_progress" });+ const duplicate = await api.createIssue(`Status picker hard to tap ${run}`, {+ status: "todo",+ });++ await page.goto(`/${slug}/issues/${duplicate.id}`);+ // The detail page can close a just-opened picker while it finishes+ // loading, so retry opening until the action takes the click.+ await expect(async () => {+ await page.getByRole("button", { name: "Todo", exact: true }).first().click();+ await page.getByRole("button", { name: "Mark as duplicate..." }).click({ timeout: 2000 });+ }).toPass();++ const picker = page.getByRole("dialog");+ await picker.getByPlaceholder("Search issues...").fill(originalTitle);+ await picker.getByText(originalTitle).click();++ const originalLink = page.getByRole("link", {+ name: `${original.identifier} ${originalTitle}`,+ });+ await expect(originalLink).toBeVisible();+ await expect(page.getByRole("button", { name: "Cancelled", exact: true }).first()).toBeVisible();++ await originalLink.click();+ await expect(page).toHaveURL(new RegExp(`/issues/${original.id}$`));+ await expect(page.getByRole("button", { name: "Duplicates" })).toBeVisible();+ await expect(page.getByRole("link", { name: new RegExp(duplicate.identifier) })).toBeVisible();++ await page.goto(`/${slug}/issues/${duplicate.id}`);+ await page.getByRole("button", { name: "Unmark and move to Todo" }).click();+ await expect(page.getByRole("button", { name: "Unmark and move to Todo" })).toHaveCount(0);+ await expect(page.getByRole("button", { name: "Todo", exact: true }).first()).toBeVisible();+ });+});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex a18d8dd128..5c77648956 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -10,6 +10,7 @@ import type {CreateIssueRequest,MoveIssueRequest,UpdateIssueRequest,+ IssueDuplicates,GroupedIssuesResponse,ListIssuesResponse,SearchIssuesResponse,@@ -259,6 +260,7 @@ import {SendChatMessageResponseSchema,StartMikaOnboardingResponseSchema,ChildIssuesResponseSchema,+ IssueDuplicatesResponseSchema,ChildIssueProgressResponseSchema,CommentsListSchema,CommentTriggerPreviewSchema,@@ -1453,6 +1455,16 @@ export class ApiClient {});}+ async listIssueDuplicates(id: string): Promise<IssueDuplicates> {+ const raw = await this.fetch<unknown>(`/api/issues/${id}/duplicates`);+ return parseWithFallback(+ raw,+ IssueDuplicatesResponseSchema,+ { duplicate_of: null, duplicates: [] },+ { endpoint: "GET /api/issues/:id/duplicates" },+ );+ }+async listChildIssues(id: string): Promise<{ issues: Issue[] }> {const raw = await this.fetch<unknown>(`/api/issues/${id}/children`);return parseWithFallback(raw, ChildIssuesResponseSchema, { issues: [] }, {diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex a6b31550b9..0769fe17b8 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -911,6 +911,22 @@ describe("ApiClient schema fallback", () => {});});+ describe("listIssueDuplicates", () => {+ it("falls back to an empty relation when the body is null", async () => {+ stubFetchJson(null);+ const client = new ApiClient("https://api.example.test");+ const res = await client.listIssueDuplicates("issue-1");+ expect(res).toEqual({ duplicate_of: null, duplicates: [] });+ });++ it("defaults missing fields instead of failing", async () => {+ stubFetchJson({});+ const client = new ApiClient("https://api.example.test");+ const res = await client.listIssueDuplicates("issue-1");+ expect(res).toEqual({ duplicate_of: null, duplicates: [] });+ });+ });+describe("getChildIssueProgress", () => {it("validates the response before query selectors iterate it", async () => {stubFetchJson({ progress: "invalid" });diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 26afa7fdd1..0298966f8a 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1528,6 +1528,11 @@ export const ChildIssuesResponseSchema = z.object({issues: z.array(IssueSchema).default([]),}).loose();+export const IssueDuplicatesResponseSchema = z.object({+ duplicate_of: IssueSchema.nullable().default(null),+ duplicates: z.array(IssueSchema).default([]),+}).loose();+export const ChildIssueProgressResponseSchema = z.object({progress: z.array(diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.tsindex fe145509ba..7cb90e04f9 100644--- a/packages/core/issues/mutations.ts+++ b/packages/core/issues/mutations.ts@@ -206,6 +206,7 @@ export function useUpdateIssue() {// a rapid follow-up edit. mutationFn still sends the full payload.const {suppress_run: _suppressRun,+ duplicate_of_issue_id: _duplicateOfIssueId,description: _description,description_base: _descriptionBase,title_base: _titleBase,@@ -317,6 +318,7 @@ export function useUpdateIssue() {// is the plain surgical patch it always was.const {suppress_run: _suppressRun,+ duplicate_of_issue_id: _duplicateOfIssueId,description_base: _descriptionBase,move_intent: _moveIntent,id: _id,@@ -377,6 +379,14 @@ export function useUpdateIssue() {if (vars.attachment_ids?.length) {qc.invalidateQueries({ queryKey: issueKeys.attachments(vars.id) });}+ // A duplicate mark is not on Issue; refresh both sides now rather than+ // waiting for the realtime echo.+ if (vars.duplicate_of_issue_id) {+ qc.invalidateQueries({ queryKey: issueKeys.duplicates(wsId, vars.id) });+ qc.invalidateQueries({+ queryKey: issueKeys.duplicates(wsId, vars.duplicate_of_issue_id),+ });+ }// Invalidate old parent's children cacheif (ctx?.parentId) {qc.invalidateQueries({diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex b8366a61fd..b7c968abd2 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -130,6 +130,11 @@ export const issueKeys = {/** Resolve a bare issue identifier (e.g. "MUL-123") to an issue. */identifier: (wsId: string, identifier: string) =>[...issueKeys.all(wsId), "identifier", identifier] as const,+ /** Prefix for every per-issue duplicate-relation query in a workspace. */+ duplicatesAll: (wsId: string) =>+ [...issueKeys.all(wsId), "duplicates"] as const,+ duplicates: (wsId: string, id: string) =>+ [...issueKeys.duplicatesAll(wsId), id] as const,/** Prefix for every per-parent children query in a workspace. */childrenAll: (wsId: string) =>[...issueKeys.all(wsId), "children"] as const,@@ -493,6 +498,18 @@ export function childIssueProgressOptions(wsId: string) {});}+/** Both sides of an issue's duplicate relation: its original and its duplicates. */+export function issueDuplicatesOptions(wsId: string, id: string) {+ return queryOptions({+ queryKey: issueKeys.duplicates(wsId, id),+ queryFn: () => api.listIssueDuplicates(id),+ // Same reason as childIssuesOptions: a mark written while this workspace+ // is not the active realtime subscription would otherwise leave the+ // Infinity-stale snapshot wrong when the issue is opened again.+ refetchOnMount: "always",+ });+}+export function childIssuesOptions(wsId: string, id: string) {return queryOptions({queryKey: issueKeys.children(wsId, id),diff --git a/packages/core/issues/ws-updaters.ts b/packages/core/issues/ws-updaters.tsindex d5fc0f400d..fa661caeb7 100644--- a/packages/core/issues/ws-updaters.ts+++ b/packages/core/issues/ws-updaters.ts@@ -753,12 +753,31 @@ export function invalidatePropertyWindowQueries(qc: QueryClient, wsId: string) {});}+/**+ * Refreshes the duplicate relations an issue:updated event touched: the issue+ * itself and the originals it was marked against before and after the write.+ */+export function onIssueDuplicateMarkChanged(+ qc: QueryClient,+ wsId: string,+ issueId: string,+ next: string | null | undefined,+ prev: string | null | undefined,+) {+ if ((next ?? null) === (prev ?? null)) return;+ for (const id of [issueId, next, prev]) {+ if (id) qc.invalidateQueries({ queryKey: issueKeys.duplicates(wsId, id) });+ }+}+export function onIssueDeleted(qc: QueryClient,wsId: string,issueId: string,) {cleanupDeletedIssueCaches(qc, wsId, issueId);+ // Deleting an original clears its duplicates' marks server-side.+ qc.invalidateQueries({ queryKey: issueKeys.duplicatesAll(wsId) });qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });diff --git a/packages/core/modals/store.ts b/packages/core/modals/store.tsindex 01ccfabc58..3c9664438b 100644--- a/packages/core/modals/store.ts+++ b/packages/core/modals/store.ts@@ -9,6 +9,7 @@ type ModalType =| "create-squad"| "feedback"| "issue-set-parent"+ | "issue-mark-duplicate"| "issue-add-child"| "issue-delete-confirm"| "issue-run-confirm"diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 6d910b3fb8..937fed3c0c 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -33,6 +33,7 @@ import { telegramKeys } from "../telegram/queries";import {onIssueCreated,onIssueUpdated,+ onIssueDuplicateMarkChanged,onIssueDeleted,onIssueLabelsChanged,onIssuePropertiesChanged,@@ -1025,6 +1026,13 @@ export function useRealtimeSync(statusChanged: payload.status_changed,projectChanged: payload.project_changed,});+ onIssueDuplicateMarkChanged(+ qc,+ wsId,+ issue.id,+ payload.duplicate_of_issue_id,+ payload.prev_duplicate_of_issue_id,+ );if (issue.status) {onInboxIssueStatusChanged(qc, wsId, issue.id, issue.status);}diff --git a/packages/core/types/api.ts b/packages/core/types/api.tsindex 178a667c00..e1fbf7cfee 100644--- a/packages/core/types/api.ts+++ b/packages/core/types/api.ts@@ -80,6 +80,19 @@ export interface UpdateIssueRequest {* MUL-3375). The assignee/status change still applies. Control field —* strip from optimistic cache patches; never written onto the Issue. */suppress_run?: boolean;+ /** Marks this issue as a duplicate of another issue (MUL-7349). The server+ * also sets status to cancelled; any later status change away from+ * cancelled removes the mark. Write-only — read it back through+ * `listIssueDuplicates`. Control field: strip from optimistic patches. */+ duplicate_of_issue_id?: string;+}++/** Both sides of an issue's duplicate relation (MUL-7349). */+export interface IssueDuplicates {+ /** The original this issue duplicates, when it is marked as a duplicate. */+ duplicate_of: Issue | null;+ /** Issues marked as duplicates of this one. */+ duplicates: Issue[];}/**diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex db0563c892..bc7d791f6a 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -117,6 +117,10 @@ export interface IssueUpdatedPayload {assignee_changed?: boolean;status_changed?: boolean;project_changed?: boolean;+ // Both ends of a duplicate-mark change (MUL-7349). The mark is not on Issue,+ // so these tell the realtime layer whose duplicate relations to refresh.+ duplicate_of_issue_id?: string | null;+ prev_duplicate_of_issue_id?: string | null;}export interface IssueDeletedPayload {diff --git a/packages/views/issues/actions/issue-actions-menu-items.tsx b/packages/views/issues/actions/issue-actions-menu-items.tsxindex fa5baf60c6..08101a300f 100644--- a/packages/views/issues/actions/issue-actions-menu-items.tsx+++ b/packages/views/issues/actions/issue-actions-menu-items.tsx@@ -8,6 +8,7 @@ import {ArrowUp,Calendar,CalendarClock,+ Copy,ExternalLink,FolderOpen,Link2,@@ -119,6 +120,7 @@ export function IssueActionsMenuItems({openSetParent,removeParent,openAddChild,+ openMarkDuplicate,openDeleteConfirm,} = actions;@@ -354,6 +356,10 @@ export function IssueActionsMenuItems({<ArrowDown className="h-3.5 w-3.5" />{t(($) => $.actions.add_sub_issue)}</P.Item>+ <P.Item onClick={openMarkDuplicate}>+ <Copy className="h-3.5 w-3.5" />+ {t(($) => $.actions.mark_duplicate)}+ </P.Item></P.SubContent></P.Sub>diff --git a/packages/views/issues/actions/use-issue-actions.ts b/packages/views/issues/actions/use-issue-actions.tsindex 3ee3cf9add..d5eafd6007 100644--- a/packages/views/issues/actions/use-issue-actions.ts+++ b/packages/views/issues/actions/use-issue-actions.ts@@ -33,6 +33,7 @@ export interface UseIssueActionsResult {openSetParent: () => void;removeParent: () => void;openAddChild: () => void;+ openMarkDuplicate: () => void;openDeleteConfirm: (opts?: { onDeletedFallbackPath?: string }) => void;}@@ -220,6 +221,11 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {openModal("issue-set-parent", { issueId });}, [openModal, issueId]);+ const openMarkDuplicate = useCallback(() => {+ if (!issueId) return;+ openModal("issue-mark-duplicate", { issueId });+ }, [openModal, issueId]);+// Detach from the parent and promote to a standalone issue. Reversible// (Set parent re-links it), non-destructive, and mirrors the clear-date// actions — so it applies directly instead of a confirm modal. `stage`@@ -292,6 +298,7 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {openSetParent,removeParent,openAddChild,+ openMarkDuplicate,openDeleteConfirm,};}diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 1802d033cc..3d839aa8f5 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -12,6 +12,7 @@ import { useState, useEffect, useCallback, useMemo, useRef, Fragment, type Reactimport { Virtuoso, type VirtuosoHandle } from "react-virtuoso";import { useDefaultLayout, usePanelRef } from "react-resizable-panels";import { AppLink, useBackOrReplace } from "../../navigation";+import { IssueDuplicateBanner, IssueDuplicatesSection } from "./issue-duplicates";import {Archive,Calendar,@@ -2323,7 +2324,12 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr{propertiesOpen && <div className="grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 pl-2">{/* Core props — always rendered. */}<PropRow label={t(($) => $.detail.prop_status)}>- <StatusPicker status={issue.status} onUpdate={handleUpdateField} align="start" />+ <StatusPicker+ status={issue.status}+ onUpdate={handleUpdateField}+ align="start"+ onMarkDuplicate={actions.openMarkDuplicate}+ /></PropRow><PropRow label={t(($) => $.detail.prop_assignee)}><AssigneePicker assigneeType={issue.assignee_type} assigneeId={issue.assignee_id} onUpdate={handleUpdateField} align="start" />@@ -2555,6 +2561,8 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr</div>)}+ <IssueDuplicatesSection issueId={issue.id} />+{/* Pull requests — hidden when the workspace disables the PR sidebar(or the GitHub master switch is off). Backend data is kept eitherway so re-enabling restores the section instantly. */}@@ -2899,6 +2907,10 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr`useStickyComposer`), so it lands here — right where the launcherfloats — once the reader scrolls to the bottom. */}<div className="mx-auto w-full max-w-4xl px-3 py-6 max-md:pb-chat-launcher md:px-8 md:py-8">+ <IssueDuplicateBanner+ issue={issue}+ onUnmark={() => handleUpdateField({ status: "todo" })}+ />{titleLazy.active && (<div className={titleLazy.ready ? undefined : "hidden"}><TitleEditordiff --git a/packages/views/issues/components/issue-duplicates.test.tsx b/packages/views/issues/components/issue-duplicates.test.tsxnew file mode 100644index 0000000000..fd7b75d089--- /dev/null+++ b/packages/views/issues/components/issue-duplicates.test.tsx@@ -0,0 +1,101 @@+// @vitest-environment jsdom++import { cleanup, fireEvent, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { buildIssueStatusCatalog } from "@multica/core/issue-statuses";+import type { Issue, IssueDuplicates } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";++const listIssueDuplicates = vi.fn<(id: string) => Promise<IssueDuplicates>>();++vi.mock("@multica/core/api", () => ({+ api: { listIssueDuplicates: (id: string) => listIssueDuplicates(id) },+}));+vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => "workspace-1",+}));+vi.mock("@multica/core/paths", () => ({+ useWorkspacePaths: () => ({ issueDetail: (id: string) => `/acme/issues/${id}` }),+}));+vi.mock("@multica/core/issue-statuses/hooks", () => ({+ useIssueStatuses: () => buildIssueStatusCatalog(undefined),+}));+vi.mock("../../navigation", () => ({+ AppLink: ({ href, children, className }: { href: string; children: ReactNode; className?: string }) => (+ <a href={href} className={className}>+ {children}+ </a>+ ),+}));++import { IssueDuplicateBanner, IssueDuplicatesSection } from "./issue-duplicates";++function issue(overrides: Partial<Issue>): Issue {+ return {+ id: "issue",+ identifier: "MUL-1",+ title: "An issue",+ status: "todo",+ ...overrides,+ } as Issue;+}++const ORIGINAL = issue({ id: "original", identifier: "MUL-6980", title: "Tap targets are too small", status: "in_progress" });+const DUPLICATE = issue({ id: "duplicate", identifier: "MUL-7412", title: "Status picker is hard to tap", status: "cancelled" });++function renderWithQuery(ui: ReactNode) {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return renderWithI18n(<QueryClientProvider client={qc}>{ui}</QueryClientProvider>);+}++afterEach(() => {+ cleanup();+ listIssueDuplicates.mockReset();+});++describe("IssueDuplicateBanner", () => {+ it("points a cancelled duplicate at its original and offers to unmark it", async () => {+ listIssueDuplicates.mockResolvedValue({ duplicate_of: ORIGINAL, duplicates: [] });+ const onUnmark = vi.fn();+ renderWithQuery(<IssueDuplicateBanner issue={DUPLICATE} onUnmark={onUnmark} />);++ const link = await screen.findByRole("link", { name: "MUL-6980 Tap targets are too small" });+ expect(link.getAttribute("href")).toBe("/acme/issues/original");++ fireEvent.click(screen.getByRole("button", { name: "Unmark and move to Todo" }));+ expect(onUnmark).toHaveBeenCalledTimes(1);+ });++ // The server clears the mark whenever the status leaves cancelled; a relation+ // fetched before that must not keep the banner up after an optimistic reopen.+ it("hides once the issue is no longer cancelled", async () => {+ listIssueDuplicates.mockResolvedValue({ duplicate_of: ORIGINAL, duplicates: [] });+ renderWithQuery(+ <IssueDuplicateBanner issue={{ ...DUPLICATE, status: "todo" }} onUnmark={() => {}} />,+ );++ await waitFor(() => expect(listIssueDuplicates).toHaveBeenCalled());+ expect(screen.queryByRole("button", { name: "Unmark and move to Todo" })).toBeNull();+ });+});++describe("IssueDuplicatesSection", () => {+ it("lists the issues marked as duplicates of this one", async () => {+ listIssueDuplicates.mockResolvedValue({ duplicate_of: null, duplicates: [DUPLICATE] });+ renderWithQuery(<IssueDuplicatesSection issueId="original" />);++ const row = await screen.findByRole("link", { name: /MUL-7412/ });+ expect(row.getAttribute("href")).toBe("/acme/issues/duplicate");+ expect(screen.getByRole("button", { name: "Duplicates" })).toBeTruthy();+ });++ it("renders nothing when there are no duplicates", async () => {+ listIssueDuplicates.mockResolvedValue({ duplicate_of: null, duplicates: [] });+ const { container } = renderWithQuery(<IssueDuplicatesSection issueId="original" />);++ await waitFor(() => expect(listIssueDuplicates).toHaveBeenCalledWith("original"));+ expect(container.textContent).toBe("");+ });+});diff --git a/packages/views/issues/components/issue-duplicates.tsx b/packages/views/issues/components/issue-duplicates.tsxnew file mode 100644index 0000000000..0750e07dc8--- /dev/null+++ b/packages/views/issues/components/issue-duplicates.tsx@@ -0,0 +1,103 @@+"use client";++import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { ChevronRight, Copy } from "lucide-react";+import type { Issue } from "@multica/core/types";+import { issueStatusCategory } from "@multica/core/issues";+import { issueDuplicatesOptions } from "@multica/core/issues/queries";+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";+import { useWorkspaceId } from "@multica/core/hooks";+import { useWorkspacePaths } from "@multica/core/paths";+import { Button } from "@multica/ui/components/ui/button";+import { AppLink } from "../../navigation";+import { StatusIcon } from "./status-icon";+import { useT } from "../../i18n";++// Duplicate marks (MUL-7349). A duplicate is a cancelled issue that remembers+// its original; the server clears the mark whenever the status leaves+// cancelled, so both surfaces below also key off the status.++/**+ * Banner shown above a duplicate's title, pointing at its original. Removing+ * the mark is a plain status change to todo, done through the caller so it+ * shares the detail page's status write path.+ */+export function IssueDuplicateBanner({+ issue,+ onUnmark,+}: {+ issue: Issue;+ onUnmark: () => void;+}) {+ const { t } = useT("issues");+ const wsId = useWorkspaceId();+ const paths = useWorkspacePaths();+ const { data } = useQuery(issueDuplicatesOptions(wsId, issue.id));+ const original = data?.duplicate_of;+ if (issue.status !== "cancelled" || !original) return null;++ return (+ <div className="mb-4 flex items-center gap-2 rounded-md border bg-muted/40 px-3 py-2 text-body">+ <Copy className="h-4 w-4 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1 truncate">+ {t(($) => $.duplicates.banner_prefix)}{" "}+ <AppLink+ href={paths.issueDetail(original.id)}+ className="font-medium underline-offset-4 hover:underline"+ >+ {original.identifier} {original.title}+ </AppLink>+ </span>+ <Button type="button" variant="ghost" size="sm" onClick={onUnmark}>+ {t(($) => $.duplicates.unmark)}+ </Button>+ </div>+ );+}++/** Sidebar list of the issues marked as duplicates of this one. */+export function IssueDuplicatesSection({ issueId }: { issueId: string }) {+ const { t } = useT("issues");+ const wsId = useWorkspaceId();+ const paths = useWorkspacePaths();+ const { colorOf, iconOf } = useIssueStatuses(wsId);+ const [open, setOpen] = useState(true);+ const { data } = useQuery(issueDuplicatesOptions(wsId, issueId));+ const duplicates = data?.duplicates ?? [];+ if (duplicates.length === 0) return null;++ return (+ <div>+ <button+ type="button"+ className={`flex w-full items-center gap-1 rounded-md px-2 py-1 text-caption font-medium transition-colors mb-2 hover:bg-accent/70 ${open ? "" : "text-muted-foreground hover:text-foreground"}`}+ onClick={() => setOpen(!open)}+ >+ {t(($) => $.duplicates.section_title)}+ <ChevronRight className={`!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform ${open ? "rotate-90" : ""}`} />+ </button>+ {open && (+ <div className="pl-2">+ {duplicates.map((duplicate) => (+ <AppLink+ key={duplicate.id}+ href={paths.issueDetail(duplicate.id)}+ className="group flex items-center gap-1.5 rounded-md px-2 -mx-2 py-1.5 text-caption hover:bg-accent/50 transition-colors"+ >+ <StatusIcon+ status={duplicate.status}+ color={colorOf(duplicate.status)}+ icon={iconOf(duplicate.status)}+ category={issueStatusCategory(duplicate) ?? undefined}+ className="h-3.5 w-3.5 shrink-0"+ />+ <span className="text-muted-foreground shrink-0">{duplicate.identifier}</span>+ <span className="truncate group-hover:text-foreground">{duplicate.title}</span>+ </AppLink>+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/packages/views/issues/components/pickers/status-picker.test.tsx b/packages/views/issues/components/pickers/status-picker.test.tsxindex ff09305981..726018d721 100644--- a/packages/views/issues/components/pickers/status-picker.test.tsx+++ b/packages/views/issues/components/pickers/status-picker.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdom-import { cleanup } from "@testing-library/react";+import { cleanup, fireEvent, screen } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";import { buildIssueStatusCatalog } from "@multica/core/issue-statuses";import type { IssueStatusEntry } from "@multica/core/types";@@ -112,3 +112,38 @@ describe("StatusPicker trigger color", () => {expect(row?.innerHTML).toBe(trigger?.innerHTML);});});++describe("StatusPicker mark-as-duplicate action", () => {+ // Create and batch surfaces must never offer it: an issue that does not+ // exist yet cannot duplicate anything.+ it("is absent unless the caller opts in", () => {+ renderWithI18n(+ <StatusPicker status="todo" onUpdate={() => {}} open onOpenChange={() => {}} />,+ );+ expect(screen.queryByRole("button", { name: "Mark as duplicate..." })).toBeNull();+ });++ it("is an action beside the options, not another status", () => {+ const onMarkDuplicate = vi.fn();+ const onUpdate = vi.fn();+ const onOpenChange = vi.fn();+ renderWithI18n(+ <StatusPicker+ status="todo"+ onUpdate={onUpdate}+ open+ onOpenChange={onOpenChange}+ onMarkDuplicate={onMarkDuplicate}+ />,+ );++ const action = screen.getByRole("button", { name: "Mark as duplicate..." });+ // Outside the arrow-key listbox, so keyboard nav and search skip it.+ expect(action.hasAttribute("data-picker-item")).toBe(false);++ fireEvent.click(action);+ expect(onMarkDuplicate).toHaveBeenCalledTimes(1);+ expect(onUpdate).not.toHaveBeenCalled();+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });+});diff --git a/packages/views/issues/components/pickers/status-picker.tsx b/packages/views/issues/components/pickers/status-picker.tsxindex d713d6fee2..f84b643c7f 100644--- a/packages/views/issues/components/pickers/status-picker.tsx+++ b/packages/views/issues/components/pickers/status-picker.tsx@@ -1,6 +1,7 @@"use client";import { useMemo, useState } from "react";+import { Copy } from "lucide-react";import type { IssueStatus, UpdateIssueRequest } from "@multica/core/types";import { STATUS_CONFIG } from "@multica/core/issues/config";import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";@@ -22,6 +23,7 @@ export function StatusPicker({open: controlledOpen,onOpenChange: controlledOnOpenChange,align,+ onMarkDuplicate,}: {/*** The currently-selected status, used to check the matching row. `null`@@ -36,6 +38,12 @@ export function StatusPicker({open?: boolean;onOpenChange?: (v: boolean) => void;align?: "start" | "center" | "end";+ /**+ * Adds the "Mark as duplicate…" action. It is an action, not a status: it+ * opens a picker for the original and only writes once one is chosen. Pass+ * it only for an existing single issue — never on create or batch surfaces.+ */+ onMarkDuplicate?: () => void;}) {const [internalOpen, setInternalOpen] = useState(false);const open = controlledOpen ?? internalOpen;@@ -80,6 +88,24 @@ export function StatusPicker({searchable={searchable}searchPlaceholder={t(($) => $.filters.search_status)}onSearchChange={setQuery}+ footer={+ onMarkDuplicate ? (+ // Rendered outside the arrow-key listbox so keyboard nav and search+ // never treat the action as another status option.+ <button+ type="button"+ onClick={() => {+ setOpen(false);+ setQuery("");+ onMarkDuplicate();+ }}+ className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-body text-muted-foreground hover:bg-accent transition-colors"+ >+ <Copy className="h-3.5 w-3.5" />+ <span>{t(($) => $.pickers.status.mark_duplicate)}</span>+ </button>+ ) : undefined+ }trigger={customTrigger ??(status != null ? (diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 14cc50d662..eca5285e78 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -769,7 +769,8 @@"remove_parent_issue": "Remove parent issue","remove_parent_issue_success": "Removed parent issue","add_sub_issue": "Add sub-issue...",- "delete_issue": "Delete issue"+ "delete_issue": "Delete issue",+ "mark_duplicate": "Mark as duplicate..."},"pickers": {"custom_property": {@@ -817,6 +818,9 @@"manage_dialog_title": "Manage labels","create_action": "Create","create_failed": "Failed to create label"+ },+ "status": {+ "mark_duplicate": "Mark as duplicate..."}},"labels_panel": {@@ -1069,5 +1073,10 @@},"hourly": "Wake every hour","today_time": "Today {{time}}"+ },+ "duplicates": {+ "banner_prefix": "Duplicate of",+ "unmark": "Unmark and move to Todo",+ "section_title": "Duplicates"}}diff --git a/packages/views/locales/en/modals.json b/packages/views/locales/en/modals.jsonindex aa3384b5c6..de7284845c 100644--- a/packages/views/locales/en/modals.json+++ b/packages/views/locales/en/modals.json@@ -246,5 +246,13 @@"error_unknown": "Failed to submit. Try again.","sub_issue_of": "Sub-issue of {{identifier}}"}+ },+ "mark_duplicate": {+ "title": "Mark as duplicate",+ "description": "Search for the original issue. This issue will be cancelled and linked to it.",+ "toast_success": "Marked as a duplicate of {{identifier}}",+ "toast_failed": "Failed to mark as duplicate",+ "error_target_is_duplicate": "{{identifier}} is itself a duplicate. Pick its original instead.",+ "error_has_duplicates": "Other issues are marked as duplicates of this one. Remove those marks first."}}diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex 49b73b2065..fb433ccf84 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -769,7 +769,8 @@"remove_parent_issue": "Retirer la tâche parente","remove_parent_issue_success": "Tâche parente retirée","add_sub_issue": "Ajouter une sous-tâche...",- "delete_issue": "Supprimer la tâche"+ "delete_issue": "Supprimer la tâche",+ "mark_duplicate": "Marquer comme doublon..."},"pickers": {"custom_property": {@@ -817,6 +818,9 @@"manage_dialog_title": "Gérer les étiquettes","create_action": "Créer","create_failed": "Échec de la création de l'étiquette"+ },+ "status": {+ "mark_duplicate": "Marquer comme doublon..."}},"labels_panel": {@@ -1069,5 +1073,10 @@},"hourly": "Réveil chaque heure","today_time": "Aujourd’hui {{time}}"+ },+ "duplicates": {+ "banner_prefix": "Doublon de",+ "unmark": "Retirer la marque et repasser en À faire",+ "section_title": "Doublons"}}diff --git a/packages/views/locales/fr/modals.json b/packages/views/locales/fr/modals.jsonindex b063b3f277..ff558191fc 100644--- a/packages/views/locales/fr/modals.json+++ b/packages/views/locales/fr/modals.json@@ -246,5 +246,13 @@"error_unknown": "Échec de l'envoi. Réessayez.","sub_issue_of": "Sous-tâche de {{identifier}}"}+ },+ "mark_duplicate": {+ "title": "Marquer comme doublon",+ "description": "Recherchez la tâche d'origine. Cette tâche sera annulée et liée à celle-ci.",+ "toast_success": "Marquée comme doublon de {{identifier}}",+ "toast_failed": "Échec du marquage comme doublon",+ "error_target_is_duplicate": "{{identifier}} est elle-même un doublon. Choisissez plutôt sa tâche d'origine.",+ "error_has_duplicates": "D'autres tâches sont marquées comme doublons de celle-ci. Retirez d'abord ces marques."}}diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 76ceebd5ab..ec9903f423 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -738,7 +738,8 @@"remove_parent_issue": "親タスクを解除","remove_parent_issue_success": "親タスクを解除しました","add_sub_issue": "サブタスクを追加...",- "delete_issue": "タスクを削除"+ "delete_issue": "タスクを削除",+ "mark_duplicate": "重複としてマーク..."},"pickers": {"custom_property": {@@ -786,6 +787,9 @@"manage_dialog_title": "ラベルを管理","create_action": "作成","create_failed": "ラベルを作成できませんでした"+ },+ "status": {+ "mark_duplicate": "重複としてマーク..."}},"labels_panel": {@@ -1038,5 +1042,10 @@},"hourly": "毎時起動","today_time": "今日 {{time}}"+ },+ "duplicates": {+ "banner_prefix": "重複元:",+ "unmark": "マークを解除して未着手に戻す",+ "section_title": "重複"}}diff --git a/packages/views/locales/ja/modals.json b/packages/views/locales/ja/modals.jsonindex df4f13ef19..4843f2b54a 100644--- a/packages/views/locales/ja/modals.json+++ b/packages/views/locales/ja/modals.json@@ -244,5 +244,13 @@"error_unknown": "送信できませんでした。再試行してください。","sub_issue_of": "{{identifier}} のサブタスク"}+ },+ "mark_duplicate": {+ "title": "重複としてマーク",+ "description": "元のタスクを検索してください。このタスクはキャンセルされ、元のタスクに関連付けられます。",+ "toast_success": "{{identifier}} の重複としてマークしました",+ "toast_failed": "重複としてマークできませんでした",+ "error_target_is_duplicate": "{{identifier}} 自体が重複です。元のタスクを選択してください",+ "error_has_duplicates": "他のタスクがこのタスクの重複としてマークされています。先にそのマークを解除してください"}}diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex b1ea52789c..561ec127e9 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -738,7 +738,8 @@"remove_parent_issue": "상위 태스크 제거","remove_parent_issue_success": "상위 태스크를 제거했습니다","add_sub_issue": "하위 태스크 추가...",- "delete_issue": "태스크 삭제"+ "delete_issue": "태스크 삭제",+ "mark_duplicate": "중복으로 표시..."},"pickers": {"custom_property": {@@ -786,6 +787,9 @@"manage_dialog_title": "라벨 관리","create_action": "만들기","create_failed": "라벨을 만들지 못했습니다"+ },+ "status": {+ "mark_duplicate": "중복으로 표시..."}},"labels_panel": {@@ -1038,5 +1042,10 @@},"hourly": "매시간 깨우기","today_time": "오늘 {{time}}"+ },+ "duplicates": {+ "banner_prefix": "중복 원본:",+ "unmark": "표시 해제 후 할 일로 이동",+ "section_title": "중복 항목"}}diff --git a/packages/views/locales/ko/modals.json b/packages/views/locales/ko/modals.jsonindex f90b53fd4e..4e2c63cfb2 100644--- a/packages/views/locales/ko/modals.json+++ b/packages/views/locales/ko/modals.json@@ -244,5 +244,13 @@"error_unknown": "제출하지 못했습니다. 다시 시도하세요.","sub_issue_of": "{{identifier}}의 하위 태스크"}+ },+ "mark_duplicate": {+ "title": "중복으로 표시",+ "description": "원본 태스크를 검색하세요. 이 태스크는 취소되고 원본 태스크에 연결됩니다.",+ "toast_success": "{{identifier}}의 중복으로 표시했습니다",+ "toast_failed": "중복으로 표시하지 못했습니다",+ "error_target_is_duplicate": "{{identifier}}은(는) 이미 중복입니다. 원본 태스크를 선택하세요",+ "error_has_duplicates": "다른 태스크가 이 태스크의 중복으로 표시되어 있습니다. 먼저 해당 표시를 해제하세요"}}diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex aeeeea963e..72966e9fc5 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -738,7 +738,8 @@"remove_parent_issue": "移除父任务","remove_parent_issue_success": "已移除父任务","add_sub_issue": "添加子任务...",- "delete_issue": "删除任务"+ "delete_issue": "删除任务",+ "mark_duplicate": "标记为重复..."},"pickers": {"custom_property": {@@ -786,6 +787,9 @@"manage_dialog_title": "管理标签","create_action": "创建","create_failed": "创建标签失败"+ },+ "status": {+ "mark_duplicate": "标记为重复..."}},"labels_panel": {@@ -1038,5 +1042,10 @@},"hourly": "每小时唤醒","today_time": "今天 {{time}}"+ },+ "duplicates": {+ "banner_prefix": "重复于",+ "unmark": "取消标记并移至待办",+ "section_title": "重复项"}}diff --git a/packages/views/locales/zh-Hans/modals.json b/packages/views/locales/zh-Hans/modals.jsonindex 25ec2f9283..e9ee3f7864 100644--- a/packages/views/locales/zh-Hans/modals.json+++ b/packages/views/locales/zh-Hans/modals.json@@ -244,5 +244,13 @@"error_unknown": "提交失败,请重试。","sub_issue_of": "作为 {{identifier}} 的子任务"}+ },+ "mark_duplicate": {+ "title": "标记为重复",+ "description": "搜索原始任务。当前任务会被取消,并关联到它。",+ "toast_success": "已标记为 {{identifier}} 的重复",+ "toast_failed": "无法标记为重复",+ "error_target_is_duplicate": "{{identifier}} 本身是重复任务,请选择它的原始任务",+ "error_has_duplicates": "已有任务被标记为此任务的重复,请先解除这些标记"}}diff --git a/packages/views/modals/mark-duplicate-issue.tsx b/packages/views/modals/mark-duplicate-issue.tsxnew file mode 100644index 0000000000..e04fca04a5--- /dev/null+++ b/packages/views/modals/mark-duplicate-issue.tsx@@ -0,0 +1,83 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { toast } from "sonner";+import { errorCode } from "@multica/core/api";+import { useWorkspaceId } from "@multica/core/hooks";+import { issueDuplicatesOptions } from "@multica/core/issues/queries";+import { useUpdateIssue } from "@multica/core/issues/mutations";+import { IssuePickerModal } from "./issue-picker-modal";+import { useT } from "../i18n";++/**+ * Marks an issue as a duplicate of the picked one (MUL-7349). A duplicate is a+ * cancelled issue that remembers its original, so the write also cancels it.+ */+export function MarkDuplicateIssueModal({+ onClose,+ data,+}: {+ onClose: () => void;+ data: Record<string, unknown> | null;+}) {+ const { t } = useT("modals");+ const issueId = (data?.issueId as string) || "";+ const wsId = useWorkspaceId();+ const updateIssue = useUpdateIssue();++ // An issue's own duplicates can never be its original.+ const { data: relations } = useQuery({+ ...issueDuplicatesOptions(wsId, issueId),+ enabled: !!issueId,+ });+ const excludeIds = [issueId, ...(relations?.duplicates.map((d) => d.id) ?? [])];++ return (+ <IssuePickerModal+ open+ onOpenChange={(v) => {+ if (!v) onClose();+ }}+ title={t(($) => $.mark_duplicate.title)}+ description={t(($) => $.mark_duplicate.description)}+ excludeIds={excludeIds}+ onSelect={(selected) => {+ updateIssue.mutate(+ {+ id: issueId,+ status: "cancelled",+ duplicate_of_issue_id: selected.id,+ },+ {+ onSuccess: () =>+ toast.success(+ t(($) => $.mark_duplicate.toast_success, {+ identifier: selected.identifier,+ }),+ ),+ onError: (err) => {+ switch (errorCode(err)) {+ case "duplicate_target_is_duplicate":+ toast.error(+ t(($) => $.mark_duplicate.error_target_is_duplicate, {+ identifier: selected.identifier,+ }),+ );+ return;+ case "issue_has_duplicates":+ toast.error(t(($) => $.mark_duplicate.error_has_duplicates));+ return;+ default:+ toast.error(+ err instanceof Error && err.message+ ? err.message+ : t(($) => $.mark_duplicate.toast_failed),+ );+ }+ },+ },+ );+ }}+ />+ );+}diff --git a/packages/views/modals/registry.tsx b/packages/views/modals/registry.tsxindex 8b8935d344..40fb5215d6 100644--- a/packages/views/modals/registry.tsx+++ b/packages/views/modals/registry.tsx@@ -7,6 +7,7 @@ import { CreateProjectModal } from "./create-project";import { CreateSquadModal } from "./create-squad";import { FeedbackModal } from "./feedback";import { SetParentIssueModal } from "./set-parent-issue";+import { MarkDuplicateIssueModal } from "./mark-duplicate-issue";import { AddChildIssueModal } from "./add-child-issue";import { DeleteIssueConfirmModal } from "./delete-issue-confirm";import { RunConfirmModal } from "./run-confirm";@@ -51,6 +52,9 @@ export function ModalRegistry() {case "issue-set-parent":activeModal = <SetParentIssueModal onClose={close} data={data} />;break;+ case "issue-mark-duplicate":+ activeModal = <MarkDuplicateIssueModal onClose={close} data={data} />;+ break;case "issue-add-child":activeModal = <AddChildIssueModal onClose={close} data={data} />;break;diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex ea5e6db811..aa41b023f1 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2004,6 +2004,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Delete("/reactions", h.RemoveIssueReaction)r.Get("/attachments", h.ListAttachments)r.Get("/children", h.ListChildIssues)+ r.Get("/duplicates", h.ListIssueDuplicates)r.Get("/labels", h.ListLabelsForIssue)r.Post("/labels", h.AttachLabel)r.Delete("/labels/{labelId}", h.DetachLabel)diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 6574dacfaf..1ff015a8be 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -269,6 +269,11 @@ func (h *Handler) updateIssueWithStatusGuard(ctx context.Context, workspaceID pgvar issue db.Issuevar cancelledWakeups []db.AgentTaskQueueerr := h.runWithIssueStatusGuard(ctx, workspaceID, statusKey, func(q *db.Queries) error {+ if params.DuplicateOfIssueID.Valid {+ if err := lockAndCheckDuplicateMark(ctx, q, workspaceID, params.ID, params.DuplicateOfIssueID); err != nil {+ return err+ }+ }var innerErr errorissue, cancelledWakeups, innerErr = updateIssueStoppingWakeups(ctx, q, params)return innerErr@@ -3408,6 +3413,13 @@ type UpdateIssueRequest struct {// predate the handoff UI removal. It is consumed only when this write starts// a run and is never stored on the issue itself.HandoffNote string `json:"handoff_note,omitempty"`+ // DuplicateOfIssueID marks this issue as a duplicate of another issue in+ // the same workspace (MUL-7349). A duplicate is an ordinary cancelled issue+ // that remembers its original, so this also sets status to cancelled.+ // Any later status change away from cancelled removes the mark; there is+ // no explicit null. Write-only: read the relation back from+ // GET /api/issues/{id}/duplicates. Not accepted by batch updates.+ DuplicateOfIssueID *string `json:"duplicate_of_issue_id,omitempty"`}func mergeIssueChannelMediaDescription(current, incoming string, base *string, attachments []db.Attachment) string {@@ -3629,6 +3641,11 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {}}+ duplicateOfID, ok := parseDuplicateMark(w, &req, rawFields, prevIssue.ID)+ if !ok {+ return+ }+// Pre-fill nullable fields (bare sqlc.narg) with current valuesparams := db.UpdateIssueParams{SourceTaskID: h.wakeupSourceTaskID(r),@@ -3640,6 +3657,8 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {ParentIssueID: prevIssue.ParentIssueID,ProjectID: prevIssue.ProjectID,Stage: prevIssue.Stage,+ // Checked against the locked rows in updateIssueWithStatusGuard.+ DuplicateOfIssueID: duplicateOfID,}if req.ExpectedRevision != nil {if *req.ExpectedRevision < 1 {@@ -3839,6 +3858,9 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {if writeIssueStatusRaceError(w, err) {return}+ if writeDuplicateMarkError(w, err) {+ return+ }if errors.Is(err, errIssueFieldConflict) {writeEditConflict(w, "issue", prevIssue.ID)return@@ -3901,6 +3923,10 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {"prev_description": textToPtr(prevIssue.Description),"creator_type": prevIssue.CreatorType,"creator_id": uuidToString(prevIssue.CreatorID),+ // The duplicate mark is not on IssueResponse, so both ends of a+ // change ride here for clients refreshing the two issues' relations.+ "duplicate_of_issue_id": uuidToPtr(issue.DuplicateOfIssueID),+ "prev_duplicate_of_issue_id": uuidToPtr(prevIssue.DuplicateOfIssueID),})if attachmentsChanged {// The full owner snapshot must be admitted before an auxiliary event at@@ -4341,6 +4367,10 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {if raw, exists := rawTop["updates"]; exists {json.Unmarshal(raw, &rawUpdates)}+ if _, ok := rawUpdates["duplicate_of_issue_id"]; ok {+ writeError(w, http.StatusBadRequest, "duplicate_of_issue_id is not supported in batch updates")+ return+ }// Short-circuit when no mutation field is present in `updates`. Without// this, the loop below runs N no-op UPDATEs (every if-guard skips, every@@ -4615,11 +4645,13 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {projectChanged := req.Updates.ProjectID != nil && uuidToString(prevIssue.ProjectID) != uuidToString(issue.ProjectID)h.publish(protocol.EventIssueUpdated, workspaceID, actorType, actorID, map[string]any{- "issue": resp,- "assignee_changed": assigneeChanged,- "status_changed": statusChanged,- "priority_changed": priorityChanged,- "project_changed": projectChanged,+ "issue": resp,+ "assignee_changed": assigneeChanged,+ "status_changed": statusChanged,+ "priority_changed": priorityChanged,+ "project_changed": projectChanged,+ "duplicate_of_issue_id": uuidToPtr(issue.DuplicateOfIssueID),+ "prev_duplicate_of_issue_id": uuidToPtr(prevIssue.DuplicateOfIssueID),})// Reassignment does not cancel existing tasks (#4963 / MUL-4113) —diff --git a/server/internal/handler/issue_duplicate.go b/server/internal/handler/issue_duplicate.gonew file mode 100644index 0000000000..9fda57ab2d--- /dev/null+++ b/server/internal/handler/issue_duplicate.go@@ -0,0 +1,178 @@+package handler++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "net/http"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/issuestatus"+ "github.com/multica-ai/multica/server/internal/logger"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Duplicate marks (MUL-7349). A duplicate is an ordinary cancelled issue that+// remembers which issue it duplicates: there is no duplicate status. Setting+// the mark goes through UpdateIssue as a status write, and any status change+// away from cancelled clears it in SQL (UpdateIssue / UpdateIssueStatus).+//+// The relation stays one level deep in both directions: a target must not be+// a duplicate itself, and an issue that others are marked as duplicates of+// cannot be marked. Nothing is collapsed or re-pointed automatically.+//+// The column and the code that maintains it shipped one release earlier, so a+// rollback lands on a server that still clears the pointer when an issue is+// reopened or its original deleted. Reads below additionally require the+// duplicate to be cancelled and its original to exist, which keeps a rollback+// that goes back further than that release readable rather than wrong.++var (+ errDuplicateTargetNotFound = errors.New("duplicate target not found in this workspace")+ errDuplicateTargetIsDuplicate = errors.New("duplicate target is itself a duplicate")+ errIssueHasDuplicates = errors.New("issue has duplicates")+)++// parseDuplicateMark reads duplicate_of_issue_id from an update request. When+// present it turns the request into a status write to cancelled, so the mark+// shares the status resolution, status_changed event and stage-barrier+// handling of cancelling by hand. It returns an invalid UUID when the request+// does not mark, and false after writing an error response.+func parseDuplicateMark(w http.ResponseWriter, req *UpdateIssueRequest, rawFields map[string]json.RawMessage, issueID pgtype.UUID) (pgtype.UUID, bool) {+ if _, present := rawFields["duplicate_of_issue_id"]; !present {+ return pgtype.UUID{}, true+ }+ if req.DuplicateOfIssueID == nil {+ writeError(w, http.StatusBadRequest, "duplicate_of_issue_id cannot be null; change the status to remove a duplicate mark")+ return pgtype.UUID{}, false+ }+ targetID, ok := parseUUIDOrBadRequest(w, *req.DuplicateOfIssueID, "duplicate_of_issue_id")+ if !ok {+ return pgtype.UUID{}, false+ }+ if targetID == issueID {+ writeError(w, http.StatusBadRequest, "an issue cannot be a duplicate of itself")+ return pgtype.UUID{}, false+ }+ if req.Status != nil && *req.Status != issuestatus.Cancelled {+ writeError(w, http.StatusBadRequest, "a duplicate is cancelled; status must be cancelled or omitted")+ return pgtype.UUID{}, false+ }+ // The description/attachment path locks attachments before the issue row,+ // while a mark locks two issue rows first. Keeping them apart keeps each+ // path's lock order fixed.+ if req.Description != nil || req.TitleBase != nil || req.DescriptionBase != nil || len(req.AttachmentIDs) > 0 {+ writeError(w, http.StatusBadRequest, "duplicate_of_issue_id cannot be combined with description or attachment changes")+ return pgtype.UUID{}, false+ }+ cancelled := issuestatus.Cancelled+ req.Status = &cancelled+ return targetID, true+}++// lockAndCheckDuplicateMark validates a mark inside the update transaction.+// Both issues are locked first, so marks that share an issue run one after+// the other and each validates what the previous one wrote. Deleting the+// target also locks it, so a mark never commits a pointer to a deleted issue.+func lockAndCheckDuplicateMark(ctx context.Context, q *db.Queries, workspaceID, issueID, targetID pgtype.UUID) error {+ rows, err := q.LockIssuesForDuplicateMark(ctx, db.LockIssuesForDuplicateMarkParams{+ WorkspaceID: workspaceID,+ IssueIds: []pgtype.UUID{issueID, targetID},+ })+ if err != nil {+ return fmt.Errorf("lock issues for duplicate mark: %w", err)+ }+ targetFound := false+ for _, row := range rows {+ if row.ID != targetID {+ continue+ }+ targetFound = true+ if row.IsDuplicate {+ return errDuplicateTargetIsDuplicate+ }+ }+ if !targetFound {+ return errDuplicateTargetNotFound+ }+ hasDuplicates, err := q.IssueHasDuplicates(ctx, db.IssueHasDuplicatesParams{+ WorkspaceID: workspaceID,+ IssueID: issueID,+ })+ if err != nil {+ return fmt.Errorf("check issue duplicates: %w", err)+ }+ if hasDuplicates {+ return errIssueHasDuplicates+ }+ return nil+}++func writeDuplicateMarkError(w http.ResponseWriter, err error) bool {+ switch {+ case errors.Is(err, errDuplicateTargetNotFound):+ writeError(w, http.StatusBadRequest, "duplicate target not found in this workspace")+ case errors.Is(err, errDuplicateTargetIsDuplicate):+ writeErrorCode(w, http.StatusConflict, "duplicate_target_is_duplicate",+ "the target issue is itself a duplicate; mark this issue as a duplicate of its original instead")+ case errors.Is(err, errIssueHasDuplicates):+ writeErrorCode(w, http.StatusConflict, "issue_has_duplicates",+ "other issues are marked as duplicates of this issue; remove those marks first")+ default:+ return false+ }+ return true+}++// ListIssueDuplicates returns both sides of an issue's duplicate relation: the+// original it duplicates, if any, and the issues marked as its duplicates.+func (h *Handler) ListIssueDuplicates(w http.ResponseWriter, r *http.Request) {+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)+ fill := h.newStatusCategoryFiller(r.Context(), issue.WorkspaceID)++ var duplicateOf *IssueResponse+ if issue.Status == issuestatus.Cancelled && issue.DuplicateOfIssueID.Valid {+ original, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{+ ID: issue.DuplicateOfIssueID,+ WorkspaceID: issue.WorkspaceID,+ })+ switch {+ case err == nil:+ resp := issueToResponse(original, prefix)+ fill(&resp)+ duplicateOf = &resp+ case !isNotFound(err):+ slog.Warn("load duplicate original failed", append(logger.RequestAttrs(r), "error", err, "issue_id", uuidToString(issue.ID))...)+ writeError(w, http.StatusInternalServerError, "failed to load duplicate original")+ return+ }+ }++ rows, err := h.Queries.ListIssueDuplicates(r.Context(), db.ListIssueDuplicatesParams{+ WorkspaceID: issue.WorkspaceID,+ IssueID: issue.ID,+ })+ if err != nil {+ slog.Warn("list issue duplicates failed", append(logger.RequestAttrs(r), "error", err, "issue_id", uuidToString(issue.ID))...)+ writeError(w, http.StatusInternalServerError, "failed to list duplicates")+ return+ }+ duplicates := make([]IssueResponse, 0, len(rows))+ for _, row := range rows {+ resp := issueToResponse(row, prefix)+ fill(&resp)+ duplicates = append(duplicates, resp)+ }++ writeJSON(w, http.StatusOK, map[string]any{+ "duplicate_of": duplicateOf,+ "duplicates": duplicates,+ })+}diff --git a/server/internal/handler/issue_duplicate_test.go b/server/internal/handler/issue_duplicate_test.gonew file mode 100644index 0000000000..ef8df03a03--- /dev/null+++ b/server/internal/handler/issue_duplicate_test.go@@ -0,0 +1,271 @@+package handler++import (+ "net/http"+ "sync"+ "testing"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// Enable step for duplicate marks (MUL-7349). The column and the code that+// keeps it correct shipped in the previous release; these tests cover creating+// a mark and reading both sides of it. How a mark is maintained across writes+// lives in issue_duplicate_maintenance_test.go.++type duplicateRelations struct {+ DuplicateOf *IssueResponse `json:"duplicate_of"`+ Duplicates []IssueResponse `json:"duplicates"`+}++func markDuplicate(t *testing.T, issueID, targetID string) *testutil.Response {+ t.Helper()+ return testutil.Call(t, testHandler.UpdateIssue, updateIssueRequest(issueID, map[string]any{+ "duplicate_of_issue_id": targetID,+ }))+}++func listDuplicates(t *testing.T, issueID string) duplicateRelations {+ t.Helper()+ var out duplicateRelations+ req := withURLParam(newRequest("GET", "/api/issues/"+issueID+"/duplicates", nil), "id", issueID)+ testutil.Call(t, testHandler.ListIssueDuplicates, req).Want(http.StatusOK).JSON(&out)+ return out+}++func TestMarkDuplicateCancelsAndLinksBothSides(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ original := dbfx.Issue(t, "dup-original", testutil.Cols{"status": "in_progress"})+ duplicate := dbfx.Issue(t, "dup-duplicate", testutil.Cols{"status": "todo"})++ // The mark is a status write: it must emit the same status_changed event a+ // manual cancel does, or parent stage barriers never hear about it.+ var mu sync.Mutex+ var payloads []map[string]any+ testHandler.Bus.Subscribe(protocol.EventIssueUpdated, func(e events.Event) {+ payload, ok := e.Payload.(map[string]any)+ if !ok {+ return+ }+ if resp, ok := payload["issue"].(IssueResponse); ok && resp.ID == duplicate {+ mu.Lock()+ payloads = append(payloads, payload)+ mu.Unlock()+ }+ })++ var resp IssueResponse+ markDuplicate(t, duplicate, original).Want(http.StatusOK).JSON(&resp)+ if resp.Status != "cancelled" {+ t.Fatalf("marked issue status = %q, want cancelled", resp.Status)+ }+ status, pointer, _ := duplicateState(t, duplicate)+ if status != "cancelled" || pointer == nil || *pointer != original {+ t.Fatalf("stored (status, duplicate_of) = (%q, %v), want (cancelled, %s)", status, pointer, original)+ }++ mu.Lock()+ if len(payloads) != 1 {+ mu.Unlock()+ t.Fatalf("got %d issue:updated events for the marked issue, want 1", len(payloads))+ }+ event := payloads[0]+ mu.Unlock()+ if event["status_changed"] != true {+ t.Errorf("status_changed = %v, want true", event["status_changed"])+ }+ if got, _ := event["duplicate_of_issue_id"].(*string); got == nil || *got != original {+ t.Errorf("event duplicate_of_issue_id = %v, want %s", event["duplicate_of_issue_id"], original)+ }++ fromDuplicate := listDuplicates(t, duplicate)+ if fromDuplicate.DuplicateOf == nil || fromDuplicate.DuplicateOf.ID != original {+ t.Fatalf("duplicate's relations: duplicate_of = %+v, want %s", fromDuplicate.DuplicateOf, original)+ }+ fromOriginal := listDuplicates(t, original)+ if fromOriginal.DuplicateOf != nil {+ t.Fatalf("original's relations: duplicate_of = %+v, want nil", fromOriginal.DuplicateOf)+ }+ if len(fromOriginal.Duplicates) != 1 || fromOriginal.Duplicates[0].ID != duplicate {+ t.Fatalf("original's relations: duplicates = %+v, want [%s]", fromOriginal.Duplicates, duplicate)+ }+}++// Reopening is the unmark action the banner offers, so it must clear both+// sides of what the mark created.+func TestReopeningRemovesMarkFromBothSides(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ original := dbfx.Issue(t, "dup-unmark-original")+ duplicate := dbfx.Issue(t, "dup-unmark-duplicate")+ markDuplicate(t, duplicate, original).Want(http.StatusOK)++ testutil.Call(t, testHandler.UpdateIssue, updateIssueRequest(duplicate, map[string]any{+ "status": "todo",+ })).Want(http.StatusOK)++ if relations := listDuplicates(t, original); len(relations.Duplicates) != 0 {+ t.Fatalf("original still lists %d duplicates after the mark was removed", len(relations.Duplicates))+ }+ if relations := listDuplicates(t, duplicate); relations.DuplicateOf != nil {+ t.Fatalf("reopened issue still reports an original: %+v", relations.DuplicateOf)+ }+}++func TestRemarkingSameTargetIsNoop(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ original := dbfx.Issue(t, "dup-noop-original")+ duplicate := dbfx.Issue(t, "dup-noop-duplicate")+ markDuplicate(t, duplicate, original).Want(http.StatusOK)+ _, _, before := duplicateState(t, duplicate)++ markDuplicate(t, duplicate, original).Want(http.StatusOK)+ if _, _, after := duplicateState(t, duplicate); after != before {+ t.Fatalf("re-marking the same target bumped revision %d -> %d", before, after)+ }+}++func TestDuplicateMarkRejections(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ original := dbfx.Issue(t, "dup-reject-original")+ marked := dbfx.Issue(t, "dup-reject-marked")+ markDuplicate(t, marked, original).Want(http.StatusOK)+ other := dbfx.Issue(t, "dup-reject-other")++ t.Run("self", func(t *testing.T) {+ markDuplicate(t, other, other).Want(http.StatusBadRequest)+ })+ t.Run("target not in workspace", func(t *testing.T) {+ markDuplicate(t, other, "00000000-0000-0000-0000-000000000001").Want(http.StatusBadRequest)+ })+ t.Run("target is itself a duplicate", func(t *testing.T) {+ body := markDuplicate(t, other, marked).Want(http.StatusConflict).Map()+ if body["code"] != "duplicate_target_is_duplicate" {+ t.Fatalf("code = %v, want duplicate_target_is_duplicate", body["code"])+ }+ })+ t.Run("issue has duplicates", func(t *testing.T) {+ body := markDuplicate(t, original, other).Want(http.StatusConflict).Map()+ if body["code"] != "issue_has_duplicates" {+ t.Fatalf("code = %v, want issue_has_duplicates", body["code"])+ }+ })+ t.Run("explicit null", func(t *testing.T) {+ testutil.Call(t, testHandler.UpdateIssue, updateIssueRequest(marked, map[string]any{+ "duplicate_of_issue_id": nil,+ })).Want(http.StatusBadRequest)+ })+ t.Run("status other than cancelled", func(t *testing.T) {+ testutil.Call(t, testHandler.UpdateIssue, updateIssueRequest(other, map[string]any{+ "duplicate_of_issue_id": original,+ "status": "done",+ })).Want(http.StatusBadRequest)+ })+ t.Run("batch update", func(t *testing.T) {+ req := newRequest("POST", "/api/issues/batch-update", map[string]any{+ "issue_ids": []string{other},+ "updates": map[string]any{"duplicate_of_issue_id": original},+ })+ testutil.Call(t, testHandler.BatchUpdateIssues, req).Want(http.StatusBadRequest)+ })++ // None of the rejected writes may have touched the issue.+ if status, pointer, _ := duplicateState(t, other); status != "todo" || pointer != nil {+ t.Fatalf("rejected marks changed the issue: (status, duplicate_of) = (%q, %v)", status, pointer)+ }+}++// Two people marking A as a duplicate of B and B as a duplicate of A at the+// same moment must not leave a cycle. Both marks lock the pair in id order, so+// whichever runs second sees the first one's pointer and is refused.+func TestConcurrentCrossMarksLeaveNoCycle(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ for attempt := 0; attempt < 5; attempt++ {+ a := dbfx.Issue(t, "dup-race-a")+ b := dbfx.Issue(t, "dup-race-b")++ var start, done sync.WaitGroup+ start.Add(1)+ codes := make([]int, 2)+ for i, pair := range [][2]string{{a, b}, {b, a}} {+ done.Add(1)+ go func(i int, issueID, targetID string) {+ defer done.Done()+ start.Wait()+ codes[i] = markDuplicate(t, issueID, targetID).Code+ }(i, pair[0], pair[1])+ }+ start.Done()+ done.Wait()++ succeeded := 0+ for _, code := range codes {+ switch code {+ case http.StatusOK:+ succeeded+++ case http.StatusConflict:+ default:+ t.Fatalf("attempt %d: unexpected status %d (codes %v)", attempt, code, codes)+ }+ }+ if succeeded != 1 {+ t.Fatalf("attempt %d: %d marks succeeded, want exactly 1 (codes %v)", attempt, succeeded, codes)+ }+ _, aPointer, _ := duplicateState(t, a)+ _, bPointer, _ := duplicateState(t, b)+ if aPointer != nil && bPointer != nil {+ t.Fatalf("attempt %d: cycle left behind: %s -> %s and %s -> %s", attempt, a, *aPointer, b, *bPointer)+ }+ }+}++// Defence in depth for a rollback that goes back past the release which added+// the column: such a server reopens duplicates and deletes originals without+// touching the pointer, so reads apply the validity rule themselves.+func TestDuplicateReadsIgnoreLeftoverMarks(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ t.Run("reopened without clearing", func(t *testing.T) {+ original := dbfx.Issue(t, "dup-leftover-reopen-original")+ duplicate := dbfx.Issue(t, "dup-leftover-reopen-duplicate")+ other := dbfx.Issue(t, "dup-leftover-reopen-other")+ markDuplicate(t, duplicate, original).Want(http.StatusOK)++ dbfx.Exec(t, `UPDATE issue SET status = 'todo' WHERE id = $1`, duplicate)++ if relations := listDuplicates(t, original); len(relations.Duplicates) != 0 {+ t.Fatalf("original lists a reopened issue: %+v", relations.Duplicates)+ }+ if relations := listDuplicates(t, duplicate); relations.DuplicateOf != nil {+ t.Fatalf("reopened issue reports an original: %+v", relations.DuplicateOf)+ }+ // The leftover does not make it a duplicate, so it can be an original.+ markDuplicate(t, other, duplicate).Want(http.StatusOK)+ })++ t.Run("original deleted without clearing", func(t *testing.T) {+ original := dbfx.Issue(t, "dup-leftover-delete-original")+ duplicate := dbfx.Issue(t, "dup-leftover-delete-duplicate")+ other := dbfx.Issue(t, "dup-leftover-delete-other")+ markDuplicate(t, duplicate, original).Want(http.StatusOK)++ dbfx.Exec(t, `DELETE FROM issue WHERE id = $1`, original)++ if relations := listDuplicates(t, duplicate); relations.DuplicateOf != nil {+ t.Fatalf("issue reports a deleted original: %+v", relations.DuplicateOf)+ }+ markDuplicate(t, other, duplicate).Want(http.StatusOK)+ })+}diff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.mdindex 8119fe01cf..dad5a06a4f 100644--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md@@ -276,6 +276,10 @@ archived statuses remain readable via an explicit status filter.`done` it enqueues no new agent work, but it does **not** stop tasks already inflight — a run in progress keeps going. To stop a running task, cancel thetask itself.+ A cancelled issue may also be marked as a **duplicate** of another issue+ (`GET /api/issues/<id>/duplicates` shows both sides). Moving it to any+ status other than `cancelled` removes the mark, so reopen a duplicate only+ when it is really separate work.- **Failed issue-triggered tasks** may roll an issue from `in_progress` back to`todo` when no active task / retry remains — that is the main server-ownedstatus write on the agent-run path.diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 6cf6e71dbe..437b4fd709 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -1027,6 +1027,32 @@ func (q *Queries) GetIssueTriageState(ctx context.Context, id pgtype.UUID) (pgtyreturn triage_state, err}+const issueHasDuplicates = `-- name: IssueHasDuplicates :one++SELECT EXISTS (+ SELECT 1 FROM issue+ WHERE workspace_id = $1+ AND duplicate_of_issue_id = $2::uuid+ AND status = 'cancelled'+) AS has_duplicates+`++type IssueHasDuplicatesParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+}++// A mark only counts while the duplicate is cancelled and its original still+// exists. Writes keep that true, but a server predating this feature (after a+// rollback that kept the column) can reopen a duplicate or delete an original+// without touching the pointer, so every read applies the rule itself.+func (q *Queries) IssueHasDuplicates(ctx context.Context, arg IssueHasDuplicatesParams) (bool, error) {+ row := q.db.QueryRow(ctx, issueHasDuplicates, arg.WorkspaceID, arg.IssueID)+ var has_duplicates bool+ err := row.Scan(&has_duplicates)+ return has_duplicates, err+}+const listChildIssues = `-- name: ListChildIssues :manySELECT 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, last_activity_at, triage_state, duplicate_of_issue_id FROM issueWHERE parent_issue_id = $1@@ -1160,6 +1186,70 @@ func (q *Queries) ListChildrenByParents(ctx context.Context, arg ListChildrenByPreturn items, nil}+const listIssueDuplicates = `-- name: ListIssueDuplicates :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, revision, last_activity_at, triage_state, duplicate_of_issue_id FROM issue+WHERE workspace_id = $1+ AND duplicate_of_issue_id = $2::uuid+ AND status = 'cancelled'+ORDER BY created_at ASC, id ASC+`++type ListIssueDuplicatesParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+}++func (q *Queries) ListIssueDuplicates(ctx context.Context, arg ListIssueDuplicatesParams) ([]Issue, error) {+ rows, err := q.db.Query(ctx, listIssueDuplicates, arg.WorkspaceID, arg.IssueID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []Issue{}+ for rows.Next() {+ var i Issue+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Title,+ &i.Description,+ &i.Status,+ &i.Priority,+ &i.AssigneeType,+ &i.AssigneeID,+ &i.CreatorType,+ &i.CreatorID,+ &i.ParentIssueID,+ &i.AcceptanceCriteria,+ &i.ContextRefs,+ &i.Position,+ &i.DueDate,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Number,+ &i.ProjectID,+ &i.OriginType,+ &i.OriginID,+ &i.FirstExecutedAt,+ &i.StartDate,+ &i.Metadata,+ &i.Stage,+ &i.Properties,+ &i.Revision,+ &i.LastActivityAt,+ &i.TriageState,+ &i.DuplicateOfIssueID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listIssueGCStatuses = `-- name: ListIssueGCStatuses :manySELECT id, status, updated_atFROM issue@@ -1698,6 +1788,55 @@ func (q *Queries) LockIssueForDescriptionUpdate(ctx context.Context, arg LockIssreturn i, err}+const lockIssuesForDuplicateMark = `-- name: LockIssuesForDuplicateMark :many+SELECT i.id,+ (i.status = 'cancelled' AND EXISTS (+ SELECT 1 FROM issue AS original+ WHERE original.id = i.duplicate_of_issue_id+ AND original.workspace_id = i.workspace_id+ ))::boolean AS is_duplicate+FROM issue AS i+WHERE i.workspace_id = $1+ AND i.id = ANY($2::uuid[])+ORDER BY i.id+FOR UPDATE OF i+`++type LockIssuesForDuplicateMarkParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueIds []pgtype.UUID `json:"issue_ids"`+}++type LockIssuesForDuplicateMarkRow struct {+ ID pgtype.UUID `json:"id"`+ IsDuplicate bool `json:"is_duplicate"`+}++// Locks the issue being marked and its target, in id order, before the mark is+// validated. Two marks that share an issue (A -> B racing B -> A, or C -> A+// racing A -> B) then run one after the other, so the second one validates+// against what the first wrote. A target outside the workspace is not returned.+// is_duplicate applies the same validity rule as the reads below.+func (q *Queries) LockIssuesForDuplicateMark(ctx context.Context, arg LockIssuesForDuplicateMarkParams) ([]LockIssuesForDuplicateMarkRow, error) {+ rows, err := q.db.Query(ctx, lockIssuesForDuplicateMark, arg.WorkspaceID, arg.IssueIds)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []LockIssuesForDuplicateMarkRow{}+ for rows.Next() {+ var i LockIssuesForDuplicateMarkRow+ if err := rows.Scan(&i.ID, &i.IsDuplicate); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const markIssueFirstExecuted = `-- name: MarkIssueFirstExecuted :oneUPDATE issueSET first_executed_at = now()@@ -1904,11 +2043,14 @@ WITH wakeup_source AS MATERIALIZED (SELECT set_config('multica.source_task_id',$13::uuid AS next_parent_issue_id,$14::uuid AS next_project_id,$15::integer AS next_stage,- -- A duplicate mark only survives a write that leaves an already- -- cancelled issue cancelled. Every other write drops it, so reopening- -- an issue removes its mark and cancelling it again does not bring the- -- mark back. Nothing writes the pointer yet; see the migration.+ -- A supplied pointer marks the issue (the handler also sets cancelled).+ -- Otherwise a mark only survives a write that leaves an already+ -- cancelled issue cancelled. Every other write drops it: reopening is+ -- how a mark is removed, and re-entering cancelled does not revive a+ -- pointer that a server predating this rule left on a reopened issue.CASE+ WHEN $16::uuid IS NOT NULL+ THEN $16::uuidWHEN i.status = 'cancelled' AND COALESCE($6::text, i.status) = 'cancelled'THEN i.duplicate_of_issue_idELSE NULL@@ -1973,21 +2115,22 @@ RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.`type UpdateIssueParams struct {- ID pgtype.UUID `json:"id"`- ExpectedRevision pgtype.Int8 `json:"expected_revision"`- SourceTaskID pgtype.UUID `json:"source_task_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"`+ ExpectedRevision pgtype.Int8 `json:"expected_revision"`+ SourceTaskID pgtype.UUID `json:"source_task_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"`+ DuplicateOfIssueID pgtype.UUID `json:"duplicate_of_issue_id"`}func (q *Queries) UpdateIssue(ctx context.Context, arg UpdateIssueParams) (Issue, error) {@@ -2007,6 +2150,7 @@ func (q *Queries) UpdateIssue(ctx context.Context, arg UpdateIssueParams) (Issuearg.ParentIssueID,arg.ProjectID,arg.Stage,+ arg.DuplicateOfIssueID,)var i Issueerr := row.Scan(diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 36d67b208a..a44f2a26c3 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -242,11 +242,14 @@ WITH wakeup_source AS MATERIALIZED (SELECT set_config('multica.source_task_id',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,- -- A duplicate mark only survives a write that leaves an already- -- cancelled issue cancelled. Every other write drops it, so reopening- -- an issue removes its mark and cancelling it again does not bring the- -- mark back. Nothing writes the pointer yet; see the migration.+ -- A supplied pointer marks the issue (the handler also sets cancelled).+ -- Otherwise a mark only survives a write that leaves an already+ -- cancelled issue cancelled. Every other write drops it: reopening is+ -- how a mark is removed, and re-entering cancelled does not revive a+ -- pointer that a server predating this rule left on a reopened issue.CASE+ WHEN sqlc.narg('duplicate_of_issue_id')::uuid IS NOT NULL+ THEN sqlc.narg('duplicate_of_issue_id')::uuidWHEN i.status = 'cancelled' AND COALESCE(sqlc.narg('status')::text, i.status) = 'cancelled'THEN i.duplicate_of_issue_idELSE NULL@@ -338,6 +341,44 @@ FROM wakeup_sourceWHERE i.id = $1 AND i.workspace_id = $3RETURNING i.*;+-- name: LockIssuesForDuplicateMark :many+-- Locks the issue being marked and its target, in id order, before the mark is+-- validated. Two marks that share an issue (A -> B racing B -> A, or C -> A+-- racing A -> B) then run one after the other, so the second one validates+-- against what the first wrote. A target outside the workspace is not returned.+-- is_duplicate applies the same validity rule as the reads below.+SELECT i.id,+ (i.status = 'cancelled' AND EXISTS (+ SELECT 1 FROM issue AS original+ WHERE original.id = i.duplicate_of_issue_id+ AND original.workspace_id = i.workspace_id+ ))::boolean AS is_duplicate+FROM issue AS i+WHERE i.workspace_id = sqlc.arg('workspace_id')+ AND i.id = ANY(sqlc.arg('issue_ids')::uuid[])+ORDER BY i.id+FOR UPDATE OF i;++-- A mark only counts while the duplicate is cancelled and its original still+-- exists. Writes keep that true, but a server predating this feature (after a+-- rollback that kept the column) can reopen a duplicate or delete an original+-- without touching the pointer, so every read applies the rule itself.++-- name: IssueHasDuplicates :one+SELECT EXISTS (+ SELECT 1 FROM issue+ WHERE workspace_id = sqlc.arg('workspace_id')+ AND duplicate_of_issue_id = sqlc.arg('issue_id')::uuid+ AND status = 'cancelled'+) AS has_duplicates;++-- name: ListIssueDuplicates :many+SELECT * FROM issue+WHERE workspace_id = sqlc.arg('workspace_id')+ AND duplicate_of_issue_id = sqlc.arg('issue_id')::uuid+ AND status = 'cancelled'+ORDER BY created_at ASC, id ASC;+-- name: ClearIssueDuplicatesOf :many-- Deleting an issue clears the pointers of its duplicates, the way deleting a-- parent detaches its children. They stay cancelled. Issues deleted in the