Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(issues): Relations section with blocked by / blocking / duplicates (MUL-10050) (#11414)
Bohan Jiang1bdb35b210ff
diff --git a/e2e/issue-blockers.spec.ts b/e2e/issue-blockers.spec.tsindex 35d2a8f050..890415b374 100644--- a/e2e/issue-blockers.spec.ts+++ b/e2e/issue-blockers.spec.ts@@ -10,7 +10,10 @@ test("waiting tasks can be added, filtered and removed without changing status",const downstream = await api.createIssue("Build the project dashboard", { status: "todo" });await page.setViewportSize({ width: 1440, height: 1000 });await page.goto(`/${slug}/issues/${downstream.identifier}`, {waitUntil:"domcontentloaded"});- await page.getByRole("button", { name: "Add blocker", exact: true }).click();+ // No relation yet, so the Relations section hides and the add row offers it.+ await page.getByTestId("issue-sidebar-add-row").getByRole("button").click();+ await page.getByRole("menuitem", { name: "Relations", exact: true }).hover();+ await page.getByRole("menuitem", { name: /^Wait for another task/ }).click();const picker = page.getByRole("dialog");await picker.getByPlaceholder("Search issues...").fill(blocker.title);await picker.getByText(blocker.title).click();@@ -30,8 +33,14 @@ test("waiting tasks can be added, filtered and removed without changing status",await page.mouse.click(1080, 300);await expect(page.getByRole("menu")).toHaveCount(0);await page.screenshot({ path: testInfo.outputPath("waiting-list.png"), fullPage: true, animations: "disabled" });+ // The blocker lists the edge under Blocking and can remove it from its side.+ await page.goto(`/${slug}/issues/${blocker.identifier}`, {waitUntil:"domcontentloaded"});+ await expect(page.getByText("Blocking", { exact: true })).toBeVisible();+ const dependentLink = page.getByRole("link", { name: `${downstream.identifier} ${downstream.title}`, exact: true });+ await dependentLink.hover();+ await page.getByRole("button", { name: `Remove ${downstream.identifier}`, exact: true }).click();+ await expect(dependentLink).not.toBeVisible();await page.goto(`/${slug}/issues/${downstream.identifier}`, {waitUntil:"domcontentloaded"});- await page.getByRole("button", { name: `Remove ${blocker.identifier}`, exact: true }).click();await expect(page.getByRole("link", { name: `${blocker.identifier} ${blocker.title}`, exact: true })).not.toBeVisible();await expect(page.getByRole("button", { name: "Todo", exact: true }).first()).toBeVisible();} finally {diff --git a/e2e/issue-duplicate.spec.ts b/e2e/issue-duplicate.spec.tsindex d17d722498..d3bbeb0336 100644--- a/e2e/issue-duplicate.spec.ts+++ b/e2e/issue-duplicate.spec.ts@@ -47,7 +47,9 @@ test.describe("Mark as duplicate", () => {await originalLink.click();await expect(page).toHaveURL(new RegExp(`/issues/${original.identifier}$`));- await expect(page.getByRole("button", { name: "Duplicates" })).toBeVisible();+ // Duplicates are a group of the Relations section.+ await expect(page.getByRole("button", { name: "Relations", exact: true })).toBeVisible();+ await expect(page.getByText("Duplicates", { exact: true })).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();diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex f185da12f8..81032fe87a 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -219,6 +219,14 @@ describe("IssueSchema (via ListIssuesResponseSchema)", () => {expect(parsed.issues[0]?.blocked_by).toBeUndefined();}});+ it("reads blocking from a detail response and tolerates it missing or malformed", () => {+ const dependent = { id: "d", identifier: "MUL-3", title: "Dashboard", status: "todo", via: "manual", closed: false };+ const parsed = ListIssuesResponseSchema.parse({+ issues: [{ ...baseIssue, blocking: [dependent] }, { ...baseIssue, blocking: "bad" }, baseIssue],+ total: 3,+ });+ expect(parsed.issues.map((issue) => issue.blocking)).toEqual([[dependent], undefined, undefined]);+ });it("carries manual and stage blockers independently of status", () => {const blocker = { id: "b", identifier: "MUL-2", title: "Contract", status: "done", via: "stage", closed: true };const parsed = ListIssuesResponseSchema.parse({ issues: [{ ...baseIssue, blocked_by: [blocker], blocked_count: 0 }], total: 1 });diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex fdc6c9ce9a..6560cdb5c3 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1698,12 +1698,16 @@ export const CommentSubIssueTaskResponseSchema = z.object({task_id: z.string().min(1),}).loose();+const IssueBlockerSchema = z.object({+ id: z.string(), identifier: z.string(), title: z.string(), status: z.string(),+ via: z.string(), closed: z.boolean(),+});+export const IssueSchema = z.object({blocked_count: z.number().int().nonnegative().optional().catch(undefined),- blocked_by: z.array(z.object({- id: z.string(), identifier: z.string(), title: z.string(), status: z.string(),- via: z.string(), closed: z.boolean(),- })).optional().catch(undefined),+ blocked_by: z.array(IssueBlockerSchema).optional().catch(undefined),+ // Detail reads only: the issues waiting on this one.+ blocking: z.array(IssueBlockerSchema).optional().catch(undefined),id: z.string(),workspace_id: z.string(),number: z.number(),diff --git a/packages/core/issues/blockers.ts b/packages/core/issues/blockers.tsindex dfb4488f80..c8d7575962 100644--- a/packages/core/issues/blockers.ts+++ b/packages/core/issues/blockers.ts@@ -11,3 +11,18 @@ export function useUpdateIssueBlockers(wsId: string, issueId: string) {},});}++/**+ * Edits the edges where this issue is the blocker. Each edge is stored on the+ * issue that waits, so the write goes to that issue and its access rules apply.+ */+export function useUpdateIssueBlocking(wsId: string, issueId: string) {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: ({ dependentId, remove = false }: { dependentId: string; remove?: boolean }) =>+ api.updateIssue(dependentId, remove ? { remove_blocked_by: [issueId] } : { blocked_by: [issueId] }),+ onSuccess: async () => {+ await qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });+ },+ });+}diff --git a/packages/core/issues/stores/issue-sidebar-sections-persistence.test.ts b/packages/core/issues/stores/issue-sidebar-sections-persistence.test.tsindex 71cef278fc..50199aa241 100644--- a/packages/core/issues/stores/issue-sidebar-sections-persistence.test.ts+++ b/packages/core/issues/stores/issue-sidebar-sections-persistence.test.ts@@ -7,12 +7,13 @@ import {} from "@multica/core/issues/stores";const STORAGE_KEY = "multica_issue_sidebar_sections";-// An order saved while the sidebar still had Sub-issues and Details sections.+// An order saved while the sidebar still had Sub-issues, Details, Waiting and+// Duplicates sections; the last two are now the Relations section.const SAVED_ORDER = [- "properties", "quick_actions", "wakeups", "plugins", "parent", "sub_issues", "duplicates",+ "properties", "quick_actions", "wakeups", "plugins", "parent", "sub_issues", "waiting", "duplicates","pull_requests", "environments", "deliverables", "apps", "execution_log", "details", "metadata",];-const RETIRED = new Set(["sub_issues", "details"]);+const RETIRED = new Set(["sub_issues", "details", "waiting", "duplicates"]);async function reloadPreferences() {const saved = localStorage.getItem(STORAGE_KEY)!;@@ -38,8 +39,8 @@ describe("issue sidebar persisted preferences", () => {await useIssueSidebarSectionsStore.persist.rehydrate();const state = useIssueSidebarSectionsStore.getState();const order = [...selectIssueSidebarOrder(state)];- expect(order.filter((id) => id !== "waiting")).toEqual(savedOrder.filter((id) => !RETIRED.has(id)));- expect(order.indexOf("waiting")).toBe(order.indexOf("parent") + 1);+ expect(order.filter((id) => id !== "relations")).toEqual(savedOrder.filter((id) => !RETIRED.has(id)));+ expect(order.indexOf("relations")).toBe(order.indexOf("parent") + 1);expect(state.hidden).toEqual(["parent", "apps"]);await reloadPreferences();expect(selectIssueSidebarOrder(useIssueSidebarSectionsStore.getState())).toEqual(order);@@ -48,12 +49,12 @@ describe("issue sidebar persisted preferences", () => {it("persists hiding and reordering, then restores defaults", async () => {const store = useIssueSidebarSectionsStore;- store.getState().setHidden("duplicates", true);- store.getState().setOrder(["duplicates", ...ISSUE_SIDEBAR_SECTIONS]);+ store.getState().setHidden("deliverables", true);+ store.getState().setOrder(["deliverables", ...ISSUE_SIDEBAR_SECTIONS]);await reloadPreferences();- expect(selectIssueSidebarOrder(store.getState())[0]).toBe("duplicates");- expect(store.getState().hidden).toEqual(["duplicates"]);- store.getState().setHidden("duplicates", false);+ expect(selectIssueSidebarOrder(store.getState())[0]).toBe("deliverables");+ expect(store.getState().hidden).toEqual(["deliverables"]);+ store.getState().setHidden("deliverables", false);await reloadPreferences();expect(store.getState().hidden).toEqual([]);store.getState().reset();diff --git a/packages/core/issues/stores/issue-sidebar-sections-store.ts b/packages/core/issues/stores/issue-sidebar-sections-store.tsindex f3aa147793..9c7df4653d 100644--- a/packages/core/issues/stores/issue-sidebar-sections-store.ts+++ b/packages/core/issues/stores/issue-sidebar-sections-store.ts@@ -11,8 +11,7 @@ export const ISSUE_SIDEBAR_SECTIONS = ["wakeups","plugins","parent",- "waiting",- "duplicates",+ "relations","pull_requests","environments","deliverables",diff --git a/packages/core/modals/store.ts b/packages/core/modals/store.tsindex 7922084338..1c4f33c253 100644--- a/packages/core/modals/store.ts+++ b/packages/core/modals/store.ts@@ -12,6 +12,7 @@ type ModalType =| "issue-mark-duplicate"| "issue-add-child"| "issue-add-blocker"+ | "issue-add-blocking"| "project-add-issue"| "project-rename"| "issue-rename"diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex b4b5c2b052..a144c4bfae 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -460,6 +460,24 @@ describe("useRealtimeSync — ws instance change", () => {expect(qc.getQueryState(issueKeys.tasks("parent"))?.isInvalidated).toBe(false);});+ it("refreshes the other end of a blocker edge: its detail lists this issue under blocking", () => {+ const emit = subtreeEvents();+ qc.setQueryData(issueKeys.detail("ws-1", "blocker"), { id: "blocker", blocking: [] });+ emit("issue:updated", { title_changed: true, issue: { id: "child" } });+ expect(qc.getQueryState(issueKeys.detail("ws-1", "blocker"))?.isInvalidated).toBe(false);+ emit("issue:updated", { blockers_changed: true, issue: { id: "child" } });+ expect(qc.getQueryState(issueKeys.detail("ws-1", "blocker"))?.isInvalidated).toBe(true);+ });++ it("refreshes blockers' details when an issue is created waiting on them", () => {+ const emit = subtreeEvents();+ qc.setQueryData(issueKeys.detail("ws-1", "blocker"), { id: "blocker", blocking: [] });+ emit("issue:created", { issue: { id: "child", blocked_by: [] } });+ expect(qc.getQueryState(issueKeys.detail("ws-1", "blocker"))?.isInvalidated).toBe(false);+ emit("issue:created", { issue: { id: "child", blocked_by: [{ id: "blocker", via: "manual" }] } });+ expect(qc.getQueryState(issueKeys.detail("ws-1", "blocker"))?.isInvalidated).toBe(true);+ });+it("does not invalidate subtree history when an issue is created", () => {const emit = subtreeEvents();emit("issue:created", { issue: { id: "child", parent_issue_id: "parent" } });diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 5aba488fad..1103beef75 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -1282,7 +1282,7 @@ export function useRealtimeSync(const unsubIssueUpdated = ws.on("issue:updated", (p) => {const payload = p as IssueUpdatedPayload;const { issue } = payload;- if (payload.status_changed || payload.parent_changed || payload.stage_changed) {+ if (payload.status_changed || payload.parent_changed || payload.stage_changed || payload.blockers_changed) {const wsId = getCurrentWsId();if (wsId) qc.invalidateQueries({queryKey: issueKeys.all(wsId)});}@@ -1329,7 +1329,8 @@ export function useRealtimeSync(const wsId = getCurrentWsId();if (wsId) {onIssueCreated(qc, wsId, issue);- if (issue.parent_issue_id && issue.stage != null) qc.invalidateQueries({queryKey:issueKeys.all(wsId)});+ // A new issue created waiting on others shows up under their `blocking`.+ if ((issue.parent_issue_id && issue.stage != null) || issue.blocked_by?.some((b) => b.via === "manual")) qc.invalidateQueries({queryKey:issueKeys.all(wsId)});}});diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex 005202253a..c0a48c8b31 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -139,6 +139,9 @@ export interface IssueUpdatedPayload {stage_changed?: boolean;title_changed?: boolean;parent_changed?: boolean;+ // A blocker edge was added or removed; the issue at its other end lists+ // this one under `blocking`, so the change reaches past this issue.+ blockers_changed?: boolean;prev_parent_issue_id?: string | null;// Both ends of a duplicate-mark change (MUL-7349). The mark is not on Issue,// so these tell the realtime layer whose duplicate relations to refresh.diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 31aa9dbc73..7c2b487ac7 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -1,5 +1,6 @@export type { Issue, IssueStatus, BuiltInIssueStatus, IssuePriority, IssueAssigneeType, IssueMetadata, IssueMetadataValue, IssueReaction, SourceContextAttachment, SourceContextAuthor, SourceContextIssueSnapshot, SourceContextCommentSnapshot, SourceContextSnapshot, SourceContextLimitUsage, SourceContextPreview, SourceContextAuthorState, IssueSourceContext,IssueDuplicateOf,+ IssueBlocker,IssueUnread,} from "./issue";export type {diff --git a/packages/core/types/issue.ts b/packages/core/types/issue.tsindex 55bb9bfdd9..ba129d2d1e 100644--- a/packages/core/types/issue.ts+++ b/packages/core/types/issue.ts@@ -191,6 +191,8 @@ export interface IssueBlocker extends IssueDuplicateOf {export interface Issue {blocked_by?: IssueBlocker[];blocked_count?: number;+ /** The issues waiting on this one. Only the detail read carries it. */+ blocking?: IssueBlocker[];id: string;workspace_id: string;number: number;diff --git a/packages/views/issues/actions/__tests__/use-issue-actions.test.tsx b/packages/views/issues/actions/__tests__/use-issue-actions.test.tsxindex bc9e885e43..9c823f3a89 100644--- a/packages/views/issues/actions/__tests__/use-issue-actions.test.tsx+++ b/packages/views/issues/actions/__tests__/use-issue-actions.test.tsx@@ -365,6 +365,13 @@ describe("useIssueActions", () => {issueId: "issue-1",});+ act(() => {+ result.current.openAddBlocking();+ });+ expect(mockOpenModal).toHaveBeenLastCalledWith("issue-add-blocking", {+ issueId: "issue-1",+ });+act(() => {result.current.openCreateSubIssue();});diff --git a/packages/views/issues/actions/issue-actions-menu-items.tsx b/packages/views/issues/actions/issue-actions-menu-items.tsxindex 528ea80e6e..7d9e8098d4 100644--- a/packages/views/issues/actions/issue-actions-menu-items.tsx+++ b/packages/views/issues/actions/issue-actions-menu-items.tsx@@ -146,6 +146,7 @@ export function IssueActionsMenuItems({openAddChild,openMarkDuplicate,openAddBlocker,+ openAddBlocking,openDeleteConfirm,} = actions;@@ -501,6 +502,10 @@ export function IssueActionsMenuItems({<Flag className="h-3.5 w-3.5" />{t(($) => $.actions.add_blocker)}</P.Item>+ <P.Item onClick={openAddBlocking}>+ <Flag className="h-3.5 w-3.5" />+ {t(($) => $.actions.add_blocking)}+ </P.Item>{/* Marking a duplicate cancels the issue. (MUL-7420) */}{workflowAllowsStatus(workflow, "cancelled") && (<P.Item onClick={openMarkDuplicate}>diff --git a/packages/views/issues/actions/use-issue-actions.ts b/packages/views/issues/actions/use-issue-actions.tsindex 58a4e64307..77c55f8c20 100644--- a/packages/views/issues/actions/use-issue-actions.ts+++ b/packages/views/issues/actions/use-issue-actions.ts@@ -41,6 +41,7 @@ export interface UseIssueActionsResult {openAddChild: () => void;openMarkDuplicate: () => void;openAddBlocker: () => void;+ openAddBlocking: () => void;openDeleteConfirm: (opts?: { onDeletedFallbackPath?: string }) => void;}@@ -326,6 +327,11 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {openModal("issue-add-blocker", { issueId });}, [openModal, issueId]);+ const openAddBlocking = useCallback(() => {+ if (!issueId) return;+ openModal("issue-add-blocking", { issueId });+ }, [openModal, issueId]);+const openDeleteConfirm = useCallback((opts?: { onDeletedFallbackPath?: string }) => {if (!issueId) return;@@ -355,6 +361,7 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {openAddChild,openMarkDuplicate,openAddBlocker,+ openAddBlocking,openDeleteConfirm,};}diff --git a/packages/views/issues/components/issue-blockers.test.tsx b/packages/views/issues/components/issue-blockers.test.tsxindex a7e4499366..d42bb45c42 100644--- a/packages/views/issues/components/issue-blockers.test.tsx+++ b/packages/views/issues/components/issue-blockers.test.tsx@@ -11,9 +11,24 @@ vi.mock("@multica/core/paths", async (importOriginal) => ({...(await importOriginal<typeof import("@multica/core/paths")>()),useWorkspacePaths: () => ({ issueDetail: (id: string) => `/issues/${id}` }),}));+const relationMocks = vi.hoisted(() => ({+ removeBlocker: vi.fn(),+ removeBlocking: vi.fn(),+ openModal: vi.fn(),+ duplicates: [] as unknown[],+}));vi.mock("@multica/core/issues/blockers", () => ({- useUpdateIssueBlockers: () => ({ mutate: vi.fn(), reset: vi.fn(), isPending: false, isError: false }),+ useUpdateIssueBlockers: () => ({ mutate: relationMocks.removeBlocker, isPending: false, isError: false, error: null }),+ useUpdateIssueBlocking: () => ({ mutate: relationMocks.removeBlocking, isPending: false, isError: false, error: null }),+}));+vi.mock("@multica/core/issues/queries", () => ({+ issueDuplicatesOptions: () => ({ queryKey: ["duplicates"], queryFn: async () => ({ duplicate_of: null, duplicates: relationMocks.duplicates }) }),}));+vi.mock("@multica/core/modals", () => {+ const state = { open: relationMocks.openModal };+ return { useModalStore: Object.assign((selector: (s: typeof state) => unknown) => selector(state), { getState: () => state }) };+});+vi.mock("../utils/status-options", () => ({ useIssueStatusOptions: () => ({ options: [], workflow: null }) }));vi.mock("../../navigation", () => ({AppLink: ({ children, href, className }: { children: React.ReactNode; href: string; className?: string }) => <a href={href} className={className}>{children}</a>,}));@@ -39,9 +54,19 @@ vi.mock("@multica/core/workspace/hooks", () => ({useActorName: () => ({ getActorName: () => "Lambda" }),}));-import { IssueBlockedMarker, IssueBlockersSection } from "./issue-blockers";+import { IssueBlockedMarker, IssueRelationsSection } from "./issue-blockers";-afterEach(cleanup);+afterEach(() => {+ cleanup();+ relationMocks.removeBlocker.mockReset();+ relationMocks.removeBlocking.mockReset();+ relationMocks.openModal.mockReset();+ relationMocks.duplicates = [];+});++function renderSection(issue: Issue) {+ return renderWithI18n(<QueryClientProvider client={new QueryClient()}><IssueRelationsSection issue={issue} /></QueryClientProvider>);+}function waitingIssue(status: string): Issue {return {@@ -53,27 +78,97 @@ function waitingIssue(status: string): Issue {} as unknown as Issue;}-describe("IssueBlockersSection hint", () => {+describe("IssueRelationsSection hint", () => {it("promises an automatic start for an issue outside Backlog", () => {- renderWithI18n(<IssueBlockersSection issue={waitingIssue("todo")} />);+ renderSection(waitingIssue("todo"));expect(screen.getByText(/starts automatically or receives a notification/)).toBeInTheDocument();expect(screen.queryByText(/is in Backlog/)).not.toBeInTheDocument();});it("says a Backlog issue stays parked after its blockers end", () => {- renderWithI18n(<IssueBlockersSection issue={waitingIssue("backlog")} />);+ renderSection(waitingIssue("backlog"));expect(screen.getByText(/is in Backlog, so it won't start automatically/)).toBeInTheDocument();expect(screen.queryByText(/starts automatically or receives a notification/)).not.toBeInTheDocument();});it("drops the start hint once the issue itself is finished", () => {- renderWithI18n(<IssueBlockersSection issue={waitingIssue("done")} />);+ renderSection(waitingIssue("done"));expect(screen.getByText("Prerequisite")).toBeInTheDocument();expect(screen.queryByText(/starts automatically or receives a notification/)).not.toBeInTheDocument();expect(screen.queryByText(/is in Backlog/)).not.toBeInTheDocument();});});+describe("IssueRelationsSection", () => {+ const ref = (id: string, title: string, extra: Record<string, unknown> = {}) =>+ ({ id, identifier: id.toUpperCase(), title, status: "todo", via: "manual", closed: false, ...extra });++ it("lists only unfinished blockers and counts the ended ones", () => {+ renderSection({+ id: "issue-1",+ status: "todo",+ blocked_count: 2,+ blocked_by: [+ ref("t-1", "Open prerequisite"),+ ref("t-2", "Finished prerequisite", { status: "done", closed: true }),+ ref("t-3", "Earlier stage", { via: "stage" }),+ ],+ blocking: [],+ } as unknown as Issue);+ expect(screen.getByText("Blocked by")).toBeInTheDocument();+ expect(screen.getByText("1/3 ended")).toBeInTheDocument();+ expect(screen.getByText("Open prerequisite")).toBeInTheDocument();+ expect(screen.queryByText("Finished prerequisite")).not.toBeInTheDocument();+ // A stage edge belongs to the parent's stages: tagged, and not removable here.+ expect(screen.getByText("Stage")).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Remove T-3" })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Remove T-1" }));+ expect(relationMocks.removeBlocker).toHaveBeenCalledWith({ remove_blocked_by: ["t-1"] });+ });++ it("lists the unfinished issues this one blocks and removes the edge on the other issue", () => {+ renderSection({+ id: "issue-1",+ status: "todo",+ blocked_count: 0,+ blocked_by: [],+ blocking: [ref("d-1", "Waiting dependent"), ref("d-2", "Finished dependent", { status: "done", closed: true })],+ } as unknown as Issue);+ expect(screen.getByText("Blocking")).toBeInTheDocument();+ expect(screen.queryByText("Blocked by")).not.toBeInTheDocument();+ expect(screen.queryByText("Finished dependent")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Remove D-1" }));+ expect(relationMocks.removeBlocking).toHaveBeenCalledWith({ dependentId: "d-1", remove: true });+ });++ it("lists duplicates", async () => {+ relationMocks.duplicates = [{ id: "dup-1", identifier: "TEST-9", title: "Same bug again", status: "cancelled" }];+ renderSection({ id: "issue-1", status: "todo", blocked_count: 0, blocked_by: [], blocking: [] } as unknown as Issue);+ expect(await screen.findByText("Same bug again")).toBeInTheDocument();+ expect(screen.getByText("Duplicates")).toBeInTheDocument();+ });++ it("renders nothing when there is no relation to list", () => {+ const { container } = renderSection({+ id: "issue-1",+ status: "todo",+ blocked_count: 0,+ blocked_by: [ref("t-2", "Finished prerequisite", { status: "done", closed: true })],+ blocking: [],+ } as unknown as Issue);+ expect(container).toBeEmptyDOMElement();+ });++ it("asks for the relation type before opening a picker", async () => {+ renderSection(waitingIssue("todo"));+ fireEvent.click(screen.getByRole("button", { name: "Add relation" }));+ expect(await screen.findByRole("menuitem", { name: /Wait for another task/ })).toBeInTheDocument();+ expect(screen.getByRole("menuitem", { name: /Mark as duplicate/ })).toBeInTheDocument();+ fireEvent.click(screen.getByRole("menuitem", { name: /Block another task/ }));+ expect(relationMocks.openModal).toHaveBeenCalledWith("issue-add-blocking", { issueId: "issue-1" });+ });+});+describe("IssueBlockedMarker", () => {it("flags a waiting issue and stays hidden once the issue is finished", () => {const { rerender } = renderWithI18n(<IssueBlockedMarker issue={waitingIssue("todo")} />);diff --git a/packages/views/issues/components/issue-blockers.tsx b/packages/views/issues/components/issue-blockers.tsxindex d678c9dba1..0040edb4e9 100644--- a/packages/views/issues/components/issue-blockers.tsx+++ b/packages/views/issues/components/issue-blockers.tsx@@ -2,12 +2,21 @@import { useState } from "react";import { useQuery } from "@tanstack/react-query";-import { Flag, Plus, X } from "@multica/ui/icons";+import { CircleEqual, Flag, Plus, X } from "@multica/ui/icons";import { Button } from "@multica/ui/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";import { HoverCard, HoverCardContent, HoverCardTrigger } from "@multica/ui/components/ui/hover-card";import { useWorkspaceId } from "@multica/core/hooks";import { issueRouteRef, useWorkspacePaths } from "@multica/core/paths";-import { useUpdateIssueBlockers } from "@multica/core/issues/blockers";+import { useUpdateIssueBlockers, useUpdateIssueBlocking } from "@multica/core/issues/blockers";+import { issueDuplicatesOptions } from "@multica/core/issues/queries";+import { workflowAllowsStatus } from "@multica/core/issue-workflows";import { useModalStore } from "@multica/core/modals";import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";import { useActorName } from "@multica/core/workspace/hooks";@@ -15,8 +24,10 @@ import { agentListOptions, squadListOptions } from "@multica/core/workspace/querimport type { Issue } from "@multica/core/types";import { AppLink } from "../../navigation";import { useT } from "../../i18n";-import { IssueSidebarSectionHeader } from "./issue-sidebar-section";+import { IssueSidebarCollapsible, IssueSidebarSectionHeader } from "./issue-sidebar-section";import { isIssueWaiting } from "../utils/waiting";+import { issueRelations } from "../utils/relations";+import { useIssueStatusOptions } from "../utils/status-options";import { StatusIcon } from "./status-icon";const MARKER_MAX_ROWS = 8;@@ -104,45 +115,122 @@ function IssueBlockedMarkerCard({ issue }: { issue: Issue }) {</div>;}-export function IssueBlockersSection({ issue }: { issue: Issue }) {+/**+ * The relation types a reader can add, for the Relations section's "+" and+ * the sidebar add row. Each opens the same modal as the Relations submenu of+ * the issue actions menu.+ */+export function IssueRelationTypeItems({ issue }: { issue: Issue }) {const { t } = useT("issues");const wsId = useWorkspaceId();- const paths = useWorkspacePaths();- const [open, setOpen] = useState(true);const openModal = useModalStore((s) => s.open);- const mutation = useUpdateIssueBlockers(wsId, issue.id);+ const { workflow } = useIssueStatusOptions(wsId, issue.project_id, issue.status);+ const item = (icon: React.ReactNode, label: string, hint: string, onClick: () => void) => (+ <DropdownMenuItem onClick={onClick} className="items-start">+ {icon}+ <span className="flex min-w-0 flex-col">+ <span>{label}</span>+ <span className="text-caption text-muted-foreground">{hint}</span>+ </span>+ </DropdownMenuItem>+ );+ return <>+ {item(<Flag className="mt-0.5 text-destructive" />, t(($) => $.actions.add_blocker), t(($) => $.relations.add_blocker_hint),+ () => openModal("issue-add-blocker", { issueId: issue.id }))}+ {item(<Flag className="mt-0.5 text-warning" />, t(($) => $.actions.add_blocking), t(($) => $.relations.add_blocking_hint),+ () => openModal("issue-add-blocking", { issueId: issue.id }))}+ {/* Marking a duplicate cancels the issue. (MUL-7420) */}+ {workflowAllowsStatus(workflow, "cancelled") && <>+ <DropdownMenuSeparator />+ {item(<CircleEqual className="mt-0.5" />, t(($) => $.actions.mark_duplicate), t(($) => $.relations.mark_duplicate_hint),+ () => openModal("issue-mark-duplicate", { issueId: issue.id }))}+ </>}+ </>;+}++/**+ * Blockers, the issues this one blocks, and its duplicates in one section+ * (MUL-10050). Only unfinished blockers are listed; the section disappears+ * when there is nothing to list.+ */+export function IssueRelationsSection({ issue }: { issue: Issue }) {+ const { t } = useT("issues");+ const wsId = useWorkspaceId();+ const [open, setOpen] = useState(true);+ const blockedByMutation = useUpdateIssueBlockers(wsId, issue.id);+ const blockingMutation = useUpdateIssueBlocking(wsId, issue.id);+ const { data } = useQuery(issueDuplicatesOptions(wsId, issue.id));+ const { categoryOf, colorOf, iconOf } = useIssueStatuses(wsId);if (issue.blocked_by === undefined) return null;- const blockers = issue.blocked_by;- const manual = blockers.filter((b) => b.via === "manual");- const stages = blockers.filter((b) => b.via === "stage");- const activeStages = stages.filter((b) => !b.closed);- const stageCount = stages.length - activeStages.length;- const restrictedCount = Math.max(0, (issue.blocked_count ?? 0) - blockers.filter((b) => !b.closed).length);+ const relations = issueRelations(issue, data?.duplicates);+ if (relations.empty) return null;+ const { blockedBy, blocking, duplicates, restricted, finished, total } = relations;+ const pending = blockedByMutation.isPending || blockingMutation.isPending;+ const error = blockedByMutation.error ?? blockingMutation.error;+ const statusIcon = (status: string) =>+ <StatusIcon status={status} category={categoryOf(status)} color={colorOf(status)} icon={iconOf(status)} className="size-3.5 shrink-0" />;+ const stageTag = <span title={t(($) => $.relations.stage_tag_hint)} className="shrink-0 rounded-xs bg-muted px-1 text-micro text-muted-foreground">+ {t(($) => $.relations.stage_tag)}+ </span>;return <div>- <IssueSidebarSectionHeader title={t(($) => $.waiting.title)} open={open} onOpenChange={setOpen} count={issue.blocked_count}- actions={<Button variant="ghost" size="icon-xs" aria-label={t(($) => $.waiting.add)} onClick={() => openModal("issue-add-blocker", { issueId: issue.id })}><Plus /></Button>} />- {open && <div className="px-4 space-y-2 text-caption">- {manual.map((blocker) => <div key={blocker.id} className="flex min-w-0 items-center gap-1">- <Flag className={blocker.closed ? "size-3.5 shrink-0 text-muted-foreground" : "size-3.5 shrink-0 text-destructive"} aria-hidden="true" />- <AppLink href={paths.issueDetail(issueRouteRef(blocker))} className="min-w-0 flex-1 truncate hover:underline" title={blocker.title}>- <span className="text-muted-foreground">{blocker.identifier}</span>{" "}{blocker.title}- </AppLink>- <Button variant="ghost" size="icon-xs" disabled={mutation.isPending} aria-label={t(($) => $.waiting.remove, { identifier: blocker.identifier })}- onClick={() => mutation.mutate({ remove_blocked_by: [blocker.id] })}><X /></Button>- </div>)}- {stages.length > 0 && <div>- <p className="text-muted-foreground">{t(($) => $.waiting.stage, { finished: stageCount, total: stages.length })}</p>- {activeStages.map((blocker) => <AppLink key={blocker.id} href={paths.issueDetail(issueRouteRef(blocker))} className="block truncate py-1 hover:underline" title={blocker.title}>- <span className="text-muted-foreground">{blocker.identifier}</span>{" "}{blocker.title}- </AppLink>)}- </div>}- {restrictedCount > 0 && <p className="text-muted-foreground">{t(($) => $.waiting.restricted, {count: restrictedCount})}</p>}- {/* Only the fixed backlog key parks work, matching the server's queue admission. */}- {isIssueWaiting(issue) && <p className="text-muted-foreground">- {issue.status === "backlog" ? t(($) => $.waiting.hint_backlog) : t(($) => $.waiting.hint)}- </p>}- {blockers.length === 0 && !restrictedCount && <p className="text-muted-foreground">{t(($) => $.waiting.empty)}</p>}- {mutation.isError && <p role="alert" className="text-destructive">{mutation.error.message}</p>}- </div>}+ <IssueSidebarSectionHeader title={t(($) => $.relations.title)} open={open} onOpenChange={setOpen}+ count={blockedBy.length + restricted + blocking.length + duplicates.length}+ actions={<DropdownMenu>+ <DropdownMenuTrigger render={<Button variant="ghost" size="icon-xs" aria-label={t(($) => $.relations.add)} />}><Plus /></DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-64"><IssueRelationTypeItems issue={issue} /></DropdownMenuContent>+ </DropdownMenu>} />+ <IssueSidebarCollapsible open={open}><div className="px-2">+ {(blockedBy.length > 0 || restricted > 0) && <>+ <RelationGroup icon={<Flag className="size-3.5 text-destructive" />} label={t(($) => $.relations.blocked_by)}+ aside={finished > 0 ? t(($) => $.waiting.marker_ended, { finished, total }) : undefined} />+ {blockedBy.map((blocker) => <RelationRow key={blocker.id} issue={blocker} icon={statusIcon(blocker.status)}+ tag={blocker.via === "stage" ? stageTag : undefined} removeLabel={t(($) => $.waiting.remove, { identifier: blocker.identifier })} pending={pending}+ onRemove={blocker.via === "manual" ? () => blockedByMutation.mutate({ remove_blocked_by: [blocker.id] }) : undefined} />)}+ {restricted > 0 && <p className="px-2 py-1 text-caption text-muted-foreground">{t(($) => $.waiting.restricted, { count: restricted })}</p>}+ {/* Only the fixed backlog key parks work, matching the server's queue admission. */}+ {isIssueWaiting(issue) && <p className="px-2 pt-0.5 pb-1 text-caption text-muted-foreground">+ {issue.status === "backlog" ? t(($) => $.waiting.hint_backlog) : t(($) => $.waiting.hint)}+ </p>}+ </>}+ {blocking.length > 0 && <>+ <RelationGroup icon={<Flag className="size-3.5 text-warning" />} label={t(($) => $.relations.blocking)} />+ {blocking.map((dependent) => <RelationRow key={dependent.id} issue={dependent} icon={statusIcon(dependent.status)}+ tag={dependent.via === "stage" ? stageTag : undefined} removeLabel={t(($) => $.waiting.remove, { identifier: dependent.identifier })} pending={pending}+ onRemove={dependent.via === "manual" ? () => blockingMutation.mutate({ dependentId: dependent.id, remove: true }) : undefined} />)}+ </>}+ {duplicates.length > 0 && <>+ <RelationGroup icon={<CircleEqual className="size-3.5" />} label={t(($) => $.duplicates.section_title)} />+ {duplicates.map((duplicate) => <RelationRow key={duplicate.id} issue={duplicate} icon={statusIcon(duplicate.status)} />)}+ </>}+ {error && <p role="alert" className="px-2 py-1 text-caption text-destructive">{error.message}</p>}+ </div></IssueSidebarCollapsible>+ </div>;+}++function RelationGroup({ icon, label, aside }: { icon: React.ReactNode; label: string; aside?: string }) {+ return <div className="flex min-w-0 items-center gap-1.5 px-2 pt-2 pb-0.5 text-caption font-medium text-muted-foreground first:pt-0">+ {icon}<span className="truncate">{label}</span>+ {aside && <span className="ml-auto shrink-0 font-normal tabular-nums">{aside}</span>}+ </div>;+}++function RelationRow({ issue, icon, tag, onRemove, removeLabel, pending }: {+ issue: Pick<Issue, "id" | "identifier" | "title">;+ icon: React.ReactNode;+ tag?: React.ReactNode;+ onRemove?: () => void;+ removeLabel?: string;+ pending?: boolean;+}) {+ const paths = useWorkspacePaths();+ return <div className="group/relation flex min-w-0 items-center gap-1 rounded-md px-2 transition-colors hover:bg-accent/50">+ <AppLink href={paths.issueDetail(issueRouteRef(issue))} title={issue.title} className="flex min-w-0 flex-1 items-center gap-1.5 py-1.5 text-label">+ {icon}+ <span className="shrink-0 text-muted-foreground">{issue.identifier}</span>+ <span className="truncate group-hover/relation:text-foreground">{issue.title}</span>+ </AppLink>+ {tag}+ {onRemove && <Button variant="ghost" size="icon-xs" disabled={pending} aria-label={removeLabel} onClick={onRemove}+ className="text-muted-foreground opacity-0 group-hover/relation:opacity-100 focus-visible:opacity-100 [@media(pointer:coarse)]:opacity-100"><X /></Button>}</div>;}diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 4b00bd5021..ab4a757e39 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -17,8 +17,8 @@ import { UI_MOTION_DURATION } from "@multica/ui/lib/motion";import { Virtuoso, type ListRange, type VirtuosoHandle } from "react-virtuoso";import { useDefaultLayout, usePanelRef } from "react-resizable-panels";import { AppLink, useBackOrReplace } from "../../navigation";-import { IssueBlockersSection } from "./issue-blockers";-import { IssueDuplicateBanner, IssueDuplicatesSection, isDuplicateIssue } from "./issue-duplicates";+import { IssueRelationsSection } from "./issue-blockers";+import { IssueDuplicateBanner, isDuplicateIssue } from "./issue-duplicates";import {AlertTriangle,Calendar,@@ -3571,8 +3571,8 @@ export function IssueDetail({ issueId, onDelete, inbox, defaultSidebarOpen = tru</div></IssueSidebarCollapsible></div>),- waiting: <IssueBlockersSection issue={issue} />,- duplicates: <IssueDuplicatesSection issueId={issue.id} />,+ // Blockers, the issues this one blocks, and duplicates (MUL-10050).+ relations: <IssueRelationsSection issue={issue} />,// Pull requests — unavailable when the workspace disables the PR sidebar// (or the GitHub master switch is off). Backend data is kept either// way so re-enabling restores the section instantly.@@ -3623,7 +3623,7 @@ export function IssueDetail({ issueId, onDelete, inbox, defaultSidebarOpen = tru? GUEST_SIDEBAR_SECTIONS.has(section): (section !== "pull_requests" || githubSettings.prSidebar) && (section !== "plugins" || pluginsEnabled),)}- addRow={<IssueSidebarAddRow items={sidebarAddables.filter((item) => item !== sidebarReveal)} onPick={setSidebarReveal} />}+ addRow={<IssueSidebarAddRow items={sidebarAddables.filter((item) => item !== sidebarReveal)} onPick={setSidebarReveal} issue={issue} />}footer={guest ? undefined : <IssueSidebarFooter issue={issue} />}/>);diff --git a/packages/views/issues/components/issue-sidebar-add-row.test.tsx b/packages/views/issues/components/issue-sidebar-add-row.test.tsxindex 91ef6c18c6..fa6b9cc26b 100644--- a/packages/views/issues/components/issue-sidebar-add-row.test.tsx+++ b/packages/views/issues/components/issue-sidebar-add-row.test.tsx@@ -3,6 +3,7 @@ import { fireEvent, renderHook, screen } from "@testing-library/react";import type { ReactNode } from "react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import type {+ Issue,IssueEnvironmentsResponse,IssuePullRequestsResponse,IssueWakeup,@@ -11,7 +12,7 @@ import type {} from "@multica/core/types";import { githubInstallationsOptions, issuePullRequestsOptions } from "@multica/core/github";import { vcsConnectionsOptions } from "@multica/core/vcs/queries";-import { issueEnvironmentsOptions } from "@multica/core/issues/queries";+import { issueDetailOptions, issueDuplicatesOptions, issueEnvironmentsOptions } from "@multica/core/issues/queries";import { issueWakeupsOptions } from "@multica/core/issues";import { useIssueSidebarSectionsStore } from "@multica/core/issues/stores";import { renderWithI18n } from "../../test/i18n";@@ -23,13 +24,23 @@ vi.mock("@multica/core/paths", async (importOriginal) => ({useCurrentWorkspace: () => ({ id: "ws-1", repos }),}));+vi.mock("@multica/core/hooks", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/hooks")>()),+ useWorkspaceId: () => "ws-1",+}));+vi.mock("../utils/status-options", () => ({ useIssueStatusOptions: () => ({ options: [], workflow: null }) }));+const declared = { environments: [], configs: [{ environments: [{ name: "web" }] }], pending_starts: [], failed_starts: [] };const noPullRequests = { pull_requests: [], auto_complete: { state: "none", pull_request_ids: [], issue_disabled: false, workspace_enabled: true } };-function seed(overrides: { wakeups?: unknown; prs?: unknown; environments?: unknown; vcsConnections?: unknown[] } = {}) {+const unrelated = { id: "issue-1", status: "todo", blocked_count: 0, blocked_by: [], blocking: [] } as unknown as Issue;++function seed(overrides: { wakeups?: unknown; prs?: unknown; environments?: unknown; vcsConnections?: unknown[]; issue?: Partial<Issue> } = {}) {// Seeded and never stale, so the hook reads exactly what each section would.const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });client.setQueryData(issueWakeupsOptions("ws-1", "issue-1").queryKey, (overrides.wakeups ?? []) as IssueWakeup[]);+ client.setQueryData(issueDetailOptions("ws-1", "issue-1").queryKey, { ...unrelated, ...overrides.issue } as Issue);+ client.setQueryData(issueDuplicatesOptions("ws-1", "issue-1").queryKey, { duplicate_of: null, duplicates: [] });client.setQueryData(issuePullRequestsOptions("issue-1").queryKey, (overrides.prs ?? noPullRequests) as IssuePullRequestsResponse);client.setQueryData(githubInstallationsOptions("ws-1").queryKey, { installations: [] } as unknown as ListGitHubInstallationsResponse);client.setQueryData(@@ -62,11 +73,19 @@ beforeEach(() => {describe("useIssueSidebarAddables", () => {it("offers every empty section the reader can start", () => {- expect(addables()).toEqual(["wakeups", "pull_requests", "environments"]);+ expect(addables()).toEqual(["wakeups", "relations", "pull_requests", "environments"]);+ });++ it("offers relations only while the Relations section has nothing to list", () => {+ const blocker = { id: "b-1", identifier: "TEST-1", title: "Prerequisite", status: "todo", via: "manual" };+ expect(addables({}, { issue: { blocked_count: 1, blocked_by: [{ ...blocker, closed: false }] } })).not.toContain("relations");+ expect(addables({}, { issue: { blocking: [{ ...blocker, closed: false }] } })).not.toContain("relations");+ // A finished blocker is not listed, so relations are offered again.+ expect(addables({}, { issue: { blocked_by: [{ ...blocker, closed: true }] } })).toContain("relations");});it("drops sections that already have content", () => {- expect(addables({}, { wakeups: [{ id: "wake" }], prs: { ...noPullRequests, pull_requests: [{ id: "pr" }] } })).toEqual(["environments"]);+ expect(addables({}, { wakeups: [{ id: "wake" }], prs: { ...noPullRequests, pull_requests: [{ id: "pr" }] } })).toEqual(["relations", "environments"]);});it("offers nothing to a reader who cannot add, such as a guest", () => {@@ -74,28 +93,28 @@ describe("useIssueSidebarAddables", () => {});it("leaves out sections hidden in the sidebar settings", () => {- useIssueSidebarSectionsStore.setState({ hidden: ["pull_requests"] });+ useIssueSidebarSectionsStore.setState({ hidden: ["pull_requests", "relations"] });expect(addables()).toEqual(["wakeups", "environments"]);});it("offers no wakeup on an ended issue", () => {- expect(addables({ closed: true })).toEqual(["pull_requests", "environments"]);+ expect(addables({ closed: true })).toEqual(["relations", "pull_requests", "environments"]);});it("offers pull requests only where the workspace has code and the sidebar shows them", () => {- expect(addables({ pullRequestsAvailable: false })).toEqual(["wakeups", "environments"]);+ expect(addables({ pullRequestsAvailable: false })).toEqual(["wakeups", "relations", "environments"]);repos = [];- expect(addables()).toEqual(["wakeups", "environments"]);+ expect(addables()).toEqual(["wakeups", "relations", "environments"]);});it("offers pull requests to a workspace that only connects a self-hosted VCS", () => {repos = [];- expect(addables({}, { vcsConnections: [{ id: "gitlab-1" }] })).toEqual(["wakeups", "pull_requests", "environments"]);+ expect(addables({}, { vcsConnections: [{ id: "gitlab-1" }] })).toEqual(["wakeups", "relations", "pull_requests", "environments"]);});it("offers an environment only when a run declared one and nothing is starting", () => {- expect(addables({}, { environments: { ...declared, configs: [] } })).toEqual(["wakeups", "pull_requests"]);- expect(addables({}, { environments: { ...declared, pending_starts: [{ id: "cmd" }] } })).toEqual(["wakeups", "pull_requests"]);+ expect(addables({}, { environments: { ...declared, configs: [] } })).toEqual(["wakeups", "relations", "pull_requests"]);+ expect(addables({}, { environments: { ...declared, pending_starts: [{ id: "cmd" }] } })).toEqual(["wakeups", "relations", "pull_requests"]);});});@@ -120,8 +139,27 @@ describe("IssueSidebarAddRow", () => {expect(onPick).toHaveBeenCalledWith("environments");});- it("names all three in one sentence", () => {- renderWithI18n(<IssueSidebarAddRow items={["wakeups", "pull_requests", "environments"]} onPick={vi.fn()} />);- expect(screen.getByRole("button", { name: "Add wakeup, pull request, or environment" })).toBeInTheDocument();+ it("names two items and leaves more to the menu", () => {+ const { unmount } = renderWithI18n(<IssueSidebarAddRow items={["wakeups", "pull_requests"]} onPick={vi.fn()} />);+ expect(screen.getByRole("button", { name: "Add wakeup or pull request" })).toBeInTheDocument();+ unmount();+ renderWithI18n(<IssueSidebarAddRow items={["wakeups", "relations", "pull_requests"]} onPick={vi.fn()} issue={unrelated} />);+ expect(screen.getByRole("button", { name: "Add..." })).toBeInTheDocument();+ });++ it("opens the relation types for relations alone", async () => {+ renderWithI18n(+ <QueryClientProvider client={new QueryClient()}>+ <IssueSidebarAddRow items={["relations"]} onPick={vi.fn()} issue={unrelated} />+ </QueryClientProvider>,+ );+ fireEvent.click(screen.getByRole("button", { name: "Add relation" }));+ expect(await screen.findByRole("menuitem", { name: /Wait for another task/ })).toBeInTheDocument();+ expect(screen.getByRole("menuitem", { name: /Block another task/ })).toBeInTheDocument();+ });++ it("leaves relations out without an issue to relate", () => {+ renderWithI18n(<IssueSidebarAddRow items={["wakeups", "relations"]} onPick={vi.fn()} />);+ expect(screen.getByRole("button", { name: "Add wakeup" })).toBeInTheDocument();});});diff --git a/packages/views/issues/components/issue-sidebar-add-row.tsx b/packages/views/issues/components/issue-sidebar-add-row.tsxindex 45cfc5e849..f0f313e4a5 100644--- a/packages/views/issues/components/issue-sidebar-add-row.tsx+++ b/packages/views/issues/components/issue-sidebar-add-row.tsx@@ -1,35 +1,35 @@"use client";import { useQuery } from "@tanstack/react-query";-import { Bell, GitPullRequest, Plus, Server, type IconComponent } from "@multica/ui/icons";+import { Bell, GitPullRequest, Network, Plus, Server, type IconComponent } from "@multica/ui/icons";import {DropdownMenu,DropdownMenuContent,DropdownMenuItem,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,DropdownMenuTrigger,} from "@multica/ui/components/ui/dropdown-menu";import { githubInstallationsOptions, issuePullRequestsOptions } from "@multica/core/github";-import { issueEnvironmentsOptions } from "@multica/core/issues/queries";+import { issueDetailOptions, issueDuplicatesOptions, issueEnvironmentsOptions } from "@multica/core/issues/queries";import { issueWakeupsOptions } from "@multica/core/issues";import { vcsConnectionsOptions } from "@multica/core/vcs/queries";import { useCurrentWorkspace } from "@multica/core/paths";import { useIssueSidebarSectionsStore } from "@multica/core/issues/stores";+import type { Issue } from "@multica/core/types";import { useT } from "../../i18n";+import { issueRelations } from "../utils/relations";+import { IssueRelationTypeItems } from "./issue-blockers";/** Sections that hide while empty and are offered from the add row instead. */-export type IssueSidebarAddable = "wakeups" | "pull_requests" | "environments";+export type IssueSidebarAddable = "wakeups" | "relations" | "pull_requests" | "environments";-const ADDABLE_ORDER: readonly IssueSidebarAddable[] = ["wakeups", "pull_requests", "environments"];--type AddRowLabel =- | IssueSidebarAddable- | "wakeups_pull_requests"- | "wakeups_environments"- | "pull_requests_environments"- | "all";+const ADDABLE_ORDER: readonly IssueSidebarAddable[] = ["wakeups", "relations", "pull_requests", "environments"];const ADDABLE_ICON: Record<IssueSidebarAddable, IconComponent> = {wakeups: Bell,+ relations: Network,pull_requests: GitPullRequest,environments: Server,};@@ -59,6 +59,8 @@ export function useIssueSidebarAddables({const installations = useQuery({ ...githubInstallationsOptions(wsId), enabled: enabled && pullRequestsAvailable && !!wsId });const vcsConnections = useQuery({ ...vcsConnectionsOptions(wsId), enabled: enabled && pullRequestsAvailable && !!wsId });const environments = useQuery({ ...issueEnvironmentsOptions(wsId, issueId), enabled: enabled && !!wsId });+ const issue = useQuery({ ...issueDetailOptions(wsId, issueId), enabled: enabled && !!wsId });+ const duplicates = useQuery({ ...issueDuplicatesOptions(wsId, issueId), enabled: enabled && !!wsId });if (!enabled) return [];// A workspace with no repository to open a pull request against has none to@@ -70,6 +72,12 @@ export function useIssueSidebarAddables({const env = environments.data;const can: Record<IssueSidebarAddable, boolean> = {wakeups: !closed && wakeups.isSuccess && wakeups.data.length === 0,+ // Offered while the Relations section has nothing to list and so hides.+ relations:+ issue.isSuccess &&+ issue.data.blocked_by !== undefined &&+ duplicates.isSuccess &&+ issueRelations(issue.data, duplicates.data.duplicates).empty,pull_requests:pullRequestsAvailable && hostsCode && prs.isSuccess && !!prs.data.auto_complete && prs.data.pull_requests.length === 0,// Only a run that declared environments leaves something to start here.@@ -86,20 +94,33 @@ export function useIssueSidebarAddables({/*** One quiet row after the last section that starts any of `items`. A single- * item opens its form directly; several open a menu to pick from.+ * item opens its form directly; several open a menu to pick from. Relations+ * have no form of their own: they open the relation types, the same items as+ * the Relations section's "+", which need the issue.*/export function IssueSidebarAddRow({items,onPick,+ issue,}: {items: readonly IssueSidebarAddable[];onPick: (item: IssueSidebarAddable) => void;+ issue?: Issue;}) {const { t } = useT("issues");- if (items.length === 0) return null;- // Whole sentences per combination: languages inflect and space the list differently.- const key = items.length === ADDABLE_ORDER.length ? "all" : (items.join("_") as AddRowLabel);- const label = t(($) => $.detail.add_row[key]);+ const shown = issue ? items : items.filter((id) => id !== "relations");+ if (shown.length === 0) return null;+ // One or two items are named; past that the menu names them, so the label+ // does not grow a sentence for every combination.+ const label =+ shown.length === 1+ ? t(($) => $.detail.add_row[shown[0]!])+ : shown.length === 2+ ? t(($) => $.detail.add_row.pair, {+ first: t(($) => $.detail.add_row.noun[shown[0]!]),+ second: t(($) => $.detail.add_row.noun[shown[1]!]),+ })+ : t(($) => $.detail.add_row.many);const rowClass ="flex h-7 max-w-full items-center gap-2.5 rounded-md px-2 text-caption text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring data-popup-open:bg-accent/50 data-popup-open:text-foreground";const content = (@@ -108,25 +129,41 @@ export function IssueSidebarAddRow({<span className="truncate">{label}</span></>);+ const only = shown.length === 1 ? shown[0]! : null;return (<div data-testid="issue-sidebar-add-row" className="px-2">- {items.length === 1 ? (- <button type="button" className={rowClass} onClick={() => onPick(items[0]!)}>+ {only && only !== "relations" ? (+ <button type="button" className={rowClass} onClick={() => onPick(only)}>{content}</button>) : (<DropdownMenu><DropdownMenuTrigger render={<button type="button" className={rowClass} />}>{content}</DropdownMenuTrigger>- <DropdownMenuContent align="start" className="w-56">- {items.map((id) => {- const Icon = ADDABLE_ICON[id];- return (- <DropdownMenuItem key={id} onClick={() => onPick(id)}>- <Icon />- {t(($) => $.detail.add_row.menu[id])}- </DropdownMenuItem>- );- })}+ <DropdownMenuContent align="start" className={only ? "w-64" : "w-56"}>+ {only ? (+ <IssueRelationTypeItems issue={issue!} />+ ) : (+ shown.map((id) => {+ const Icon = ADDABLE_ICON[id];+ const name = t(($) => $.detail.add_row.menu[id]);+ return id === "relations" ? (+ <DropdownMenuSub key={id}>+ <DropdownMenuSubTrigger>+ <Icon />+ {name}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="w-64">+ <IssueRelationTypeItems issue={issue!} />+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ ) : (+ <DropdownMenuItem key={id} onClick={() => onPick(id)}>+ <Icon />+ {name}+ </DropdownMenuItem>+ );+ })+ )}</DropdownMenuContent></DropdownMenu>)}diff --git a/packages/views/issues/components/issue-sidebar-settings.tsx b/packages/views/issues/components/issue-sidebar-settings.tsxindex 89ad9bc7fa..9b8c09efce 100644--- a/packages/views/issues/components/issue-sidebar-settings.tsx+++ b/packages/views/issues/components/issue-sidebar-settings.tsx@@ -55,8 +55,7 @@ export function useIssueSidebarSectionLabels(): Record<IssueSidebarSection, striwakeups: t(($) => $.wakeups.title),plugins: t(($) => $.plugins.panels),parent: t(($) => $.detail.section_parent_issue),- waiting: t(($) => $.waiting.title),- duplicates: t(($) => $.duplicates.section_title),+ relations: t(($) => $.relations.title),pull_requests: t(($) => $.detail.section_pull_requests),environments: t(($) => $.environments.section_title),deliverables: t(($) => $.deliverables.section_title),diff --git a/packages/views/issues/utils/relations.ts b/packages/views/issues/utils/relations.tsnew file mode 100644index 0000000000..3b85fb631f--- /dev/null+++ b/packages/views/issues/utils/relations.ts@@ -0,0 +1,38 @@+import type { Issue, IssueBlocker } from "@multica/core/types";++export interface IssueRelations {+ /** Unfinished issues this one waits for. */+ blockedBy: IssueBlocker[];+ /** Unfinished issues waiting for this one. */+ blocking: IssueBlocker[];+ /** Issues marked as duplicates of this one. */+ duplicates: Issue[];+ /** Unfinished blockers the reader may not see, counted but not listed. */+ restricted: number;+ /** Blockers that ended, and all of them, for "1/3 ended". */+ finished: number;+ total: number;+ empty: boolean;+}++/**+ * What the sidebar's Relations section lists (MUL-10050). Finished issues+ * drop out of both blocker groups: they no longer hold anything up, and the+ * ended count keeps the progress. The section renders nothing when empty, and+ * the sidebar's add row offers relations instead.+ */+export function issueRelations(issue: Issue, duplicates: Issue[] = []): IssueRelations {+ const all = issue.blocked_by ?? [];+ const blockedBy = all.filter((b) => !b.closed);+ const blocking = (issue.blocking ?? []).filter((b) => !b.closed);+ const restricted = Math.max(0, (issue.blocked_count ?? 0) - blockedBy.length);+ return {+ blockedBy,+ blocking,+ duplicates,+ restricted,+ finished: all.length - blockedBy.length,+ total: all.length + restricted,+ empty: !blockedBy.length && !restricted && !blocking.length && !duplicates.length,+ };+}diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 1e095d81bd..d275c0fd7e 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -610,14 +610,20 @@"wakeups": "Add wakeup","pull_requests": "Add pull request","environments": "Add environment",- "wakeups_pull_requests": "Add wakeup or pull request",- "wakeups_environments": "Add wakeup or environment",- "pull_requests_environments": "Add pull request or environment",- "all": "Add wakeup, pull request, or environment",+ "relations": "Add relation",+ "pair": "Add {{first}} or {{second}}",+ "many": "Add...",+ "noun": {+ "wakeups": "wakeup",+ "pull_requests": "pull request",+ "environments": "environment",+ "relations": "relation"+ },"menu": {"wakeups": "Wakeup","pull_requests": "Pull request",- "environments": "Environment"+ "environments": "Environment",+ "relations": "Relations"}},"footer": {@@ -1134,7 +1140,8 @@"remove_parent_issue": "Remove parent issue","remove_parent_issue_success": "Removed parent issue","add_sub_issue": "Add sub-issue...",- "add_blocker": "Add blocker...",+ "add_blocker": "Wait for another task...",+ "add_blocking": "Block another task...","delete_issue": "Delete issue","mark_duplicate": "Mark as duplicate...","open_in_new_window": "Open in new window"@@ -2149,15 +2156,25 @@"retry": "Retry","dismiss": "Dismiss"},+ "relations": {+ "title": "Relations",+ "add": "Add relation",+ "wait_title": "Wait for another task",+ "block_title": "Block another task",+ "blocked_by": "Blocked by",+ "blocking": "Blocking",+ "stage_tag": "Stage",+ "stage_tag_hint": "Set by the parent issue's stages",+ "add_blocker_hint": "This task starts after it ends",+ "add_blocking_hint": "It starts after this task ends",+ "mark_duplicate_hint": "Cancels this task",+ "blocking_picker_hint": "Select a task that can't start until this one ends."+ },"waiting": {- "title": "Waiting",- "add": "Add blocker","remove": "Remove {{identifier}}","count": "Waiting for {{count}} tasks",- "stage": "Earlier stages · {{finished}}/{{total}} ended","hint": "After these tasks end, the assignee starts automatically or receives a notification.","hint_backlog": "This task is in Backlog, so it won't start automatically when these tasks end. It starts once it leaves Backlog.",- "empty": "No tasks to wait for","picker_hint": "Select a task that must end before this one can start.","restricted": "{{count}} restricted prerequisites","ended": "Waiting tasks ended",diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.jsonindex dc9d2bc6f5..826caabf5c 100644--- a/packages/views/locales/es/issues.json+++ b/packages/views/locales/es/issues.json@@ -593,14 +593,20 @@"wakeups": "Añadir activación","pull_requests": "Añadir pull request","environments": "Añadir entorno",- "wakeups_pull_requests": "Añadir activación o pull request",- "wakeups_environments": "Añadir activación o entorno",- "pull_requests_environments": "Añadir pull request o entorno",- "all": "Añadir activación, pull request o entorno",+ "relations": "Añadir relación",+ "pair": "Añadir {{first}} o {{second}}",+ "many": "Añadir...",+ "noun": {+ "wakeups": "activación",+ "pull_requests": "pull request",+ "environments": "entorno",+ "relations": "relación"+ },"menu": {"wakeups": "Activación","pull_requests": "Pull request",- "environments": "Entorno"+ "environments": "Entorno",+ "relations": "Relaciones"}},"footer": {@@ -1041,7 +1047,8 @@"remove_parent_issue": "Quitar tarea principal","remove_parent_issue_success": "Tarea principal quitada","add_sub_issue": "Añadir subtarea...",- "add_blocker": "Añadir requisito...",+ "add_blocker": "Esperar a otra tarea...",+ "add_blocking": "Bloquear otra tarea...","delete_issue": "Eliminar tarea","mark_duplicate": "Marcar como duplicada...","rename_issue": "Renombrar tarea",@@ -2149,17 +2156,27 @@"retry": "Reintentar","dismiss": "Descartar"},+ "relations": {+ "title": "Relaciones",+ "add": "Añadir relación",+ "wait_title": "Esperar a otra tarea",+ "block_title": "Bloquear otra tarea",+ "blocked_by": "Bloqueada por",+ "blocking": "Bloqueando",+ "stage_tag": "Etapa",+ "stage_tag_hint": "Lo fijan las etapas de la tarea principal",+ "add_blocker_hint": "Esta tarea empieza cuando termine",+ "add_blocking_hint": "Empieza cuando termine esta tarea",+ "mark_duplicate_hint": "Cancela esta tarea",+ "blocking_picker_hint": "Selecciona una tarea que no pueda empezar hasta que termine esta."+ },"waiting": {- "title": "En espera",- "add": "Añadir requisito","remove": "Quitar {{identifier}}","count": "Esperando {{count}} tareas","count_one": "Esperando {{count}} tarea","count_other": "Esperando {{count}} tareas",- "stage": "Etapas anteriores · {{finished}}/{{total}} terminadas","hint": "Al terminar estas tareas, el responsable comienza automáticamente o recibe una notificación.","hint_backlog": "Esta tarea está en Backlog, así que no comenzará automáticamente cuando terminen estas tareas. Comenzará cuando salga de Backlog.",- "empty": "Sin tareas pendientes","picker_hint": "Selecciona una tarea que deba terminar antes que esta.","restricted": "{{count}} requisitos restringidos","ended": "Las tareas en espera terminaron",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex 70e23b154a..19e5c7e876 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -610,14 +610,20 @@"wakeups": "Ajouter un réveil","pull_requests": "Ajouter une pull request","environments": "Ajouter un environnement",- "wakeups_pull_requests": "Ajouter un réveil ou une pull request",- "wakeups_environments": "Ajouter un réveil ou un environnement",- "pull_requests_environments": "Ajouter une pull request ou un environnement",- "all": "Ajouter un réveil, une pull request ou un environnement",+ "relations": "Ajouter une relation",+ "pair": "Ajouter {{first}} ou {{second}}",+ "many": "Ajouter...",+ "noun": {+ "wakeups": "un réveil",+ "pull_requests": "une pull request",+ "environments": "un environnement",+ "relations": "une relation"+ },"menu": {"wakeups": "Réveil","pull_requests": "Pull request",- "environments": "Environnement"+ "environments": "Environnement",+ "relations": "Relations"}},"footer": {@@ -1134,7 +1140,8 @@"remove_parent_issue": "Retirer la tâche parente","remove_parent_issue_success": "Tâche parente retirée","add_sub_issue": "Ajouter une sous-tâche...",- "add_blocker": "Ajouter un prérequis...",+ "add_blocker": "Attendre une autre tâche...",+ "add_blocking": "Bloquer une autre tâche...","delete_issue": "Supprimer la tâche","mark_duplicate": "Marquer comme doublon...","open_in_new_window": "Ouvrir dans une nouvelle fenêtre"@@ -2149,17 +2156,27 @@"retry": "Réessayer","dismiss": "Ignorer"},+ "relations": {+ "title": "Relations",+ "add": "Ajouter une relation",+ "wait_title": "Attendre une autre tâche",+ "block_title": "Bloquer une autre tâche",+ "blocked_by": "Bloquée par",+ "blocking": "Bloque",+ "stage_tag": "Étape",+ "stage_tag_hint": "Défini par les étapes de la tâche parente",+ "add_blocker_hint": "Cette tâche commence quand elle se termine",+ "add_blocking_hint": "Elle commence quand cette tâche se termine",+ "mark_duplicate_hint": "Annule cette tâche",+ "blocking_picker_hint": "Sélectionnez une tâche qui ne peut pas commencer avant la fin de celle-ci."+ },"waiting": {- "title": "En attente",- "add": "Ajouter un prérequis","remove": "Retirer {{identifier}}","count": "En attente de {{count}} tâches","count_one": "En attente de {{count}} tâche","count_other": "En attente de {{count}} tâches",- "stage": "Étapes précédentes · {{finished}}/{{total}} terminées","hint": "Une fois ces tâches terminées, le responsable démarre automatiquement ou reçoit une notification.","hint_backlog": "Cette tâche est « À planifier » : elle ne démarrera pas automatiquement à la fin de ces tâches. Elle démarrera une fois sortie de « À planifier ».",- "empty": "Aucune tâche à attendre","picker_hint": "Sélectionnez une tâche qui doit se terminer avant celle-ci.","restricted": "{{count}} prérequis à accès restreint","ended": "Les tâches attendues sont terminées",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 96da34b2c6..b551de88d9 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -599,14 +599,20 @@"wakeups": "ウェイクアップを追加","pull_requests": "Pull request を追加","environments": "環境を追加",- "wakeups_pull_requests": "ウェイクアップまたは Pull request を追加",- "wakeups_environments": "ウェイクアップまたは環境を追加",- "pull_requests_environments": "Pull request または環境を追加",- "all": "ウェイクアップ、Pull request、環境を追加",+ "relations": "関係を追加",+ "pair": "{{first}}または{{second}}を追加",+ "many": "追加...",+ "noun": {+ "wakeups": "ウェイクアップ",+ "pull_requests": "Pull request",+ "environments": "環境",+ "relations": "関係"+ },"menu": {"wakeups": "ウェイクアップ","pull_requests": "Pull request",- "environments": "環境"+ "environments": "環境",+ "relations": "関係"}},"footer": {@@ -1076,7 +1082,8 @@"remove_parent_issue": "親タスクを解除","remove_parent_issue_success": "親タスクを解除しました","add_sub_issue": "サブタスクを追加...",- "add_blocker": "先行タスクを追加...",+ "add_blocker": "他のタスクを待つ...",+ "add_blocking": "他のタスクをブロック...","delete_issue": "タスクを削除","mark_duplicate": "重複としてマーク...","open_in_new_window": "新しいウィンドウで開く"@@ -2058,16 +2065,26 @@"retry": "再試行","dismiss": "閉じる"},+ "relations": {+ "title": "関係",+ "add": "関係を追加",+ "wait_title": "他のタスクを待つ",+ "block_title": "他のタスクをブロック",+ "blocked_by": "ブロック元",+ "blocking": "ブロック中",+ "stage_tag": "ステージ",+ "stage_tag_hint": "親タスクのステージで決まります",+ "add_blocker_hint": "終了後にこのタスクが始まります",+ "add_blocking_hint": "このタスクの終了後に始まります",+ "mark_duplicate_hint": "このタスクはキャンセルされます",+ "blocking_picker_hint": "このタスクが終了するまで開始できないタスクを選択してください。"+ },"waiting": {- "title": "待機",- "add": "先行タスクを追加","remove": "{{identifier}} を削除","count": "{{count}} 件のタスクを待機中","count_other": "{{count}} 件のタスクを待機中",- "stage": "前のステージ · {{finished}}/{{total}} 件終了","hint": "すべて終了すると、担当者が自動的に開始するか通知を受け取ります。","hint_backlog": "このタスクはバックログにあるため、すべて終了しても自動では開始しません。バックログから移動すると開始します。",- "empty": "待機するタスクはありません","picker_hint": "このタスクの前に終了する必要があるタスクを選択してください。","restricted": "閲覧できない先行タスク {{count}} 件","ended": "待機中のタスクが終了しました",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex bfd86c33dd..6810dfe8ec 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -599,14 +599,20 @@"wakeups": "깨우기 추가","pull_requests": "Pull request 추가","environments": "환경 추가",- "wakeups_pull_requests": "깨우기 또는 Pull request 추가",- "wakeups_environments": "깨우기 또는 환경 추가",- "pull_requests_environments": "Pull request 또는 환경 추가",- "all": "깨우기, Pull request 또는 환경 추가",+ "relations": "관계 추가",+ "pair": "{{first}} 또는 {{second}} 추가",+ "many": "추가...",+ "noun": {+ "wakeups": "깨우기",+ "pull_requests": "Pull request",+ "environments": "환경",+ "relations": "관계"+ },"menu": {"wakeups": "깨우기","pull_requests": "Pull request",- "environments": "환경"+ "environments": "환경",+ "relations": "관계"}},"footer": {@@ -1076,7 +1082,8 @@"remove_parent_issue": "상위 태스크 제거","remove_parent_issue_success": "상위 태스크를 제거했습니다","add_sub_issue": "하위 태스크 추가...",- "add_blocker": "선행 작업 추가...",+ "add_blocker": "다른 작업 기다리기...",+ "add_blocking": "다른 작업 막기...","delete_issue": "태스크 삭제","mark_duplicate": "중복으로 표시...","open_in_new_window": "새 창에서 열기"@@ -2058,16 +2065,26 @@"retry": "다시 시도","dismiss": "닫기"},+ "relations": {+ "title": "관계",+ "add": "관계 추가",+ "wait_title": "다른 작업 기다리기",+ "block_title": "다른 작업 막기",+ "blocked_by": "선행 작업",+ "blocking": "막고 있는 작업",+ "stage_tag": "단계",+ "stage_tag_hint": "상위 작업의 단계로 정해짐",+ "add_blocker_hint": "이 작업은 그 작업이 끝난 뒤 시작됩니다",+ "add_blocking_hint": "그 작업은 이 작업이 끝난 뒤 시작됩니다",+ "mark_duplicate_hint": "이 작업이 취소됩니다",+ "blocking_picker_hint": "이 작업이 끝나야 시작할 수 있는 작업을 선택하세요."+ },"waiting": {- "title": "대기",- "add": "선행 작업 추가","remove": "{{identifier}} 제거","count": "작업 {{count}}개 대기 중","count_other": "작업 {{count}}개 대기 중",- "stage": "이전 단계 · {{finished}}/{{total}}개 종료","hint": "모두 종료되면 담당자가 자동으로 시작하거나 알림을 받습니다.","hint_backlog": "이 작업은 백로그에 있어 모두 종료되어도 자동으로 시작되지 않습니다. 백로그에서 옮기면 시작됩니다.",- "empty": "대기할 작업 없음","picker_hint": "이 작업보다 먼저 종료되어야 하는 작업을 선택하세요.","restricted": "볼 수 없는 선행 작업 {{count}}개","ended": "대기 중인 작업 종료",diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.jsonindex 288c6bcb1d..ead02bb373 100644--- a/packages/views/locales/ru/issues.json+++ b/packages/views/locales/ru/issues.json@@ -631,14 +631,20 @@"wakeups": "Добавить будильник","pull_requests": "Добавить pull request","environments": "Добавить окружение",- "wakeups_pull_requests": "Добавить будильник или pull request",- "wakeups_environments": "Добавить будильник или окружение",- "pull_requests_environments": "Добавить pull request или окружение",- "all": "Добавить будильник, pull request или окружение",+ "relations": "Добавить связь",+ "pair": "Добавить {{first}} или {{second}}",+ "many": "Добавить...",+ "noun": {+ "wakeups": "будильник",+ "pull_requests": "pull request",+ "environments": "окружение",+ "relations": "связь"+ },"menu": {"wakeups": "Будильник","pull_requests": "Pull request",- "environments": "Окружение"+ "environments": "Окружение",+ "relations": "Связи"}},"footer": {@@ -1247,7 +1253,8 @@"remove_parent_issue": "Убрать родительскую задачу","remove_parent_issue_success": "Родительская задача убрана","add_sub_issue": "Добавить подзадачу...",- "add_blocker": "Добавить зависимость...",+ "add_blocker": "Ждать другую задачу...",+ "add_blocking": "Блокировать другую задачу...","delete_issue": "Удалить задачу","mark_duplicate": "Отметить как дубликат...","locate_in_sidebar": "Показать на боковой панели",@@ -2337,19 +2344,29 @@"retry": "Повторить","dismiss": "Скрыть"},+ "relations": {+ "title": "Связи",+ "add": "Добавить связь",+ "wait_title": "Ждать другую задачу",+ "block_title": "Блокировать другую задачу",+ "blocked_by": "Заблокировано",+ "blocking": "Блокирует",+ "stage_tag": "Этап",+ "stage_tag_hint": "Задано этапами родительской задачи",+ "add_blocker_hint": "Эта задача начнётся после её завершения",+ "add_blocking_hint": "Она начнётся после завершения этой задачи",+ "mark_duplicate_hint": "Отменяет эту задачу",+ "blocking_picker_hint": "Выберите задачу, которая не может начаться, пока не завершится эта."+ },"waiting": {- "title": "Ожидание",- "add": "Добавить зависимость","remove": "Удалить {{identifier}}","count": "Ожидание задач: {{count}}","count_one": "Ожидание задач: {{count}}","count_few": "Ожидание задач: {{count}}","count_many": "Ожидание задач: {{count}}","count_other": "Ожидание задач: {{count}}",- "stage": "Предыдущие этапы · {{finished}}/{{total}} завершено","hint": "После завершения этих задач исполнитель начнёт работу автоматически или получит уведомление.","hint_backlog": "Задача в бэклоге, поэтому она не начнётся автоматически после завершения этих задач. Она начнётся, когда её переведут из бэклога.",- "empty": "Нет ожидаемых задач","picker_hint": "Выберите задачу, которая должна завершиться раньше этой.","restricted": "Ограниченные зависимости: {{count}}","ended": "Ожидаемые задачи завершены",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 9a9f0ef76a..8a9813da0a 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -599,14 +599,20 @@"wakeups": "添加唤醒","pull_requests": "添加 Pull Request","environments": "添加环境",- "wakeups_pull_requests": "添加唤醒或 Pull Request",- "wakeups_environments": "添加唤醒或环境",- "pull_requests_environments": "添加 Pull Request 或环境",- "all": "添加唤醒、Pull Request 或环境",+ "relations": "添加关系",+ "pair": "添加{{first}}或{{second}}",+ "many": "添加...",+ "noun": {+ "wakeups": "唤醒",+ "pull_requests": "Pull Request",+ "environments": "环境",+ "relations": "关系"+ },"menu": {"wakeups": "唤醒","pull_requests": "Pull Request",- "environments": "环境"+ "environments": "环境",+ "relations": "关系"}},"footer": {@@ -1076,7 +1082,8 @@"remove_parent_issue": "移除父任务","remove_parent_issue_success": "已移除父任务","add_sub_issue": "添加子任务...",- "add_blocker": "添加前置任务...",+ "add_blocker": "等待其他任务...",+ "add_blocking": "阻塞其他任务...","delete_issue": "删除任务","mark_duplicate": "标记为重复...","open_in_new_window": "在新窗口中打开"@@ -2058,16 +2065,26 @@"retry": "重试","dismiss": "忽略"},+ "relations": {+ "title": "关系",+ "add": "添加关系",+ "wait_title": "等待其他任务",+ "block_title": "阻塞其他任务",+ "blocked_by": "被阻塞",+ "blocking": "正在阻塞",+ "stage_tag": "阶段",+ "stage_tag_hint": "由父任务的阶段决定",+ "add_blocker_hint": "它们结束后,本任务才开工",+ "add_blocking_hint": "本任务结束后,它们才开工",+ "mark_duplicate_hint": "本任务会被取消",+ "blocking_picker_hint": "选择一个要等本任务结束才能开工的任务。"+ },"waiting": {- "title": "等待",- "add": "添加前置任务","remove": "移除 {{identifier}}","count": "等待 {{count}} 个任务","count_other": "等待 {{count}} 个任务",- "stage": "更早阶段 · {{finished}}/{{total}} 已结束","hint": "全部结束后,负责人将自动开工或收到通知。","hint_backlog": "任务在待规划中,全部结束后不会自动开始,移出待规划后才会开始。",- "empty": "没有等待的任务","picker_hint": "选择一个必须先结束的任务。","restricted": "{{count}} 个无权查看的前置任务","ended": "等待的任务已结束",diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.jsonindex 3aa52926e8..0c88c8b577 100644--- a/packages/views/locales/zh-Hant/issues.json+++ b/packages/views/locales/zh-Hant/issues.json@@ -599,14 +599,20 @@"wakeups": "新增喚醒","pull_requests": "新增 Pull Request","environments": "新增環境",- "wakeups_pull_requests": "新增喚醒或 Pull Request",- "wakeups_environments": "新增喚醒或環境",- "pull_requests_environments": "新增 Pull Request 或環境",- "all": "新增喚醒、Pull Request 或環境",+ "relations": "新增關係",+ "pair": "新增{{first}}或{{second}}",+ "many": "新增...",+ "noun": {+ "wakeups": "喚醒",+ "pull_requests": "Pull Request",+ "environments": "環境",+ "relations": "關係"+ },"menu": {"wakeups": "喚醒","pull_requests": "Pull Request",- "environments": "環境"+ "environments": "環境",+ "relations": "關係"}},"footer": {@@ -1076,7 +1082,8 @@"remove_parent_issue": "移除父任務","remove_parent_issue_success": "已移除父任務","add_sub_issue": "新增子任務...",- "add_blocker": "新增前置任務...",+ "add_blocker": "等待其他任務...",+ "add_blocking": "阻塞其他任務...","delete_issue": "刪除任務","mark_duplicate": "標記為重複...","open_in_new_window": "在新視窗中開啟"@@ -2058,16 +2065,26 @@"retry": "重試","dismiss": "忽略"},+ "relations": {+ "title": "關係",+ "add": "新增關係",+ "wait_title": "等待其他任務",+ "block_title": "阻塞其他任務",+ "blocked_by": "被阻塞",+ "blocking": "正在阻塞",+ "stage_tag": "階段",+ "stage_tag_hint": "由父任務的階段決定",+ "add_blocker_hint": "它們結束後,本任務才開工",+ "add_blocking_hint": "本任務結束後,它們才開工",+ "mark_duplicate_hint": "本任務會被取消",+ "blocking_picker_hint": "選擇一個要等本任務結束才能開工的任務。"+ },"waiting": {- "title": "等待",- "add": "新增前置任務","remove": "移除 {{identifier}}","count": "等待 {{count}} 個任務","count_other": "等待 {{count}} 個任務",- "stage": "更早階段 · {{finished}}/{{total}} 已結束","hint": "全部結束後,負責人將自動開始或收到通知。","hint_backlog": "任務在待規劃中,全部結束後不會自動開始,移出待規劃後才會開始。",- "empty": "沒有等待的任務","picker_hint": "選擇一個必須先結束的任務。","restricted": "{{count}} 個無權查看的前置任務","ended": "等待的任務已結束",diff --git a/packages/views/modals/add-blocker-issue.test.tsx b/packages/views/modals/add-blocker-issue.test.tsxindex 0966ef84be..bc1f7ea16d 100644--- a/packages/views/modals/add-blocker-issue.test.tsx+++ b/packages/views/modals/add-blocker-issue.test.tsx@@ -13,6 +13,7 @@ type PickerProps = {const mocks = vi.hoisted(() => ({mutate: vi.fn(),+ mutateBlocking: vi.fn(),mutation: { isError: false, isPending: false, error: null as Error | null },picker: null as PickerProps | null,}));@@ -20,6 +21,7 @@ const mocks = vi.hoisted(() => ({vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));vi.mock("@multica/core/issues/blockers", () => ({useUpdateIssueBlockers: () => ({ ...mocks.mutation, mutate: mocks.mutate }),+ useUpdateIssueBlocking: () => ({ ...mocks.mutation, mutate: mocks.mutateBlocking }),}));vi.mock("@multica/core/issues/queries", () => ({issueDetailOptions: (_wsId: string, issueId: string) => ({ queryKey: ["issues", "detail", issueId] }),@@ -33,6 +35,10 @@ vi.mock("@tanstack/react-query", () => ({{ id: "manual-1", via: "manual" },{ id: "stage-1", via: "stage" },],+ blocking: [+ { id: "dependent-1", via: "manual" },+ { id: "later-stage-1", via: "stage" },+ ],},}),}));@@ -49,12 +55,16 @@ vi.mock("./issue-picker-modal", () => ({vi.mock("../i18n", () => ({useT: () => ({t: (selector: (labels: Record<string, Record<string, string>>) => string) =>- selector({ waiting: { add: "Add blocker", picker_hint: "Pick a blocker" } }),+ selector({+ waiting: { picker_hint: "Pick a blocker" },+ relations: { wait_title: "Wait for another task", block_title: "Block another task", blocking_picker_hint: "Pick a dependent" },+ }),}),}));beforeEach(() => {mocks.mutate.mockReset();+ mocks.mutateBlocking.mockReset();mocks.mutation = { isError: false, isPending: false, error: null };mocks.picker = null;});@@ -82,4 +92,15 @@ describe("AddBlockerIssueModal", () => {render(<AddBlockerIssueModal onClose={vi.fn()} data={{ issueId: "issue-1" }} />);expect(mocks.picker?.error).toBe("would create a cycle");});++ it("blocks the picked issue by writing the edge on that issue", () => {+ const onClose = vi.fn();+ render(<AddBlockerIssueModal onClose={onClose} data={{ issueId: "issue-1" }} direction="blocking" />);+ expect(mocks.picker?.excludeIds).toEqual(["issue-1", "parent-1", "dependent-1"]);+ expect(mocks.picker?.isSelectable({ parent_issue_id: "issue-1" })).toBe(false);++ fireEvent.click(screen.getByText("Select issue"));+ expect(mocks.mutateBlocking).toHaveBeenCalledWith({ dependentId: "blocker-1" }, { onSuccess: onClose });+ expect(mocks.mutate).not.toHaveBeenCalled();+ });});diff --git a/packages/views/modals/add-blocker-issue.tsx b/packages/views/modals/add-blocker-issue.tsxindex 0ab637d356..600a173ab0 100644--- a/packages/views/modals/add-blocker-issue.tsx+++ b/packages/views/modals/add-blocker-issue.tsx@@ -3,42 +3,50 @@import { useQuery } from "@tanstack/react-query";import { useWorkspaceId } from "@multica/core/hooks";import { issueDetailOptions } from "@multica/core/issues/queries";-import { useUpdateIssueBlockers } from "@multica/core/issues/blockers";+import { useUpdateIssueBlockers, useUpdateIssueBlocking } from "@multica/core/issues/blockers";import { IssuePickerModal } from "./issue-picker-modal";import { useT } from "../i18n";/**- * Adds a manual blocker to an issue (MUL-8860). Shared by the sidebar's- * Waiting section and the Relations submenu of the issue actions menu, so- * both entry points write through the same path. The picker stays open while- * the write is in flight and shows the server's error in place (a cycle, a- * blocker the caller can't see), closing only once the blocker is saved.+ * Adds a manual blocker edge (MUL-8860). `blocked_by` picks an issue this one+ * waits for; `blocking` picks an issue that waits for this one, written on+ * that issue (MUL-10050). Shared by the sidebar's Relations section, its add+ * row and the Relations submenu of the issue actions menu, so every entry+ * point writes through the same path. The picker stays open while the write+ * is in flight and shows the server's error in place (a cycle, an issue the+ * caller can't see), closing only once the edge is saved.*/export function AddBlockerIssueModal({open = true,onClose,onOpenChangeComplete,data,+ direction = "blocked_by",}: {open?: boolean;onClose: () => void;onOpenChangeComplete?: (open: boolean) => void;data: Record<string, unknown> | null;+ direction?: "blocked_by" | "blocking";}) {const { t } = useT("issues");const issueId = (data?.issueId as string) || "";const wsId = useWorkspaceId();- const mutation = useUpdateIssueBlockers(wsId, issueId);+ const blockedBy = useUpdateIssueBlockers(wsId, issueId);+ const blocking = useUpdateIssueBlocking(wsId, issueId);+ const mutation = direction === "blocking" ? blocking : blockedBy;- // List rows don't carry blocked_by, so read the detail for what to exclude.+ // List rows don't carry blocked_by or blocking, so read the detail for+ // what to exclude.const { data: issue } = useQuery({...issueDetailOptions(wsId, issueId),enabled: !!issueId,});+ const linked = direction === "blocking" ? issue?.blocking : issue?.blocked_by;const excludeIds = [issueId,...(issue?.parent_issue_id ? [issue.parent_issue_id] : []),- ...(issue?.blocked_by ?? []).filter((b) => b.via === "manual").map((b) => b.id),+ ...(linked ?? []).filter((b) => b.via === "manual").map((b) => b.id),];return (@@ -48,16 +56,18 @@ export function AddBlockerIssueModal({if (!v) onClose();}}onOpenChangeComplete={onOpenChangeComplete}- title={t(($) => $.waiting.add)}- description={t(($) => $.waiting.picker_hint)}+ title={direction === "blocking" ? t(($) => $.relations.block_title) : t(($) => $.relations.wait_title)}+ description={direction === "blocking" ? t(($) => $.relations.blocking_picker_hint) : t(($) => $.waiting.picker_hint)}error={mutation.isError ? mutation.error.message : undefined}pending={mutation.isPending}closeOnSelect={false}excludeIds={excludeIds}- // A sub-issue can't block its own parent.+ // A parent and its sub-issues can't block each other either way.isSelectable={(candidate) => candidate.parent_issue_id !== issueId}onSelect={(candidate) =>- mutation.mutate({ blocked_by: [candidate.id] }, { onSuccess: onClose })+ direction === "blocking"+ ? blocking.mutate({ dependentId: candidate.id }, { onSuccess: onClose })+ : blockedBy.mutate({ blocked_by: [candidate.id] }, { onSuccess: onClose })}/>);diff --git a/packages/views/modals/registry.tsx b/packages/views/modals/registry.tsxindex 03e8f08f50..4f0b07fde0 100644--- a/packages/views/modals/registry.tsx+++ b/packages/views/modals/registry.tsx@@ -175,6 +175,7 @@ export function ModalRegistry() {);break;case "issue-add-blocker":+ case "issue-add-blocking":activeModal = (<AddBlockerIssueModalkey={sessionKey}@@ -182,6 +183,7 @@ export function ModalRegistry() {onClose={close}onOpenChangeComplete={handleOpenChangeComplete}data={currentData}+ direction={currentModal === "issue-add-blocking" ? "blocking" : "blocked_by"}/>);break;diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 1431d45f8f..c65ae9faf1 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -73,6 +73,9 @@ type IssueResponse struct {ParentIssueID *string `json:"parent_issue_id"`BlockedBy []IssueBlockerResponse `json:"blocked_by"`BlockedCount int `json:"blocked_count"`+ // Blocking lists the issues that wait on this one. Only the detail read+ // fills it; every other rendering omits the key.+ Blocking *[]IssueBlockerResponse `json:"blocking,omitempty"`// 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;@@ -2566,6 +2569,17 @@ func (h *Handler) GetIssue(w http.ResponseWriter, r *http.Request) {}resp.Labels = &detailLabels+ blocking, err := h.issueDependents(r.Context(), issue, prefix, hidden)+ if writeQueryCancellation(w, r, err) {+ return+ }+ if err != nil {+ // Leave the key out rather than claim nothing waits on this issue.+ slog.Warn("list issue dependents failed", append(logger.RequestAttrs(r), "issue_id", uuidToString(issue.ID), "error", err)...)+ } else {+ resp.Blocking = &blocking+ }+// Fetch issue reactions.reactions, err := h.Queries.ListIssueReactions(r.Context(), issue.ID)if writeQueryCancellation(w, r, err) {@@ -4494,6 +4508,9 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {"duplicate_of_issue_id": liveDuplicateMark(issue.Status, issue.DuplicateOfIssueID),"prev_duplicate_of_issue_id": liveDuplicateMark(prevIssue.Status, prevIssue.DuplicateOfIssueID),}+ // The other end of each edge lists this issue under blocking, so clients+ // refresh more than this issue when its blockers change.+ updatedPayload["blockers_changed"] = len(req.BlockedBy)+len(req.RemoveBlockedBy) > 0if handoff != nil {updatedPayload["workflow_handoff"] = workflowHandoffPayload(issue, handoff, h.workflowHandoffBrief(r.Context(), issue, handoff), willRun)}@@ -5373,6 +5390,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {"title_changed": req.Updates.Title != nil && prevIssue.Title != issue.Title,"prev_title": prevIssue.Title,"parent_changed": prevIssue.ParentIssueID != issue.ParentIssueID,+ "blockers_changed": len(req.Updates.BlockedBy)+len(req.Updates.RemoveBlockedBy) > 0,"prev_parent_issue_id": uuidToPtr(prevIssue.ParentIssueID),"prev_status": prevIssue.Status,"duplicate_of_issue_id": liveDuplicateMark(issue.Status, issue.DuplicateOfIssueID),diff --git a/server/internal/handler/issue_blocker.go b/server/internal/handler/issue_blocker.goindex 63a8c8b19f..847a4dd58f 100644--- a/server/internal/handler/issue_blocker.go+++ b/server/internal/handler/issue_blocker.go@@ -101,7 +101,10 @@ func (h *Handler) newIssueBlockerFiller(ctx context.Context, ws pgtype.UUID, idsif !row.Closed.Bool {cache[key].count++}- if row.Private && (accessErr != nil || !hidden.CanSeeProject(row.ProjectID)) {+ // A guest's hidden set also holds ordinary projects and NoProject,+ // so visibility is checked for every row, not only private ones.+ // Without a resolved hidden set nothing is listed; the count stays.+ if accessErr != nil || !hidden.CanSeeProject(row.ProjectID) {continue}cache[key].refs = append(cache[key].refs, IssueBlockerResponse{private: row.Private, projectID: row.ProjectID, IssueRefResponse: IssueRefResponse{ID: uuidToString(row.ID), Identifier: fmt.Sprintf("%s-%d", prefix, row.Number), Title: row.Title, Status: row.Status}, Via: row.Via, Closed: row.Closed.Bool})@@ -119,6 +122,23 @@ func (h *Handler) newIssueBlockerFiller(ctx context.Context, ws pgtype.UUID, ids}}+// issueDependents lists the issues waiting on issue, hiding the ones the+// reader cannot see the same way the blocked_by projection does.+func (h *Handler) issueDependents(ctx context.Context, issue db.Issue, prefix string, hidden projectaccess.Hidden) ([]IssueBlockerResponse, error) {+ rows, err := h.Queries.ListIssueDependents(ctx, db.ListIssueDependentsParams{WorkspaceID: issue.WorkspaceID, IssueID: issue.ID})+ if err != nil {+ return nil, err+ }+ refs := make([]IssueBlockerResponse, 0, len(rows))+ for _, row := range rows {+ if !hidden.CanSeeProject(row.ProjectID) {+ continue+ }+ refs = append(refs, IssueBlockerResponse{private: row.Private, projectID: row.ProjectID, IssueRefResponse: IssueRefResponse{ID: uuidToString(row.ID), Identifier: fmt.Sprintf("%s-%d", prefix, row.Number), Title: row.Title, Status: row.Status}, Via: row.Via, Closed: row.Closed.Bool})+ }+ return refs, nil+}+type blockerViewerKey struct{}func (h *Handler) withBlockerViewer(r *http.Request) *http.Request {diff --git a/server/internal/handler/issue_blocker_test.go b/server/internal/handler/issue_blocker_test.goindex 39f937d5c0..d1688f4189 100644--- a/server/internal/handler/issue_blocker_test.go+++ b/server/internal/handler/issue_blocker_test.go@@ -6,6 +6,7 @@ import ("net/http""strings""testing"+ "time""github.com/google/uuid""github.com/jackc/pgx/v5/pgtype"@@ -233,3 +234,127 @@ func TestIssueBlockerFilterSkipsFinishedIssues(t *testing.T) {}}}++func TestIssueBlockerDetailListsBlocking(t *testing.T) {+ prerequisite := blockerTestIssue(t, map[string]any{"status": "todo"})+ waiting := blockerTestIssue(t, map[string]any{"status": "todo", "blocked_by": []string{prerequisite.ID}})+ parent := blockerTestIssue(t, map[string]any{"status": "todo"})+ earlier := blockerTestIssue(t, map[string]any{"status": "todo", "parent_issue_id": parent.ID, "stage": 1})+ later := blockerTestIssue(t, map[string]any{"status": "todo", "parent_issue_id": parent.ID, "stage": 2})+ detail := func(id string) IssueResponse {+ t.Helper()+ var issue IssueResponse+ req := withURLParam(newRequest("GET", "/api/issues/"+id, nil), "id", id)+ testutil.Call(t, testHandler.GetIssue, req).Want(200).JSON(&issue)+ if issue.Blocking == nil {+ t.Fatalf("detail of %s omitted blocking", id)+ }+ return issue+ }+ if got := *detail(prerequisite.ID).Blocking; len(got) != 1 || got[0].ID != waiting.ID || got[0].Via != "manual" || got[0].Closed {+ t.Fatalf("prerequisite blocking = %+v", got)+ }+ if got := *detail(earlier.ID).Blocking; len(got) != 1 || got[0].ID != later.ID || got[0].Via != "stage" {+ t.Fatalf("earlier stage blocking = %+v", got)+ }+ if got := *detail(waiting.ID).Blocking; len(got) != 0 {+ t.Fatalf("waiting issue blocks %+v", got)+ }+ updateIssueForTest(t, waiting.ID, map[string]any{"status": "done"}).Want(200)+ if got := *detail(prerequisite.ID).Blocking; len(got) != 1 || !got[0].Closed {+ t.Fatalf("finished dependent not marked closed: %+v", got)+ }+ // Lists and broadcasts stay as they were: only the detail read pays for it.+ body := testutil.Call(t, testHandler.ListIssues, newRequest("GET", "/api/issues?workspace_id="+testWorkspaceID+"&limit=100", nil)).Want(200).Text()+ if strings.Contains(body, `"blocking"`) {+ t.Fatal("issue list carried blocking")+ }+}++func TestIssueBlockerBlockingHidesPrivateDependents(t *testing.T) {+ f := newPrivateProjectFixture(t)+ if err := service.AddIssueBlocker(context.Background(), testHandler.Queries, parseUUID(testWorkspaceID), parseUUID(f.secretIssue), parseUUID(f.publicIssue), "member", parseUUID(testUserID)); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { dbfx.Exec(t, "DELETE FROM issue_blocker WHERE issue_id=$1", f.secretIssue) })+ get := func(user string) []IssueBlockerResponse {+ t.Helper()+ var issue IssueResponse+ req := withURLParam(asUser(newRequest("GET", "/api/issues/"+f.publicIssue, nil), user), "id", f.publicIssue)+ testutil.Call(t, testHandler.GetIssue, req).Want(200).JSON(&issue)+ return *issue.Blocking+ }+ if got := get(testUserID); len(got) != 1 || got[0].ID != f.secretIssue {+ t.Fatalf("authorized owner lost the dependent: %+v", got)+ }+ if got := get(f.outsider); len(got) != 0 {+ t.Fatalf("outsider saw a private dependent: %+v", got)+ }+}++func TestIssueBlockerUpdateFlagsBlockersChanged(t *testing.T) {+ a := blockerTestIssue(t, map[string]any{"status": "todo"})+ b := blockerTestIssue(t, map[string]any{"status": "todo"})+ publisher := *testHandler+ publisher.Bus = events.New()+ var changed []bool+ publisher.Bus.Subscribe(protocol.EventIssueUpdated, func(e events.Event) {+ payload, _ := e.Payload.(map[string]any)+ flag, _ := payload["blockers_changed"].(bool)+ changed = append(changed, flag)+ })+ for _, body := range []map[string]any{+ {"blocked_by": []string{a.ID}},+ {"title": "renamed " + uuid.NewString()},+ {"remove_blocked_by": []string{a.ID}},+ } {+ req := withURLParam(newRequest("PUT", "/api/issues/"+b.ID, body), "id", b.ID)+ testutil.Call(t, publisher.UpdateIssue, req).Want(200)+ }+ batch := newRequest("POST", "/api/issues/batch-update?workspace_id="+testWorkspaceID, map[string]any{"issue_ids": []string{b.ID}, "updates": map[string]any{"blocked_by": []string{a.ID}}})+ testutil.Call(t, publisher.BatchUpdateIssues, batch).Want(200)+ if want := []bool{true, false, true, true}; len(changed) != len(want) || changed[0] != want[0] || changed[1] != want[1] || changed[2] != want[2] || changed[3] != want[3] {+ t.Fatalf("blockers_changed = %v, want %v", changed, want)+ }+}++// A guest sees only its own projects, so blocker references to issues in+// other projects or outside any project are hidden in both directions, not+// only references into private projects.+func TestIssueBlockerGuestSeesOnlyItsProjectsReferences(t *testing.T) {+ f := newGuestFixture(t)+ ctx := context.Background()+ ws := parseUUID(testWorkspaceID)+ waiting := dbfx.Issue(t, f.marker+" waiting shared issue", testutil.Cols{"project_id": f.shared, "number": 790000 + int(time.Now().UnixNano()%9000)})+ edges := [][2]string{+ {f.otherIssue, f.sharedIssue}, {f.looseIssue, f.sharedIssue}, // shared blocks two issues the guest can't open+ {waiting, f.otherIssue}, {waiting, f.looseIssue}, // waiting is blocked by them+ }+ for _, e := range edges {+ if err := service.AddIssueBlocker(ctx, testHandler.Queries, ws, parseUUID(e[0]), parseUUID(e[1]), "member", parseUUID(testUserID)); err != nil {+ t.Fatal(err)+ }+ }+ t.Cleanup(func() {+ dbfx.Exec(t, "DELETE FROM issue_blocker WHERE issue_id = ANY($1::uuid[])", []string{f.otherIssue, f.looseIssue, waiting})+ })+ get := func(user, id string) IssueResponse {+ t.Helper()+ var issue IssueResponse+ guestRequest(t, testHandler.GetIssue, user, http.MethodGet, "/api/issues/"+id, nil, "id", id).Want(http.StatusOK).JSON(&issue)+ return issue+ }+ if got := *get(f.guest, f.sharedIssue).Blocking; len(got) != 0 {+ t.Fatalf("guest saw dependents outside its project: %+v", got)+ }+ if got := *get(testUserID, f.sharedIssue).Blocking; len(got) != 2 {+ t.Fatalf("member lost dependents: %+v", got)+ }+ guestView := get(f.guest, waiting)+ if len(guestView.BlockedBy) != 0 || guestView.BlockedCount != 2 {+ t.Fatalf("guest blocked_by projection = %+v (count %d)", guestView.BlockedBy, guestView.BlockedCount)+ }+ if got := get(testUserID, waiting).BlockedBy; len(got) != 2 {+ t.Fatalf("member lost blockers: %+v", got)+ }+}diff --git a/server/pkg/db/generated/issue_blocker.sql.go b/server/pkg/db/generated/issue_blocker.sql.goindex ca7d963728..20d940db71 100644--- a/server/pkg/db/generated/issue_blocker.sql.go+++ b/server/pkg/db/generated/issue_blocker.sql.go@@ -149,6 +149,61 @@ func (q *Queries) ListIssueBlockers(ctx context.Context, arg ListIssueBlockersPareturn items, nil}+const listIssueDependents = `-- name: ListIssueDependents :many+SELECT i.id,i.number,i.title,i.status,i.project_id,COALESCE(p.visibility='private',false)::boolean AS private,b.via,+ (i.status IN ('done','cancelled') OR EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'))) AS closed+FROM effective_issue_blocker b JOIN issue i ON i.id=b.issue_id AND i.workspace_id=b.workspace_id+LEFT JOIN project p ON p.id=i.project_id AND p.workspace_id=i.workspace_id+WHERE b.workspace_id = $1 AND b.blocker_issue_id = $2+ORDER BY b.via,i.number+`++type ListIssueDependentsParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+}++type ListIssueDependentsRow struct {+ ID pgtype.UUID `json:"id"`+ Number int32 `json:"number"`+ Title string `json:"title"`+ Status string `json:"status"`+ ProjectID pgtype.UUID `json:"project_id"`+ Private bool `json:"private"`+ Via string `json:"via"`+ Closed pgtype.Bool `json:"closed"`+}++// The reverse of ListIssueBlockers: the issues that wait on one issue.+func (q *Queries) ListIssueDependents(ctx context.Context, arg ListIssueDependentsParams) ([]ListIssueDependentsRow, error) {+ rows, err := q.db.Query(ctx, listIssueDependents, arg.WorkspaceID, arg.IssueID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListIssueDependentsRow{}+ for rows.Next() {+ var i ListIssueDependentsRow+ if err := rows.Scan(+ &i.ID,+ &i.Number,+ &i.Title,+ &i.Status,+ &i.ProjectID,+ &i.Private,+ &i.Via,+ &i.Closed,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const lockIssueBlockerGraph = `-- name: LockIssueBlockerGraph :execSELECT pg_advisory_xact_lock(hashtextextended('issue-blockers:' || $1::uuid::text,0))`diff --git a/server/pkg/db/queries/issue_blocker.sql b/server/pkg/db/queries/issue_blocker.sqlindex 5f1c995be8..5c04dedfef 100644--- a/server/pkg/db/queries/issue_blocker.sql+++ b/server/pkg/db/queries/issue_blocker.sql@@ -6,6 +6,15 @@ LEFT JOIN project p ON p.id=i.project_id AND p.workspace_id=i.workspace_idWHERE b.workspace_id = sqlc.arg('workspace_id') AND b.issue_id=ANY(sqlc.arg('issue_ids')::uuid[])ORDER BY b.issue_id,b.via,i.number;+-- name: ListIssueDependents :many+-- The reverse of ListIssueBlockers: the issues that wait on one issue.+SELECT i.id,i.number,i.title,i.status,i.project_id,COALESCE(p.visibility='private',false)::boolean AS private,b.via,+ (i.status IN ('done','cancelled') OR EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'))) AS closed+FROM effective_issue_blocker b JOIN issue i ON i.id=b.issue_id AND i.workspace_id=b.workspace_id+LEFT JOIN project p ON p.id=i.project_id AND p.workspace_id=i.workspace_id+WHERE b.workspace_id = sqlc.arg('workspace_id') AND b.blocker_issue_id = sqlc.arg('issue_id')+ORDER BY b.via,i.number;+-- name: HasOpenIssueBlockers :oneSELECT issue_has_open_blockers(sqlc.arg('workspace_id')::uuid,sqlc.arg('issue_id')::uuid)::boolean AS blocked;