Skip to content

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

Go

feat(views): show linked pull requests across issue view layouts (#10351)

Tim2f3afce6c054
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 7bbd7cf1af..a86c46d2a5 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -191,6 +191,7 @@ import type {
IssueEnvironmentAction,
IssueEnvironmentCommand,
StartIssueEnvironmentRequest,
+ IssuePullRequestSummariesResponse,
ListGitHubInstallationsResponse,
ListGitHubRepositoriesResponse,
GitHubConnectResponse,
@@ -509,6 +510,8 @@ import {
EMPTY_ISSUE_ENVIRONMENTS_RESPONSE,
IssueEnvironmentsResponseSchema,
IssueEnvironmentCommandSchema,
+ EMPTY_ISSUE_PULL_REQUEST_SUMMARIES_RESPONSE,
+ IssuePullRequestSummariesResponseSchema,
ResourceLabelsResponseSchema,
EMPTY_LABEL,
EMPTY_LIST_LABELS_RESPONSE,
@@ -5429,6 +5432,17 @@ export class ApiClient {
return parseWithFallback(raw, IssueEnvironmentCommandSchema, fallback, { endpoint: `${init?.method ?? "GET"} ${path.replace(/[0-9a-f-]{36}/g, ":id")}` });
}
+ /** Every linked PR in the workspace, for PR chips on issue cards and rows. */
+ async listIssuePullRequestSummaries(): Promise<IssuePullRequestSummariesResponse> {
+ const raw = await this.fetch<unknown>("/api/issues/pull-requests");
+ return parseWithFallback(
+ raw,
+ IssuePullRequestSummariesResponseSchema,
+ EMPTY_ISSUE_PULL_REQUEST_SUMMARIES_RESPONSE,
+ { endpoint: "GET /api/issues/pull-requests" },
+ );
+ }
+
/** Link a PR the workspace already mirrors, by pasted URL or by id (undo). */
async linkIssuePullRequest(
issueId: string,
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index 6835c0d0d8..75788597c4 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -1130,6 +1130,51 @@ describe("ApiClient schema fallback", () => {
});
});
+ describe("listIssuePullRequestSummaries", () => {
+ it("drops a malformed row instead of blanking every card's PR chips", async () => {
+ stubFetchJson({
+ pull_requests: [
+ {
+ issue_id: "issue-1",
+ id: "pr-1",
+ repo_owner: "acme",
+ repo_name: "widget",
+ number: 1,
+ state: "merged",
+ html_url: "https://github.com/acme/widget/pull/1",
+ },
+ { issue_id: "issue-1", id: "pr-2", number: "two" },
+ ],
+ });
+ const client = new ApiClient("https://api.example.test");
+
+ await expect(client.listIssuePullRequestSummaries()).resolves.toEqual({
+ pull_requests: [
+ {
+ issue_id: "issue-1",
+ id: "pr-1",
+ provider: "github",
+ repo_owner: "acme",
+ repo_name: "widget",
+ number: 1,
+ title: "",
+ state: "merged",
+ html_url: "https://github.com/acme/widget/pull/1",
+ },
+ ],
+ });
+ });
+
+ it("falls back to no PRs when the list is not an array", async () => {
+ stubFetchJson({ pull_requests: "invalid" });
+ const client = new ApiClient("https://api.example.test");
+
+ await expect(client.listIssuePullRequestSummaries()).resolves.toEqual({
+ pull_requests: [],
+ });
+ });
+ });
+
describe("listAutopilotDeliveries", () => {
it("falls back to an empty list when the body is null", async () => {
stubFetchJson(null);
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 4948957266..81ce8287fe 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -59,6 +59,7 @@ import type {
GitHubConnectResponse,
IssuePullRequestsResponse,
IssueEnvironmentsResponse,
+ IssuePullRequestSummariesResponse,
InboxItem,
InboxWorkspaceUnread,
IssueUnread,
@@ -569,6 +570,28 @@ export const EMPTY_ISSUE_ENVIRONMENTS_RESPONSE: IssueEnvironmentsResponse = {
failed_starts: [],
};
+// A malformed row is dropped rather than failing the whole workspace read, so
+// one bad link never blanks the PR chips on every card.
+const IssuePullRequestSummarySchema = z.object({
+ issue_id: z.string(),
+ id: z.string(),
+ provider: z.string().optional().default("github"),
+ repo_owner: z.string(),
+ repo_name: z.string(),
+ number: z.number(),
+ title: z.string().optional().default(""),
+ state: z.string(),
+ html_url: z.string(),
+}).loose();
+
+export const IssuePullRequestSummariesResponseSchema = z.object({
+ pull_requests: lenientArray(IssuePullRequestSummarySchema),
+}).loose();
+
+export const EMPTY_ISSUE_PULL_REQUEST_SUMMARIES_RESPONSE: IssuePullRequestSummariesResponse = {
+ pull_requests: [],
+};
+
// Label responses are consumed by settings tables and resource pickers. Keep
// the resource type lenient so newer server scopes do not break older clients,
// while defaulting fields that predate scoped label catalogs.
diff --git a/packages/core/github/mutations.ts b/packages/core/github/mutations.ts
index 59200b7e32..84efb66fc0 100644
--- a/packages/core/github/mutations.ts
+++ b/packages/core/github/mutations.ts
@@ -11,6 +11,7 @@ function useWritePullRequests(issueId: string) {
const qc = useQueryClient();
return (data: IssuePullRequestsResponse) => {
qc.setQueryData(githubKeys.pullRequests(issueId), data);
+ qc.invalidateQueries({ queryKey: ["github", "pull-requests", "summaries"] });
};
}
diff --git a/packages/core/github/queries.ts b/packages/core/github/queries.ts
index 389104df11..fc5be70cb6 100644
--- a/packages/core/github/queries.ts
+++ b/packages/core/github/queries.ts
@@ -1,5 +1,6 @@
import { infiniteQueryOptions, queryOptions } from "@tanstack/react-query";
import { api } from "../api";
+import type { IssuePullRequestSummary } from "../types";
export const githubKeys = {
all: (wsId: string) => ["github", wsId] as const,
@@ -7,6 +8,9 @@ export const githubKeys = {
repositories: (wsId: string, installationId: string) =>
[...githubKeys.all(wsId), "installations", installationId, "repositories"] as const,
pullRequests: (issueId: string) => ["github", "pull-requests", issueId] as const,
+ /** Under the same prefix as `pullRequests`, so every `pull_request` realtime
+ * event and link/unlink refreshes the issue views' PR chips too. */
+ pullRequestSummaries: (wsId: string) => ["github", "pull-requests", "summaries", wsId] as const,
};
export const githubInstallationsOptions = (wsId: string) =>
@@ -32,6 +36,29 @@ export const githubInstallationRepositoriesOptions = (
enabled: !!wsId && !!installationId,
});
+export type IssuePullRequestSummariesByIssue = Readonly<
+ Record<string, readonly IssuePullRequestSummary[]>
+>;
+
+/**
+ * Every linked PR in the workspace, grouped by issue id (newest first). One
+ * workspace-wide read backs the PR chips on board cards, list rows and table
+ * cells; enable it only while one of those surfaces shows PRs.
+ */
+export const issuePullRequestSummariesOptions = (wsId: string) =>
+ queryOptions({
+ queryKey: githubKeys.pullRequestSummaries(wsId),
+ queryFn: async (): Promise<IssuePullRequestSummariesByIssue> => {
+ const { pull_requests } = await api.listIssuePullRequestSummaries();
+ const byIssue: Record<string, IssuePullRequestSummary[]> = {};
+ for (const pr of pull_requests) {
+ (byIssue[pr.issue_id] ??= []).push(pr);
+ }
+ return byIssue;
+ },
+ enabled: !!wsId,
+ });
+
export const issuePullRequestsOptions = (issueId: string) =>
queryOptions({
queryKey: githubKeys.pullRequests(issueId),
diff --git a/packages/core/issues/stores/view-store-status.test.ts b/packages/core/issues/stores/view-store-status.test.ts
index 2a9b6e68a1..8d82811201 100644
--- a/packages/core/issues/stores/view-store-status.test.ts
+++ b/packages/core/issues/stores/view-store-status.test.ts
@@ -115,6 +115,7 @@ describe("issue view defaults", () => {
project: true,
childProgress: true,
labels: false,
+ pullRequests: false,
});
});
diff --git a/packages/core/issues/stores/view-store.ts b/packages/core/issues/stores/view-store.ts
index eaa3d399bb..0c473e1939 100644
--- a/packages/core/issues/stores/view-store.ts
+++ b/packages/core/issues/stores/view-store.ts
@@ -78,6 +78,7 @@ export type TableSystemColumnKey =
| "created_at"
| "updated_at"
| "child_progress"
+ | "pull_requests"
| "creator";
export type TableColumnKey = TableSystemColumnKey | `property:${string}`;
export interface TableColumnConfig {
@@ -105,6 +106,7 @@ export const TABLE_SYSTEM_COLUMNS: readonly TableSystemColumnKey[] = [
"created_at",
"updated_at",
"child_progress",
+ "pull_requests",
"creator",
];
@@ -134,6 +136,7 @@ export interface CardProperties {
project: boolean;
childProgress: boolean;
labels: boolean;
+ pullRequests: boolean;
}
export interface ActorFilterValue {
@@ -245,6 +248,7 @@ export const CARD_PROPERTY_OPTIONS: { key: keyof CardProperties; label: string }
{ key: "project", label: "Project" },
{ key: "labels", label: "Labels" },
{ key: "childProgress", label: "Sub-issue progress" },
+ { key: "pullRequests", label: "Pull requests" },
];
export const DEFAULT_CARD_PROPERTIES: Readonly<CardProperties> = {
@@ -256,6 +260,7 @@ export const DEFAULT_CARD_PROPERTIES: Readonly<CardProperties> = {
project: true,
childProgress: true,
labels: false,
+ pullRequests: false,
};
export const DEFAULT_HIDDEN_STATUSES: readonly IssueStatus[] = [
diff --git a/packages/core/types/github.ts b/packages/core/types/github.ts
index dc56e4eb89..1d059cf058 100644
--- a/packages/core/types/github.ts
+++ b/packages/core/types/github.ts
@@ -157,6 +157,26 @@ export interface GitHubPullRequest {
changed_files?: number;
}
+/** One issue -> PR link as issue cards, list rows and table cells render it.
+ * The CI / merge snapshot stays on the issue's own PR list. */
+export interface IssuePullRequestSummary {
+ issue_id: string;
+ id: string;
+ provider: string;
+ repo_owner: string;
+ repo_name: string;
+ number: number;
+ title: string;
+ /** Unknown future states are kept as strings; chips fall back to "open". */
+ state: GitHubPullRequestState | (string & {});
+ html_url: string;
+}
+
+export interface IssuePullRequestSummariesResponse {
+ /** Newest first. */
+ pull_requests: IssuePullRequestSummary[];
+}
+
export interface ListGitHubInstallationsResponse {
installations: GitHubInstallation[];
/** Whether the deployment has GitHub App credentials configured. When false, the Connect button is hidden / disabled. */
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 4674d546ff..72e606f3c3 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -231,6 +231,8 @@ export type {
GitHubPullRequestMergeStateStatus,
GitHubPullRequestState,
IssuePullRequestsResponse,
+ IssuePullRequestSummary,
+ IssuePullRequestSummariesResponse,
PRAutoComplete,
PRAutoCompleteState,
PullRequestLinkSource,
diff --git a/packages/views/common/single-row-fit.ts b/packages/views/common/single-row-fit.ts
new file mode 100644
index 0000000000..7135ed7943
--- /dev/null
+++ b/packages/views/common/single-row-fit.ts
@@ -0,0 +1,88 @@
+"use client";
+
+import { useCallback, useLayoutEffect, useRef, useState } from "react";
+
+/**
+ * Fit calculator for a single row of chips that collapses its tail into
+ * a trailing overflow element (e.g. issue PR chips with a "+N" count).
+ *
+ * The caller renders every candidate twice: once for real (slice to
+ * `fitCount`) and once inside a hidden mirror row attached to
+ * `measureRef` (absolutely positioned, `visibility: hidden`, same
+ * classes). Natural widths are read off the mirror, so the fit answer
+ * never depends on what is currently mounted for real — no feedback
+ * loop between measurement and rendering.
+ *
+ * Rule: the longest prefix that fits alongside `reserve` px of trailing
+ * chrome wins. `reserve` must cover everything that is ALWAYS rendered
+ * after the items (triggers, menus) — it is subtracted even when every
+ * item fits, otherwise a row that exactly fits its items clips the
+ * chrome off the end. With `reserveOnOverflow`, the chrome only renders
+ * once something falls out (a "+N" count), so a row whose items all fit
+ * keeps them all.
+ *
+ * Remeasures on container resize (ResizeObserver) and after every
+ * commit (labels/items change the mirror); state only updates when the
+ * answer actually changes, so the extra passes are free.
+ */
+export function useSingleRowFit<E extends HTMLElement = HTMLDivElement>({
+ count,
+ gap,
+ reserve,
+ reserveOnOverflow = false,
+}: {
+ /** Number of candidate items (mirror children must match). */
+ count: number;
+ /** Horizontal gap between items in px (the container's `gap`). */
+ gap: number;
+ /** Width in px to hold back for the overflow trigger. */
+ reserve: number;
+ /** Hold `reserve` back only when not every item fits. */
+ reserveOnOverflow?: boolean;
+}) {
+ const containerRef = useRef<E | null>(null);
+ const measureRef = useRef<E | null>(null);
+ const [fitCount, setFitCount] = useState(count);
+
+ const recompute = useCallback(() => {
+ const container = containerRef.current;
+ const mirror = measureRef.current;
+ if (!container || !mirror) return;
+ const available = container.clientWidth;
+ const widths = Array.from(mirror.children).map(
+ (child) => (child as HTMLElement).offsetWidth,
+ );
+ const natural = widths.reduce((sum, width, i) => sum + width + (i > 0 ? gap : 0), 0);
+ if (reserveOnOverflow && natural <= available) {
+ setFitCount((current) => (current === widths.length ? current : widths.length));
+ return;
+ }
+
+ let used = 0;
+ let next = 0;
+ for (let i = 0; i < widths.length; i++) {
+ const withItem = used + (i > 0 ? gap : 0) + widths[i]!;
+ if (withItem + gap + reserve > available) break;
+ used = withItem;
+ next = i + 1;
+ }
+ setFitCount((current) => (current === next ? current : next));
+ }, [gap, reserve, reserveOnOverflow]);
+
+ // After every commit: the mirror just re-rendered with current labels.
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- deliberate every-commit measure; the setState inside is change-guarded
+ useLayoutEffect(() => {
+ recompute();
+ });
+
+ useLayoutEffect(() => {
+ const container = containerRef.current;
+ if (!container || typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(() => recompute());
+ observer.observe(container);
+ return () => observer.disconnect();
+ }, [recompute]);
+
+ // Never report more than exists (items can shrink between renders).
+ return { containerRef, measureRef, fitCount: Math.min(fitCount, count) };
+}
diff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsx
index 764990da0b..00c7e07776 100644
--- a/packages/views/issues/components/board-card.tsx
+++ b/packages/views/issues/components/board-card.tsx
@@ -30,6 +30,7 @@ import { LabelChip } from "../../labels/label-chip";
import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";
import { CustomStatusChip, useIsCustomStatus } from "./custom-status-chip";
import { IssueDuplicateOfMarker } from "./issue-duplicates";
+import { IssuePullRequestChips, useIssuePullRequestSummaries } from "./pull-request-chips";
import { useIssueSurfaceActionsOptional } from "../surface/actions-context";
import {
PEEK_TARGET_ATTR,
@@ -114,6 +115,8 @@ export const BoardCardContent = memo(function BoardCardContent({
storeProperties.project && cardGrouping !== "project" && project;
const showChildProgress = storeProperties.childProgress && childProgress;
const showLabels = storeProperties.labels && labels.length > 0;
+ const pullRequests = useIssuePullRequestSummaries(issue.id, storeProperties.pullRequests);
+ const showPullRequests = storeProperties.pullRequests && pullRequests.length > 0;
// Keeps the chip row from rendering an empty flex container when the status
// chip is the only thing in it and it decides to render nothing.
const showCustomStatus = useIsCustomStatus(issue.status);
@@ -229,10 +232,10 @@ export const BoardCardContent = memo(function BoardCardContent({
);
})()}
- {/* Chip row: status + project + labels + custom property values.
+ {/* Chip row: status + project + labels + PRs + custom property values.
The status chip renders only for a CUSTOM status — the column header
already names the category. (MUL-6243) */}
- {(showCustomStatus || showProject || showLabels || cardCustomProperties.length > 0) && (
+ {(showCustomStatus || showProject || showLabels || showPullRequests || cardCustomProperties.length > 0) && (
<div className="mt-1.5 flex items-center gap-1.5 flex-wrap">
<CustomStatusChip status={issue.status} />
{showProject && (
@@ -249,6 +252,9 @@ export const BoardCardContent = memo(function BoardCardContent({
+{labels.length - 2}
</span>
)}
+ {showPullRequests && (
+ <IssuePullRequestChips pullRequests={pullRequests} max={2} />
+ )}
{cardCustomProperties.map((property) => (
<span
key={property.id}
diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsx
index 45f039d641..b2453c0bbf 100644
--- a/packages/views/issues/components/issues-header.tsx
+++ b/packages/views/issues/components/issues-header.tsx
@@ -2003,7 +2003,7 @@ export function IssueDisplayControls({
project: "group_project",
assignee: "group_assignee",
};
- const CARD_PROPERTY_LABEL_KEY: Record<typeof CARD_PROPERTY_OPTIONS[number]["key"], "card_priority" | "card_description" | "card_assignee" | "card_start_date" | "card_due_date" | "card_project" | "card_labels" | "card_child_progress"> = {
+ const CARD_PROPERTY_LABEL_KEY: Record<typeof CARD_PROPERTY_OPTIONS[number]["key"], "card_priority" | "card_description" | "card_assignee" | "card_start_date" | "card_due_date" | "card_project" | "card_labels" | "card_child_progress" | "card_pull_requests"> = {
priority: "card_priority",
description: "card_description",
assignee: "card_assignee",
@@ -2012,6 +2012,7 @@ export function IssueDisplayControls({
project: "card_project",
labels: "card_labels",
childProgress: "card_child_progress",
+ pullRequests: "card_pull_requests",
};
const availableCardPropertyOptions = cardPropertyOptionsForView(viewMode);
const availableSortOptions = sortOptionsForView(viewMode, grouping);
diff --git a/packages/views/issues/components/list-row.tsx b/packages/views/issues/components/list-row.tsx
index 507c1d947d..b0eca059fc 100644
--- a/packages/views/issues/components/list-row.tsx
+++ b/packages/views/issues/components/list-row.tsx
@@ -25,6 +25,7 @@ import { LabelChip } from "../../labels/label-chip";
import { CustomStatusChip } from "./custom-status-chip";
import { IssueDuplicateOfMarker } from "./issue-duplicates";
import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";
+import { IssuePullRequestChips, useIssuePullRequestSummaries } from "./pull-request-chips";
import { useIssueSurfaceSelection } from "../surface/selection-context";
import {
PEEKED_ROW_CLASS,
@@ -84,6 +85,8 @@ function ListRowContent({
const showStartDate = storeProperties.startDate && issue.start_date;
const showDueDate = storeProperties.dueDate && issue.due_date;
const showLabels = storeProperties.labels && labels.length > 0;
+ const pullRequests = useIssuePullRequestSummaries(issue.id, storeProperties.pullRequests);
+ const showPullRequests = storeProperties.pullRequests && pullRequests.length > 0;
return (
<IssueActionsContextMenu issue={issue}>
@@ -147,6 +150,14 @@ function ListRowContent({
</span>
</span>
)}
+ {showPullRequests && (
+ // Capped so a long PR set never squeezes the title away.
+ <IssuePullRequestChips
+ pullRequests={pullRequests}
+ max={2}
+ className="max-w-[40%]"
+ />
+ )}
{showLabels && (
<span className="ml-1.5 hidden md:inline-flex shrink-0 items-center gap-1 max-w-[260px] overflow-hidden">
{labels.slice(0, 3).map((label) => (
diff --git a/packages/views/issues/components/pull-request-chips.test.tsx b/packages/views/issues/components/pull-request-chips.test.tsx
new file mode 100644
index 0000000000..15fc248826
--- /dev/null
+++ b/packages/views/issues/components/pull-request-chips.test.tsx
@@ -0,0 +1,100 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { I18nProvider } from "@multica/core/i18n/react";
+import type { IssuePullRequestSummary } from "@multica/core/types";
+import enCommon from "../../locales/en/common.json";
+import enIssues from "../../locales/en/issues.json";
+
+const TEST_RESOURCES = { en: { common: enCommon, issues: enIssues } };
+
+const apiMock = vi.hoisted(() => ({
+ listIssuePullRequestSummaries: vi.fn(),
+}));
+vi.mock("@multica/core/api", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/api")>()),
+ api: apiMock,
+}));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+
+import { IssuePullRequestChips, useIssuePullRequestSummaries } from "./pull-request-chips";
+
+function summary(overrides: Partial<IssuePullRequestSummary>): IssuePullRequestSummary {
+ return {
+ issue_id: "issue-1",
+ id: "pr-1",
+ provider: "github",
+ repo_owner: "acme",
+ repo_name: "widget",
+ number: 1,
+ title: "Fix the widget",
+ state: "open",
+ html_url: "https://github.com/acme/widget/pull/1",
+ ...overrides,
+ };
+}
+
+function Chips({ enabled, linked = false }: { enabled: boolean; linked?: boolean }) {
+ const pullRequests = useIssuePullRequestSummaries("issue-1", enabled);
+ return <IssuePullRequestChips pullRequests={pullRequests} max={2} linked={linked} />;
+}
+
+function renderChips(props: { enabled: boolean; linked?: boolean }, onRowClick = vi.fn()) {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return render(
+ <QueryClientProvider client={qc}>
+ <I18nProvider resources={TEST_RESOURCES} locale="en">
+ <div onClick={onRowClick}>
+ <Chips {...props} />
+ </div>
+ </I18nProvider>
+ </QueryClientProvider>,
+ );
+}
+
+describe("issue pull request chips", () => {
+ beforeEach(() => {
+ apiMock.listIssuePullRequestSummaries.mockReset();
+ // jsdom has no layout; only count capping is exercised here.
+ vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(1000);
+ vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(60);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("does not request PRs while the display option is off", () => {
+ renderChips({ enabled: false });
+ expect(apiMock.listIssuePullRequestSummaries).not.toHaveBeenCalled();
+ expect(screen.queryByTestId("issue-pull-request-chip")).not.toBeInTheDocument();
+ });
+
+ it("shows linked PRs for this issue with states and overflow without opening the row", async () => {
+ apiMock.listIssuePullRequestSummaries.mockResolvedValue({
+ pull_requests: [
+ summary({
+ id: "pr-3",
+ number: 3,
+ state: "merged",
+ html_url: "https://github.com/acme/widget/pull/3",
+ }),
+ summary({ id: "pr-2", number: 2, state: "draft", repo_name: "api" }),
+ summary({ id: "pr-1", number: 1 }),
+ summary({ id: "pr-9", issue_id: "issue-2", number: 9 }),
+ ],
+ });
+ const onRowClick = vi.fn();
+ renderChips({ enabled: true, linked: true }, onRowClick);
+
+ const chips = await screen.findAllByTestId("issue-pull-request-chip");
+ expect(chips.map((chip) => chip.textContent)).toEqual(["Mergedwidget#3", "Draftapi#2"]);
+ const mergedLink = screen.getByRole("link", { name: /Merged/ });
+ expect(mergedLink).toHaveAttribute("href", "https://github.com/acme/widget/pull/3");
+ expect(mergedLink).toHaveAttribute("target", "_blank");
+ fireEvent.click(mergedLink);
+ expect(onRowClick).not.toHaveBeenCalled();
+ expect(screen.getByText("+1")).toBeInTheDocument();
+ expect(screen.queryByText(/#9/)).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/issues/components/pull-request-chips.tsx b/packages/views/issues/components/pull-request-chips.tsx
new file mode 100644
index 0000000000..dcb5ee0809
--- /dev/null
+++ b/packages/views/issues/components/pull-request-chips.tsx
@@ -0,0 +1,193 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+import {
+ GitMerge,
+ GitPullRequest,
+ GitPullRequestArrow,
+ GitPullRequestClosed,
+ GitPullRequestDraft,
+} from "@multica/ui/icons";
+import { issuePullRequestSummariesOptions } from "@multica/core/github";
+import { useWorkspaceId } from "@multica/core/hooks";
+import type { GitHubPullRequestState, IssuePullRequestSummary } from "@multica/core/types";
+import { cn } from "@multica/ui/lib/utils";
+import { useSingleRowFit } from "../../common/single-row-fit";
+import { useT } from "../../i18n";
+
+export const PULL_REQUEST_STATE_ICON: Record<
+ GitHubPullRequestState,
+ { icon: React.ComponentType<{ className?: string }>; className: string }
+> = {
+ open: { icon: GitPullRequestArrow, className: "text-emerald-600 dark:text-emerald-400" },
+ draft: { icon: GitPullRequestDraft, className: "text-muted-foreground" },
+ merged: { icon: GitMerge, className: "text-violet-600 dark:text-violet-400" },
+ closed: { icon: GitPullRequestClosed, className: "text-rose-600 dark:text-rose-400" },
+};
+
+const EMPTY: readonly IssuePullRequestSummary[] = [];
+
+/**
+ * The issue's linked PRs, newest first, from the one workspace-wide summary
+ * read. Disabled callers never start that request.
+ */
+export function useIssuePullRequestSummaries(
+ issueId: string,
+ enabled: boolean,
+): readonly IssuePullRequestSummary[] {
+ const wsId = useWorkspaceId();
+ const { data } = useQuery({
+ ...issuePullRequestSummariesOptions(wsId),
+ enabled: enabled && !!wsId,
+ select: (byIssue) => byIssue[issueId] ?? EMPTY,
+ });
+ return enabled ? (data ?? EMPTY) : EMPTY;
+}
+
+function isKnownState(state: string): state is GitHubPullRequestState {
+ return state in PULL_REQUEST_STATE_ICON;
+}
+
+const CHIP_GAP = 4;
+// Room for "+N" (up to "+99" at text-micro) beside the chips that fit.
+const OVERFLOW_RESERVE = 24;
+
+/**
+ * Compact "state icon + #number" chips for issue cards, rows and table cells.
+ * Board cards and list rows sit inside the issue link, so their chips stay
+ * plain text; the table cell has no wrapping link and opens the PR instead.
+ *
+ * The group fits whatever width its slot gives it: the newest PRs that fit at
+ * their natural width are shown and "+N" counts every PR that is not. At
+ * least one chip always shows; squeezed further, its repo name truncates
+ * while the number stays whole.
+ */
+export function IssuePullRequestChips({
+ pullRequests,
+ max,
+ linked = false,
+ className,
+}: {
+ pullRequests: readonly IssuePullRequestSummary[];
+ /** Most chips to show even when more would fit. */
+ max: number;
+ /** Render each chip as a link to the PR. Never inside another link. */
+ linked?: boolean;
+ className?: string;
+}) {
+ const { t } = useT("issues");
+ const candidates = pullRequests.slice(0, max);
+ const { containerRef, measureRef, fitCount } = useSingleRowFit<HTMLSpanElement>({
+ count: candidates.length,
+ gap: CHIP_GAP,
+ reserve: OVERFLOW_RESERVE,
+ // Past `max`, "+N" always shows, so its room is always held back.
+ reserveOnOverflow: candidates.length === pullRequests.length,
+ });
+ if (pullRequests.length === 0) return null;
+ const visible = candidates.slice(0, Math.max(1, fitCount));
+ const hidden = pullRequests.length - visible.length;
+ // The repo name only tells chips apart when the PRs span repos.
+ const showRepo =
+ new Set(pullRequests.map((pr) => `${pr.repo_owner}/${pr.repo_name}`)).size > 1;
+
+ const stateLabel = (state: string) => {
+ switch (state) {
+ case "merged":
+ return t(($) => $.detail.pull_request_state_merged);
+ case "closed":
+ return t(($) => $.detail.pull_request_state_closed);
+ case "draft":
+ return t(($) => $.detail.pull_request_state_draft);
+ default:
+ return t(($) => $.detail.pull_request_state_open);
+ }
+ };
+
+ const chipClass =
+ "inline-flex min-w-0 max-w-[140px] items-center gap-1 rounded-full bg-muted/60 px-1.5 py-0.5 text-micro text-muted-foreground tabular-nums";
+ const chipContent = (pr: IssuePullRequestSummary, label: string) => {
+ const cfg = isKnownState(pr.state)
+ ? PULL_REQUEST_STATE_ICON[pr.state]
+ : { icon: GitPullRequest, className: "" };
+ const Icon = cfg.icon;
+ return (
+ <>
+ <Icon aria-hidden className={cn("size-3 shrink-0", cfg.className)} />
+ <span className="sr-only">{label}</span>
+ {/* "repo#n" reads as one token; squeezed, the repo name truncates. */}
+ <span className="flex min-w-0">
+ {showRepo ? <span className="min-w-0 truncate">{pr.repo_name}</span> : null}
+ <span data-testid="issue-pull-request-number" className="shrink-0">#{pr.number}</span>
+ </span>
+ </>
+ );
+ };
+
+ // The grid sizes the group from the mirror's natural width (capped by the
+ // slot), never from the chips currently shown — otherwise a group that
+ // dropped a chip could never grow wide enough to bring it back.
+ return (
+ <span
+ data-testid="issue-pull-request-chips"
+ className={cn("inline-grid min-w-0 max-w-full", className)}
+ >
+ <span
+ ref={containerRef}
+ className="flex min-w-0 items-center gap-1 overflow-hidden"
+ >
+ {visible.map((pr) => {
+ const label = stateLabel(pr.state);
+ const title = `${pr.repo_owner}/${pr.repo_name}#${pr.number} · ${label}${pr.title ? `\n${pr.title}` : ""}`;
+ return linked ? (
+ <a
+ key={pr.id}
+ href={pr.html_url}
+ target="_blank"
+ rel="noreferrer noopener"
+ title={title}
+ data-testid="issue-pull-request-chip"
+ className={cn(chipClass, "hover:bg-accent hover:text-foreground")}
+ onClick={(event) => event.stopPropagation()}
+ onAuxClick={(event) => event.stopPropagation()}
+ >
+ {chipContent(pr, label)}
+ </a>
+ ) : (
+ <span
+ key={pr.id}
+ title={title}
+ data-testid="issue-pull-request-chip"
+ className={chipClass}
+ >
+ {chipContent(pr, label)}
+ </span>
+ );
+ })}
+ {hidden > 0 && (
+ <span
+ data-testid="issue-pull-request-overflow"
+ className="shrink-0 text-micro text-muted-foreground tabular-nums"
+ >
+ +{hidden}
+ </span>
+ )}
+ </span>
+ {/* Measurement mirror: every candidate at natural width, no height. */}
+ <span
+ ref={measureRef}
+ aria-hidden
+ className={cn(
+ "pointer-events-none invisible flex h-0 gap-1 overflow-hidden",
+ candidates.length < pullRequests.length && "pr-7",
+ )}
+ >
+ {candidates.map((pr) => (
+ <span key={pr.id} className={cn(chipClass, "shrink-0")}>
+ {chipContent(pr, "")}
+ </span>
+ ))}
+ </span>
+ </span>
+ );
+}
diff --git a/packages/views/issues/components/pull-request-list.tsx b/packages/views/issues/components/pull-request-list.tsx
index 875f6499c1..b71449c97e 100644
--- a/packages/views/issues/components/pull-request-list.tsx
+++ b/packages/views/issues/components/pull-request-list.tsx
@@ -14,7 +14,6 @@ import {
MoreHorizontal,
Unlink,
GitPullRequest,
- GitPullRequestArrow,
GitPullRequestClosed,
GitPullRequestDraft,
TriangleAlert,
@@ -35,7 +34,6 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import type {
GitHubPullRequest,
- GitHubPullRequestState,
PRAutoComplete,
} from "@multica/core/types";
import { IconButton } from "@multica/ui/components/common/icon-button";
@@ -52,6 +50,7 @@ import { cn } from "@multica/ui/lib/utils";
import { useT, useTimeAgo } from "../../i18n";
import { useStatusLabel } from "../utils/status-label";
import { StatusIcon } from "./status-icon";
+import { PULL_REQUEST_STATE_ICON } from "./pull-request-chips";
type IssuesT = ReturnType<typeof useT<"issues">>["t"];
@@ -60,16 +59,6 @@ type IssuesT = ReturnType<typeof useT<"issues">>["t"];
// collapse the rest once the section reaches 4 rows.
const PR_LIMIT_BEFORE_COLLAPSE = 4;
-const STATE_ICON: Record<
- GitHubPullRequestState,
- { icon: React.ComponentType<{ className?: string }>; className: string }
-> = {
- open: { icon: GitPullRequestArrow, className: "text-emerald-600 dark:text-emerald-400" },
- draft: { icon: GitPullRequestDraft, className: "text-muted-foreground" },
- merged: { icon: GitMerge, className: "text-violet-600 dark:text-violet-400" },
- closed: { icon: GitPullRequestClosed, className: "text-rose-600 dark:text-rose-400" },
-};
-
export function PullRequestList({
issueId,
identifier = "",
@@ -393,7 +382,7 @@ function PullRequestRow({
}) {
const { t } = useT("issues");
const timeAgo = useTimeAgo();
- const cfg = STATE_ICON[pr.state] ?? { icon: GitPullRequest, className: "" };
+ const cfg = PULL_REQUEST_STATE_ICON[pr.state] ?? { icon: GitPullRequest, className: "" };
const StateIcon = cfg.icon;
const verdict = derivePullRequestVerdict(pr);
const pill = getVerdictPill(verdict, t);
@@ -498,7 +487,7 @@ function PullRequestRow({
*/
export function PullRequestInlineSummary({ pr }: { pr: GitHubPullRequest }) {
const { t } = useT("issues");
- const cfg = STATE_ICON[pr.state] ?? { icon: GitPullRequest, className: "" };
+ const cfg = PULL_REQUEST_STATE_ICON[pr.state] ?? { icon: GitPullRequest, className: "" };
const StateIcon = cfg.icon;
const pill = getVerdictPill(derivePullRequestVerdict(pr), t);
const isTerminal = pr.state === "merged" || pr.state === "closed";
diff --git a/packages/views/issues/components/table-view-model.ts b/packages/views/issues/components/table-view-model.ts
index 3285ef9f06..f414fff044 100644
--- a/packages/views/issues/components/table-view-model.ts
+++ b/packages/views/issues/components/table-view-model.ts
@@ -118,6 +118,7 @@ function columnValue(
case "updated_at":
return issue.updated_at;
case "child_progress":
+ case "pull_requests":
return undefined;
case "creator":
return issue.creator_id;
diff --git a/packages/views/issues/components/table-view.tsx b/packages/views/issues/components/table-view.tsx
index f68a8b166f..bada60ad50 100644
--- a/packages/views/issues/components/table-view.tsx
+++ b/packages/views/issues/components/table-view.tsx
@@ -166,6 +166,8 @@ import type { ChildProgress } from "./list-row";
import { ListLoadMoreFooter } from "./list-load-more-footer";
import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";
import { IssueDuplicateOfMarker } from "./issue-duplicates";
+import { IssuePullRequestChips, useIssuePullRequestSummaries } from "./pull-request-chips";
+import { issuePullRequestSummariesOptions } from "@multica/core/github";
// Enough placeholder rows to cover a typical viewport; the virtualizer only
// mounts what fits, so overshooting costs nothing.
@@ -299,6 +301,7 @@ type ColumnLabelKey =
| "created_at"
| "updated_at"
| "child_progress"
+ | "pull_requests"
| "creator";
const SORTABLE_COLUMNS: Partial<Record<TableSystemColumnKey, SortField>> = {
@@ -1306,6 +1309,8 @@ function IssueTableBodyCell({
<span className="text-muted-foreground">{t(($) => $.table.empty_value)}</span>
);
}
+ case "pull_requests":
+ return <PullRequestsCell issueId={issue.id} />;
case "creator":
return (
<span className="flex min-w-0 items-center gap-1.5">
@@ -1323,6 +1328,16 @@ function IssueTableBodyCell({
return null;
}
+function PullRequestsCell({ issueId }: { issueId: string }) {
+ const { t } = useT("issues");
+ const pullRequests = useIssuePullRequestSummaries(issueId, true);
+ return pullRequests.length > 0 ? (
+ <IssuePullRequestChips pullRequests={pullRequests} max={3} linked />
+ ) : (
+ <span className="text-muted-foreground">{t(($) => $.table.empty_value)}</span>
+ );
+}
+
export function TableView({
serverQuery,
childProgressMap,
@@ -2271,6 +2286,9 @@ export function TableView({
cell: IssueTableBodyCell,
};
if (config.width !== undefined) definition.size = config.width;
+ // Room for three "#123" chips before the overflow count; the 150px
+ // default clips the second repo-prefixed chip mid-number.
+ else if (config.key === "pull_requests") definition.size = 200;
return definition;
}),
{
@@ -2363,7 +2381,7 @@ export function TableView({
const property = propertyId ? exportPropertyById.get(propertyId) : undefined;
return property ? isActorPropertyType(property.type) : false;
});
- const [rows, exportLookups, exportActorName] = await Promise.all([
+ const [rows, exportLookups, exportActorName, exportPullRequests] = await Promise.all([
mode === "all" ? exportIssues() : Promise.resolve(selectedIssues),
resolveExportLookups({
projects: csvColumns.some((column) => column.key === "project"),
@@ -2380,6 +2398,9 @@ export function TableView({
buildActorNameResolver({ members, agents, squads }),
)
: Promise.resolve(getActorName),
+ csvColumns.some((column) => column.key === "pull_requests")
+ ? queryClient.fetchQuery(issuePullRequestSummariesOptions(wsId))
+ : Promise.resolve(null),
]);
const headers = csvColumns.map((column) => {
const propertyId = propertyIdFromViewKey(column.key);
@@ -2428,6 +2449,10 @@ export function TableView({
const progress = exportLookups.childProgressMap.get(issue.id);
return progress ? `${progress.done}/${progress.total}` : "";
}
+ case "pull_requests":
+ return (exportPullRequests?.[issue.id] ?? [])
+ .map((pr) => pr.html_url)
+ .join(", ");
case "creator":
return exportActorName(issue.creator_type, issue.creator_id);
}
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 73759befb8..1e929212d8 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -322,6 +322,7 @@
"card_project": "Project",
"card_labels": "Labels",
"card_child_progress": "Sub-issue progress",
+ "card_pull_requests": "Pull requests",
"show_sub_issues": "Show sub-issues",
"layout_options": "{{layout}} options"
},
@@ -393,6 +394,7 @@
"created_at": "Created",
"updated_at": "Updated",
"child_progress": "Sub-issue progress",
+ "pull_requests": "Pull requests",
"creator": "Created by"
},
"calculation": {
@@ -518,6 +520,7 @@
"quick_action_blocked_body": "“{{name}}” runs as an agent you’re not allowed to trigger. Ask a workspace admin to make that agent available to the team, or to point this action at a shared one.",
"quick_action_blocked_ok": "Got it",
"pull_requests_loading": "Loading…",
+ "pull_request_state_open": "Open",
"pull_request_state_draft": "Draft",
"pull_request_state_merged": "Merged",
"pull_request_state_closed": "Closed",
diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.json
index 8e14bda512..362dae6309 100644
--- a/packages/views/locales/es/issues.json
+++ b/packages/views/locales/es/issues.json
@@ -309,6 +309,7 @@
"card_project": "Proyecto",
"card_labels": "Etiquetas",
"card_child_progress": "Progreso de subtareas",
+ "card_pull_requests": "Pull requests",
"show_sub_issues": "Mostrar subtareas",
"columns_section": "Columnas",
"columns_locked_by_filter": "Quita el filtro de estado para mostrar u ocultar columnas.",
@@ -383,6 +384,7 @@
"created_at": "Creada",
"updated_at": "Actualizada",
"child_progress": "Progreso de subtareas",
+ "pull_requests": "Pull requests",
"creator": "Creada por"
},
"calculation": {
@@ -490,6 +492,7 @@
"quick_action_blocked_body": "\"{{name}}\" se ejecuta como un agente que no tienes permiso para activar. Pide a un administrador del espacio de trabajo que ponga ese agente a disposición del equipo o que dirija esta acción a uno compartido.",
"quick_action_blocked_ok": "Entendido",
"pull_requests_loading": "Cargando…",
+ "pull_request_state_open": "Abierto",
"pull_request_state_draft": "Borrador",
"pull_request_state_merged": "Fusionado",
"pull_request_state_closed": "Cerrado",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index 1d6325a105..0cebeff3ba 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -322,6 +322,7 @@
"card_project": "Projet",
"card_labels": "Étiquettes",
"card_child_progress": "Avancement des sous-tâches",
+ "card_pull_requests": "Pull requests",
"show_sub_issues": "Afficher les sous-tâches",
"layout_options": "Options de la vue {{layout}}"
},
@@ -393,6 +394,7 @@
"created_at": "Création",
"updated_at": "Mise à jour",
"child_progress": "Avancement des sous-tâches",
+ "pull_requests": "Pull requests",
"creator": "Créé par"
},
"calculation": {
@@ -518,6 +520,7 @@
"quick_action_blocked_body": "« {{name}} » s'exécute sous un agent que vous n'êtes pas autorisé à déclencher. Demandez à un administrateur de l'espace de travail de rendre cet agent accessible à l'équipe, ou de rattacher cette action à un agent partagé.",
"quick_action_blocked_ok": "Compris",
"pull_requests_loading": "Chargement…",
+ "pull_request_state_open": "Ouverte",
"pull_request_state_draft": "Brouillon",
"pull_request_state_merged": "Fusionnée",
"pull_request_state_closed": "Fermée",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 4262ff1edf..1ad5104c35 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -316,6 +316,7 @@
"card_project": "プロジェクト",
"card_labels": "ラベル",
"card_child_progress": "サブタスクの進捗",
+ "card_pull_requests": "Pull requests",
"show_sub_issues": "サブタスクを表示",
"layout_options": "{{layout}}のオプション"
},
@@ -387,6 +388,7 @@
"created_at": "作成日",
"updated_at": "更新日",
"child_progress": "サブタスクの進捗",
+ "pull_requests": "Pull requests",
"creator": "作成者"
},
"calculation": {
@@ -511,6 +513,7 @@
"quick_action_blocked_body": "「{{name}}」は、あなたが実行を許可されていないエージェントで動作します。ワークスペース管理者にそのエージェントをチームへ公開してもらうか、共有エージェントへの変更を依頼してください。",
"quick_action_blocked_ok": "了解",
"pull_requests_loading": "読み込み中...",
+ "pull_request_state_open": "オープン",
"pull_request_state_draft": "ドラフト",
"pull_request_state_merged": "マージ済み",
"pull_request_state_closed": "クローズ",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 0a50dfa20a..0568bdb9c3 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -316,6 +316,7 @@
"card_project": "프로젝트",
"card_labels": "라벨",
"card_child_progress": "하위 태스크 진행률",
+ "card_pull_requests": "Pull requests",
"show_sub_issues": "하위 태스크 표시",
"layout_options": "{{layout}} 옵션"
},
@@ -387,6 +388,7 @@
"created_at": "생성일",
"updated_at": "수정일",
"child_progress": "하위 태스크 진행률",
+ "pull_requests": "Pull requests",
"creator": "작성자"
},
"calculation": {
@@ -511,6 +513,7 @@
"quick_action_blocked_body": "“{{name}}”은(는) 트리거 권한이 없는 에이전트로 실행됩니다. 워크스페이스 관리자에게 해당 에이전트를 팀에 공개하거나 공유 에이전트로 변경해 달라고 요청하세요.",
"quick_action_blocked_ok": "확인",
"pull_requests_loading": "불러오는 중...",
+ "pull_request_state_open": "열림",
"pull_request_state_draft": "초안",
"pull_request_state_merged": "병합됨",
"pull_request_state_closed": "닫힘",
diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.json
index 04e12f6052..35c63fcef0 100644
--- a/packages/views/locales/ru/issues.json
+++ b/packages/views/locales/ru/issues.json
@@ -333,6 +333,7 @@
"card_project": "Проект",
"card_labels": "Метки",
"card_child_progress": "Прогресс подзадач",
+ "card_pull_requests": "Pull request'ы",
"show_sub_issues": "Показывать подзадачи",
"layout_options": "Настройки вида «{{layout}}»"
},
@@ -404,6 +405,7 @@
"created_at": "Создано",
"updated_at": "Обновлено",
"child_progress": "Прогресс подзадач",
+ "pull_requests": "Pull request'ы",
"creator": "Автор"
},
"calculation": {
@@ -528,6 +530,7 @@
"quick_action_blocked_body": "«{{name}}» выполняется от имени агента, которого вам не разрешено запускать. Попросите администратора рабочего пространства сделать этого агента доступным команде или направить это действие на общего агента.",
"quick_action_blocked_ok": "Понятно",
"pull_requests_loading": "Загрузка…",
+ "pull_request_state_open": "Открыт",
"pull_request_state_draft": "Черновик",
"pull_request_state_merged": "Смёрджен",
"pull_request_state_closed": "Закрыт",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 8446c866d4..14a783d5a2 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -316,6 +316,7 @@
"card_project": "项目",
"card_labels": "标签",
"card_child_progress": "子任务进度",
+ "card_pull_requests": "Pull Request",
"show_sub_issues": "显示子任务",
"layout_options": "{{layout}}选项"
},
@@ -387,6 +388,7 @@
"created_at": "创建时间",
"updated_at": "更新时间",
"child_progress": "子任务进度",
+ "pull_requests": "Pull Request",
"creator": "创建者"
},
"calculation": {
@@ -511,6 +513,7 @@
"quick_action_blocked_body": "\"{{name}}\"由一个你无权触发的智能体执行。可以请工作区管理员把该智能体开放给团队,或把这条操作改绑一个共享的智能体。",
"quick_action_blocked_ok": "知道了",
"pull_requests_loading": "加载中...",
+ "pull_request_state_open": "Open",
"pull_request_state_draft": "Draft",
"pull_request_state_merged": "Merged",
"pull_request_state_closed": "Closed",
diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.json
index b02a7ad8b6..cbe5d09b11 100644
--- a/packages/views/locales/zh-Hant/issues.json
+++ b/packages/views/locales/zh-Hant/issues.json
@@ -316,6 +316,7 @@
"card_project": "專案",
"card_labels": "標籤",
"card_child_progress": "子任務進度",
+ "card_pull_requests": "Pull Request",
"show_sub_issues": "顯示子任務",
"layout_options": "{{layout}}選項"
},
@@ -387,6 +388,7 @@
"created_at": "建立時間",
"updated_at": "更新時間",
"child_progress": "子任務進度",
+ "pull_requests": "Pull Request",
"creator": "建立者"
},
"calculation": {
@@ -511,6 +513,7 @@
"quick_action_blocked_body": "\"{{name}}\"由一個你無權觸發的 AI 代理執行。可以請工作區管理員把該 AI 代理開放給團隊,或把這條操作改綁一個共享的 AI 代理。",
"quick_action_blocked_ok": "知道了",
"pull_requests_loading": "載入中...",
+ "pull_request_state_open": "Open",
"pull_request_state_draft": "Draft",
"pull_request_state_merged": "Merged",
"pull_request_state_closed": "Closed",
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 57a54485ae..5bfab42058 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -2130,6 +2130,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/table/facets", h.ListIssueTableFacets)
r.Get("/search", h.SearchIssues)
r.Get("/child-progress", h.ChildIssueProgress)
+ r.Get("/pull-requests", h.ListIssuePullRequestSummaries)
r.Get("/children", h.ListChildrenByParents)
r.Get("/grouped", h.ListGroupedIssues)
// The caller's issues with an agent result they have not seen
diff --git a/server/internal/handler/github.go b/server/internal/handler/github.go
index da018f385f..e70c97a58b 100644
--- a/server/internal/handler/github.go
+++ b/server/internal/handler/github.go
@@ -1135,6 +1135,64 @@ func (h *Handler) ListPullRequestsForIssue(w http.ResponseWriter, r *http.Reques
})
}
+// ── Linked PR summaries for issue views ─────────────────────────────────────
+
+// IssuePullRequestSummaryResponse is one issue -> PR link as an issue card,
+// list row or table cell renders it: enough for a state icon, "#number", and
+// a title tooltip. The CI / mergeability snapshot stays on the per-issue list.
+type IssuePullRequestSummaryResponse struct {
+ IssueID string `json:"issue_id"`
+ ID string `json:"id"`
+ Provider string `json:"provider"`
+ RepoOwner string `json:"repo_owner"`
+ RepoName string `json:"repo_name"`
+ Number int32 `json:"number"`
+ Title string `json:"title"`
+ State string `json:"state"`
+ HtmlURL string `json:"html_url"`
+}
+
+// ListIssuePullRequestSummaries returns every linked PR in the workspace,
+// GitHub and self-hosted providers together, newest first. Like child-progress
+// it is one workspace-wide read so board / list / table views never fetch PRs
+// per issue.
+func (h *Handler) ListIssuePullRequestSummaries(w http.ResponseWriter, r *http.Request) {
+ wsID := h.resolveWorkspaceID(r)
+ wsUUID, ok := parseUUIDOrBadRequest(w, wsID, "workspace_id")
+ if !ok {
+ return
+ }
+ hidden, ok := h.requestHiddenProjects(w, r, wsID)
+ if !ok {
+ return
+ }
+ rows, err := h.Queries.ListIssuePullRequestSummaries(r.Context(), db.ListIssuePullRequestSummariesParams{
+ WorkspaceID: wsUUID,
+ HiddenProjectIds: hidden.Param(),
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list pull requests")
+ return
+ }
+ out := make([]IssuePullRequestSummaryResponse, 0, len(rows))
+ for _, row := range rows {
+ out = append(out, IssuePullRequestSummaryResponse{
+ IssueID: uuidToString(row.IssueID),
+ ID: uuidToString(row.ID),
+ Provider: row.Provider,
+ RepoOwner: row.RepoOwner,
+ RepoName: row.RepoName,
+ Number: row.PrNumber,
+ Title: row.Title,
+ State: row.State,
+ HtmlURL: row.HtmlUrl,
+ })
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "pull_requests": out,
+ })
+}
+
// broadcastPRSnapshotApplied is the ghsnapshot pipeline's onApplied callback:
// once an API snapshot is written to a PR row, re-broadcast the PR so every
// open issue detail page re-queries its PR list and picks up the fresh CI /
diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.go
index 1cc28f9c68..b203ad6cc8 100644
--- a/server/internal/handler/github_test.go
+++ b/server/internal/handler/github_test.go
@@ -1423,6 +1423,57 @@ func TestLinkIssuePullRequest_ByURL(t *testing.T) {
}
}
+// TestListIssuePullRequestSummaries: the workspace-wide read behind the issue
+// views' "Pull requests" display option returns each linked PR under its
+// issue, and drops a PR once it is unlinked.
+func TestListIssuePullRequestSummaries(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("handler test fixture not initialized (no DB?)")
+ }
+ secret := "pr-summaries-secret"
+ t.Setenv("GITHUB_WEBHOOK_SECRET", secret)
+ const installationID int64 = 30264009
+ created := prAutoCompleteTestIssue(t, "pr summaries", installationID)
+
+ firePRWebhook(t, secret, installationID, 61, created.Identifier+": first", "", "fix/first", "opened")
+ firePRWebhook(t, secret, installationID, 62, created.Identifier+": second", "", "fix/second", "merged")
+
+ summaries := func() map[int32]IssuePullRequestSummaryResponse {
+ t.Helper()
+ req := newRequest("GET", "/api/issues/pull-requests?workspace_id="+testWorkspaceID, nil)
+ w := testutil.Call(t, testHandler.ListIssuePullRequestSummaries, req).Want(http.StatusOK)
+ var body struct {
+ PullRequests []IssuePullRequestSummaryResponse `json:"pull_requests"`
+ }
+ if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
+ t.Fatalf("decode summaries: %v", err)
+ }
+ out := map[int32]IssuePullRequestSummaryResponse{}
+ for _, pr := range body.PullRequests {
+ if pr.IssueID == created.ID {
+ out[pr.Number] = pr
+ }
+ }
+ return out
+ }
+
+ got := summaries()
+ if len(got) != 2 {
+ t.Fatalf("summaries for issue = %+v, want #61 and #62", got)
+ }
+ if pr := got[61]; pr.State != "open" || pr.Provider != "github" || pr.RepoName != "widget" || pr.HtmlURL == "" {
+ t.Errorf("#61 = %+v, want an open github PR on widget with a URL", pr)
+ }
+ if pr := got[62]; pr.State != "merged" {
+ t.Errorf("#62 state = %q, want merged", pr.State)
+ }
+
+ unlinkPRForTest(t, created.ID, githubPRIDForTest(t, "widget", 61))
+ if got := summaries(); len(got) != 1 || got[62].Number != 62 {
+ t.Errorf("after unlinking #61: summaries = %+v, want only #62", got)
+ }
+}
+
// setWorkspacePRMergeStatusForTest pins settings.pr_merge_status for the test
// workspace and restores the previous settings afterwards. An empty value
// removes the key (the Done default).
diff --git a/server/internal/handler/private_project_test.go b/server/internal/handler/private_project_test.go
index f47793a224..b1fd9add95 100644
--- a/server/internal/handler/private_project_test.go
+++ b/server/internal/handler/private_project_test.go
@@ -923,3 +923,62 @@ func TestPrivateProjectChildProgressSkipsHiddenSubIssues(t *testing.T) {
}
}
}
+
+func TestPrivateProjectPullRequestSummariesSkipHiddenIssues(t *testing.T) {
+ f := newPrivateProjectFixture(t)
+ now := time.Now()
+ linkGitHub := func(issueID string, number int) string {
+ prID := dbfx.Insert(t, "github_pull_request", testutil.Cols{
+ "workspace_id": testWorkspaceID, "installation_id": 0,
+ "repo_owner": "acme", "repo_name": f.marker, "pr_number": number,
+ "title": "pr", "state": "open", "html_url": "https://github.test/pr",
+ "pr_created_at": now, "pr_updated_at": now,
+ })
+ dbfx.InsertNoID(t, "issue_pull_request", testutil.Cols{"issue_id": issueID, "pull_request_id": prID},
+ "pull_request_id = $1", prID)
+ return prID
+ }
+ publicPR := linkGitHub(f.publicIssue, 1)
+ secretGitHubPR := linkGitHub(f.secretIssue, 2)
+ secretGitLabPR := dbfx.Insert(t, "vcs_pull_request", testutil.Cols{
+ "workspace_id": testWorkspaceID, "connection_id": testWorkspaceID, "provider": "gitlab",
+ "repo_owner": "acme", "repo_name": f.marker, "pr_number": 3,
+ "title": "mr", "state": "open", "html_url": "https://gitlab.test/mr",
+ "pr_created_at": now, "pr_updated_at": now,
+ })
+ dbfx.InsertNoID(t, "issue_vcs_pull_request", testutil.Cols{"issue_id": f.secretIssue, "pull_request_id": secretGitLabPR},
+ "pull_request_id = $1", secretGitLabPR)
+
+ visible := func(userID string) map[string]bool {
+ t.Helper()
+ var body struct {
+ PullRequests []IssuePullRequestSummaryResponse `json:"pull_requests"`
+ }
+ req := asUser(newRequest(http.MethodGet, "/api/issues/pull-requests", nil), userID)
+ testutil.Call(t, testHandler.ListIssuePullRequestSummaries, req).Want(http.StatusOK).JSON(&body)
+ out := map[string]bool{}
+ for _, pr := range body.PullRequests {
+ out[pr.ID] = true
+ }
+ return out
+ }
+ for _, tc := range []struct {
+ name string
+ userID string
+ seesSecret bool
+ }{
+ {"project member", f.insider, true},
+ {"workspace owner outside the member list", testUserID, true},
+ {"workspace member outside the project", f.outsider, false},
+ } {
+ got := visible(tc.userID)
+ if !got[publicPR] {
+ t.Errorf("%s: missing the PR linked to a public issue", tc.name)
+ }
+ for _, prID := range []string{secretGitHubPR, secretGitLabPR} {
+ if got[prID] != tc.seesSecret {
+ t.Errorf("%s: sees PR %s on a private-project issue = %v, want %v", tc.name, prID, got[prID], tc.seesSecret)
+ }
+ }
+ }
+}
diff --git a/server/pkg/db/generated/github.sql.go b/server/pkg/db/generated/github.sql.go
index 68c70c4672..65c761dc63 100644
--- a/server/pkg/db/generated/github.sql.go
+++ b/server/pkg/db/generated/github.sql.go
@@ -533,6 +533,85 @@ func (q *Queries) ListIssueIDsForPullRequest(ctx context.Context, pullRequestID
return items, nil
}
+const listIssuePullRequestSummaries = `-- name: ListIssuePullRequestSummaries :many
+SELECT
+ ipr.issue_id,
+ pr.id, 'github'::text AS provider, pr.repo_owner, pr.repo_name,
+ pr.pr_number, pr.title, pr.state, pr.html_url, pr.pr_created_at
+FROM github_pull_request pr
+JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id
+JOIN issue i ON i.id = ipr.issue_id
+WHERE pr.workspace_id = $1
+ AND i.workspace_id = $1
+ AND ($2::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY($2::uuid[])))
+UNION ALL
+SELECT
+ ipr.issue_id,
+ pr.id, pr.provider, pr.repo_owner, pr.repo_name,
+ pr.pr_number, pr.title, pr.state, pr.html_url, pr.pr_created_at
+FROM vcs_pull_request pr
+JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id
+JOIN issue i ON i.id = ipr.issue_id
+WHERE pr.workspace_id = $1
+ AND i.workspace_id = $1
+ AND ($2::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY($2::uuid[])))
+ORDER BY pr_created_at DESC
+`
+
+type ListIssuePullRequestSummariesParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`
+}
+
+type ListIssuePullRequestSummariesRow struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ ID pgtype.UUID `json:"id"`
+ Provider string `json:"provider"`
+ RepoOwner string `json:"repo_owner"`
+ RepoName string `json:"repo_name"`
+ PrNumber int32 `json:"pr_number"`
+ Title string `json:"title"`
+ State string `json:"state"`
+ HtmlUrl string `json:"html_url"`
+ PrCreatedAt pgtype.Timestamptz `json:"pr_created_at"`
+}
+
+// Every issue -> PR link in the workspace, GitHub and self-hosted providers
+// together, newest first. Carries only what an issue card or row needs to
+// render a PR chip (no CI/merge snapshot). Backs the workspace wide "Pull
+// requests" display option on board / list / table views. Links on issues in
+// private projects the caller cannot see are left out, as in the issue lists.
+func (q *Queries) ListIssuePullRequestSummaries(ctx context.Context, arg ListIssuePullRequestSummariesParams) ([]ListIssuePullRequestSummariesRow, error) {
+ rows, err := q.db.Query(ctx, listIssuePullRequestSummaries, arg.WorkspaceID, arg.HiddenProjectIds)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListIssuePullRequestSummariesRow{}
+ for rows.Next() {
+ var i ListIssuePullRequestSummariesRow
+ if err := rows.Scan(
+ &i.IssueID,
+ &i.ID,
+ &i.Provider,
+ &i.RepoOwner,
+ &i.RepoName,
+ &i.PrNumber,
+ &i.Title,
+ &i.State,
+ &i.HtmlUrl,
+ &i.PrCreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listPullRequestsByIssue = `-- name: ListPullRequestsByIssue :many
WITH issue_prs AS (
SELECT pr.id, pr.snapshot_head_sha
diff --git a/server/pkg/db/queries/github.sql b/server/pkg/db/queries/github.sql
index e11463788a..72fca389d0 100644
--- a/server/pkg/db/queries/github.sql
+++ b/server/pkg/db/queries/github.sql
@@ -194,6 +194,35 @@ LEFT JOIN checks c ON c.pr_id = pr.id
WHERE ipr.issue_id = sqlc.arg('issue_id')
ORDER BY pr.pr_created_at DESC;
+-- name: ListIssuePullRequestSummaries :many
+-- Every issue -> PR link in the workspace, GitHub and self-hosted providers
+-- together, newest first. Carries only what an issue card or row needs to
+-- render a PR chip (no CI/merge snapshot). Backs the workspace wide "Pull
+-- requests" display option on board / list / table views. Links on issues in
+-- private projects the caller cannot see are left out, as in the issue lists.
+SELECT
+ ipr.issue_id,
+ pr.id, 'github'::text AS provider, pr.repo_owner, pr.repo_name,
+ pr.pr_number, pr.title, pr.state, pr.html_url, pr.pr_created_at
+FROM github_pull_request pr
+JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id
+JOIN issue i ON i.id = ipr.issue_id
+WHERE pr.workspace_id = sqlc.arg('workspace_id')
+ AND i.workspace_id = sqlc.arg('workspace_id')
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+UNION ALL
+SELECT
+ ipr.issue_id,
+ pr.id, pr.provider, pr.repo_owner, pr.repo_name,
+ pr.pr_number, pr.title, pr.state, pr.html_url, pr.pr_created_at
+FROM vcs_pull_request pr
+JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id
+JOIN issue i ON i.id = ipr.issue_id
+WHERE pr.workspace_id = sqlc.arg('workspace_id')
+ AND i.workspace_id = sqlc.arg('workspace_id')
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ORDER BY pr_created_at DESC;
+
-- name: GetIssueReviewHeadSha :one
-- Returns the head SHA of the commit currently "under review" for an issue:
-- the most-recently-updated linked PR that still has an open/draft state and a