feat(pull-requests): link multiple pull requests to threads (#10839)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-09-09 15:50:58 -07:00
1 parent 383cc40f4d
commit afb84898be
172 files changed
+12063 -914

No files matched your search

@@ -0,0 +1,54 @@
import type { ScopedThreadRef } from "@t3tools/contracts";
import { Link2 } from "lucide-react";
import { useState } from "react";
import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
import { Button } from "../ui/button";
import { toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
/** Adopts a branch discovery as a durable link, even after the thread changes branches. */
export function LinkBranchPullRequestButton({
threadRef,
url,
}: {
threadRef: ScopedThreadRef;
url: string;
}) {
const linking = usePullRequestLinking(threadRef.environmentId);
const [pending, setPending] = useState(false);
if (!linking.canLink(url)) return null;
return (
<Tooltip>
<TooltipTrigger
render={
<Button
size="icon-tiny"
variant="ghost-muted"
aria-label="Link this PR"
disabled={pending}
onPointerDown={(event) => event.stopPropagation()}
onClick={async (event) => {
event.preventDefault();
event.stopPropagation();
setPending(true);
try {
await linking.changeLink(threadRef, url, true);
} catch (error) {
toastManager.add({
type: "error",
title: "Could not link pull request",
description: error instanceof Error ? error.message : String(error),
});
} finally {
setPending(false);
}
}}
>
<Link2 className="size-3" />
</Button>
}
/>
<TooltipPopup>Link this PR to keep it with this thread</TooltipPopup>
</Tooltip>
);
}
@@ -0,0 +1,136 @@
import { describe, expect, it } from "vite-plus/test";
import { changeRequestWebUrl, resolveLinkPullRequestInput } from "./LinkPullRequestDialog";
const project = {
host: "github.com",
repository: "acme/web",
webUrl: (number: number) => changeRequestWebUrl("github", "github.com", "acme/web", number),
};
describe("resolveLinkPullRequestInput", () => {
it.each([
["https://bitbucket.org/acme/web/pull-requests/42", "bitbucket.org"],
["https://github.acme.test/acme/web/pull/42", "github.acme.test"],
["https://git.acme.test/acme/web/-/merge_requests/42", "git.acme.test"],
])("links supported host URL %s without a thread project", (url, host) => {
expect(
resolveLinkPullRequestInput({
reference: ` ${url} `,
project: null,
hasProject: (candidate) => candidate.host === host,
}),
).toEqual({ link: { host, repository: "acme/web", number: 42, url } });
});
it("validates the full Azure repository when resolving a browser URL", () => {
const hasProject = (reference: { host: string; repository: string }) =>
reference.host === "dev.azure.com" && reference.repository === "org-a/project/_git/web";
expect(
resolveLinkPullRequestInput({
reference: "https://dev.azure.com/org-a/project/_git/web/pullrequest/42",
project: null,
hasProject,
}),
).toMatchObject({ link: { repository: "org-a/project/_git/web", number: 42 } });
expect(
resolveLinkPullRequestInput({
reference: "https://dev.azure.com/org-b/project/_git/web/pullrequest/42",
project: null,
hasProject,
}),
).toMatchObject({ error: expect.stringContaining("org-b/project/_git/web") });
});
it("resolves bare Azure numbers into canonical browser URLs", () => {
expect(
resolveLinkPullRequestInput({
reference: "#42",
project: {
host: "ssh.dev.azure.com",
repository: "v3/org/project/web",
webUrl: (number) =>
changeRequestWebUrl("azure-devops", "ssh.dev.azure.com", "v3/org/project/web", number),
},
hasProject: () => true,
}),
).toMatchObject({
link: {
host: "dev.azure.com",
repository: "org/project/_git/web",
number: 42,
url: "https://dev.azure.com/org/project/_git/web/pullrequest/42",
},
});
});
it("returns null for input that is not a reference", () => {
expect(
resolveLinkPullRequestInput({ reference: "hello", project, hasProject: () => true }),
).toBeNull();
});
it("resolves a bare number against the thread's own repository", () => {
expect(
resolveLinkPullRequestInput({ reference: "#42", project, hasProject: () => true }),
).toEqual({
link: {
host: "github.com",
repository: "acme/web",
number: 42,
url: "https://github.com/acme/web/pull/42",
},
});
});
it("links a URL from another repository on a host with a project", () => {
expect(
resolveLinkPullRequestInput({
reference: "https://github.com/acme/api/pull/7",
project,
hasProject: (reference) => reference.host === "github.com",
}),
).toEqual({
link: {
host: "github.com",
repository: "acme/api",
number: 7,
url: "https://github.com/acme/api/pull/7",
},
});
});
it("refuses a URL on a host nothing is checked out from", () => {
const result = resolveLinkPullRequestInput({
reference: "https://gitlab.com/acme/api/-/merge_requests/7",
project,
hasProject: () => false,
});
expect(result).toMatchObject({ error: expect.stringContaining("gitlab.com") });
});
it("asks for a URL when a bare number has no project to resolve against", () => {
expect(
resolveLinkPullRequestInput({ reference: "12", project: null, hasProject: () => true }),
).toMatchObject({ error: expect.stringContaining("full URL") });
});
it("accepts a checkout command as a reference", () => {
expect(
resolveLinkPullRequestInput({
reference: "gh pr checkout https://github.com/acme/web/pull/3",
project,
hasProject: () => true,
}),
).toMatchObject({ link: { number: 3, repository: "acme/web" } });
});
});
describe("changeRequestWebUrl", () => {
it("knows the four hosts and nothing else", () => {
expect(changeRequestWebUrl("gitlab", "gitlab.com", "g/sub/repo", 5)).toBe(
"https://gitlab.com/g/sub/repo/-/merge_requests/5",
);
expect(changeRequestWebUrl("unknown", "x", "a/b", 1)).toBeNull();
});
});
@@ -0,0 +1,254 @@
import { changeRequestUrlFor as changeRequestWebUrl } from "@t3tools/shared/changeRequestUrl";
export { changeRequestUrlFor as changeRequestWebUrl } from "@t3tools/shared/changeRequestUrl";
import {
pullRequestHostOf,
type ScopedThreadRef,
type SourceControlProviderKind,
} from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { parseChangeRequestUrl } from "~/lib/openPullRequestLink";
import { parsePullRequestReference } from "~/pullRequestReference";
import { useProjects, useThreadShell } from "~/state/entities";
import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
import { appAtomRegistry } from "~/rpc/atomRegistry";
import { Atom } from "effect/unstable/reactivity";
import { Button } from "../ui/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "../ui/dialog";
import { Input } from "../ui/input";
/**
* Which thread has the link dialog open, set by whichever entry point asked (command palette,
* pull-requests surface, detail panel) and rendered once by the chat view so the dialog outlives
* a palette that closes the moment its command runs.
*/
const linkPullRequestDialogThreadAtom = Atom.make<ScopedThreadRef | null>(null).pipe(
Atom.keepAlive,
Atom.withLabel("pull-requests:link-dialog-thread"),
);
export function openLinkPullRequestDialog(threadRef: ScopedThreadRef): void {
appAtomRegistry.set(linkPullRequestDialogThreadAtom, threadRef);
}
interface LinkPullRequestDialogProps {
open: boolean;
threadRef: ScopedThreadRef;
/** The thread's own project: bare numbers resolve against its repository. */
projectId: string | null;
onOpenChange: (open: boolean) => void;
}
/** Mounted once per chat view; shows the dialog for whichever thread asked for it. */
export function LinkPullRequestDialogHost() {
const threadRef = useAtomValue(linkPullRequestDialogThreadAtom);
const thread = useThreadShell(threadRef);
const linking = usePullRequestLinking(threadRef?.environmentId);
if (threadRef === null || linking.mode === "unsupported") return null;
return (
<LinkPullRequestDialog
open
threadRef={threadRef}
projectId={thread?.projectId ?? null}
onOpenChange={(open) => {
if (!open) appAtomRegistry.set(linkPullRequestDialogThreadAtom, null);
}}
/>
);
}
interface ResolvedLink {
readonly host: string;
readonly repository: string;
readonly number: number;
readonly url: string;
}
/**
* Which pull request an input names, or why it cannot. A URL carries its own host and
* repository and may point at any repository on a host this environment has a project for; a
* bare `#123` can only mean the thread's own repository.
*/
export function resolveLinkPullRequestInput(input: {
readonly reference: string;
readonly project: {
readonly host: string;
readonly repository: string;
readonly webUrl: (number: number) => string | null;
} | null;
readonly hasProject: (reference: ResolvedLink) => boolean;
}): { link: ResolvedLink } | { error: string } | null {
const parsed =
parseChangeRequestUrl(input.reference.trim()) !== null
? input.reference.trim()
: parsePullRequestReference(input.reference);
if (parsed === null) return null;
const url = parseChangeRequestUrl(parsed);
if (url !== null) {
if (!input.hasProject({ ...url, url: parsed })) {
return { error: `No project in this environment can read ${url.host}/${url.repository}.` };
}
return {
link: { host: url.host, repository: url.repository, number: url.number, url: parsed },
};
}
const number = Number(parsed);
if (!Number.isSafeInteger(number) || number < 1) return null;
if (input.project === null) {
return { error: "Paste a full URL to link a pull request from another repository." };
}
const webUrl = input.project.webUrl(number);
const webReference = webUrl === null ? null : parseChangeRequestUrl(webUrl);
if (webUrl === null || webReference === null) {
return { error: "Paste a full URL; this project's host has no known pull request URL." };
}
return {
link: { ...webReference, url: webUrl },
};
}
function LinkPullRequestDialog({
open,
threadRef,
projectId,
onOpenChange,
}: LinkPullRequestDialogProps) {
const inputRef = useRef<HTMLInputElement>(null);
const [reference, setReference] = useState("");
const [dirty, setDirty] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
const projects = useProjects();
const environmentProjects = useMemo(
() => projects.filter((project) => project.environmentId === threadRef.environmentId),
[projects, threadRef.environmentId],
);
const ownProject = useMemo(() => {
const project = environmentProjects.find((candidate) => candidate.id === projectId);
const identity = project?.repositoryIdentity;
if (!project || !identity) return null;
const repository =
identity.displayName ??
(identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null);
if (repository === null) return null;
const kind = identity.provider as SourceControlProviderKind;
const host = pullRequestHostOf(identity, kind);
return {
host,
repository,
webUrl: (number: number) => changeRequestWebUrl(kind, host, repository, number),
};
}, [environmentProjects, projectId]);
const linking = usePullRequestLinking(threadRef.environmentId);
const [pending, setPending] = useState(false);
useEffect(() => {
if (!open) return;
setReference("");
setDirty(false);
setSubmitError(null);
const frame = window.requestAnimationFrame(() => inputRef.current?.focus());
return () => window.cancelAnimationFrame(frame);
}, [open]);
const resolved = useMemo(
() =>
resolveLinkPullRequestInput({
reference,
project: ownProject,
hasProject: (reference) => linking.canLink(reference.url),
}),
[linking, ownProject, reference],
);
const submit = useCallback(async () => {
setDirty(true);
if (resolved === null || "error" in resolved) return;
setSubmitError(null);
setPending(true);
try {
await linking.changeLink(threadRef, resolved.link.url, true);
} catch (error) {
setSubmitError(error instanceof Error ? error.message : "Could not link the pull request.");
return;
} finally {
setPending(false);
}
onOpenChange(false);
}, [linking, onOpenChange, resolved, threadRef]);
const validation = !dirty
? null
: reference.trim().length === 0
? "Paste a pull request URL or enter 123 / #123."
: resolved === null
? "Use a pull request URL, 123, or #123."
: "error" in resolved
? resolved.error
: null;
return (
<Dialog open={open} onOpenChange={(next) => (pending ? undefined : onOpenChange(next))}>
<DialogPopup className="max-w-xl">
<DialogHeader>
<DialogTitle>Link pull request</DialogTitle>
<DialogDescription>
Attach a pull request to this thread. A full URL can point at any repository on a host
this environment has a project for.
</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-3">
<Input
ref={inputRef}
placeholder="Pull request URL or #42"
value={reference}
onChange={(event) => {
setDirty(true);
setReference(event.target.value);
}}
onKeyDown={(event) => {
if (event.key !== "Enter") return;
event.preventDefault();
void submit();
}}
/>
{resolved !== null && "link" in resolved ? (
<p className="truncate text-muted-foreground text-xs">
{resolved.link.host}/{resolved.link.repository} #{resolved.link.number}
</p>
) : null}
{(validation ?? submitError) ? (
<p className="text-destructive text-xs">{validation ?? submitError}</p>
) : null}
</DialogPanel>
<DialogFooter>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => onOpenChange(false)}
disabled={pending}
>
Cancel
</Button>
<Button
type="button"
size="sm"
onClick={() => void submit()}
disabled={pending || resolved === null || "error" in resolved}
>
{pending ? "Linking..." : "Link"}
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
);
}
@@ -66,16 +66,15 @@ import { cn } from "~/lib/utils";
import { readLocalApi } from "~/localApi";
import type { ReviewCommentContext } from "~/reviewCommentContext";
import { buildPhysicalToLogicalProjectKeyMap } from "~/sidebarProjectGrouping";
import { useProjects } from "~/state/entities";
import { useProjects, useServerConfigs } from "~/state/entities";
import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";
import { useEnvironmentQuery } from "~/state/query";
import { useLiveRefresh } from "~/hooks/useLiveRefresh";
import {
pullRequestEnvironment,
usePullRequestTurnRefresh,
useSharedPullRequestSummary,
} from "~/state/pullRequests";
import { pullRequestEnvironment, pullRequestStackAtom } from "~/state/pullRequests";
import { usePullRequestTurnRefresh, useSharedPullRequestSummary } from "~/state/pullRequests";
import { useAtomCommand } from "~/state/use-atom-command";
import { PullRequestStackMap } from "./PullRequestStackMap";
import { PullRequestThreadLinks } from "./PullRequestThreadLinks";
import { vcsEnvironment } from "~/state/vcs";
import { formatRelativeTimeLabel } from "~/timestampFormat";
import { useUiStateStore } from "~/uiStateStore";
@@ -452,13 +451,14 @@ function PullRequestBaseFreshnessWarning({
export function PullRequestDetailPanel({
environmentId,
threadRef = null,
reference,
reference: requestedReference,
listEntry = null,
refreshToken: forcedRefreshToken = 0,
onActed,
onClose,
context = "page",
composerDraftTarget,
onBack,
}: {
environmentId: EnvironmentId;
/**
@@ -495,14 +495,35 @@ export function PullRequestDetailPanel({
* land here instead of opening a new thread — the branch is already under the reader's feet.
*/
composerDraftTarget?: ScopedThreadRef | DraftId;
/**
* Beside a thread, the way back to that thread's list of pull requests. The tab strip can
* close this surface, but closing is not going back: the reader came from the list and
* expects to land on it, with this one still open behind.
*/
onBack?: (() => void) | undefined;
}) {
const pullRequestKey = `${reference.projectId}:${reference.repository}#${reference.number}`;
const environmentConfigs = useServerConfigs();
const supportsThreadPullRequests =
environmentConfigs.get(environmentId)?.environment.capabilities.threadPullRequests === true;
const reference = useMemo(
() =>
supportsThreadPullRequests
? requestedReference
: {
projectId: requestedReference.projectId,
repository: requestedReference.repository,
number: requestedReference.number,
},
[requestedReference, supportsThreadPullRequests],
);
const pullRequestKey = `${reference.projectId}:${reference.host ?? ""}:${reference.repository}#${reference.number}`;
const matchingListEntry =
listEntry?.projectId === reference.projectId &&
listEntry.repository.toLowerCase() === reference.repository.toLowerCase() &&
listEntry.number === reference.number
? listEntry
: null;
const [threadPickerOpen, setThreadPickerOpen] = useState(false);
const [tab, setTab] = useState<DetailTab>("summary");
const [timelineOrder, setTimelineOrder] = useState<"newest" | "oldest">("newest");
const [codeCommitScope, setCodeCommitScope] = useState<{
@@ -631,6 +652,11 @@ export function PullRequestDetailPanel({
: {
...resolvedCoreDetail,
...sharedSummary,
author: sharedSummary.author ?? resolvedCoreDetail.author,
additions: sharedSummary.additions ?? resolvedCoreDetail.additions,
deletions: sharedSummary.deletions ?? resolvedCoreDetail.deletions,
changedFiles: sharedSummary.changedFiles ?? resolvedCoreDetail.changedFiles,
mergeability: sharedSummary.mergeability ?? resolvedCoreDetail.mergeability,
closedAt:
sharedSummary.closedAt === undefined
? resolvedCoreDetail.closedAt
@@ -702,6 +728,13 @@ export function PullRequestDetailPanel({
const isStackedPullRequest =
detail !== null &&
isStackedPullRequestBase(detail.baseBranch, branchRefsQuery.data?.refs ?? []);
// The host's own stack, where it keeps one. Only asked for once the detail has landed so a
// pull request nobody can read costs one request rather than two.
const nativeStack = useEnvironmentQuery(
detail === null || detail.capabilities.stacks !== true || !supportsThreadPullRequests
? null
: pullRequestStackAtom({ environmentId, input: reference }),
).data;
const activityPending = activityQuery.isPending && activity === null;
const activityError = activity === null ? activityQuery.error : null;
const refreshDetail = useCallback(() => {
@@ -1379,6 +1412,17 @@ export function PullRequestDetailPanel({
return (
<div className="flex h-full min-h-0 w-full flex-col bg-background">
{threadPickerOpen && detail ? (
<PullRequestThreadLinks
key={`${environmentId}:${detail.url}`}
display="picker"
environmentId={environmentId}
reference={reference}
url={detail.url}
threadRef={null}
onPickerOpenChange={setThreadPickerOpen}
/>
) : null}
<div className="@container/pr-header grid min-w-0 shrink-0 grid-cols-[minmax(0,1fr)_auto] items-start gap-x-2 border-b border-border/60">
<div className="ml-4 grid h-7 min-w-0 items-center overflow-hidden">
<div
@@ -1393,6 +1437,24 @@ export function PullRequestDetailPanel({
>
{detail && statePresentation ? (
<>
{onBack ? (
<Tooltip>
<TooltipTrigger
render={
<Button
size="icon-micro"
variant="ghost-muted"
onClick={onBack}
className="-ml-1.5"
aria-label="Back to this thread's pull requests"
>
<ArrowLeftIcon aria-hidden className="size-3.5" />
</Button>
}
/>
<TooltipPopup side="top">Back to pull requests</TooltipPopup>
</Tooltip>
) : null}
<Tooltip>
<TooltipTrigger
render={
@@ -1450,6 +1512,25 @@ export function PullRequestDetailPanel({
>
{detail && statePresentation ? (
<>
{onBack ? (
<Tooltip>
<TooltipTrigger
render={
<Button
size="icon-micro"
variant="ghost-muted"
tabIndex={condensed ? 0 : -1}
onClick={onBack}
className="-ml-1.5"
aria-label="Back to this thread's pull requests"
>
<ArrowLeftIcon aria-hidden className="size-3.5" />
</Button>
}
/>
<TooltipPopup side="top">Back to pull requests</TooltipPopup>
</Tooltip>
) : null}
<Tooltip>
<TooltipTrigger
render={
@@ -1488,6 +1569,15 @@ export function PullRequestDetailPanel({
<div className="mr-4 flex h-7 shrink-0 items-center justify-end gap-1">
{detail ? (
<>
{context === "page" ? (
<PullRequestThreadLinks
display="count"
environmentId={environmentId}
reference={reference}
url={detail.url}
threadRef={null}
/>
) : null}
{/* Checking a pull request out is the reason to open one here at all, so it is a
button of its own rather than a side effect of asking an agent for something.
It asks where, because the two answers are not interchangeable: one leaves your
@@ -1714,6 +1804,17 @@ export function PullRequestDetailPanel({
<MoreHorizontalIcon className="size-4" />
</MenuTrigger>
<MenuPopup align="end" side="bottom" className="min-w-72">
<PullRequestThreadLinks
display="menu-item"
environmentId={environmentId}
reference={reference}
url={detail.url}
threadRef={
threadRef ??
(typeof composerDraftTarget === "object" ? composerDraftTarget : null)
}
onPickerOpenChange={setThreadPickerOpen}
/>
<MenuItem
disabled={isInvalidating || detailQuery.isPending}
onClick={() => void refreshFromHost()}
@@ -2001,6 +2102,13 @@ export function PullRequestDetailPanel({
/>
</span>
</div>
{nativeStack ? (
<PullRequestStackMap
stack={nativeStack}
currentNumber={detail.number}
className="mt-1"
/>
) : null}
</div>
) : null}
</div>
@@ -0,0 +1,87 @@
import type { PullRequestStack } from "@t3tools/contracts";
import { GitPullRequestArrowIcon } from "lucide-react";
import { InlineButton } from "../ui/button";
import { cn } from "~/lib/utils";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { resolvePullRequestState } from "./pullRequestPresentation";
/**
* The host's stack as one line of layers, bottom to top, with this pull request marked. Mirrors
* the map GitHub draws above a stacked pull request so a reader who came from there finds the
* same shape here.
*/
export function PullRequestStackMap({
stack,
currentNumber,
onSelect,
className,
}: {
stack: PullRequestStack;
currentNumber: number;
/** Opens another layer in the same panel; absent where the panel cannot swap references. */
onSelect?: ((number: number) => void) | undefined;
className?: string;
}) {
return (
<div
className={cn(
"flex min-w-0 items-center gap-1 overflow-x-auto text-[11px] text-muted-foreground",
className,
)}
aria-label={`Stack ${stack.number} on ${stack.base}, ${stack.layers.length} layers`}
>
<Tooltip>
<TooltipTrigger
render={<span className="inline-flex shrink-0 items-center gap-1 font-mono" />}
>
<GitPullRequestArrowIcon aria-hidden className="size-3" />
<code className="truncate">{stack.base}</code>
</TooltipTrigger>
<TooltipPopup side="top">
Stack #{stack.number} on {stack.base}. Merging a layer lands every layer below it.
</TooltipPopup>
</Tooltip>
{stack.layers.map((layer) => {
const presentation = resolvePullRequestState({ state: layer.state, isDraft: false });
const isCurrent = layer.number === currentNumber;
const chip = (
<span
className={cn(
"inline-flex shrink-0 items-center gap-1 rounded-full border px-1.5 py-0 font-mono tabular-nums",
isCurrent
? "border-foreground/40 bg-accent text-foreground"
: "border-border/70 hover:bg-accent/60",
)}
>
<presentation.Icon aria-hidden className={cn("size-3", presentation.toneClassName)} />#
{layer.number}
</span>
);
return (
<span key={layer.number} className="inline-flex shrink-0 items-center gap-1">
<span aria-hidden className="text-muted-foreground/50">
→
</span>
<Tooltip>
<TooltipTrigger
render={
onSelect && !isCurrent ? (
<InlineButton onClick={() => onSelect(layer.number)} />
) : (
<span aria-current={isCurrent ? "true" : undefined} />
)
}
>
{chip}
</TooltipTrigger>
<TooltipPopup side="top">
#{layer.number} · {layer.headBranch} · {presentation.label}
</TooltipPopup>
</Tooltip>
</span>
);
})}
</div>
);
}
@@ -314,12 +314,14 @@ function Section({
function CommentComposer({
environmentId,
reference,
detail,
actionPending,
onCommentAction,
onCommented,
}: {
environmentId: EnvironmentId;
reference: PullRequestRef;
detail: PullRequestDetailView;
actionPending: boolean;
onCommentAction: (
@@ -355,9 +357,7 @@ function CommentComposer({
const result = await postComment({
environmentId,
input: {
projectId: detail.projectId,
repository: detail.repository,
number: detail.number,
...reference,
body: trimmed,
},
});
@@ -996,7 +996,14 @@ export function PullRequestSummaryTab({
{/* Posting is a core capability and remains usable even if the activity read failed. */}
{detail.capabilities.comment && detail.viewerPermissions.comment ? (
<CommentComposer
key={`${environmentId}:${detail.projectId}/${detail.repository}#${detail.number}`}
reference={reference}
key={JSON.stringify([
environmentId,
reference.projectId,
reference.host,
reference.repository,
reference.number,
])}
environmentId={environmentId}
detail={detail}
actionPending={actionPending}
@@ -0,0 +1,255 @@
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { Link } from "@tanstack/react-router";
import type { EnvironmentId, PullRequestRef, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import { CheckIcon, LinkIcon, MessageSquareIcon, UnlinkIcon } from "lucide-react";
import { useState } from "react";
import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility";
import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
import { parseChangeRequestUrl } from "~/lib/openPullRequestLink";
import { useProjects, useServerConfigs, useThreadShell, useThreadShells } from "~/state/entities";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { useEnvironmentQuery } from "~/state/query";
import { appAtomRegistry } from "~/rpc/atomRegistry";
import { buildThreadRouteParams } from "~/threadRoutes";
import { Button } from "../ui/button";
import { Command, CommandInput, CommandItem, CommandList } from "../ui/command";
import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
import { toastManager } from "../ui/toast";
interface PullRequestThreadLinksProps {
environmentId: EnvironmentId;
reference: PullRequestRef;
url: string;
threadRef: ScopedThreadRef | null;
display: "count" | "menu-item" | "picker";
onPickerOpenChange?: (open: boolean) => void;
}
/** Thread relations belong to the detail environment, including when another environment is active. */
export function PullRequestThreadLinks(props: PullRequestThreadLinksProps) {
const configs = useServerConfigs();
if (
threadPullRequestLinkMode(configs.get(props.environmentId)?.environment.capabilities) ===
"unsupported"
) {
return null;
}
return <EnabledPullRequestThreadLinks key={`${props.environmentId}:${props.url}`} {...props} />;
}
function EnabledPullRequestThreadLinks({
environmentId,
reference,
url,
threadRef,
display,
onPickerOpenChange,
}: PullRequestThreadLinksProps) {
const parsed = parseChangeRequestUrl(url);
const currentThreadRef = threadRef?.environmentId === environmentId ? threadRef : null;
const thread = useThreadShell(currentThreadRef);
const linking = usePullRequestLinking(environmentId);
const linkedHere = linking.isLinked(thread, url);
const relations = useEnvironmentQuery(
linking.mode === "multiple" && display !== "menu-item"
? pullRequestEnvironment.linkedThreads({
environmentId,
input: parsed === null ? reference : { ...reference, ...parsed },
})
: null,
);
// Refreshes can briefly clear the query value. Keep the last response so polling
// does not unmount an open menu or move its highlighted thread.
const [lastRelations, setLastRelations] = useState(relations.data);
if (relations.data !== null && relations.data !== lastRelations) {
setLastRelations(relations.data);
}
const [pending, setPending] = useState(false);
const changeLink = async (threadId: ThreadId, remove: boolean) => {
if (parsed === null || pending) return;
setPending(true);
try {
await linking.changeLink(scopeThreadRef(environmentId, threadId), url, !remove);
} catch (error) {
toastManager.add({
type: "error",
title: remove ? "Could not unlink the pull request" : "Could not link the pull request",
description: error instanceof Error ? error.message : String(error),
});
return;
} finally {
setPending(false);
}
if (linking.mode === "multiple") {
appAtomRegistry.refresh(
pullRequestEnvironment.linkedThreads({ environmentId, input: { ...reference, ...parsed } }),
);
}
onPickerOpenChange?.(false);
};
if (parsed === null || (!linkedHere && !linking.canLink(url))) return null;
const linkedThreads =
linking.mode === "multiple" ? ((relations.data ?? lastRelations)?.threads ?? []) : [];
const linkedThreadsLabel =
linkedThreads.length > 0
? `Linked from ${linkedThreads.length} ${linkedThreads.length === 1 ? "thread" : "threads"}`
: "Linked threads";
return (
<>
{display === "count" && (linkedThreads.length > 0 || relations.error !== null) ? (
<Menu>
<MenuTrigger
render={
<Button
size="xs"
variant="ghost"
aria-label={linkedThreadsLabel}
title={linkedThreadsLabel}
/>
}
>
<MessageSquareIcon aria-hidden className="size-3.5" />
<span className="@max-[40rem]/pr-header:hidden">{linkedThreadsLabel}</span>
<span aria-hidden className="hidden @max-[40rem]/pr-header:inline">
{linkedThreads.length || "?"}
</span>
</MenuTrigger>
<MenuPopup align="end" className="max-h-72 max-w-80 overflow-y-auto">
{relations.error !== null ? (
<MenuItem onClick={relations.refresh}>Could not load linked threads. Retry</MenuItem>
) : null}
{linkedThreads.map((linkedThread) => (
<MenuItem
key={linkedThread.id}
render={
<Link
to="/$environmentId/$threadId"
params={buildThreadRouteParams(scopeThreadRef(environmentId, linkedThread.id))}
/>
}
>
<span className="min-w-0 flex-1 truncate">
{linkedThread.title || "Untitled thread"}
</span>
{linkedThread.archivedAt !== null ? (
<span className="text-xs text-muted-foreground">Archived</span>
) : null}
</MenuItem>
))}
</MenuPopup>
</Menu>
) : null}
{display === "menu-item" ? (
<MenuItem
disabled={pending}
onClick={() => {
if (currentThreadRef !== null) {
void changeLink(currentThreadRef.threadId, linkedHere);
} else {
onPickerOpenChange?.(true);
}
}}
>
{linkedHere ? (
<UnlinkIcon aria-hidden className="size-3.5" />
) : (
<LinkIcon aria-hidden className="size-3.5" />
)}
{linkedHere
? "Unlink from this thread"
: currentThreadRef
? "Link to this thread"
: "Link to thread"}
</MenuItem>
) : null}
{display === "picker" ? (
<Dialog open onOpenChange={onPickerOpenChange}>
<DialogPopup className="max-w-md" showCloseButton={false}>
<DialogTitle className="sr-only">Link pull request to a thread</DialogTitle>
<ThreadPicker
environmentId={environmentId}
url={url}
pending={pending}
onSelect={(threadId) => void changeLink(threadId, false)}
/>
</DialogPopup>
</Dialog>
) : null}
</>
);
}
function ThreadPicker({
environmentId,
url,
pending,
onSelect,
}: {
environmentId: EnvironmentId;
url: string;
pending: boolean;
onSelect: (threadId: ThreadId) => void;
}) {
const threads = useThreadShells();
const linking = usePullRequestLinking(environmentId);
const projects = useProjects();
const [query, setQuery] = useState("");
const projectNames = new Map(
projects
.filter((project) => project.environmentId === environmentId)
.map((project) => [project.id, project.title]),
);
const search = query.trim().toLocaleLowerCase();
const candidates = threads
.filter(
(thread) =>
thread.environmentId === environmentId &&
thread.archivedAt === null &&
`${thread.title} ${projectNames.get(thread.projectId) ?? ""}`
.toLocaleLowerCase()
.includes(search),
)
.toSorted((a, b) => b.updatedAt.localeCompare(a.updatedAt));
return (
<Command mode="none" value={query} onValueChange={setQuery} aria-label="Choose a thread">
<CommandInput placeholder="Search threads or projects..." disabled={pending} />
<CommandList className="max-h-80 overflow-y-auto">
{candidates.length === 0 ? (
<div className="px-3 py-6 text-center text-sm text-muted-foreground">
No active threads found.
</div>
) : (
candidates.map((thread) => {
const linked = linking.isLinked(thread, url);
return (
<CommandItem
key={thread.id}
value={thread.id}
disabled={pending || linked}
onClick={() => onSelect(thread.id)}
>
<MessageSquareIcon aria-hidden className="size-4 shrink-0" />
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate">{thread.title || "Untitled thread"}</span>
<span className="truncate text-xs text-muted-foreground">
{projectNames.get(thread.projectId)}
</span>
</span>
{linked ? (
<>
<CheckIcon aria-hidden className="size-3.5" />
<span className="text-xs text-muted-foreground">Linked</span>
</>
) : null}
</CommandItem>
);
})
)}
</CommandList>
</Command>
);
}
@@ -0,0 +1,296 @@
import type { ScopedThreadRef, ThreadPullRequestLink } from "@t3tools/contracts";
import {
resolveThreadPullRequestChains,
visibleThreadPullRequests,
} from "@t3tools/shared/threadPullRequests";
import {
GitPullRequestArrow,
LayersIcon,
LinkIcon,
MoreHorizontalIcon,
PlusIcon,
} from "lucide-react";
import { useCallback, useMemo } from "react";
import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
import { useOpenPrLink } from "~/lib/openPullRequestLink";
import { cn } from "~/lib/utils";
import { useServerConfigs, useThreadShell } from "~/state/entities";
import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";
import { threadEnvironment } from "~/state/threads";
import { useAtomCommand } from "~/state/use-atom-command";
import { formatRelativeTimeLabel } from "~/timestampFormat";
import { Button } from "../ui/button";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
import { ScrollArea } from "../ui/scroll-area";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { openLinkPullRequestDialog } from "./LinkPullRequestDialog";
import { pullRequestListLines, type PullRequestListLine } from "./pullRequestListLines";
import {
PullRequestActorAvatar,
PullRequestDiffStat,
PullRequestStateGlyph,
pullRequestChecksStatePresentation,
} from "./pullRequestPresentation";
const SOURCE_LABELS: Record<ThreadPullRequestLink["source"], string> = {
manual: "Linked by you",
created: "Created from this thread",
agent: "Linked by the agent",
stack: "Found in the stack",
"stack-dismissed": "Dismissed",
};
function ChecksGlyph({
state,
}: {
state: NonNullable<ThreadPullRequestLink["snapshot"]>["checksState"] & string;
}) {
const presentation = pullRequestChecksStatePresentation(state);
return (
<Tooltip>
<TooltipTrigger render={<span className="inline-flex shrink-0" />}>
<presentation.Icon
role="img"
aria-label={presentation.label}
className={cn("size-3.5", presentation.toneClassName)}
/>
</TooltipTrigger>
<TooltipPopup>{presentation.label}</TooltipPopup>
</Tooltip>
);
}
function LinkRow({
line,
threadRef,
onUnlink,
}: {
line: PullRequestListLine;
threadRef: ScopedThreadRef;
onUnlink: (link: ThreadPullRequestLink) => void;
}) {
const openPrLink = useOpenPrLink(threadRef);
const { link, depth, stack } = line;
const snapshot = link.snapshot;
return (
<div
className="group/pr-row flex items-center gap-2 rounded-md py-1 pr-1 hover:bg-accent/60"
// Each layer steps in under the one it targets. The step is capped: beyond a few layers
// the indent only says "still in the stack", which the connector line already does, and
// a sixteen-layer stack would otherwise stair-step off the right edge.
style={{ paddingLeft: `${0.5 + Math.min(depth, 3) * 1.25}rem` }}
>
{depth > 0 ? <span aria-hidden className="-ml-2 h-6 w-px shrink-0 bg-border/70" /> : null}
{snapshot === null ? (
<GitPullRequestArrow
aria-label="Waiting for host state"
className="size-4 shrink-0 text-muted-foreground"
/>
) : (
<PullRequestStateGlyph state={snapshot.state} isDraft={snapshot.isDraft} />
)}
<a
href={link.url}
onClick={(event) => openPrLink(event, link.url, threadRef)}
className="min-w-0 flex-1"
>
<span className="flex min-w-0 items-center gap-1.5">
<Tooltip>
<TooltipTrigger
render={
<span className="shrink-0 font-mono text-xs tabular-nums text-muted-foreground" />
}
>
#{link.number}
</TooltipTrigger>
<TooltipPopup>
{SOURCE_LABELS[link.source]} · {formatRelativeTimeLabel(link.linkedAt)}
</TooltipPopup>
</Tooltip>
<span className="min-w-0 flex-1 truncate text-sm">
{snapshot?.title ?? link.repository}
</span>
{/* Right-aligned signals, in the order a reviewer scans them: are checks green,
has someone ruled, how big is it. Each is absent rather than neutral when the
host said nothing, so a row without them reads as unknown, not as fine. */}
<span className="ml-auto flex shrink-0 items-center gap-1.5 text-[11px]">
{snapshot?.checksState ? <ChecksGlyph state={snapshot.checksState} /> : null}
{snapshot?.state === "open" &&
(snapshot.reviewDecision === "approved" ||
snapshot.reviewDecision === "changes-requested") ? (
<span
className={cn(
snapshot.reviewDecision === "approved"
? "text-emerald-600/90 dark:text-emerald-400/80"
: "text-amber-600/90 dark:text-amber-400/80",
)}
>
{snapshot.reviewDecision === "approved" ? "Approved" : "Changes requested"}
</span>
) : null}
{snapshot?.state === "open" && snapshot.mergeability === "conflicting" ? (
<span className="text-destructive">Conflicts</span>
) : null}
<PullRequestDiffStat
additions={snapshot?.additions ?? 0}
deletions={snapshot?.deletions ?? 0}
className="font-mono"
/>
</span>
</span>
<span className="flex min-w-0 items-center gap-1.5 text-[11px] text-muted-foreground">
{stack ? (
<Tooltip>
<TooltipTrigger
render={
<span className="inline-flex shrink-0 items-center gap-0.5 text-foreground/70" />
}
>
{stack.kind === "native" ? (
<LayersIcon aria-hidden className="size-3" />
) : (
<GitPullRequestArrow aria-hidden className="size-3" />
)}
{stack.size}
</TooltipTrigger>
<TooltipPopup>
{stack.kind === "native"
? `GitHub stack of ${stack.size}: merging a layer lands the ones below it.`
: `${stack.size} pull requests chained by base branch.`}
</TooltipPopup>
</Tooltip>
) : null}
{snapshot?.author ? (
<span className="inline-flex shrink-0 items-center gap-1">
<PullRequestActorAvatar actor={snapshot.author} className="size-3.5" />
<span className="max-w-28 truncate">{snapshot.author.login}</span>
</span>
) : null}
<span className="truncate font-mono">
{snapshot !== null
? `${snapshot.headBranch} → ${snapshot.baseBranch}`
: `${link.host}/${link.repository}`}
</span>
{snapshot?.updatedAt ? (
<span className="shrink-0">· {formatRelativeTimeLabel(snapshot.updatedAt)}</span>
) : null}
</span>
</a>
<Menu>
<MenuTrigger
render={
<Button
variant="ghost"
size="icon-xs"
aria-label={`Actions for #${link.number}`}
className={cn(
"opacity-0 group-hover/pr-row:opacity-100 data-[popup-open]:opacity-100",
)}
>
<MoreHorizontalIcon className="size-3.5" />
</Button>
}
/>
<MenuPopup align="end" side="bottom">
<MenuItem onClick={() => void writeTextToClipboard(link.url, "link")}>Copy link</MenuItem>
<MenuItem onClick={(event) => openPrLink(event, link.url, threadRef)}>Open</MenuItem>
<MenuItem onClick={() => onUnlink(link)}>
{link.source === "stack" ? "Dismiss from thread" : "Unlink from thread"}
</MenuItem>
</MenuPopup>
</Menu>
</div>
);
}
export function ThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThreadRef }) {
const configs = useServerConfigs();
if (configs.get(threadRef.environmentId)?.environment.capabilities.threadPullRequests !== true) {
return (
<PullRequestsUnavailableState
title="Linked pull requests unavailable"
error="This environment does not support multiple linked pull requests."
/>
);
}
return <EnabledThreadPullRequestsPanel threadRef={threadRef} />;
}
function EnabledThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThreadRef }) {
const thread = useThreadShell(threadRef);
const openLinkDialog = useCallback(() => openLinkPullRequestDialog(threadRef), [threadRef]);
const unlink = useAtomCommand(threadEnvironment.unlinkPullRequest, { reportFailure: true });
const links = useMemo(() => visibleThreadPullRequests(thread?.pullRequests ?? []), [thread]);
const lines = useMemo(() => pullRequestListLines(resolveThreadPullRequestChains(links)), [links]);
const handleUnlink = useCallback(
(link: ThreadPullRequestLink) => {
void unlink({
environmentId: threadRef.environmentId,
input: {
threadId: threadRef.threadId,
host: link.host,
repository: link.repository,
number: link.number,
},
});
},
[threadRef, unlink],
);
const openCount = useMemo(
() => links.filter((link) => link.snapshot === null || link.snapshot.state === "open").length,
[links],
);
const lastSynced = useMemo(() => {
let latest: string | null = null;
for (const link of links) {
const at = link.snapshot?.syncedAt;
if (at !== undefined && (latest === null || at > latest)) latest = at;
}
return latest;
}, [links]);
if (links.length === 0) {
return (
<div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
<LinkIcon aria-hidden className="size-6 text-muted-foreground/60" />
<p className="text-sm font-medium">No linked pull requests</p>
<p className="max-w-60 text-xs text-muted-foreground">
Pull requests the agent opens from this thread land here. Link one yourself from a URL or
a number.
</p>
<Button size="sm" variant="outline" onClick={openLinkDialog}>
<PlusIcon className="size-3.5" />
Link pull request
</Button>
</div>
);
}
return (
<div className="flex h-full min-h-0 flex-col">
<ScrollArea className="min-h-0 flex-1">
<div className="flex flex-col p-1.5">
{lines.map((line) => (
<LinkRow
key={`${line.link.host}/${line.link.repository}#${line.link.number}`}
line={line}
threadRef={threadRef}
onUnlink={handleUnlink}
/>
))}
</div>
</ScrollArea>
<footer className="flex items-center justify-between border-t border-border/60 px-2 py-1.5 text-[.7rem] text-muted-foreground">
<span>
{openCount} open · {links.length} linked
{lastSynced ? ` · synced ${formatRelativeTimeLabel(lastSynced)}` : ""}
</span>
<Button size="xs" variant="ghost" onClick={openLinkDialog}>
<PlusIcon className="size-3.5" />
Link
</Button>
</footer>
</div>
);
}
@@ -1420,6 +1420,42 @@ describe("cached pull request detail", () => {
expect(readPullRequestDetailSnapshot(makeStorage(), "env-2", reference)).toBeNull();
});
it("isolates stored and displayed details between hosts with the same repository and number", () => {
const storage = makeStorage();
const publicRef = { ...reference, host: "github.com" };
const enterpriseRef = { ...reference, host: "github.example.com" };
const publicDetail = detail();
const enterpriseDetail = detail({
title: "Enterprise change",
url: "https://github.example.com/acme/web/pull/7",
});
writePullRequestDetailSnapshot(storage, "env-1", publicRef, publicDetail);
expect(readPullRequestDetailSnapshot(storage, "env-1", enterpriseRef)).toBeNull();
writePullRequestDetailSnapshot(storage, "env-1", enterpriseRef, enterpriseDetail);
expect(readPullRequestDetailSnapshot(storage, "env-1", publicRef)?.title).toBe(
publicDetail.title,
);
expect(readPullRequestDetailSnapshot(storage, "env-1", enterpriseRef)?.title).toBe(
enterpriseDetail.title,
);
expect(
resolveDisplayedPullRequestDetail({
live: null,
cached: publicDetail,
reference: enterpriseRef,
}),
).toBeNull();
expect(
resolveDisplayedPullRequestDetail({
live: null,
cached: enterpriseDetail,
reference: enterpriseRef,
}),
).toBe(enterpriseDetail);
writePullRequestDetailSnapshot(storage, "env-1", enterpriseRef, publicDetail);
expect(readPullRequestDetailSnapshot(storage, "env-1", enterpriseRef)).toBeNull();
});
it("shrugs off corrupt storage and no storage at all", () => {
const storage = makeStorage();
storage.setItem("t3.pullRequests.detail:env-1:project-1:acme/web#7", "{not json");
@@ -1,4 +1,5 @@
import * as Schema from "effect/Schema";
import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
import {
PullRequestDetail,
@@ -1028,6 +1029,7 @@ export function pullRequestActionNeedsHostRefresh(action: PullRequestAction): bo
type SnapshotStorage = Pick<Storage, "getItem" | "setItem">;
export interface PullRequestDetailSnapshotRef {
readonly host?: string | undefined;
readonly projectId: string;
readonly repository: string;
readonly number: number;
@@ -1037,7 +1039,9 @@ const pullRequestDetailSnapshotKey = (
environmentId: string,
reference: PullRequestDetailSnapshotRef,
) =>
`t3.pullRequests.detail:${environmentId}:${reference.projectId}:${reference.repository}#${reference.number}`;
reference.host
? `t3.pullRequests.detail:${JSON.stringify([environmentId, reference.projectId, reference.host.toLowerCase(), reference.repository.toLowerCase(), reference.number])}`
: `t3.pullRequests.detail:${environmentId}:${reference.projectId}:${reference.repository}#${reference.number}`;
const decodeDetailSnapshot = Schema.decodeUnknownOption(PullRequestDetail);
@@ -1056,7 +1060,9 @@ export function readPullRequestDetailSnapshot(
const raw = storage?.getItem(pullRequestDetailSnapshotKey(environmentId, reference));
if (!raw) return null;
const decoded = decodeDetailSnapshot(JSON.parse(raw));
return decoded._tag === "Some" ? decoded.value : null;
return decoded._tag === "Some"
? resolveDisplayedPullRequestDetail({ live: null, cached: decoded.value, reference })
: null;
} catch {
return null;
}
@@ -1090,7 +1096,9 @@ export function resolveDisplayedPullRequestDetail(input: {
input.cached !== null &&
input.cached.projectId === input.reference.projectId &&
input.cached.repository.toLowerCase() === input.reference.repository.toLowerCase() &&
input.cached.number === input.reference.number
input.cached.number === input.reference.number &&
(input.reference.host === undefined ||
parseChangeRequestUrl(input.cached.url)?.host === input.reference.host.toLowerCase())
) {
return input.cached;
}
@@ -0,0 +1,76 @@
import type { ThreadPullRequestLink } from "@t3tools/contracts";
import { resolveThreadPullRequestChains } from "@t3tools/shared/threadPullRequests";
import { describe, expect, it } from "vite-plus/test";
import { pullRequestListLines } from "./pullRequestListLines";
function link(
number: number,
head: string,
base: string,
updatedAt: string,
stack: ThreadPullRequestLink["stack"] = null,
): ThreadPullRequestLink {
return {
host: "github.com",
repository: "acme/web",
number,
url: `https://github.com/acme/web/pull/${number}`,
source: "manual",
linkedAt: "2026-01-01T00:00:00.000Z",
snapshot: {
state: "open",
title: `PR ${number}`,
headBranch: head,
baseBranch: base,
isDraft: false,
updatedAt,
syncedAt: updatedAt,
},
stack,
};
}
describe("pullRequestListLines", () => {
it("orders newest first and keeps a stack together under its base layer", () => {
const lines = pullRequestListLines(
resolveThreadPullRequestChains([
link(1, "a", "main", "2026-01-01T10:00:00Z"),
link(2, "b", "a", "2026-01-01T12:00:00Z"),
link(9, "solo", "main", "2026-01-01T11:00:00Z"),
link(5, "old", "main", "2026-01-01T09:00:00Z"),
]),
);
expect(lines.map((line) => [line.link.number, line.depth, line.stack?.size ?? null])).toEqual([
// The stack's newest layer is #2 at 12:00, so the whole stack outranks #9 at 11:00.
[1, 0, 2],
[2, 1, null],
[9, 0, null],
[5, 0, null],
]);
});
it("marks native stacks on their base layer", () => {
const stack = {
kind: "native" as const,
id: "1",
number: 1,
url: "https://github.com/acme/web/stacks/1",
base: "main",
layers: [
{ number: 3, headBranch: "x", state: "open" as const },
{ number: 4, headBranch: "y", state: "open" as const },
],
};
const lines = pullRequestListLines(
resolveThreadPullRequestChains([
link(4, "y", "x", "2026-01-01T10:00:00Z", stack),
link(3, "x", "main", "2026-01-01T10:00:00Z", stack),
]),
);
expect(lines.map((line) => [line.link.number, line.depth, line.stack?.kind ?? null])).toEqual([
[3, 0, "native"],
[4, 1, null],
]);
});
});
@@ -0,0 +1,49 @@
import type { ThreadPullRequestLink } from "@t3tools/contracts";
import type { ThreadPullRequestChain } from "@t3tools/shared/threadPullRequests";
/** One line of a thread's pull-request list: a link plus how deep it sits in its stack. */
export interface PullRequestListLine {
readonly link: ThreadPullRequestLink;
/** 0 for a pull request on the base branch; each layer above steps in by one. */
readonly depth: number;
/** Which chain the line belongs to, so callers can tell one stack's lines from another's. */
readonly chainKey: string;
/** Set on the bottom layer of a multi-layer stack, so that row can name the whole stack. */
readonly stack: { readonly kind: ThreadPullRequestChain["kind"]; readonly size: number } | null;
}
function activityAt(link: ThreadPullRequestLink): number {
const ms = Date.parse(link.snapshot?.updatedAt ?? link.linkedAt);
return Number.isNaN(ms) ? 0 : ms;
}
function chainKeyOf(chain: ThreadPullRequestChain): string {
const bottom = chain.layers[0]!;
return `${bottom.host}/${bottom.repository}#${bottom.number}`;
}
/**
* Flattens chains into indented lines, newest first. A stack sorts by its most recent layer and
* then reads bottom to top beneath that slot, so the layer you would review first is at the
* bottom of the indent and a fresh push anywhere in the stack floats the whole stack up.
*/
export function pullRequestListLines(
chains: ReadonlyArray<ThreadPullRequestChain>,
): ReadonlyArray<PullRequestListLine> {
const ordered = [...chains].sort(
(left, right) =>
Math.max(...right.layers.map(activityAt)) - Math.max(...left.layers.map(activityAt)),
);
return ordered.flatMap((chain) => {
const chainKey = chainKeyOf(chain);
return chain.layers.map((link, depth) => ({
link,
depth,
chainKey,
stack:
depth === 0 && chain.layers.length > 1
? { kind: chain.kind, size: chain.layers.length }
: null,
}));
});
}
@@ -1,6 +1,11 @@
import { beforeEach, describe, expect, it } from "vite-plus/test";
import { ProjectId } from "@t3tools/contracts";
import { type PendingReviewComment, usePullRequestReviewStore } from "./pullRequestReviewStore";
import {
type PendingReviewComment,
pullRequestReviewKey,
usePullRequestReviewStore,
} from "./pullRequestReviewStore";
function comment(id: string, body = id): PendingReviewComment {
return { id, body, path: "src/app.ts", position: { kind: "added", newLine: 1 } };
@@ -36,6 +41,30 @@ describe("pull request review drafts", () => {
});
});
it("keeps drafts on different hosts separate when a thread reviews the same repository and number", () => {
const reference = {
projectId: ProjectId.make("project-a"),
repository: "owner/repo",
number: 7,
};
const publicKey = pullRequestReviewKey({ ...reference, host: "github.com" });
const enterpriseKey = pullRequestReviewKey({ ...reference, host: "github.example.com" });
const store = usePullRequestReviewStore.getState();
store.addComment(publicKey, comment("public"));
store.setSummary(publicKey, "Public review");
expect(usePullRequestReviewStore.getState().drafts[enterpriseKey]).toBeUndefined();
expect(usePullRequestReviewStore.getState().summaries[enterpriseKey]).toBeUndefined();
store.addComment(enterpriseKey, comment("enterprise"));
store.setSummary(enterpriseKey, "Enterprise review");
store.clear(enterpriseKey);
store.clearSummary(enterpriseKey, "Enterprise review");
expect(usePullRequestReviewStore.getState().drafts[publicKey]).toEqual([comment("public")]);
expect(usePullRequestReviewStore.getState().summaries[publicKey]).toBe("Public review");
});
it("does not clear a summary revised while submission is in flight", () => {
const store = usePullRequestReviewStore.getState();
store.setSummary("review-a", "Submitted body");
@@ -6,7 +6,7 @@
* hosts that have no pending review of their own. That also means a draft lives only as long
* as the tab does, which is why this is deliberately not persisted.
*/
import type { ProjectId, PullRequestRef, PullRequestReviewCommentDraft } from "@t3tools/contracts";
import type { PullRequestRef, PullRequestReviewCommentDraft } from "@t3tools/contracts";
import { create } from "zustand";
export type PendingReviewComment = PullRequestReviewCommentDraft & { readonly id: string };
@@ -24,9 +24,14 @@ export function nextPendingReviewCommentId(): string {
return `pending-review-comment-${pendingCommentSequence}`;
}
/** One pull request's draft, scoped by project as well as repository: a repository can be checked out twice. */
/** A project's thread can review the same repository path and number on different hosts. */
export function pullRequestReviewKey(reference: PullRequestRef): string {
return `${reference.projectId}/${reference.repository}#${reference.number}`;
return JSON.stringify([
reference.projectId,
reference.host?.toLowerCase() ?? null,
reference.repository.toLowerCase(),
reference.number,
]);
}
interface PullRequestReviewStoreState {
@@ -81,11 +86,9 @@ export const usePullRequestReviewStore = create<PullRequestReviewStoreState>()((
}));
/** The comments a pull request's draft holds, stable across renders while it is empty. */
export function usePendingReviewComments(reference: {
readonly projectId: ProjectId;
readonly repository: string;
readonly number: number;
}): ReadonlyArray<PendingReviewComment> {
export function usePendingReviewComments(
reference: PullRequestRef,
): ReadonlyArray<PendingReviewComment> {
return usePullRequestReviewStore(
(store) => store.drafts[pullRequestReviewKey(reference)] ?? EMPTY,
);