Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(issues): make duplicate marks traceable and one click from the original (MUL-7349) (#8741)
Bohan Jiang1539c54ec5fb
diff --git a/apps/mobile/lib/format-activity.ts b/apps/mobile/lib/format-activity.tsindex 7d41b5e5b4..cf1632200d 100644--- a/apps/mobile/lib/format-activity.ts+++ b/apps/mobile/lib/format-activity.ts@@ -92,6 +92,23 @@ export function formatActivity(return `renamed: "${details.from ?? "?"}" → "${details.to ?? "?"}"`;case "description_updated":return "updated description";+ // Duplicate marks (MUL-7349); copy mirrors packages/views/locales/en.+ case "duplicate_marked":+ return `marked this issue as a duplicate of ${details.original_identifier ?? "?"}`;+ case "duplicate_unmarked": {+ const identifier = details.original_identifier ?? "?";+ if (details.reason === "original_deleted") {+ return `removed the duplicate mark, ${identifier} was deleted`;+ }+ if (details.to) {+ return `unmarked this issue as a duplicate of ${identifier} and moved it to ${statusName(details.to, resolveStatusLabel)}`;+ }+ return `unmarked this issue as a duplicate of ${identifier}`;+ }+ case "duplicate_added":+ return `marked ${details.duplicate_identifier ?? "?"} as a duplicate of this issue`;+ case "duplicate_removed":+ return `unmarked ${details.duplicate_identifier ?? "?"} as a duplicate of this issue`;case "task_completed": {const n = entry.coalesced_count ?? 1;return n > 1 ? `completed ${n} tasks` : "completed a task";diff --git a/e2e/issue-duplicate.spec.ts b/e2e/issue-duplicate.spec.tsindex 9b1e987c27..5304105ba9 100644--- a/e2e/issue-duplicate.spec.ts+++ b/e2e/issue-duplicate.spec.ts@@ -21,9 +21,8 @@ test.describe("Mark as duplicate", () => {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",- });+ const duplicateTitle = `Status picker hard to tap ${run}`;+ const duplicate = await api.createIssue(duplicateTitle, { status: "todo" });await page.goto(`/${slug}/issues/${duplicate.id}`);// The detail page can close a just-opened picker while it finishes@@ -42,15 +41,22 @@ test.describe("Mark as duplicate", () => {});await expect(originalLink).toBeVisible();await expect(page.getByRole("button", { name: "Cancelled", exact: true }).first()).toBeVisible();+ // The mark is logged, with the original linked by its bare identifier.+ await expect(page.getByText(`marked this issue as a duplicate of ${original.identifier}`)).toBeVisible();+ await expect(page.getByRole("link", { name: original.identifier, exact: true })).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();+ // The sidebar row names the duplicate with its title; the activity feed+ // links it by identifier alone.+ await expect(page.getByRole("link", { name: `${duplicate.identifier} ${duplicateTitle}` })).toBeVisible();+ await expect(page.getByText(`marked ${duplicate.identifier} as a duplicate of this issue`)).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 page.getByRole("button", { name: "Not a duplicate" }).click();+ await expect(page.getByRole("button", { name: "Not a duplicate" })).toHaveCount(0);await expect(page.getByRole("button", { name: "Todo", exact: true }).first()).toBeVisible();+ await expect(page.getByText(`unmarked this issue as a duplicate of ${original.identifier}`)).toBeVisible();});});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 003ad9a264..28406b2e48 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1290,6 +1290,13 @@ export const IssueSchema = z.object({creator_type: z.string(),creator_id: z.string(),parent_issue_id: z.string().nullable(),+ // Additive pointer (MUL-7349); same disproportionate-failure reasoning as+ // status_name above, and older backends do not send it at all.+ duplicate_of: z+ .object({ id: z.string(), identifier: z.string(), title: z.string(), status: z.string() })+ .nullable()+ .optional()+ .catch(undefined),project_id: z.string().nullable(),position: z.number(),// Older backends predate `stage`; default to null so a missing field parsesdiff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex ba3c091e15..17e85f789f 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -1,4 +1,6 @@-export type { Issue, IssueStatus, BuiltInIssueStatus, IssuePriority, IssueAssigneeType, IssueMetadata, IssueMetadataValue, IssueReaction, SourceContextAttachment, SourceContextAuthor, SourceContextIssueSnapshot, SourceContextCommentSnapshot, SourceContextSnapshot, SourceContextLimitUsage, SourceContextPreview, SourceContextAuthorState, IssueSourceContext } from "./issue";+export type { Issue, IssueStatus, BuiltInIssueStatus, IssuePriority, IssueAssigneeType, IssueMetadata, IssueMetadataValue, IssueReaction, SourceContextAttachment, SourceContextAuthor, SourceContextIssueSnapshot, SourceContextCommentSnapshot, SourceContextSnapshot, SourceContextLimitUsage, SourceContextPreview, SourceContextAuthorState, IssueSourceContext,+ IssueDuplicateOf,+} from "./issue";export type {IssueStatusCategory,IssueStatusEntry,diff --git a/packages/core/types/issue.ts b/packages/core/types/issue.tsindex 964d136676..d04c4fc016 100644--- a/packages/core/types/issue.ts+++ b/packages/core/types/issue.ts@@ -159,6 +159,14 @@ export interface IssueSourceContext {snapshot: SourceContextSnapshot;}+/** The original a duplicate points at: enough to link it and show its status. */+export interface IssueDuplicateOf {+ id: string;+ identifier: string;+ title: string;+ status: IssueStatus;+}+export interface Issue {id: string;workspace_id: string;@@ -188,6 +196,12 @@ export interface Issue {creator_type: IssueAssigneeType;creator_id: string;parent_issue_id: string | null;+ /**+ * The original this issue duplicates (MUL-7349): present only while the+ * issue is cancelled and the original still exists, resolved by the server.+ * Absent when connected to an older backend.+ */+ duplicate_of?: IssueDuplicateOf | null;project_id: string | null;position: number;// Ordered barrier group among sibling sub-issues (null = unstaged). Thediff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsxindex 79942cd494..573460a07f 100644--- a/packages/views/issues/components/board-card.tsx+++ b/packages/views/issues/components/board-card.tsx@@ -29,6 +29,7 @@ import { IssueActionsContextMenu } from "../actions";import { LabelChip } from "../../labels/label-chip";import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";import { CustomStatusChip, useIsCustomStatus } from "./custom-status-chip";+import { IssueDuplicateOfMarker } from "./issue-duplicates";import { useIssueSurfaceActionsOptional } from "../surface/actions-context";function formatDate(date: string, locale: string): string {return formatDateOnly(date, { month: "short", day: "numeric" }, locale);@@ -196,6 +197,7 @@ export const BoardCardContent = memo(function BoardCardContent({<div className="flex items-center gap-1.5 min-w-0">{priorityIconNode}<p className="text-caption text-muted-foreground truncate">{issue.identifier}</p>+ <IssueDuplicateOfMarker issue={issue} insideLink /></div><IssueAgentActivityIndicator issueId={issue.id} /></div>diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex 95ad33cfad..127960d09c 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -1756,6 +1756,50 @@ describe("IssueDetail (shared)", () => {expect(screen.getByText(/changed priority/i)).toBeInTheDocument();});+ // Duplicate marks (MUL-7349) name another issue; the identifier is a link+ // to it, and a mark removed because its original was deleted is plain text.+ it("links a duplicate mark to the issue it names", async () => {+ mockApiObj.listTimeline.mockResolvedValue([+ {+ type: "activity",+ id: "act-dup-marked",+ actor_type: "member",+ actor_id: "user-1",+ action: "duplicate_marked",+ details: { original_id: "issue-9", original_identifier: "MUL-9" },+ created_at: "2026-01-16T00:00:00Z",+ },+ {+ type: "activity",+ id: "act-dup-unmarked",+ actor_type: "member",+ actor_id: "user-1",+ action: "duplicate_unmarked",+ details: { original_id: "issue-8", original_identifier: "MUL-8", reason: "original_deleted" },+ created_at: "2026-01-16T00:00:30Z",+ },+ {+ type: "activity",+ id: "act-dup-reopened",+ actor_type: "member",+ actor_id: "user-1",+ action: "duplicate_unmarked",+ details: { original_id: "issue-9", original_identifier: "MUL-9", to: "todo" },+ created_at: "2026-01-16T00:01:00Z",+ },+ ]);+ renderIssueDetail();++ const links = await screen.findAllByRole("link", { name: "MUL-9" });+ expect(links[0]?.getAttribute("href")).toBe("/test/issues/issue-9");+ expect(screen.getByText(/^marked this issue as a duplicate of/i)).toBeInTheDocument();+ expect(screen.getByText(/removed the duplicate mark, MUL-8 was deleted/i)).toBeInTheDocument();+ expect(screen.queryByRole("link", { name: "MUL-8" })).not.toBeInTheDocument();+ // Reopening replaces the status row, so the unmarked row says where it went.+ expect(screen.getByText(/and moved it to Todo/i)).toBeInTheDocument();+ expect(screen.getAllByRole("link", { name: "MUL-9" })).toHaveLength(2);+ });+it("renders activity rows with unknown status values without crashing", async () => {mockApiObj.listTimeline.mockResolvedValue([{diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 3d839aa8f5..fb10f05a47 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -12,7 +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 { IssueDuplicateBanner, IssueDuplicatesSection, isDuplicateIssue } from "./issue-duplicates";import {Archive,Calendar,@@ -344,6 +344,33 @@ function formatActivity(});case "description_updated":return t(($) => $.activity.description_updated);+ case "duplicate_marked":+ return t(($) => $.activity.duplicate_marked, {+ identifier: details.original_identifier || "?",+ });+ case "duplicate_unmarked": {+ const identifier = details.original_identifier || "?";+ if (details.reason === "original_deleted") {+ return t(($) => $.activity.duplicate_unmarked_original_deleted, { identifier });+ }+ // The row stands in for the status row of the reopen, so it says where+ // the status went.+ if (details.to) {+ return t(($) => $.activity.duplicate_unmarked_to, {+ identifier,+ status: statusLabel(details.to, t, resolveStatusLabel),+ });+ }+ return t(($) => $.activity.duplicate_unmarked, { identifier });+ }+ case "duplicate_added":+ return t(($) => $.activity.duplicate_added, {+ identifier: details.duplicate_identifier || "?",+ });+ case "duplicate_removed":+ return t(($) => $.activity.duplicate_removed, {+ identifier: details.duplicate_identifier || "?",+ });case "task_completed":return t(($) => $.activity.task_completed, { count: entry.coalesced_count ?? 1 });case "task_failed":@@ -372,6 +399,50 @@ function formatActivity(}}+/**+ * The issue a duplicate-mark activity (MUL-7349) names, when it can still be+ * opened. A mark removed because its original was deleted has nowhere to+ * link, so it renders as plain text.+ */+function duplicateActivityLink(entry: TimelineEntry): { id: string; identifier: string } | null {+ const details = (entry.details ?? {}) as Record<string, string>;+ switch (entry.action) {+ case "duplicate_marked":+ case "duplicate_unmarked":+ if (details.reason === "original_deleted") return null;+ return details.original_id && details.original_identifier+ ? { id: details.original_id, identifier: details.original_identifier }+ : null;+ case "duplicate_added":+ case "duplicate_removed":+ return details.duplicate_id && details.duplicate_identifier+ ? { id: details.duplicate_id, identifier: details.duplicate_identifier }+ : null;+ default:+ return null;+ }+}++/** Activity copy with the issue it names turned into a link. */+function ActivityText({ entry, text }: { entry: TimelineEntry; text: string }) {+ const paths = useWorkspacePaths();+ const link = duplicateActivityLink(entry);+ const at = link ? text.indexOf(link.identifier) : -1;+ if (!link || at < 0) return <>{text}</>;+ return (+ <>+ {text.slice(0, at)}+ <AppLink+ href={paths.issueDetail(link.id)}+ newTabTitle={link.identifier}+ className="font-medium text-foreground underline-offset-4 hover:underline"+ >+ {link.identifier}+ </AppLink>+ {text.slice(at + link.identifier.length)}+ </>+ );+}// ---------------------------------------------------------------------------// Helpers@@ -620,19 +691,24 @@ function ActivityBlock({)}{visibleEntries.map((entry) => {const details = (entry.details ?? {}) as Record<string, string>;+ // Duplicate rows replace the status rows of the same write, so they+ // carry the status glyph those rows would have had.const isStatusChange = entry.action === "status_changed";+ const markedDuplicate = entry.action === "duplicate_marked";+ const unmarkedDuplicate = entry.action === "duplicate_unmarked" && !!details.to;const isPriorityChange = entry.action === "priority_changed";const isStartDateChange = entry.action === "start_date_changed";const isDueDateChange = entry.action === "due_date_changed";let leadIcon: React.ReactNode;- if (isStatusChange && details.to) {+ if ((isStatusChange && details.to) || markedDuplicate || unmarkedDuplicate) {+ const to = markedDuplicate ? "cancelled" : details.to;leadIcon = (<StatusIcon- status={details.to as IssueStatus}- category={resolveStatusCategory(details.to ?? "")}- color={resolveStatusColor(details.to ?? "")}- icon={resolveStatusIcon(details.to ?? "")}+ status={to as IssueStatus}+ category={resolveStatusCategory(to ?? "")}+ color={resolveStatusColor(to ?? "")}+ icon={resolveStatusIcon(to ?? "")}className="h-4 w-4 shrink-0"/>);@@ -664,7 +740,12 @@ function ActivityBlock({<span className="shrink-0 font-medium">{entry.actor_name || getActorName(entry.actor_type, entry.actor_id)}</span>- <span className="truncate">{formatActivity(entry, t, locale, getActorName, resolveStatusLabel)}</span>+ <span className="truncate">+ <ActivityText+ entry={entry}+ text={formatActivity(entry, t, locale, getActorName, resolveStatusLabel)}+ />+ </span>{(entry.coalesced_count ?? 1) > 1 &&entry.action !== "task_completed" &&entry.action !== "task_failed" && (@@ -1532,7 +1613,14 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// - squad_leader_evaluated: never coalesce; outcome/reason are audit dataconst COALESCE_MS = 2 * 60 * 1000;const NO_TIME_LIMIT_ACTIONS = new Set(["task_completed", "task_failed"]);- const NEVER_COALESCE_ACTIONS = new Set(["squad_leader_evaluated"]);+ // Duplicate marks name a different issue on every row.+ const NEVER_COALESCE_ACTIONS = new Set([+ "squad_leader_evaluated",+ "duplicate_marked",+ "duplicate_unmarked",+ "duplicate_added",+ "duplicate_removed",+ ]);// Unanchored runs join the timeline at the time their card shows: a// published reply's own time, the live end while still working.const entryById = new Map(displayTimeline.map((entry) => [entry.id, entry]));@@ -2329,6 +2417,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tronUpdate={handleUpdateField}align="start"onMarkDuplicate={actions.openMarkDuplicate}+ isDuplicate={isDuplicateIssue(issue)}/></PropRow><PropRow label={t(($) => $.detail.prop_assignee)}>@@ -2909,7 +2998,12 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr<div className="mx-auto w-full max-w-4xl px-3 py-6 max-md:pb-chat-launcher md:px-8 md:py-8"><IssueDuplicateBannerissue={issue}- onUnmark={() => handleUpdateField({ status: "todo" })}+ onUnmark={() =>+ handleUpdateField(+ { status: "todo" },+ { onSuccess: () => toast.success(t(($) => $.duplicates.unmark_toast)) },+ )+ }/>{titleLazy.active && (<div className={titleLazy.ready ? undefined : "hidden"}>diff --git a/packages/views/issues/components/issue-duplicates.test.tsx b/packages/views/issues/components/issue-duplicates.test.tsxindex fd7b75d089..33d4cdc1bf 100644--- a/packages/views/issues/components/issue-duplicates.test.tsx+++ b/packages/views/issues/components/issue-duplicates.test.tsx@@ -9,9 +9,12 @@ import type { Issue, IssueDuplicates } from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";const listIssueDuplicates = vi.fn<(id: string) => Promise<IssueDuplicates>>();+const navigate = vi.fn();vi.mock("@multica/core/api", () => ({- api: { listIssueDuplicates: (id: string) => listIssueDuplicates(id) },+ api: {+ listIssueDuplicates: (id: string) => listIssueDuplicates(id),+ },}));vi.mock("@multica/core/hooks", () => ({useWorkspaceId: () => "workspace-1",@@ -22,15 +25,43 @@ vi.mock("@multica/core/paths", () => ({vi.mock("@multica/core/issue-statuses/hooks", () => ({useIssueStatuses: () => buildIssueStatusCatalog(undefined),}));+vi.mock("../../common/actor-avatar", () => ({+ ActorAvatar: ({ actorId }: { actorId: string }) => <span data-testid="avatar">{actorId}</span>,+}));vi.mock("../../navigation", () => ({- AppLink: ({ href, children, className }: { href: string; children: ReactNode; className?: string }) => (- <a href={href} className={className}>+ AppLink: ({+ href,+ children,+ className,+ title,+ onClick,+ onAuxClick,+ }: {+ href: string;+ children: ReactNode;+ className?: string;+ title?: string;+ onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;+ onAuxClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;+ }) => (+ <a href={href} className={className} title={title} onClick={onClick} onAuxClick={onAuxClick}>{children}</a>),+ resolveClickIntent: () => "push",+ rowLinkInteractiveProps: {+ onClick: (e: React.MouseEvent) => e.stopPropagation(),+ onAuxClick: (e: React.MouseEvent) => e.stopPropagation(),+ },+ useIntentNavigate: () => (...args: unknown[]) => navigate(...args),}));-import { IssueDuplicateBanner, IssueDuplicatesSection } from "./issue-duplicates";+import {+ IssueDuplicateBanner,+ IssueDuplicateOfMarker,+ IssueDuplicatesSection,+ isDuplicateIssue,+} from "./issue-duplicates";function issue(overrides: Partial<Issue>): Issue {return {@@ -38,12 +69,21 @@ function issue(overrides: Partial<Issue>): Issue {identifier: "MUL-1",title: "An issue",status: "todo",+ creator_type: "member",+ creator_id: "user-1",...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" });+const DUPLICATE = issue({+ id: "duplicate",+ identifier: "MUL-7412",+ title: "Status picker is hard to tap",+ status: "cancelled",+ creator_id: "user-2",+ duplicate_of: { id: "original", identifier: "MUL-6980", title: "Tap targets are too small", status: "in_progress" },+});function renderWithQuery(ui: ReactNode) {const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });@@ -53,18 +93,32 @@ function renderWithQuery(ui: ReactNode) {afterEach(() => {cleanup();listIssueDuplicates.mockReset();+ navigate.mockReset();+});++describe("isDuplicateIssue", () => {+ it("only counts a pointer while the issue is cancelled", () => {+ expect(isDuplicateIssue(DUPLICATE)).toBe(true);+ expect(isDuplicateIssue({ ...DUPLICATE, status: "todo" })).toBe(false);+ expect(isDuplicateIssue({ ...DUPLICATE, duplicate_of: null })).toBe(false);+ expect(isDuplicateIssue({ status: "cancelled" } as Issue)).toBe(false);+ });});describe("IssueDuplicateBanner", () => {- it("points a cancelled duplicate at its original and offers to unmark it", async () => {+ it("links the whole strip to the original and keeps unmark secondary", 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" });+ // The original's identifier and title sit inside the link, after the prefix.+ const link = await screen.findByRole("link", { name: /Duplicate of MUL-6980 Tap targets are too small/ });expect(link.getAttribute("href")).toBe("/acme/issues/original");+ // The unmark control is not nested inside the link.+ const unmark = screen.getByRole("button", { name: "Not a duplicate" });+ expect(link.contains(unmark)).toBe(false);- fireEvent.click(screen.getByRole("button", { name: "Unmark and move to Todo" }));+ fireEvent.click(unmark);expect(onUnmark).toHaveBeenCalledTimes(1);});@@ -77,18 +131,22 @@ describe("IssueDuplicateBanner", () => {);await waitFor(() => expect(listIssueDuplicates).toHaveBeenCalled());- expect(screen.queryByRole("button", { name: "Unmark and move to Todo" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Not a duplicate" })).toBeNull();});});describe("IssueDuplicatesSection", () => {- it("lists the issues marked as duplicates of this one", async () => {- listIssueDuplicates.mockResolvedValue({ duplicate_of: null, duplicates: [DUPLICATE] });+ it("lists the duplicates with their reporters and a count", async () => {+ const second = issue({ id: "second", identifier: "MUL-7413", title: "Cannot tap priority", status: "cancelled", creator_id: "user-3" });+ listIssueDuplicates.mockResolvedValue({ duplicate_of: null, duplicates: [DUPLICATE, second] });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();+ expect(screen.getByRole("button", { name: "Duplicates 2" })).toBeTruthy();+ // Every duplicate is cancelled, so the row shows who reported it instead+ // of a status icon that would be identical on each line.+ expect(screen.getAllByTestId("avatar").map((el) => el.textContent)).toEqual(["user-2", "user-3"]);});it("renders nothing when there are no duplicates", async () => {@@ -99,3 +157,42 @@ describe("IssueDuplicatesSection", () => {expect(container.textContent).toBe("");});});++describe("IssueDuplicateOfMarker", () => {+ it("is a real link to the original where the row is not one", () => {+ const rowClick = vi.fn();+ renderWithQuery(+ <div onClick={rowClick}>+ {DUPLICATE.title} <IssueDuplicateOfMarker issue={DUPLICATE} />+ </div>,+ );++ const marker = screen.getByRole("link", { name: "MUL-6980" });+ expect(marker.tagName).toBe("A");+ expect(marker.getAttribute("href")).toBe("/acme/issues/original");+ expect(marker.getAttribute("title")).toBe("Duplicate of MUL-6980 Tap targets are too small");++ fireEvent.click(marker);+ expect(rowClick).not.toHaveBeenCalled();+ });++ it("navigates without an anchor when nested inside the row's link", () => {+ const rowClick = vi.fn();+ renderWithQuery(+ <a href="/acme/issues/duplicate" onClick={rowClick}>+ {DUPLICATE.title} <IssueDuplicateOfMarker issue={DUPLICATE} insideLink />+ </a>,+ );++ const marker = screen.getByRole("link", { name: "MUL-6980" });+ expect(marker.tagName).toBe("SPAN");+ fireEvent.click(marker);+ expect(navigate).toHaveBeenCalledWith("/acme/issues/original", "push", "MUL-6980");+ expect(rowClick).not.toHaveBeenCalled();+ });++ it("renders nothing for an issue that is not a duplicate", () => {+ const { container } = renderWithQuery(<IssueDuplicateOfMarker issue={ORIGINAL} />);+ expect(container.textContent).toBe("");+ });+});diff --git a/packages/views/issues/components/issue-duplicates.tsx b/packages/views/issues/components/issue-duplicates.tsxindex 7523bc3dd6..c861b0b3cf 100644--- a/packages/views/issues/components/issue-duplicates.tsx+++ b/packages/views/issues/components/issue-duplicates.tsx@@ -2,26 +2,35 @@import { useState } from "react";import { useQuery } from "@tanstack/react-query";-import { ChevronRight, CircleEqual } from "lucide-react";-import type { Issue } from "@multica/core/types";+import { ArrowRight, ChevronRight } from "lucide-react";+import type { Issue, IssueDuplicateOf } 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 { ActorAvatar } from "../../common/actor-avatar";+import { AppLink, resolveClickIntent, rowLinkInteractiveProps, useIntentNavigate } 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.+// cancelled, so every surface below also keys off the status.++/** True while the mark counts: the issue is cancelled and the server resolved its original. */+export function isDuplicateIssue(issue: Pick<Issue, "status" | "duplicate_of">): boolean {+ return issue.status === "cancelled" && !!issue.duplicate_of;+}/**- * 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.+ * Banner above a duplicate's title. Its one job is to send the reader on:+ * the whole strip links to the original and shows the original's own status,+ * so "is that one done yet?" is answered before the click. Removing the mark+ * is the rare correction, so it stays a quiet secondary action; the write is a+ * plain status change to todo, done through the caller so it shares the+ * detail page's status path.*/export function IssueDuplicateBanner({issue,@@ -33,35 +42,56 @@ export function IssueDuplicateBanner({const { t } = useT("issues");const wsId = useWorkspaceId();const paths = useWorkspacePaths();+ const { colorOf, iconOf } = useIssueStatuses(wsId);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">- <CircleEqual 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}>+ <div className="mb-4 flex items-center gap-1 rounded-md border bg-muted/40 py-1 pl-3 pr-1 text-body">+ <AppLink+ href={paths.issueDetail(original.id)}+ newTabTitle={original.identifier}+ className="group flex min-w-0 flex-1 items-center gap-2 py-1"+ >+ <span className="shrink-0 text-muted-foreground">+ {t(($) => $.duplicates.banner_prefix)}+ </span>{" "}+ <StatusIcon+ status={original.status}+ color={colorOf(original.status)}+ icon={iconOf(original.status)}+ category={issueStatusCategory(original) ?? undefined}+ className="h-3.5 w-3.5 shrink-0"+ />+ <span className="shrink-0 text-muted-foreground">{original.identifier}</span>{" "}+ <span className="truncate font-medium underline-offset-4 group-hover:underline">+ {original.title}+ </span>+ <ArrowRight className="ml-auto h-4 w-4 shrink-0 text-muted-foreground transition-colors group-hover:text-foreground" />+ </AppLink>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="shrink-0 text-muted-foreground"+ onClick={onUnmark}+ >{t(($) => $.duplicates.unmark)}</Button></div>);}-/** Sidebar list of the issues marked as duplicates of this one. */+/**+ * Sidebar list of the issues marked as duplicates of this one. Every entry is+ * cancelled, so a status icon would say the same thing on each row; the+ * reporter is the signal — several faces means several people hit this.+ */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 ?? [];@@ -74,7 +104,10 @@ export function IssueDuplicatesSection({ issueId }: { issueId: string }) {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)}+ {t(($) => $.duplicates.section_title)}{" "}+ <span className="rounded-xs bg-muted px-1 text-micro font-medium tabular-nums text-muted-foreground">+ {duplicates.length}+ </span><ChevronRight className={`!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform ${open ? "rotate-90" : ""}`} /></button>{open && (@@ -85,12 +118,11 @@ export function IssueDuplicatesSection({ issueId }: { issueId: string }) {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"+ <ActorAvatar+ actorType={duplicate.creator_type}+ actorId={duplicate.creator_id}+ size="xs"+ profileLink={false}/><span className="text-muted-foreground shrink-0">{duplicate.identifier}</span><span className="truncate group-hover:text-foreground">{duplicate.title}</span>@@ -101,3 +133,112 @@ export function IssueDuplicatesSection({ issueId }: { issueId: string }) {</div>);}++/**+ * "→ MUL-123" beside a duplicate in list rows, board cards and table cells,+ * so the original is one click away instead of two. The server resolves the+ * original into `issue.duplicate_of`, so this needs no request of its own,+ * and rows that are not duplicates render nothing.+ *+ * It is a real link wherever the row is not one itself (the table's rows are+ * plain elements). List rows and board cards are anchors, and an anchor may+ * not contain another, so there it is a keyboard-operable control that+ * navigates like a link and stops the row from also opening the duplicate.+ */+export function IssueDuplicateOfMarker({+ issue,+ className,+ insideLink = false,+}: {+ issue: Issue;+ className?: string;+ /** The row containing this marker is itself an anchor. */+ insideLink?: boolean;+}) {+ if (!isDuplicateIssue(issue)) return null;+ const original = issue.duplicate_of!;+ return insideLink ? (+ <DuplicateOfControl original={original} className={className} />+ ) : (+ <DuplicateOfAnchor original={original} className={className} />+ );+}++const MARKER_CLASS =+ "inline-flex shrink-0 cursor-pointer items-center gap-0.5 text-caption text-muted-foreground underline-offset-4 hover:text-foreground hover:underline";++function useMarkerTooltip(original: IssueDuplicateOf) {+ const { t } = useT("issues");+ return `${t(($) => $.duplicates.banner_prefix)} ${original.identifier} ${original.title}`;+}++const stopPress = (e: React.SyntheticEvent) => e.stopPropagation();++function DuplicateOfAnchor({+ original,+ className,+}: {+ original: IssueDuplicateOf;+ className?: string;+}) {+ const paths = useWorkspacePaths();+ const tooltip = useMarkerTooltip(original);+ return (+ <AppLink+ href={paths.issueDetail(original.id)}+ newTabTitle={original.identifier}+ title={tooltip}+ {...rowLinkInteractiveProps}+ onMouseDown={stopPress}+ onPointerDown={stopPress}+ className={`${MARKER_CLASS} ${className ?? ""}`}+ >+ <ArrowRight className="size-3" />+ {original.identifier}+ </AppLink>+ );+}++function DuplicateOfControl({+ original,+ className,+}: {+ original: IssueDuplicateOf;+ className?: string;+}) {+ const paths = useWorkspacePaths();+ const navigate = useIntentNavigate();+ const tooltip = useMarkerTooltip(original);+ const href = paths.issueDetail(original.id);+ const stop = (e: React.SyntheticEvent) => {+ e.preventDefault();+ e.stopPropagation();+ };+ return (+ <span+ role="link"+ tabIndex={0}+ title={tooltip}+ onMouseDown={stopPress}+ onPointerDown={stopPress}+ onClick={(e) => {+ stop(e);+ navigate(href, resolveClickIntent(e), original.identifier);+ }}+ onAuxClick={(e) => {+ if (e.button !== 1) return;+ stop(e);+ navigate(href, "background-tab", original.identifier);+ }}+ onKeyDown={(e) => {+ if (e.key !== "Enter") return;+ stop(e);+ navigate(href, "push", original.identifier);+ }}+ className={`${MARKER_CLASS} ${className ?? ""}`}+ >+ <ArrowRight className="size-3" />+ {original.identifier}+ </span>+ );+}diff --git a/packages/views/issues/components/list-row.tsx b/packages/views/issues/components/list-row.tsxindex 36df290844..1e23b9e03d 100644--- a/packages/views/issues/components/list-row.tsx+++ b/packages/views/issues/components/list-row.tsx@@ -23,6 +23,7 @@ import { ProgressRing } from "./progress-ring";import { IssueActionsContextMenu } from "../actions";import { LabelChip } from "../../labels/label-chip";import { CustomStatusChip } from "./custom-status-chip";+import { IssueDuplicateOfMarker } from "./issue-duplicates";import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";import { useIssueSurfaceSelection } from "../surface/selection-context";import { useLocale } from "../../i18n";@@ -122,6 +123,7 @@ function ListRowContent({<span className="truncate">{issue.title}</span>{/* Keep custom names visible when this row appears outside a status section. */}<CustomStatusChip status={issue.status} className="shrink-0" />+ <IssueDuplicateOfMarker issue={issue} insideLink />{showChildProgress && (<span className="inline-flex shrink-0 items-center gap-1 rounded-full bg-muted/60 px-1.5 py-0.5"><ProgressRing done={childProgress!.done} total={childProgress!.total} size={14} />diff --git a/packages/views/issues/components/pickers/status-picker.test.tsx b/packages/views/issues/components/pickers/status-picker.test.tsxindex 8bc3e7a3b6..b89eba69bd 100644--- a/packages/views/issues/components/pickers/status-picker.test.tsx+++ b/packages/views/issues/components/pickers/status-picker.test.tsx@@ -147,3 +147,19 @@ describe("StatusPicker mark-as-duplicate action", () => {expect(onOpenChange).toHaveBeenCalledWith(false);});});++describe("StatusPicker on an issue that already is a duplicate", () => {+ it("relabels the action to re-point the mark", () => {+ renderWithI18n(+ <StatusPicker+ status="cancelled"+ onUpdate={() => {}}+ open+ onOpenChange={() => {}}+ onMarkDuplicate={() => {}}+ isDuplicate+ />,+ );+ expect(screen.getByRole("button", { name: "Change original" })).toBeTruthy();+ });+});diff --git a/packages/views/issues/components/pickers/status-picker.tsx b/packages/views/issues/components/pickers/status-picker.tsxindex 1d38a784c4..19b9ec3289 100644--- a/packages/views/issues/components/pickers/status-picker.tsx+++ b/packages/views/issues/components/pickers/status-picker.tsx@@ -24,6 +24,7 @@ export function StatusPicker({onOpenChange: controlledOnOpenChange,align,onMarkDuplicate,+ isDuplicate,}: {/*** The currently-selected status, used to check the matching row. `null`@@ -44,6 +45,8 @@ export function StatusPicker({* it only for an existing single issue — never on create or batch surfaces.*/onMarkDuplicate?: () => void;+ /** The issue already carries a mark, so the action re-points it. */+ isDuplicate?: boolean;}) {const [internalOpen, setInternalOpen] = useState(false);const open = controlledOpen ?? internalOpen;@@ -102,7 +105,11 @@ export function StatusPicker({className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-body hover:bg-accent transition-colors"><CircleEqual className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />- <span>{t(($) => $.pickers.status.mark_duplicate)}</span>+ <span>+ {t(($) =>+ isDuplicate ? $.pickers.status.change_original : $.pickers.status.mark_duplicate,+ )}+ </span></button>) : undefined}diff --git a/packages/views/issues/components/table-view.tsx b/packages/views/issues/components/table-view.tsxindex 233ebc056c..0f6840fc6c 100644--- a/packages/views/issues/components/table-view.tsx+++ b/packages/views/issues/components/table-view.tsx@@ -149,6 +149,7 @@ import {import type { ChildProgress } from "./list-row";import { ListLoadMoreFooter } from "./list-load-more-footer";import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";+import { IssueDuplicateOfMarker } from "./issue-duplicates";// Enough placeholder rows to cover a typical viewport; the virtualizer only// mounts what fits, so overshooting costs nothing.@@ -746,6 +747,7 @@ export function InlineTitle({>{row.issue.title}</button>+ <IssueDuplicateOfMarker issue={row.issue} />{/* Lifted out of the flex flow, the way SidebarMenuAction is. Laid* out inline these two reserved ~40px of the title column for* buttons that are invisible until hovered — and title is thediff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 612aa1ea38..08da980bb0 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -514,7 +514,13 @@"activity_count_one": "{{count}} activity","activity_count_other": "{{count}} activities","show_more_activities_one": "Show {{count}} more activity",- "show_more_activities_other": "Show {{count}} more activities"+ "show_more_activities_other": "Show {{count}} more activities",+ "duplicate_marked": "marked this issue as a duplicate of {{identifier}}",+ "duplicate_unmarked": "unmarked this issue as a duplicate of {{identifier}}",+ "duplicate_unmarked_to": "unmarked this issue as a duplicate of {{identifier}} and moved it to {{status}}",+ "duplicate_unmarked_original_deleted": "removed the duplicate mark, {{identifier}} was deleted",+ "duplicate_added": "marked {{identifier}} as a duplicate of this issue",+ "duplicate_removed": "unmarked {{identifier}} as a duplicate of this issue"},"comment": {"add_reaction": "Add reaction",@@ -841,7 +847,8 @@"create_failed": "Failed to create label"},"status": {- "mark_duplicate": "Mark as duplicate"+ "mark_duplicate": "Mark as duplicate",+ "change_original": "Change original"}},"labels_panel": {@@ -1097,7 +1104,8 @@},"duplicates": {"banner_prefix": "Duplicate of",- "unmark": "Unmark and move to Todo",- "section_title": "Duplicates"+ "unmark": "Not a duplicate",+ "section_title": "Duplicates",+ "unmark_toast": "Reopened as Todo"}}diff --git a/packages/views/locales/en/modals.json b/packages/views/locales/en/modals.jsonindex de7284845c..501fda546e 100644--- a/packages/views/locales/en/modals.json+++ b/packages/views/locales/en/modals.json@@ -35,7 +35,9 @@"search_placeholder": "Search issues...","searching": "Searching...","no_results": "No issues found.",- "prompt_to_search": "Type to search issues"+ "prompt_to_search": "Type to search issues",+ "suggested_similar": "Similar titles",+ "suggested_recent": "Recently viewed"},"set_parent": {"title": "Set parent issue",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex 034569db25..838b537afe 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -514,7 +514,13 @@"activity_count_one": "{{count}} activité","activity_count_other": "{{count}} activités","show_more_activities_one": "Afficher {{count}} activité de plus",- "show_more_activities_other": "Afficher {{count}} activités de plus"+ "show_more_activities_other": "Afficher {{count}} activités de plus",+ "duplicate_marked": "a marqué cette tâche comme doublon de {{identifier}}",+ "duplicate_unmarked": "a retiré la marque de doublon de {{identifier}} sur cette tâche",+ "duplicate_unmarked_to": "a retiré la marque de doublon de {{identifier}} sur cette tâche et l'a passée en {{status}}",+ "duplicate_unmarked_original_deleted": "a retiré la marque de doublon, {{identifier}} a été supprimée",+ "duplicate_added": "a marqué {{identifier}} comme doublon de cette tâche",+ "duplicate_removed": "a retiré la marque de doublon de {{identifier}}"},"comment": {"add_reaction": "Ajouter une réaction",@@ -841,7 +847,8 @@"create_failed": "Échec de la création de l'étiquette"},"status": {- "mark_duplicate": "Marquer comme doublon"+ "mark_duplicate": "Marquer comme doublon",+ "change_original": "Changer la tâche d'origine"}},"labels_panel": {@@ -1097,7 +1104,8 @@},"duplicates": {"banner_prefix": "Doublon de",- "unmark": "Retirer la marque et repasser en À faire",- "section_title": "Doublons"+ "unmark": "Pas un doublon",+ "section_title": "Doublons",+ "unmark_toast": "Rouverte en À faire"}}diff --git a/packages/views/locales/fr/modals.json b/packages/views/locales/fr/modals.jsonindex ff558191fc..b26c1d6b39 100644--- a/packages/views/locales/fr/modals.json+++ b/packages/views/locales/fr/modals.json@@ -35,7 +35,9 @@"search_placeholder": "Rechercher des tâches...","searching": "Recherche...","no_results": "Aucune tâche trouvée.",- "prompt_to_search": "Saisissez du texte pour rechercher des tâches"+ "prompt_to_search": "Saisissez du texte pour rechercher des tâches",+ "suggested_similar": "Titres similaires",+ "suggested_recent": "Consultées récemment"},"set_parent": {"title": "Définir la tâche parente",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex b45bb53c65..b572368c3f 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -505,7 +505,13 @@"squad_leader_failed_reason": "評価に失敗しました: {{reason}}","coalesced_badge": "×{{count}}","activity_count_other": "アクティビティ {{count}} 件",- "show_more_activities_other": "アクティビティをさらに {{count}} 件表示"+ "show_more_activities_other": "アクティビティをさらに {{count}} 件表示",+ "duplicate_marked": "このタスクを {{identifier}} の重複としてマークしました",+ "duplicate_unmarked": "このタスクの {{identifier}} との重複マークを解除しました",+ "duplicate_unmarked_to": "このタスクの {{identifier}} との重複マークを解除し、{{status}} に移動しました",+ "duplicate_unmarked_original_deleted": "重複マークを解除しました({{identifier}} は削除されました)",+ "duplicate_added": "{{identifier}} をこのタスクの重複としてマークしました",+ "duplicate_removed": "{{identifier}} の重複マークを解除しました"},"comment": {"add_reaction": "リアクションを追加",@@ -810,7 +816,8 @@"create_failed": "ラベルを作成できませんでした"},"status": {- "mark_duplicate": "重複としてマーク"+ "mark_duplicate": "重複としてマーク",+ "change_original": "元のタスクを変更"}},"labels_panel": {@@ -1066,7 +1073,8 @@},"duplicates": {"banner_prefix": "重複元:",- "unmark": "マークを解除して未着手に戻す",- "section_title": "重複"+ "unmark": "重複ではない",+ "section_title": "重複",+ "unmark_toast": "未着手として再開しました"}}diff --git a/packages/views/locales/ja/modals.json b/packages/views/locales/ja/modals.jsonindex 4843f2b54a..f30875d7a7 100644--- a/packages/views/locales/ja/modals.json+++ b/packages/views/locales/ja/modals.json@@ -35,7 +35,9 @@"search_placeholder": "タスクを検索...","searching": "検索中...","no_results": "タスクが見つかりません。",- "prompt_to_search": "タスクを検索するには入力してください"+ "prompt_to_search": "タスクを検索するには入力してください",+ "suggested_similar": "タイトルが似ているタスク",+ "suggested_recent": "最近表示したタスク"},"set_parent": {"title": "親タスクを設定",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex a5a806ec67..d1190985ed 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -505,7 +505,13 @@"squad_leader_failed_reason": "평가 실패: {{reason}}","coalesced_badge": "×{{count}}","activity_count_other": "활동 {{count}}개",- "show_more_activities_other": "활동 {{count}}개 더 보기"+ "show_more_activities_other": "활동 {{count}}개 더 보기",+ "duplicate_marked": "이 태스크를 {{identifier}}의 중복으로 표시했습니다",+ "duplicate_unmarked": "이 태스크의 {{identifier}} 중복 표시를 해제했습니다",+ "duplicate_unmarked_to": "이 태스크의 {{identifier}} 중복 표시를 해제하고 {{status}}(으)로 이동했습니다",+ "duplicate_unmarked_original_deleted": "중복 표시를 해제했습니다 ({{identifier}} 삭제됨)",+ "duplicate_added": "{{identifier}}을(를) 이 태스크의 중복으로 표시했습니다",+ "duplicate_removed": "{{identifier}}의 중복 표시를 해제했습니다"},"comment": {"add_reaction": "반응 추가",@@ -810,7 +816,8 @@"create_failed": "라벨을 만들지 못했습니다"},"status": {- "mark_duplicate": "중복으로 표시"+ "mark_duplicate": "중복으로 표시",+ "change_original": "원본 변경"}},"labels_panel": {@@ -1066,7 +1073,8 @@},"duplicates": {"banner_prefix": "중복 원본:",- "unmark": "표시 해제 후 할 일로 이동",- "section_title": "중복 항목"+ "unmark": "중복 아님",+ "section_title": "중복 항목",+ "unmark_toast": "할 일로 다시 열었습니다"}}diff --git a/packages/views/locales/ko/modals.json b/packages/views/locales/ko/modals.jsonindex 4e2c63cfb2..6b41ccb593 100644--- a/packages/views/locales/ko/modals.json+++ b/packages/views/locales/ko/modals.json@@ -35,7 +35,9 @@"search_placeholder": "태스크 검색...","searching": "검색 중...","no_results": "태스크를 찾을 수 없습니다.",- "prompt_to_search": "태스크를 검색하려면 입력하세요"+ "prompt_to_search": "태스크를 검색하려면 입력하세요",+ "suggested_similar": "제목이 비슷한 태스크",+ "suggested_recent": "최근 본 태스크"},"set_parent": {"title": "상위 태스크 설정",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 93e42a8a7f..08997db140 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -505,7 +505,13 @@"squad_leader_failed_reason": "评估失败:{{reason}}","coalesced_badge": "×{{count}}","activity_count_other": "{{count}} 条动态",- "show_more_activities_other": "展开更早 {{count}} 条动态"+ "show_more_activities_other": "展开更早 {{count}} 条动态",+ "duplicate_marked": "把这个任务标记为 {{identifier}} 的重复",+ "duplicate_unmarked": "取消了这个任务对 {{identifier}} 的重复标记",+ "duplicate_unmarked_to": "取消了这个任务对 {{identifier}} 的重复标记,并移至{{status}}",+ "duplicate_unmarked_original_deleted": "移除了重复标记,{{identifier}} 已被删除",+ "duplicate_added": "把 {{identifier}} 标记为这个任务的重复",+ "duplicate_removed": "取消了 {{identifier}} 对这个任务的重复标记"},"comment": {"add_reaction": "添加表情回应",@@ -810,7 +816,8 @@"create_failed": "创建标签失败"},"status": {- "mark_duplicate": "标记为重复"+ "mark_duplicate": "标记为重复",+ "change_original": "更改原始任务"}},"labels_panel": {@@ -1066,7 +1073,8 @@},"duplicates": {"banner_prefix": "重复于",- "unmark": "取消标记并移至待办",- "section_title": "重复项"+ "unmark": "不是重复",+ "section_title": "重复项",+ "unmark_toast": "已重新打开为待办"}}diff --git a/packages/views/locales/zh-Hans/modals.json b/packages/views/locales/zh-Hans/modals.jsonindex e9ee3f7864..61b1e92817 100644--- a/packages/views/locales/zh-Hans/modals.json+++ b/packages/views/locales/zh-Hans/modals.json@@ -35,7 +35,9 @@"search_placeholder": "搜索任务...","searching": "搜索中...","no_results": "未找到任务。",- "prompt_to_search": "输入关键词搜索任务"+ "prompt_to_search": "输入关键词搜索任务",+ "suggested_similar": "标题相似",+ "suggested_recent": "最近查看"},"set_parent": {"title": "设置父任务",diff --git a/packages/views/modals/issue-picker-modal.test.tsx b/packages/views/modals/issue-picker-modal.test.tsxnew file mode 100644index 0000000000..c4160488c2--- /dev/null+++ b/packages/views/modals/issue-picker-modal.test.tsx@@ -0,0 +1,82 @@+// @vitest-environment jsdom++import { cleanup, fireEvent, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { buildIssueStatusCatalog } from "@multica/core/issue-statuses";+import type { Issue } from "@multica/core/types";+import { renderWithI18n } from "../test/i18n";++const searchIssues = vi.fn();++vi.mock("@multica/core/api", () => ({+ api: { searchIssues: (params: unknown) => searchIssues(params) },+}));+vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => "workspace-1",+}));+vi.mock("@multica/core/issue-statuses/hooks", () => ({+ useIssueStatuses: () => buildIssueStatusCatalog(undefined),+}));++import { IssuePickerModal } from "./issue-picker-modal";++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-1", title: "Tap targets too small" });+const DUPLICATE = issue({+ id: "duplicate",+ identifier: "MUL-2",+ title: "Tap targets too small on iPhone",+ status: "cancelled",+ duplicate_of: { id: "original", identifier: "MUL-1", title: "Tap targets too small", status: "todo" },+});++afterEach(() => {+ cleanup();+ searchIssues.mockReset();+});++// The mark-as-duplicate picker must not offer an issue that is itself a+// duplicate; the server would reject it after the dialog has already closed.+describe("IssuePickerModal isSelectable", () => {+ it("drops unselectable issues from search results", async () => {+ searchIssues.mockResolvedValue({ issues: [ORIGINAL, DUPLICATE] });+ renderWithI18n(+ <IssuePickerModal+ open+ onOpenChange={() => {}}+ title="Mark as duplicate"+ description="Pick the original"+ excludeIds={[]}+ isSelectable={(candidate) => !candidate.duplicate_of}+ onSelect={() => {}}+ />,+ );++ fireEvent.change(screen.getByPlaceholderText("Search issues..."), { target: { value: "tap" } });+ await waitFor(() => expect(searchIssues).toHaveBeenCalled());+ await screen.findByText("Tap targets too small");+ expect(screen.queryByText("Tap targets too small on iPhone")).toBeNull();+ });++ it("drops unselectable issues from suggestions too", () => {+ renderWithI18n(+ <IssuePickerModal+ open+ onOpenChange={() => {}}+ title="Mark as duplicate"+ description="Pick the original"+ excludeIds={[]}+ suggestions={[{ key: "recent", heading: "Recently viewed", issues: [DUPLICATE, ORIGINAL] }]}+ isSelectable={(candidate) => !candidate.duplicate_of}+ onSelect={() => {}}+ />,+ );++ expect(screen.getByText("Recently viewed")).toBeTruthy();+ expect(screen.getByText("Tap targets too small")).toBeTruthy();+ expect(screen.queryByText("Tap targets too small on iPhone")).toBeNull();+ });+});diff --git a/packages/views/modals/issue-picker-modal.tsx b/packages/views/modals/issue-picker-modal.tsxindex 54a6e748fb..8d15fdae5a 100644--- a/packages/views/modals/issue-picker-modal.tsx+++ b/packages/views/modals/issue-picker-modal.tsx@@ -18,6 +18,13 @@ import {import { StatusIcon } from "../issues/components/status-icon";import { useT } from "../i18n";+/** Issues offered before the user types, under a heading. */+export interface IssuePickerSuggestionGroup {+ key: string;+ heading: string;+ issues: Issue[];+}+interface IssuePickerModalProps {open: boolean;onOpenChange: (open: boolean) => void;@@ -25,6 +32,10 @@ interface IssuePickerModalProps {description: string;excludeIds: string[];onSelect: (issue: Issue) => void;+ /** Shown while the query is empty; groups without issues are skipped. */+ suggestions?: IssuePickerSuggestionGroup[];+ /** Drops issues from results and suggestions alike; excludeIds always applies. */+ isSelectable?: (issue: Issue) => boolean;}export function IssuePickerModal({@@ -34,6 +45,8 @@ export function IssuePickerModal({description,excludeIds,onSelect,+ suggestions,+ isSelectable,}: IssuePickerModalProps) {const { t } = useT("modals");const { colorOf, iconOf } = useIssueStatuses(useWorkspaceId());@@ -42,6 +55,13 @@ export function IssuePickerModal({const [isLoading, setIsLoading] = useState(false);const debounceRef = useRef<ReturnType<typeof setTimeout>>(undefined);const abortRef = useRef<AbortController>(undefined);+ const selectable = useCallback(+ (issue: Issue) => !excludeIds.includes(issue.id) && (isSelectable?.(issue) ?? true),+ [excludeIds, isSelectable],+ );+ const suggestionGroups = (suggestions ?? [])+ .map((group) => ({ ...group, issues: group.issues.filter(selectable) }))+ .filter((group) => group.issues.length > 0);useEffect(() => {if (!open) {@@ -74,7 +94,7 @@ export function IssuePickerModal({signal: controller.signal,});if (!controller.signal.aborted) {- setResults(res.issues.filter((i) => !excludeIds.includes(i.id)));+ setResults(res.issues.filter(selectable));setIsLoading(false);}} catch {@@ -84,7 +104,28 @@ export function IssuePickerModal({}}, 300);},- [excludeIds],+ [selectable],+ );++ const row = (issue: Issue) => (+ <CommandItem+ key={issue.id}+ value={issue.id}+ onSelect={() => {+ onSelect(issue);+ onOpenChange(false);+ }}+ >+ <StatusIcon+ status={issue.status}+ color={colorOf(issue.status)}+ icon={iconOf(issue.status)}+ category={issueStatusCategory(issue) ?? undefined}+ className="h-3.5 w-3.5 shrink-0"+ />+ <span className="text-muted-foreground shrink-0">{issue.identifier}</span>+ <span className="truncate">{issue.title}</span>+ </CommandItem>);return (@@ -112,35 +153,18 @@ export function IssuePickerModal({{!isLoading && query.trim() && results.length === 0 && (<CommandEmpty>{t(($) => $.issue_picker.no_results)}</CommandEmpty>)}- {!isLoading && !query.trim() && (+ {!isLoading && !query.trim() && suggestionGroups.length === 0 && (<div className="py-6 text-center text-body text-muted-foreground">{t(($) => $.issue_picker.prompt_to_search)}</div>)}- {results.length > 0 && (- <CommandGroup>- {results.map((issue) => (- <CommandItem- key={issue.id}- value={issue.id}- onSelect={() => {- onSelect(issue);- onOpenChange(false);- }}- >- <StatusIcon- status={issue.status}- color={colorOf(issue.status)}- icon={iconOf(issue.status)}- category={issueStatusCategory(issue) ?? undefined}- className="h-3.5 w-3.5 shrink-0"- />- <span className="text-muted-foreground shrink-0">{issue.identifier}</span>- <span className="truncate">{issue.title}</span>- </CommandItem>- ))}- </CommandGroup>- )}+ {!isLoading && !query.trim() &&+ suggestionGroups.map((group) => (+ <CommandGroup key={group.key} heading={group.heading}>+ {group.issues.map(row)}+ </CommandGroup>+ ))}+ {results.length > 0 && <CommandGroup>{results.map(row)}</CommandGroup>}</CommandList></Command></CommandDialog>diff --git a/packages/views/modals/mark-duplicate-issue.tsx b/packages/views/modals/mark-duplicate-issue.tsxindex e04fca04a5..8b86db0ec0 100644--- a/packages/views/modals/mark-duplicate-issue.tsx+++ b/packages/views/modals/mark-duplicate-issue.tsx@@ -1,17 +1,38 @@"use client";-import { useQuery } from "@tanstack/react-query";+import { useMemo } from "react";+import { useQueries, useQuery } from "@tanstack/react-query";import { toast } from "sonner";-import { errorCode } from "@multica/core/api";+import { api, errorCode } from "@multica/core/api";import { useWorkspaceId } from "@multica/core/hooks";-import { issueDuplicatesOptions } from "@multica/core/issues/queries";+import {+ issueDetailOptions,+ issueDuplicatesOptions,+ issueKeys,+} from "@multica/core/issues/queries";import { useUpdateIssue } from "@multica/core/issues/mutations";-import { IssuePickerModal } from "./issue-picker-modal";+import {+ selectRecentIssues,+ useRecentIssuesStore,+} from "@multica/core/issues/stores/recent-issues-store";+import type { Issue } from "@multica/core/types";+import { isDuplicateIssue } from "../issues/components/issue-duplicates";+import { IssuePickerModal, type IssuePickerSuggestionGroup } from "./issue-picker-modal";import { useT } from "../i18n";+const SUGGESTION_LIMIT = 6;++const notDuplicate = (candidate: Issue) => !isDuplicateIssue(candidate);+/*** 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.+ *+ * The picker opens with candidates instead of an empty search: issues whose+ * title matches this one's (the same bug filed twice) and the issues viewed+ * most recently, since the original is usually the one that prompted the+ * mark. Issues that are duplicates themselves cannot be originals and are+ * left out of candidates and search results alike.*/export function MarkDuplicateIssueModal({onClose,@@ -32,6 +53,43 @@ export function MarkDuplicateIssueModal({});const excludeIds = [issueId, ...(relations?.duplicates.map((d) => d.id) ?? [])];+ const { data: issue } = useQuery({+ ...issueDetailOptions(wsId, issueId),+ enabled: !!issueId,+ });+ const title = issue?.title.trim() ?? "";+ const { data: sameTitle } = useQuery({+ queryKey: [...issueKeys.all(wsId), "duplicate-candidates", issueId, title],+ queryFn: () => api.searchIssues({ q: title, limit: SUGGESTION_LIMIT, include_closed: true }),+ enabled: title !== "",+ staleTime: 60_000,+ });++ const recentEntries = useRecentIssuesStore(selectRecentIssues(wsId));+ const recentQueries = useQueries({+ queries: recentEntries+ .filter((entry) => entry.id !== issueId)+ .slice(0, SUGGESTION_LIMIT)+ .map((entry) => issueDetailOptions(wsId, entry.id)),+ });+ const recent = useMemo(+ () => recentQueries.flatMap((q) => (q.data ? [q.data] : [])),+ [recentQueries],+ );++ const suggestions = useMemo<IssuePickerSuggestionGroup[]>(() => {+ const similar = sameTitle?.issues ?? [];+ const seen = new Set(similar.map((i) => i.id));+ return [+ { key: "similar", heading: t(($) => $.issue_picker.suggested_similar), issues: similar },+ {+ key: "recent",+ heading: t(($) => $.issue_picker.suggested_recent),+ issues: recent.filter((i) => !seen.has(i.id)),+ },+ ];+ }, [sameTitle, recent, t]);+return (<IssuePickerModalopen@@ -41,6 +99,8 @@ export function MarkDuplicateIssueModal({title={t(($) => $.mark_duplicate.title)}description={t(($) => $.mark_duplicate.description)}excludeIds={excludeIds}+ suggestions={suggestions}+ isSelectable={notDuplicate}onSelect={(selected) => {updateIssue.mutate({diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex c762006363..2922c8528c 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -496,7 +496,7 @@ var validIssueFields = []string{"id", "workspace_id", "number", "identifier", "title", "description","status", "status_category", "status_name", "priority", "assignee_type","assignee_id", "creator_type", "creator_id", "parent_issue_id",- "project_id", "position", "stage", "start_date", "due_date", "created_at",+ "duplicate_of", "project_id", "position", "stage", "start_date", "due_date", "created_at","updated_at", "revision", "last_activity_at", "metadata", "properties","labels",}diff --git a/server/cmd/multica/cmd_issue_timeline.go b/server/cmd/multica/cmd_issue_timeline.goindex c1fd84e038..6a0decc441 100644--- a/server/cmd/multica/cmd_issue_timeline.go+++ b/server/cmd/multica/cmd_issue_timeline.go@@ -71,7 +71,7 @@ Examples:func init() {issueTimelineCmd.Flags().String("output", "table", "Output format: table or json")issueTimelineCmd.Flags().Bool("activity-only", false, "Drop comments and return every activity record — including the task_completed / task_failed entries the server already writes, not just field changes. Much cheaper to read than the full timeline; use --action when you want only state transitions.")- issueTimelineCmd.Flags().StringSlice("action", nil, "Only return activities with these actions (repeatable or comma-separated). Implies --activity-only, since comments carry no action. Known actions: created, status_changed, priority_changed, assignee_changed, title_changed, description_updated, start_date_changed, due_date_changed, task_completed, task_failed, squad_leader_evaluated.")+ issueTimelineCmd.Flags().StringSlice("action", nil, "Only return activities with these actions (repeatable or comma-separated). Implies --activity-only, since comments carry no action. Known actions: created, status_changed, priority_changed, assignee_changed, title_changed, description_updated, start_date_changed, due_date_changed, task_completed, task_failed, squad_leader_evaluated, duplicate_marked, duplicate_unmarked, duplicate_added, duplicate_removed.")issueTimelineCmd.Flags().String("since", "", "Only return entries created after this timestamp (RFC3339)")issueTimelineCmd.Flags().Int("tail", 0, "Only return the N most recent entries (applied after every other filter)")issueTimelineCmd.Flags().Bool("full-id", false, "Show full UUIDs in table output")diff --git a/server/cmd/server/activity_listeners.go b/server/cmd/server/activity_listeners.goindex 3a492766ee..5a3814bd01 100644--- a/server/cmd/server/activity_listeners.go+++ b/server/cmd/server/activity_listeners.go@@ -7,6 +7,7 @@ import ("github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/handler"+ "github.com/multica-ai/multica/server/internal/service""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/dbid"@@ -62,6 +63,12 @@ func registerActivityListeners(bus *events.Bus, queries *db.Queries) {}statusChanged, _ := payload["status_changed"].(bool)+ // A duplicate mark change is a status change with a better name: the+ // duplicate row names the other issue and where the status went, so+ // the generic status row would only repeat it (MUL-7349).+ if duplicateMarkChanged(payload) {+ statusChanged = false+ }priorityChanged, _ := payload["priority_changed"].(bool)assigneeChanged, _ := payload["assignee_changed"].(bool)descriptionChanged, _ := payload["description_changed"].(bool)@@ -248,6 +255,8 @@ func registerActivityListeners(bus *events.Bus, queries *db.Queries) {publishActivityEvent(bus, e, activity)}}++ recordDuplicateMarkActivities(ctx, bus, queries, e, issue, payload)})// task:completed — record "task_completed" activity@@ -326,3 +335,93 @@ func publishActivityEvent(bus *events.Bus, original events.Event, activity db.Ac},})}++// recordDuplicateMarkActivities logs a duplicate mark change on both issues+// (MUL-7349): duplicate_marked / duplicate_unmarked on the duplicate and+// duplicate_added / duplicate_removed on its original. Every publisher of a+// mark change carries both ends as duplicate_of_issue_id and+// prev_duplicate_of_issue_id. Details name the other issue by id, for+// linking, and by identifier, so the row still reads once that issue is gone.+func recordDuplicateMarkActivities(ctx context.Context, bus *events.Bus, queries *db.Queries, e events.Event, issue handler.IssueResponse, payload map[string]any) {+ if !duplicateMarkChanged(payload) {+ return+ }+ next := derefPayloadString(payload["duplicate_of_issue_id"])+ prev := derefPayloadString(payload["prev_duplicate_of_issue_id"])+ statusChanged, _ := payload["status_changed"].(bool)+ record := func(issueID, action string, details map[string]string) {+ body, _ := json.Marshal(details)+ activity, err := queries.CreateActivity(ctx, db.CreateActivityParams{+ ID: dbid.NewV7(),+ WorkspaceID: parseUUID(issue.WorkspaceID),+ IssueID: parseUUID(issueID),+ ActorType: util.StrToText(e.ActorType),+ ActorID: optionalUUID(e.ActorID),+ Action: action,+ Details: body,+ })+ if err != nil {+ slog.Error("activity: failed to record duplicate mark change",+ "issue_id", issueID, "action", action, "error", err)+ return+ }+ publishActivityEvent(bus, e, activity)+ }+ self := map[string]string{"duplicate_id": issue.ID, "duplicate_identifier": issue.Identifier}++ if prev != "" {+ if identifier, ok := lookupIssueIdentifier(ctx, queries, issue.WorkspaceID, prev); ok {+ details := map[string]string{"original_id": prev, "original_identifier": identifier}+ if statusChanged {+ // Removing a mark by reopening moved the status too; this row+ // stands in for the status row, so it says where.+ details["to"] = issue.Status+ }+ record(issue.ID, "duplicate_unmarked", details)+ record(prev, "duplicate_removed", self)+ } else if identifier, _ := payload["prev_duplicate_of_identifier"].(string); identifier != "" {+ // The original was deleted and took its own log with it; the delete+ // path passes the identifier it can no longer be looked up by.+ record(issue.ID, "duplicate_unmarked", map[string]string{+ "original_id": prev, "original_identifier": identifier, "reason": "original_deleted",+ })+ }+ }+ if next != "" {+ if identifier, ok := lookupIssueIdentifier(ctx, queries, issue.WorkspaceID, next); ok {+ record(issue.ID, "duplicate_marked", map[string]string{"original_id": next, "original_identifier": identifier})+ record(next, "duplicate_added", self)+ }+ }+}++// duplicateMarkChanged reports whether an issue:updated payload carries a+// duplicate mark change: both ends ride as *string fields.+func duplicateMarkChanged(payload map[string]any) bool {+ return derefPayloadString(payload["duplicate_of_issue_id"]) != derefPayloadString(payload["prev_duplicate_of_issue_id"])+}++// derefPayloadString reads a *string payload field; nil and absent read as "".+func derefPayloadString(v any) string {+ if s, ok := v.(*string); ok && s != nil {+ return *s+ }+ return ""+}++// lookupIssueIdentifier renders the identifier of an issue in the workspace;+// ok is false when the issue no longer exists.+func lookupIssueIdentifier(ctx context.Context, queries *db.Queries, workspaceID, issueID string) (string, bool) {+ row, err := queries.GetIssueInWorkspace(ctx, db.GetIssueInWorkspaceParams{+ ID: parseUUID(issueID),+ WorkspaceID: parseUUID(workspaceID),+ })+ if err != nil {+ return "", false+ }+ ws, err := queries.GetWorkspace(ctx, row.WorkspaceID)+ if err != nil {+ return "", false+ }+ return service.IssueIdentifier(ws.IssuePrefix, row.Number), true+}diff --git a/server/cmd/server/activity_listeners_test.go b/server/cmd/server/activity_listeners_test.goindex df163c67f2..fe9f5fb4df 100644--- a/server/cmd/server/activity_listeners_test.go+++ b/server/cmd/server/activity_listeners_test.go@@ -3,6 +3,7 @@ package mainimport ("context""encoding/json"+ "net/http""testing""github.com/multica-ai/multica/server/internal/events"@@ -404,3 +405,260 @@ func TestActivityTaskFailed(t *testing.T) {t.Fatalf("expected action 'task_failed', got %q", activities[0].Action)}}++// ---------------------------------------------------------------------------+// Duplicate marks (MUL-7349) log on both issues. Every publisher of a mark+// change carries both ends of it, the way UpdateIssue does, and the mark row+// stands in for the status row the same write would otherwise log.+// ---------------------------------------------------------------------------++func duplicateMarkEvent(issueID, identifier, status string, prev, next *string, extra map[string]any) events.Event {+ payload := map[string]any{+ "issue": handler.IssueResponse{+ ID: issueID,+ WorkspaceID: testWorkspaceID,+ Identifier: identifier,+ Title: "duplicate activity test issue",+ Status: status,+ Priority: "medium",+ CreatorType: "member",+ CreatorID: testUserID,+ },+ "duplicate_of_issue_id": next,+ "prev_duplicate_of_issue_id": prev,+ }+ for k, v := range extra {+ payload[k] = v+ }+ return events.Event{+ Type: protocol.EventIssueUpdated,+ WorkspaceID: testWorkspaceID,+ ActorType: "member",+ ActorID: testUserID,+ Payload: payload,+ }+}++// activityDetails returns the details of the one activity with this action on+// the issue, failing when there are none or several.+func activityDetails(t *testing.T, queries *db.Queries, issueID, action string) map[string]string {+ t.Helper()+ var found []db.ActivityLog+ for _, a := range listActivitiesForIssue(t, queries, issueID) {+ if a.Action == action {+ found = append(found, a)+ }+ }+ if len(found) != 1 {+ t.Fatalf("expected exactly 1 %q activity on %s, got %d", action, issueID, len(found))+ }+ var details map[string]string+ if err := json.Unmarshal(found[0].Details, &details); err != nil {+ t.Fatalf("failed to unmarshal details: %v", err)+ }+ return details+}++func activityActions(t *testing.T, queries *db.Queries, issueID string) []string {+ t.Helper()+ var actions []string+ for _, a := range listActivitiesForIssue(t, queries, issueID) {+ actions = append(actions, a.Action)+ }+ return actions+}++func testIssueIdentifier(t *testing.T, queries *db.Queries, issueID string) string {+ t.Helper()+ ctx := context.Background()+ issue, err := queries.GetIssue(ctx, util.MustParseUUID(issueID))+ if err != nil {+ t.Fatalf("GetIssue: %v", err)+ }+ ws, err := queries.GetWorkspace(ctx, issue.WorkspaceID)+ if err != nil {+ t.Fatalf("GetWorkspace: %v", err)+ }+ return service.IssueIdentifier(ws.IssuePrefix, issue.Number)+}++func newDuplicateTestIssues(t *testing.T, queries *db.Queries) (bus *events.Bus, duplicateID, originalID string) {+ t.Helper()+ bus = events.New()+ registerActivityListeners(bus, queries)+ duplicateID = createTestIssue(t, testWorkspaceID, testUserID)+ originalID = createTestIssue(t, testWorkspaceID, testUserID)+ t.Cleanup(func() {+ cleanupActivities(t, duplicateID)+ cleanupActivities(t, originalID)+ cleanupTestIssue(t, duplicateID)+ cleanupTestIssue(t, originalID)+ })+ return bus, duplicateID, originalID+}++// Marking is a status write to cancelled; the mark row replaces the status+// row rather than sitting beside it.+func TestActivityIssueUpdated_DuplicateMarked(t *testing.T) {+ queries := db.New(testPool)+ bus, duplicateID, originalID := newDuplicateTestIssues(t, queries)++ bus.Publish(duplicateMarkEvent(duplicateID, "MUL-7624", "cancelled", nil, &originalID, map[string]any{+ "status_changed": true,+ "prev_status": "todo",+ }))++ marked := activityDetails(t, queries, duplicateID, "duplicate_marked")+ if marked["original_id"] != originalID {+ t.Fatalf("original_id = %q, want %q", marked["original_id"], originalID)+ }+ if want := testIssueIdentifier(t, queries, originalID); marked["original_identifier"] != want {+ t.Fatalf("original_identifier = %q, want %q", marked["original_identifier"], want)+ }+ added := activityDetails(t, queries, originalID, "duplicate_added")+ if added["duplicate_id"] != duplicateID || added["duplicate_identifier"] != "MUL-7624" {+ t.Fatalf("duplicate_added details = %v", added)+ }+ if got := activityActions(t, queries, duplicateID); len(got) != 1 {+ t.Fatalf("expected only the duplicate_marked row on the duplicate, got %v", got)+ }+}++// Reopening removes the mark; the unmarked row carries the new status the+// suppressed status row would have named.+func TestActivityIssueUpdated_DuplicateUnmarked(t *testing.T) {+ queries := db.New(testPool)+ bus, duplicateID, originalID := newDuplicateTestIssues(t, queries)++ bus.Publish(duplicateMarkEvent(duplicateID, "MUL-7624", "todo", &originalID, nil, map[string]any{+ "status_changed": true,+ "prev_status": "cancelled",+ }))++ unmarked := activityDetails(t, queries, duplicateID, "duplicate_unmarked")+ if unmarked["original_id"] != originalID || unmarked["reason"] != "" || unmarked["to"] != "todo" {+ t.Fatalf("duplicate_unmarked details = %v", unmarked)+ }+ removed := activityDetails(t, queries, originalID, "duplicate_removed")+ if removed["duplicate_id"] != duplicateID {+ t.Fatalf("duplicate_removed details = %v", removed)+ }+ if got := activityActions(t, queries, duplicateID); len(got) != 1 {+ t.Fatalf("expected only the duplicate_unmarked row on the duplicate, got %v", got)+ }+}++// Moving a mark from one original to another reads as leaving the first and+// joining the second, on all three issues. The status did not move.+func TestActivityIssueUpdated_DuplicateRepointed(t *testing.T) {+ queries := db.New(testPool)+ bus, duplicateID, firstID := newDuplicateTestIssues(t, queries)+ secondID := createTestIssue(t, testWorkspaceID, testUserID)+ t.Cleanup(func() {+ cleanupActivities(t, secondID)+ cleanupTestIssue(t, secondID)+ })++ bus.Publish(duplicateMarkEvent(duplicateID, "MUL-7624", "cancelled", &firstID, &secondID, nil))++ unmarked := activityDetails(t, queries, duplicateID, "duplicate_unmarked")+ if unmarked["original_id"] != firstID || unmarked["to"] != "" {+ t.Fatalf("duplicate_unmarked details = %v", unmarked)+ }+ if got := activityDetails(t, queries, duplicateID, "duplicate_marked"); got["original_id"] != secondID {+ t.Fatalf("duplicate_marked original_id = %q, want %q", got["original_id"], secondID)+ }+ activityDetails(t, queries, firstID, "duplicate_removed")+ activityDetails(t, queries, secondID, "duplicate_added")+}++// Deleting the original clears the mark. The original's log goes with it, so+// only the duplicate gets a row, naming the identifier the delete path passed.+func TestActivityIssueUpdated_DuplicateOriginalDeleted(t *testing.T) {+ queries := db.New(testPool)+ bus, duplicateID, _ := newDuplicateTestIssues(t, queries)+ gone := "00000000-0000-4000-8000-00000000dead"++ bus.Publish(duplicateMarkEvent(duplicateID, "MUL-7624", "cancelled", &gone, nil, map[string]any{+ "prev_duplicate_of_identifier": "MUL-7349",+ }))++ unmarked := activityDetails(t, queries, duplicateID, "duplicate_unmarked")+ if unmarked["original_identifier"] != "MUL-7349" || unmarked["reason"] != "original_deleted" || unmarked["to"] != "" {+ t.Fatalf("duplicate_unmarked details = %v", unmarked)+ }+}++func TestActivityIssueUpdated_DuplicateUnchanged(t *testing.T) {+ queries := db.New(testPool)+ bus, duplicateID, originalID := newDuplicateTestIssues(t, queries)++ // Re-marking the same original is a no-op on the server and must not log.+ bus.Publish(duplicateMarkEvent(duplicateID, "MUL-7624", "cancelled", &originalID, &originalID, nil))++ if got := activityActions(t, queries, duplicateID); len(got) != 0 {+ t.Fatalf("expected no activities on the duplicate, got %v", got)+ }+ if got := activityActions(t, queries, originalID); len(got) != 0 {+ t.Fatalf("expected no activities on the original, got %v", got)+ }+}++// A plain cancel with no mark still logs its status row: only a mark change+// replaces it.+func TestActivityIssueUpdated_PlainCancelKeepsStatusRow(t *testing.T) {+ queries := db.New(testPool)+ bus, issueID, _ := newDuplicateTestIssues(t, queries)++ bus.Publish(duplicateMarkEvent(issueID, "MUL-7624", "cancelled", nil, nil, map[string]any{+ "status_changed": true,+ "prev_status": "todo",+ }))++ if got := activityActions(t, queries, issueID); len(got) != 1 || got[0] != "status_changed" {+ t.Fatalf("expected only status_changed, got %v", got)+ }+}++// The real write path: marking and reopening through UpdateIssue produce one+// duplicate row per side and no generic status row.+func TestActivityDuplicateMarkThroughUpdateIssue(t *testing.T) {+ queries := db.New(testPool)+ duplicateID := createTestIssue(t, testWorkspaceID, testUserID)+ originalID := createTestIssue(t, testWorkspaceID, testUserID)+ t.Cleanup(func() {+ cleanupActivities(t, duplicateID)+ cleanupActivities(t, originalID)+ cleanupTestIssue(t, duplicateID)+ cleanupTestIssue(t, originalID)+ })++ resp := authRequest(t, "PUT", "/api/issues/"+duplicateID, map[string]any{+ "duplicate_of_issue_id": originalID,+ })+ resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("mark: expected 200, got %d", resp.StatusCode)+ }+ if got := activityActions(t, queries, duplicateID); len(got) != 1 || got[0] != "duplicate_marked" {+ t.Fatalf("after mark, duplicate activities = %v, want [duplicate_marked]", got)+ }+ if got := activityActions(t, queries, originalID); len(got) != 1 || got[0] != "duplicate_added" {+ t.Fatalf("after mark, original activities = %v, want [duplicate_added]", got)+ }++ resp = authRequest(t, "PUT", "/api/issues/"+duplicateID, map[string]any{"status": "todo"})+ resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("reopen: expected 200, got %d", resp.StatusCode)+ }+ if got := activityActions(t, queries, duplicateID); len(got) != 2 || got[1] != "duplicate_unmarked" {+ t.Fatalf("after reopen, duplicate activities = %v, want [duplicate_marked duplicate_unmarked]", got)+ }+ if got := activityDetails(t, queries, duplicateID, "duplicate_unmarked"); got["to"] != "todo" {+ t.Fatalf("duplicate_unmarked to = %q, want todo", got["to"])+ }+ if got := activityActions(t, queries, originalID); len(got) != 2 || got[1] != "duplicate_removed" {+ t.Fatalf("after reopen, original activities = %v, want [duplicate_added duplicate_removed]", got)+ }+}diff --git a/server/cmd/server/integration_test.go b/server/cmd/server/integration_test.goindex a4bb9f6b89..70fb7f7590 100644--- a/server/cmd/server/integration_test.go+++ b/server/cmd/server/integration_test.go@@ -21,6 +21,7 @@ import ("github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/realtime"+ db "github.com/multica-ai/multica/server/pkg/db/generated")var (@@ -71,6 +72,8 @@ func TestMain(m *testing.M) {bus := events.New()registerListeners(bus, hub)+ // Same wiring as main.go: HTTP writes through the test server log activity.+ registerActivityListeners(bus, db.New(pool))router := NewRouter(pool, hub, bus, analytics.NoopClient{}, nil)testServer = httptest.NewServer(router)@@ -1518,21 +1521,8 @@ func TestWebSocketIntegration(t *testing.T) {readJSON(t, resp, &issue)issueID := issue["id"].(string)- // Read the WebSocket message- conn.SetReadDeadline(time.Now().Add(3 * time.Second))- _, msg, err := conn.ReadMessage()- if err != nil {- t.Fatalf("WebSocket read error: %v", err)- }-- // Verify the message contains the issue event- var wsMsg map[string]any- if err := json.Unmarshal(msg, &wsMsg); err != nil {- t.Fatalf("failed to parse WebSocket message: %v", err)- }- if wsMsg["type"] != "issue:created" {- t.Fatalf("expected type 'issue:created', got '%s'", wsMsg["type"])- }+ // Verify the broadcast carries the issue event+ readWSMessageOfType(t, conn, "issue:created")// Update the issue — should trigger another broadcastresp = authRequest(t, "PUT", "/api/issues/"+issueID, map[string]any{@@ -1540,29 +1530,36 @@ func TestWebSocketIntegration(t *testing.T) {})resp.Body.Close()- conn.SetReadDeadline(time.Now().Add(3 * time.Second))- _, msg, err = conn.ReadMessage()- if err != nil {- t.Fatalf("WebSocket read error on update: %v", err)- }- var updateMsg map[string]any- json.Unmarshal(msg, &updateMsg)- if updateMsg["type"] != "issue:updated" {- t.Fatalf("expected type 'issue:updated', got '%s'", updateMsg["type"])- }+ readWSMessageOfType(t, conn, "issue:updated")// Delete the issue — should trigger another broadcastresp = authRequest(t, "DELETE", "/api/issues/"+issueID, nil)resp.Body.Close()- conn.SetReadDeadline(time.Now().Add(3 * time.Second))- _, msg, err = conn.ReadMessage()- if err != nil {- t.Fatalf("WebSocket read error on delete: %v", err)- }- var deleteMsg map[string]any- json.Unmarshal(msg, &deleteMsg)- if deleteMsg["type"] != "issue:deleted" {- t.Fatalf("expected type 'issue:deleted', got '%s'", deleteMsg["type"])+ readWSMessageOfType(t, conn, "issue:deleted")+}++// readWSMessageOfType reads frames until one of the wanted type arrives. The+// activity listeners are wired like production, so an activity:created frame+// for the same write can land before or after the issue event itself.+func readWSMessageOfType(t *testing.T, conn *websocket.Conn, wantType string) map[string]any {+ t.Helper()+ deadline := time.Now().Add(3 * time.Second)+ for {+ conn.SetReadDeadline(deadline)+ _, msg, err := conn.ReadMessage()+ if err != nil {+ t.Fatalf("WebSocket read error waiting for %s: %v", wantType, err)+ }+ var wsMsg map[string]any+ if err := json.Unmarshal(msg, &wsMsg); err != nil {+ t.Fatalf("failed to parse WebSocket message: %v", err)+ }+ if wsMsg["type"] == wantType {+ return wsMsg+ }+ if wsMsg["type"] != "activity:created" {+ t.Fatalf("expected type '%s', got '%s'", wantType, wsMsg["type"])+ }}}diff --git a/server/internal/handler/github.go b/server/internal/handler/github.goindex 752ad846f4..6151f0df35 100644--- a/server/internal/handler/github.go+++ b/server/internal/handler/github.go@@ -1968,6 +1968,10 @@ func (h *Handler) advanceIssueToDone(ctx context.Context, issue db.Issue, worksp"creator_type": issue.CreatorType,"creator_id": uuidToString(issue.CreatorID),"source": "github_pr_merged",+ // Reaching done clears a duplicate mark (MUL-7349); carry both ends so+ // the activity log and clients see the mark go.+ "duplicate_of_issue_id": uuidToPtr(updated.DuplicateOfIssueID),+ "prev_duplicate_of_issue_id": uuidToPtr(issue.DuplicateOfIssueID),})}diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 1ff015a8be..28bfbd0696 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -67,8 +67,13 @@ type IssueResponse struct {CreatorType string `json:"creator_type"`CreatorID string `json:"creator_id"`ParentIssueID *string `json:"parent_issue_id"`- ProjectID *string `json:"project_id"`- Position float64 `json:"position"`+ // DuplicateOf is the original this issue duplicates (MUL-7349), set only+ // while the mark counts: the issue is cancelled and the original still+ // exists. newStatusCategoryFiller resolves it from duplicateOfIssueID;+ // an endpoint that skips the filler emits null rather than a bare pointer.+ DuplicateOf *IssueRefResponse `json:"duplicate_of"`+ ProjectID *string `json:"project_id"`+ Position float64 `json:"position"`// Stage groups sub-issues under the same parent into ordered barrier// groups (null = unstaged). See issue_child_done.go for how a closed// stage gates the child-done -> parent wake.@@ -100,6 +105,17 @@ type IssueResponse struct {// SourceContext is detail-only. List, board, search, and children responses// deliberately omit the potentially large immutable snapshot.SourceContext *sourceContextDetailResponse `json:"source_context,omitempty"`+ // duplicateOfIssueID is the raw mark, kept off the wire; see DuplicateOf.+ duplicateOfIssueID pgtype.UUID+}++// IssueRefResponse names another issue inside a response: enough to render+// a link and its status without a second request.+type IssueRefResponse struct {+ ID string `json:"id"`+ Identifier string `json:"identifier"`+ Title string `json:"title"`+ Status string `json:"status"`}// validIssuePriorities mirrors the CHECK constraint on the issue table. Write@@ -351,8 +367,15 @@ func (h *Handler) fillStatusCategories(ctx context.Context, wsID pgtype.UUID, re// this exists to avoid. (MUL-6243)func (h *Handler) newStatusCategoryFiller(ctx context.Context, wsID pgtype.UUID) func(*IssueResponse) {resolver := issuestatus.NewResolver(wsID)+ originals := map[pgtype.UUID]*IssueRefResponse{}return func(resp *IssueResponse) {- if resp == nil || resp.StatusCategory != "" {+ if resp == nil {+ return+ }+ // Every response that resolves its status also resolves its duplicate+ // mark, so the two never disagree about which endpoints carry them.+ h.fillDuplicateOf(ctx, wsID, resp, originals)+ if resp.StatusCategory != "" {return}resp.StatusCategory = issuestatus.WireCategory(resp.Status, resolver.Category(ctx, h.Queries, resp.Status))@@ -368,6 +391,53 @@ func (h *Handler) fillStatusCategory(ctx context.Context, wsID pgtype.UUID, resph.newStatusCategoryFiller(ctx, wsID)(resp)}+// duplicateOfPointer keeps a duplicate mark only while the issue is+// cancelled. Whether the original still exists is checked when the response+// is filled (fillDuplicateOf), so a pointer an older server left behind+// never surfaces. Same rule as IssueHasDuplicates in issue.sql.+func duplicateOfPointer(status string, id pgtype.UUID) pgtype.UUID {+ if status != issuestatus.Cancelled {+ return pgtype.UUID{}+ }+ return id+}++// fillDuplicateOf resolves a duplicate mark to its original (MUL-7349): a+// primary-key read per distinct original, memoised in memo across one+// response so many duplicates of one issue cost one read. A missing original+// (memoised as nil) leaves DuplicateOf unset.+func (h *Handler) fillDuplicateOf(ctx context.Context, wsID pgtype.UUID, resp *IssueResponse, memo map[pgtype.UUID]*IssueRefResponse) {+ if !resp.duplicateOfIssueID.Valid {+ return+ }+ ref, seen := memo[resp.duplicateOfIssueID]+ if !seen {+ row, err := h.Queries.GetIssueRefInWorkspace(ctx, db.GetIssueRefInWorkspaceParams{+ ID: resp.duplicateOfIssueID,+ WorkspaceID: wsID,+ })+ switch {+ case err == nil:+ // The response already rendered its own identifier with the+ // workspace prefix; the original shares it.+ prefix := strings.TrimSuffix(resp.Identifier, "-"+strconv.Itoa(int(resp.Number)))+ ref = &IssueRefResponse{+ ID: uuidToString(row.ID),+ Identifier: prefix + "-" + strconv.Itoa(int(row.Number)),+ Title: row.Title,+ Status: row.Status,+ }+ case !isNotFound(err):+ slog.Warn("resolve duplicate original failed", "error", err, "issue_id", resp.ID)+ }+ memo[resp.duplicateOfIssueID] = ref+ }+ if ref != nil {+ copied := *ref+ resp.DuplicateOf = &copied+ }+}+func issueToResponse(i db.Issue, issuePrefix string) IssueResponse {identifier := issuePrefix + "-" + strconv.Itoa(int(i.Number))// Built-ins map to public categories without a catalog lookup. A custom@@ -377,31 +447,32 @@ func issueToResponse(i db.Issue, issuePrefix string) IssueResponse {statusCategory = i.Status}return IssueResponse{- ID: uuidToString(i.ID),- WorkspaceID: uuidToString(i.WorkspaceID),- Number: i.Number,- Identifier: identifier,- Title: i.Title,- Description: textToPtr(i.Description),- Status: i.Status,- StatusCategory: statusCategory,- Priority: i.Priority,- AssigneeType: textToPtr(i.AssigneeType),- AssigneeID: uuidToPtr(i.AssigneeID),- CreatorType: i.CreatorType,- CreatorID: uuidToString(i.CreatorID),- ParentIssueID: uuidToPtr(i.ParentIssueID),- ProjectID: uuidToPtr(i.ProjectID),- Position: i.Position,- Stage: int4ToPtr(i.Stage),- StartDate: dateToPtr(i.StartDate),- DueDate: dateToPtr(i.DueDate),- CreatedAt: timestampToString(i.CreatedAt),- UpdatedAt: timestampToString(i.UpdatedAt),- Revision: i.Revision,- LastActivityAt: timestampToNanoPtr(i.LastActivityAt),- Metadata: parseIssueMetadata(i.Metadata),- Properties: parseIssueProperties(i.Properties),+ ID: uuidToString(i.ID),+ WorkspaceID: uuidToString(i.WorkspaceID),+ Number: i.Number,+ Identifier: identifier,+ Title: i.Title,+ Description: textToPtr(i.Description),+ Status: i.Status,+ StatusCategory: statusCategory,+ Priority: i.Priority,+ AssigneeType: textToPtr(i.AssigneeType),+ AssigneeID: uuidToPtr(i.AssigneeID),+ CreatorType: i.CreatorType,+ CreatorID: uuidToString(i.CreatorID),+ ParentIssueID: uuidToPtr(i.ParentIssueID),+ duplicateOfIssueID: duplicateOfPointer(i.Status, i.DuplicateOfIssueID),+ ProjectID: uuidToPtr(i.ProjectID),+ Position: i.Position,+ Stage: int4ToPtr(i.Stage),+ StartDate: dateToPtr(i.StartDate),+ DueDate: dateToPtr(i.DueDate),+ CreatedAt: timestampToString(i.CreatedAt),+ UpdatedAt: timestampToString(i.UpdatedAt),+ Revision: i.Revision,+ LastActivityAt: timestampToNanoPtr(i.LastActivityAt),+ Metadata: parseIssueMetadata(i.Metadata),+ Properties: parseIssueProperties(i.Properties),}}@@ -414,31 +485,32 @@ func issueListRowToResponse(i db.ListIssuesRow, issuePrefix string) IssueRespons}identifier := issuePrefix + "-" + strconv.Itoa(int(i.Number))return IssueResponse{- ID: uuidToString(i.ID),- WorkspaceID: uuidToString(i.WorkspaceID),- Number: i.Number,- Identifier: identifier,- Title: i.Title,- Description: textToPtr(i.Description),- Status: i.Status,- StatusCategory: statusCategory,- Priority: i.Priority,- AssigneeType: textToPtr(i.AssigneeType),- AssigneeID: uuidToPtr(i.AssigneeID),- CreatorType: i.CreatorType,- CreatorID: uuidToString(i.CreatorID),- ParentIssueID: uuidToPtr(i.ParentIssueID),- ProjectID: uuidToPtr(i.ProjectID),- Position: i.Position,- Stage: int4ToPtr(i.Stage),- StartDate: dateToPtr(i.StartDate),- DueDate: dateToPtr(i.DueDate),- CreatedAt: timestampToString(i.CreatedAt),- UpdatedAt: timestampToString(i.UpdatedAt),- Revision: i.Revision,- LastActivityAt: timestampToNanoPtr(i.LastActivityAt),- Metadata: parseIssueMetadata(i.Metadata),- Properties: parseIssueProperties(i.Properties),+ ID: uuidToString(i.ID),+ WorkspaceID: uuidToString(i.WorkspaceID),+ Number: i.Number,+ Identifier: identifier,+ Title: i.Title,+ Description: textToPtr(i.Description),+ Status: i.Status,+ StatusCategory: statusCategory,+ Priority: i.Priority,+ AssigneeType: textToPtr(i.AssigneeType),+ AssigneeID: uuidToPtr(i.AssigneeID),+ CreatorType: i.CreatorType,+ CreatorID: uuidToString(i.CreatorID),+ ParentIssueID: uuidToPtr(i.ParentIssueID),+ duplicateOfIssueID: duplicateOfPointer(i.Status, i.DuplicateOfIssueID),+ ProjectID: uuidToPtr(i.ProjectID),+ Position: i.Position,+ Stage: int4ToPtr(i.Stage),+ StartDate: dateToPtr(i.StartDate),+ DueDate: dateToPtr(i.DueDate),+ CreatedAt: timestampToString(i.CreatedAt),+ UpdatedAt: timestampToString(i.UpdatedAt),+ Revision: i.Revision,+ LastActivityAt: timestampToNanoPtr(i.LastActivityAt),+ Metadata: parseIssueMetadata(i.Metadata),+ Properties: parseIssueProperties(i.Properties),}}@@ -483,31 +555,32 @@ func openIssueRowToResponse(i db.ListOpenIssuesRow, issuePrefix string) IssueRes}identifier := issuePrefix + "-" + strconv.Itoa(int(i.Number))return IssueResponse{- ID: uuidToString(i.ID),- WorkspaceID: uuidToString(i.WorkspaceID),- Number: i.Number,- Identifier: identifier,- Title: i.Title,- Description: textToPtr(i.Description),- Status: i.Status,- StatusCategory: statusCategory,- Priority: i.Priority,- AssigneeType: textToPtr(i.AssigneeType),- AssigneeID: uuidToPtr(i.AssigneeID),- CreatorType: i.CreatorType,- CreatorID: uuidToString(i.CreatorID),- ParentIssueID: uuidToPtr(i.ParentIssueID),- ProjectID: uuidToPtr(i.ProjectID),- Position: i.Position,- Stage: int4ToPtr(i.Stage),- StartDate: dateToPtr(i.StartDate),- DueDate: dateToPtr(i.DueDate),- CreatedAt: timestampToString(i.CreatedAt),- UpdatedAt: timestampToString(i.UpdatedAt),- Revision: i.Revision,- LastActivityAt: timestampToNanoPtr(i.LastActivityAt),- Metadata: parseIssueMetadata(i.Metadata),- Properties: parseIssueProperties(i.Properties),+ ID: uuidToString(i.ID),+ WorkspaceID: uuidToString(i.WorkspaceID),+ Number: i.Number,+ Identifier: identifier,+ Title: i.Title,+ Description: textToPtr(i.Description),+ Status: i.Status,+ StatusCategory: statusCategory,+ Priority: i.Priority,+ AssigneeType: textToPtr(i.AssigneeType),+ AssigneeID: uuidToPtr(i.AssigneeID),+ CreatorType: i.CreatorType,+ CreatorID: uuidToString(i.CreatorID),+ ParentIssueID: uuidToPtr(i.ParentIssueID),+ duplicateOfIssueID: duplicateOfPointer(i.Status, i.DuplicateOfIssueID),+ ProjectID: uuidToPtr(i.ProjectID),+ Position: i.Position,+ Stage: int4ToPtr(i.Stage),+ StartDate: dateToPtr(i.StartDate),+ DueDate: dateToPtr(i.DueDate),+ CreatedAt: timestampToString(i.CreatedAt),+ UpdatedAt: timestampToString(i.UpdatedAt),+ Revision: i.Revision,+ LastActivityAt: timestampToNanoPtr(i.LastActivityAt),+ Metadata: parseIssueMetadata(i.Metadata),+ Properties: parseIssueProperties(i.Properties),}}@@ -990,7 +1063,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.last_activity_at, i.number, i.project_id,- i.revision,+ i.revision, i.duplicate_of_issue_id,pc.match_source,COALESCE(c.content, '') AS matched_comment_contentFROM page_candidates pc@@ -1086,6 +1159,7 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {&sr.issue.Number,&sr.issue.ProjectID,&sr.issue.Revision,+ &sr.issue.DuplicateOfIssueID,&sr.matchSource,&sr.matchedCommentContent,); err != nil {@@ -1633,7 +1707,7 @@ 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.last_activity_at, i.number, i.project_id, i.metadata, i.stage, i.properties,- i.revision+ i.revision, i.duplicate_of_issue_idFROM issue iWHERE %sORDER BY %s@@ -1674,6 +1748,7 @@ LIMIT %s OFFSET %s`, whereSql, orderBy, limitRef, offsetRef)&row.Stage,&row.Properties,&row.Revision,+ &row.DuplicateOfIssueID,); err != nil {slog.Warn("ListIssues scan failed", "error", err)writeError(w, http.StatusInternalServerError, "failed to list issues")@@ -2232,7 +2307,7 @@ WITH ranked AS (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.last_activity_at,- i.number, i.project_id, i.metadata, i.stage, i.properties, i.revision,+ i.number, i.project_id, i.metadata, i.stage, i.properties, i.revision, i.duplicate_of_issue_id,COUNT(*) OVER (PARTITION BY i.assignee_type, i.assignee_id) AS group_total,ROW_NUMBER() OVER (PARTITION BY i.assignee_type, i.assignee_id@@ -2245,7 +2320,7 @@ SELECTid, workspace_id, title, description, status, priority,assignee_type, assignee_id, creator_type, creator_id,parent_issue_id, position, start_date, due_date, created_at, updated_at, last_activity_at,- number, project_id, metadata, stage, properties, revision, group_total+ number, project_id, metadata, stage, properties, revision, duplicate_of_issue_id, group_totalFROM rankedWHERE rn > %s AND rn <= %s + %sORDER BY@@ -2294,6 +2369,7 @@ ORDER BY&row.Stage,&row.Properties,&row.Revision,+ &row.DuplicateOfIssueID,&row.GroupTotal,); err != nil {slog.Warn("ListGroupedIssues scan failed", "error", err)@@ -4211,7 +4287,7 @@ func (h *Handler) DeleteIssue(w http.ResponseWriter, r *http.Request) {resolvedID := uuidToString(issue.ID)h.publish(protocol.EventIssueDeleted, uuidToString(issue.WorkspaceID), actorType, actorID, map[string]any{"issue_id": resolvedID})h.publishIssueSnapshots(r.Context(), deleteResult.DetachedChildren, actorType, actorID)- h.publishIssueSnapshots(r.Context(), deleteResult.ClearedDuplicates, actorType, actorID)+ h.publishClearedDuplicates(r.Context(), deleteResult.ClearedDuplicates, actorType, actorID)slog.Info("issue deleted", append(logger.RequestAttrs(r), "issue_id", resolvedID, "workspace_id", uuidToString(issue.WorkspaceID))...)w.WriteHeader(http.StatusNoContent)}@@ -4226,7 +4302,14 @@ type issueDeleteResult struct {DetachedChildren []db.Issue// ClearedDuplicates lost their duplicate mark because their original was// deleted. They stay cancelled.- ClearedDuplicates []db.Issue+ ClearedDuplicates []clearedDuplicate+}++// clearedDuplicate pairs a duplicate whose mark a delete cleared with the+// original that delete removed, so the broadcast can still name it.+type clearedDuplicate struct {+ Issue db.Issue+ Original db.Issue}func (h *Handler) deleteIssueAndCollectAttachmentURLs(ctx context.Context, issue db.Issue, excludedIssueIDs []pgtype.UUID) (issueDeleteResult, error) {@@ -4264,7 +4347,9 @@ func (h *Handler) deleteIssuesAndCollectAttachmentURLs(ctx context.Context, issuif err != nil {return issueDeleteResult{}, fmt.Errorf("clear duplicate marks: %w", err)}- result.ClearedDuplicates = append(result.ClearedDuplicates, cleared...)+ for _, duplicate := range cleared {+ result.ClearedDuplicates = append(result.ClearedDuplicates, clearedDuplicate{Issue: duplicate, Original: issue})+ }attachmentURLs, err := qtx.ListAttachmentURLsByIssueOrComments(ctx, issue.ID)if err != nil {return issueDeleteResult{}, fmt.Errorf("list issue attachment URLs: %w", err)@@ -4327,6 +4412,24 @@ func (h *Handler) publishIssueSnapshots(ctx context.Context, issues []db.Issue,}}+// publishClearedDuplicates broadcasts issue:updated for duplicates whose+// original a delete removed. The pointer went with the original, so the+// payload names both ends the way UpdateIssue does, plus the identifier the+// activity log can no longer look up (MUL-7349).+func (h *Handler) publishClearedDuplicates(ctx context.Context, cleared []clearedDuplicate, actorType, actorID string) {+ for _, c := range cleared {+ prefix := h.getIssuePrefix(ctx, c.Issue.WorkspaceID)+ response := issueToResponse(c.Issue, prefix)+ h.fillStatusCategory(ctx, c.Issue.WorkspaceID, &response)+ h.publish(protocol.EventIssueUpdated, uuidToString(c.Issue.WorkspaceID), actorType, actorID, map[string]any{+ "issue": response,+ "duplicate_of_issue_id": uuidToPtr(c.Issue.DuplicateOfIssueID),+ "prev_duplicate_of_issue_id": uuidToPtr(c.Original.ID),+ "prev_duplicate_of_identifier": prefix + "-" + strconv.Itoa(int(c.Original.Number)),+ })+ }+}+// ---------------------------------------------------------------------------// Batch operations// ---------------------------------------------------------------------------@@ -4774,7 +4877,7 @@ func (h *Handler) BatchDeleteIssues(w http.ResponseWriter, r *http.Request) {h.publish(protocol.EventIssueDeleted, workspaceID, actorType, actorID, map[string]any{"issue_id": uuidToString(issue.ID)})}h.publishIssueSnapshots(r.Context(), deleteResult.DetachedChildren, actorType, actorID)- h.publishIssueSnapshots(r.Context(), deleteResult.ClearedDuplicates, actorType, actorID)+ h.publishClearedDuplicates(r.Context(), deleteResult.ClearedDuplicates, actorType, actorID)deleted := len(issues)slog.Info("batch delete issues", append(logger.RequestAttrs(r), "count", deleted)...)diff --git a/server/internal/handler/issue_duplicate_test.go b/server/internal/handler/issue_duplicate_test.goindex ef8df03a03..451bc55ce7 100644--- a/server/internal/handler/issue_duplicate_test.go+++ b/server/internal/handler/issue_duplicate_test.go@@ -269,3 +269,67 @@ func TestDuplicateReadsIgnoreLeftoverMarks(t *testing.T) {markDuplicate(t, other, duplicate).Want(http.StatusOK)})}++// Responses carry the original as a validated summary (MUL-7349). An older+// server can delete an original without clearing the pointers of its+// duplicates, so detail, list and search must all check the original exists+// rather than expose the bare pointer.+func TestDuplicateOfSummaryFollowsTheOriginal(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ original := dbfx.Issue(t, "summary-original", testutil.Cols{"status": "in_progress"})+ duplicate := dbfx.Issue(t, "summary-duplicate-needle", testutil.Cols{"status": "todo"})+ markDuplicate(t, duplicate, original).Want(http.StatusOK)++ type page struct {+ Issues []IssueResponse `json:"issues"`+ }+ find := func(issues []IssueResponse) *IssueResponse {+ for i := range issues {+ if issues[i].ID == duplicate {+ return &issues[i]+ }+ }+ return nil+ }+ read := func() (detail IssueResponse, listed, searched *IssueResponse) {+ t.Helper()+ testutil.Call(t, testHandler.GetIssue, withURLParam(newRequest("GET", "/api/issues/"+duplicate, nil), "id", duplicate)).+ Want(http.StatusOK).JSON(&detail)+ var list, search page+ testutil.Call(t, testHandler.ListIssues, newRequest("GET", "/api/issues?status=cancelled&limit=200", nil)).+ Want(http.StatusOK).JSON(&list)+ testutil.Call(t, testHandler.SearchIssues, newRequest("GET", "/api/issues/search?q=summary-duplicate-needle&include_closed=true", nil)).+ Want(http.StatusOK).JSON(&search)+ return detail, find(list.Issues), find(search.Issues)+ }++ var originalDetail IssueResponse+ testutil.Call(t, testHandler.GetIssue, withURLParam(newRequest("GET", "/api/issues/"+original, nil), "id", original)).+ Want(http.StatusOK).JSON(&originalDetail)++ detail, listed, searched := read()+ for name, resp := range map[string]*IssueResponse{"detail": &detail, "list": listed, "search": searched} {+ if resp == nil {+ t.Fatalf("%s: duplicate missing from response", name)+ }+ want := IssueRefResponse{ID: original, Identifier: originalDetail.Identifier, Title: "summary-original", Status: "in_progress"}+ if resp.DuplicateOf == nil || *resp.DuplicateOf != want {+ t.Fatalf("%s: duplicate_of = %+v, want %+v", name, resp.DuplicateOf, want)+ }+ }++ // An older server deleting the original leaves the pointer behind.+ dbfx.Exec(t, `DELETE FROM issue WHERE id = $1`, original)++ detail, listed, searched = read()+ for name, resp := range map[string]*IssueResponse{"detail": &detail, "list": listed, "search": searched} {+ if resp == nil {+ t.Fatalf("%s: duplicate missing from response", name)+ }+ if resp.DuplicateOf != nil {+ t.Fatalf("%s: duplicate_of = %+v after the original was deleted, want null", name, resp.DuplicateOf)+ }+ }+}diff --git a/server/internal/handler/issue_table_rows.go b/server/internal/handler/issue_table_rows.goindex a97cc396b9..a410e9232f 100644--- a/server/internal/handler/issue_table_rows.go+++ b/server/internal/handler/issue_table_rows.go@@ -393,7 +393,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.last_activity_at, i.number, i.project_id, i.metadata, i.stage, i.properties,- i.revision,+ i.revision, i.duplicate_of_issue_id,%s AS direct_child_count, i.table_sort_keyFROM page iORDER BY %s`, cte, childCountExpr, resolvedSort.orderBy())@@ -438,6 +438,7 @@ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,&row.issue.Stage,&row.issue.Properties,&row.issue.Revision,+ &row.issue.DuplicateOfIssueID,&row.childCount,&row.sortKey,); err != nil {diff --git a/server/internal/handler/search_candidate_parity_test.go b/server/internal/handler/search_candidate_parity_test.goindex 56959c7734..bc62885e1d 100644--- a/server/internal/handler/search_candidate_parity_test.go+++ b/server/internal/handler/search_candidate_parity_test.go@@ -314,6 +314,7 @@ func runSearchForParity(t *testing.T, label, query string, args []any) []searchP&sr.issue.Number,&sr.issue.ProjectID,&sr.issue.Revision,+ &sr.issue.DuplicateOfIssueID,&sr.matchSource,&sr.matchedCommentContent,); err != nil {@@ -332,7 +333,8 @@ func runSearchForParity(t *testing.T, label, query string, args []any) []searchP}// buildLegacySearchQueryForParity is the parent commit's buildSearchQuery copied-// verbatim except for its name. Keeping the original implementation here avoids+// verbatim except for its name and the duplicate_of_issue_id column, which both+// queries project so one scanner reads them (MUL-7349). Keeping the original implementation here avoids// proving parity against a re-derived oracle that could share the new query's// assumptions. This remains test-only; production has no legacy fallback path.func buildLegacySearchQueryForParity(phrase string, terms []string, queryNum int, hasNum bool, includeClosed bool, terminalStatusKeys []string) (string, []any) {@@ -575,7 +577,7 @@ func buildLegacySearchQueryForParity(phrase string, terms []string, queryNum inti.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.last_activity_at, i.number, i.project_id,- i.revision,+ i.revision, i.duplicate_of_issue_id,%s AS match_source,%s AS matched_comment_contentFROM issue idiff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.mdindex dad5a06a4f..24a15c1b40 100644--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md@@ -277,9 +277,13 @@ archived statuses remain readable via an explicit status filter.flight — 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+ (`GET /api/issues/<id>/duplicates` shows both sides; issue responses carry+ the original as `duplicate_of` with its id, identifier, title and status+ while the mark counts). Moving it to anystatus other than `cancelled` removes the mark, so reopen a duplicate only- when it is really separate work.+ when it is really separate work. Marking logs `duplicate_marked` on the+ duplicate and `duplicate_added` on the original; removing the mark logs+ `duplicate_unmarked` / `duplicate_removed` (`multica issue timeline --action`).- **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/internal/service/task.go b/server/internal/service/task.goindex f1a8a03190..b85482e515 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -7614,13 +7614,17 @@ func IssueToMap(issue db.Issue, issuePrefix string) map[string]any {// — clients localize those from the key — and a CUSTOM one is filled in// by IssueToMapResolved, which has the catalog. Emitted unconditionally// so this rendering cannot lose a key the HTTP one carries. (MUL-6749)- "status_name": "",- "priority": issue.Priority,- "assignee_type": util.TextToPtr(issue.AssigneeType),- "assignee_id": util.UUIDToPtr(issue.AssigneeID),- "creator_type": issue.CreatorType,- "creator_id": util.UUIDToString(issue.CreatorID),- "parent_issue_id": util.UUIDToPtr(issue.ParentIssueID),+ "status_name": "",+ "priority": issue.Priority,+ "assignee_type": util.TextToPtr(issue.AssigneeType),+ "assignee_id": util.UUIDToPtr(issue.AssigneeID),+ "creator_type": issue.CreatorType,+ "creator_id": util.UUIDToString(issue.CreatorID),+ "parent_issue_id": util.UUIDToPtr(issue.ParentIssueID),+ // Mirrors handler.IssueResponse.DuplicateOf. The paths that render this+ // map (autopilot creates, background status resets) never carry a live+ // duplicate mark, and a reset clears one, so null is the true value.+ "duplicate_of": nil,"project_id": util.UUIDToPtr(issue.ProjectID),"position": issue.Position,"stage": util.Int4ToPtr(issue.Stage),diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex e885650774..4a0deade45 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -1019,6 +1019,36 @@ func (q *Queries) GetIssueMetadataInWorkspace(ctx context.Context, arg GetIssueMreturn i, err}+const getIssueRefInWorkspace = `-- name: GetIssueRefInWorkspace :one+SELECT id, number, title, status FROM issue+WHERE id = $1 AND workspace_id = $2+`++type GetIssueRefInWorkspaceParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++type GetIssueRefInWorkspaceRow struct {+ ID pgtype.UUID `json:"id"`+ Number int32 `json:"number"`+ Title string `json:"title"`+ Status string `json:"status"`+}++// The summary a duplicate's response carries for its original (MUL-7349).+func (q *Queries) GetIssueRefInWorkspace(ctx context.Context, arg GetIssueRefInWorkspaceParams) (GetIssueRefInWorkspaceRow, error) {+ row := q.db.QueryRow(ctx, getIssueRefInWorkspace, arg.ID, arg.WorkspaceID)+ var i GetIssueRefInWorkspaceRow+ err := row.Scan(+ &i.ID,+ &i.Number,+ &i.Title,+ &i.Status,+ )+ return i, err+}+const getIssueTriageState = `-- name: GetIssueTriageState :oneSELECT triage_state FROM issue WHERE id = $1`@@ -1298,7 +1328,7 @@ const listIssues = `-- name: ListIssues :manySELECT 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.last_activity_at, i.number, i.project_id, i.metadata, i.stage, i.properties,- i.revision+ i.revision, i.duplicate_of_issue_idFROM issue iWHERE i.workspace_id = $1AND ($4::text IS NULL OR i.status = $4)@@ -1369,29 +1399,30 @@ type ListIssuesParams struct {}type ListIssuesRow struct {- ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- Title string `json:"title"`- Description pgtype.Text `json:"description"`- Status string `json:"status"`- Priority string `json:"priority"`- AssigneeType pgtype.Text `json:"assignee_type"`- AssigneeID pgtype.UUID `json:"assignee_id"`- CreatorType string `json:"creator_type"`- CreatorID pgtype.UUID `json:"creator_id"`- ParentIssueID pgtype.UUID `json:"parent_issue_id"`- Position float64 `json:"position"`- StartDate pgtype.Date `json:"start_date"`- DueDate pgtype.Date `json:"due_date"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- UpdatedAt pgtype.Timestamptz `json:"updated_at"`- LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`- Number int32 `json:"number"`- ProjectID pgtype.UUID `json:"project_id"`- Metadata []byte `json:"metadata"`- Stage pgtype.Int4 `json:"stage"`- Properties []byte `json:"properties"`- Revision int64 `json:"revision"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Title string `json:"title"`+ Description pgtype.Text `json:"description"`+ Status string `json:"status"`+ Priority string `json:"priority"`+ AssigneeType pgtype.Text `json:"assignee_type"`+ AssigneeID pgtype.UUID `json:"assignee_id"`+ CreatorType string `json:"creator_type"`+ CreatorID pgtype.UUID `json:"creator_id"`+ ParentIssueID pgtype.UUID `json:"parent_issue_id"`+ Position float64 `json:"position"`+ StartDate pgtype.Date `json:"start_date"`+ DueDate pgtype.Date `json:"due_date"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`+ Number int32 `json:"number"`+ ProjectID pgtype.UUID `json:"project_id"`+ Metadata []byte `json:"metadata"`+ Stage pgtype.Int4 `json:"stage"`+ Properties []byte `json:"properties"`+ Revision int64 `json:"revision"`+ DuplicateOfIssueID pgtype.UUID `json:"duplicate_of_issue_id"`}// involves_user_id widens the assignee filter to surface issues where the user@@ -1446,6 +1477,7 @@ func (q *Queries) ListIssues(ctx context.Context, arg ListIssuesParams) ([]ListI&i.Stage,&i.Properties,&i.Revision,+ &i.DuplicateOfIssueID,); err != nil {return nil, err}@@ -1461,7 +1493,7 @@ const listOpenIssues = `-- name: ListOpenIssues :manySELECT 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.last_activity_at, i.number, i.project_id, i.metadata, i.stage, i.properties,- i.revision+ i.revision, i.duplicate_of_issue_idFROM issue iWHERE i.workspace_id = $1-- Negate only known terminal keys so an unknown legacy key remains visible.@@ -1578,29 +1610,30 @@ type ListOpenIssuesParams struct {}type ListOpenIssuesRow struct {- ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- Title string `json:"title"`- Description pgtype.Text `json:"description"`- Status string `json:"status"`- Priority string `json:"priority"`- AssigneeType pgtype.Text `json:"assignee_type"`- AssigneeID pgtype.UUID `json:"assignee_id"`- CreatorType string `json:"creator_type"`- CreatorID pgtype.UUID `json:"creator_id"`- ParentIssueID pgtype.UUID `json:"parent_issue_id"`- Position float64 `json:"position"`- StartDate pgtype.Date `json:"start_date"`- DueDate pgtype.Date `json:"due_date"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- UpdatedAt pgtype.Timestamptz `json:"updated_at"`- LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`- Number int32 `json:"number"`- ProjectID pgtype.UUID `json:"project_id"`- Metadata []byte `json:"metadata"`- Stage pgtype.Int4 `json:"stage"`- Properties []byte `json:"properties"`- Revision int64 `json:"revision"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Title string `json:"title"`+ Description pgtype.Text `json:"description"`+ Status string `json:"status"`+ Priority string `json:"priority"`+ AssigneeType pgtype.Text `json:"assignee_type"`+ AssigneeID pgtype.UUID `json:"assignee_id"`+ CreatorType string `json:"creator_type"`+ CreatorID pgtype.UUID `json:"creator_id"`+ ParentIssueID pgtype.UUID `json:"parent_issue_id"`+ Position float64 `json:"position"`+ StartDate pgtype.Date `json:"start_date"`+ DueDate pgtype.Date `json:"due_date"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`+ Number int32 `json:"number"`+ ProjectID pgtype.UUID `json:"project_id"`+ Metadata []byte `json:"metadata"`+ Stage pgtype.Int4 `json:"stage"`+ Properties []byte `json:"properties"`+ Revision int64 `json:"revision"`+ DuplicateOfIssueID pgtype.UUID `json:"duplicate_of_issue_id"`}// See ListIssues for the semantics of involves_user_id (mirrors the 4-branch@@ -1649,6 +1682,7 @@ func (q *Queries) ListOpenIssues(ctx context.Context, arg ListOpenIssuesParams)&i.Stage,&i.Properties,&i.Revision,+ &i.DuplicateOfIssueID,); err != nil {return nil, err}diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 06cd8fb03b..0de8e7f182 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -8,7 +8,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.last_activity_at, i.number, i.project_id, i.metadata, i.stage, i.properties,- i.revision+ i.revision, i.duplicate_of_issue_idFROM issue iWHERE i.workspace_id = $1AND (sqlc.narg('status')::text IS NULL OR i.status = sqlc.narg('status'))@@ -379,6 +379,11 @@ WHERE workspace_id = sqlc.arg('workspace_id')AND status = 'cancelled'ORDER BY created_at ASC, id ASC;+-- name: GetIssueRefInWorkspace :one+-- The summary a duplicate's response carries for its original (MUL-7349).+SELECT id, number, title, status FROM issue+WHERE id = $1 AND workspace_id = $2;+-- 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@@ -489,7 +494,7 @@ DELETE FROM issue WHERE issue.id IN (SELECT target.id FROM target);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.last_activity_at, i.number, i.project_id, i.metadata, i.stage, i.properties,- i.revision+ i.revision, i.duplicate_of_issue_idFROM issue iWHERE i.workspace_id = $1-- Negate only known terminal keys so an unknown legacy key remains visible.