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

@@ -43,6 +43,7 @@ vi.mock("../state/session", async (importOriginal) => ({
vi.mock("../state/entities", () => ({
readThreadShell: () => null,
useProjects: () => [],
useServerConfigs: () => new Map(),
}));
vi.mock("../remoteOpen", () => ({
useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }),
@@ -52,8 +53,7 @@ vi.mock("../editorPreferences", () => ({
usePreferredEditor: () => [null, vi.fn()],
}));
vi.mock("~/lib/openPullRequestLink", () => ({
findProjectForChangeRequest: () => undefined,
matchesLinkedPullRequestUrl: () => false,
findProjectOnChangeRequestHost: () => undefined,
parseChangeRequestUrl: () => null,
useOpenChangeRequestLink: () => vi.fn(),
}));
+25 -50
View File
@@ -1,3 +1,4 @@
import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
import { useAtomValue } from "@effect/atom-react";
import {
CheckIcon,
@@ -26,7 +27,7 @@ import type {
EnvironmentId,
ScopedThreadRef,
ServerProviderSkill,
ThreadLinkedPullRequest,
ThreadPullRequestKey,
} from "@t3tools/contracts";
import { faviconUrlForOrigin } from "@t3tools/shared/favicon";
import {
@@ -155,7 +156,6 @@ import { previewEnvironment } from "../state/preview";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { projectEnvironment } from "../state/projects";
import { threadEnvironment } from "../state/threads";
import {
claimWorkspaceBasenameLookup,
needsWorkspaceBasenameLookup,
@@ -164,7 +164,6 @@ import {
} from "../workspaceBasenameLookup";
import {
findProjectForChangeRequest,
matchesLinkedPullRequestUrl,
parseChangeRequestUrl,
pullRequestCandidateUrlFromReferenceAutolink,
useOpenChangeRequestLink,
@@ -2185,9 +2184,7 @@ function useChatMarkdownState({
const openPreview = useAtomCommand(previewEnvironment.open, {
reportFailure: false,
});
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const pullRequestLinking = usePullRequestLinking(threadRef?.environmentId);
const environmentId = threadRef?.environmentId ?? explicitEnvironmentId ?? null;
const remoteOpen = useRemoteOpenResolution(environmentId);
const canUseShellActions = canUseMarkdownFileShellActions(
@@ -2239,9 +2236,6 @@ function useChatMarkdownState({
[createAssetUrl, cwd, expandMedia, preparedConnection, threadRef],
);
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
const threadServerConfig = useAtomValue(
serverEnvironment.configValueAtom(threadRef?.environmentId ?? environmentId),
);
const projects = useProjects();
const availableEditors = serverConfig?.availableEditors ?? [];
const [preferredEditor] = usePreferredEditor(availableEditors);
@@ -2331,52 +2325,33 @@ function useChatMarkdownState({
// makes a persisted "app" apply once settings hydrate after launch.
const linkTargetPreference = useClientSettings((settings) => settings.browserLinkTarget);
const resolveThreadPullRequest = useCallback(
(href: string): ThreadLinkedPullRequest | null => {
(href: string): (ThreadPullRequestKey & { readonly url: string }) | null => {
if (
threadRef === undefined ||
readThreadShell(threadRef) === null ||
threadServerConfig?.environment.capabilities.threadPullRequestLinking !== true
) {
!pullRequestLinking.canLink(href)
)
return null;
}
const parsed = parseChangeRequestUrl(href);
if (parsed === null) return null;
const project = findProjectForChangeRequest(
projects.filter((candidate) => candidate.environmentId === threadRef.environmentId),
parsed,
);
if (project === undefined) return null;
return {
projectId: project.id,
repository: project.repositoryIdentity?.displayName ?? parsed.repository,
number: parsed.number,
url: href,
};
return parsed === null ? null : { ...parsed, url: href };
},
[projects, threadRef, threadServerConfig],
[pullRequestLinking, threadRef],
);
const linkedThreadPullRequestFor = useCallback(
(href: string) => {
if (threadRef === undefined || !pullRequestLinking.isLinked(readThreadShell(threadRef), href))
return null;
const parsed = parseChangeRequestUrl(href);
return parsed === null ? null : { ...parsed, url: href };
},
[pullRequestLinking, threadRef],
);
const updateThreadPullRequestLink = useCallback(
async (href: string, linked: boolean) => {
if (threadRef === undefined) return;
const linkedPullRequest = linked ? resolveThreadPullRequest(href) : null;
if (linked && linkedPullRequest === null) {
throw new Error("The pull request is not available in this environment.");
}
if (!linked) {
const currentPullRequest = readThreadShell(threadRef)?.linkedPullRequest;
if (currentPullRequest == null || !matchesLinkedPullRequestUrl(currentPullRequest, href)) {
return;
}
}
const result = await updateThreadMetadata({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId, linkedPullRequest },
});
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
throw squashAtomCommandFailure(result);
}
if (threadRef === undefined || (!linked && linkedThreadPullRequestFor(href) === null)) return;
await pullRequestLinking.changeLink(threadRef, href, linked);
},
[resolveThreadPullRequest, threadRef, updateThreadMetadata],
[linkedThreadPullRequestFor, pullRequestLinking, threadRef],
);
const openExternalLinkInPreview = useCallback(
(url: string) => {
@@ -2588,6 +2563,7 @@ function useChatMarkdownState({
openExternalLinkInPreview,
openMarkdownMedia,
projects,
linkedThreadPullRequestFor,
resolveThreadPullRequest,
resolvedTheme,
serverConfig,
@@ -2614,6 +2590,7 @@ function useChatMarkdownState({
openExternalLinkInPreview,
openMarkdownMedia,
projects,
linkedThreadPullRequestFor,
resolveThreadPullRequest,
resolvedTheme,
serverConfig,
@@ -2732,6 +2709,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
linkTargetPreference,
openExternalLinkInPreview,
projects,
linkedThreadPullRequestFor,
resolveThreadPullRequest,
serverConfig,
updateThreadPullRequestLink,
@@ -2866,13 +2844,10 @@ const CHAT_MARKDOWN_COMPONENTS = {
event.stopPropagation();
const api = readLocalApi();
if (!api) return;
const pullRequest = resolveThreadPullRequest(href);
const currentPullRequest =
threadRef === undefined ? null : readThreadShell(threadRef)?.linkedPullRequest;
const threadLinkAction =
currentPullRequest != null && matchesLinkedPullRequestUrl(currentPullRequest, href)
linkedThreadPullRequestFor(href) !== null
? "unlink-from-thread"
: pullRequest === null
: resolveThreadPullRequest(href) === null
? undefined
: "link-to-thread";
void showExternalLinkContextMenu({
@@ -32,6 +32,7 @@ vi.mock("../state/session", async (importOriginal) => ({
vi.mock("../state/entities", () => ({
readThreadShell: () => null,
useProjects: () => [],
useServerConfigs: () => new Map(),
}));
vi.mock("../remoteOpen", () => ({
useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }),
@@ -41,8 +42,7 @@ vi.mock("../editorPreferences", () => ({
usePreferredEditor: () => [null, vi.fn()],
}));
vi.mock("~/lib/openPullRequestLink", () => ({
findProjectForChangeRequest: () => undefined,
matchesLinkedPullRequestUrl: () => false,
findProjectOnChangeRequestHost: () => undefined,
parseChangeRequestUrl: () => null,
useOpenChangeRequestLink: () => vi.fn(),
}));
@@ -726,6 +726,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
proposedPlans: [],
activities: [],
checkpoints: [],
pullRequests: [],
createdAt: now,
updatedAt: now,
archivedAt: null,
@@ -843,6 +844,7 @@ describe("buildLoadingThreadFromShell", () => {
snoozedUntil: null,
snoozedAt: null,
session: null,
pullRequests: [],
latestUserMessageAt: now,
hasPendingApprovals: false,
hasPendingUserInput: false,
@@ -353,6 +353,7 @@ export function buildLocalDraftThread(
branch: draftThread.branch,
worktreePath: draftThread.worktreePath,
checkpoints: [],
pullRequests: [],
activities: [],
proposedPlans: [],
};
+30 -2
View File
@@ -203,6 +203,8 @@ import { PullRequestDetailGhost } from "./pullRequest/PullRequestGhosts";
import { PullRequestsUnavailableState } from "./pullRequest/PullRequestsUnavailableState";
import { RightPanelTabs } from "./RightPanelTabs";
import { AgentsPanel } from "./AgentsPanel";
import { LinkPullRequestDialogHost } from "./pullRequest/LinkPullRequestDialog";
import { ThreadPullRequestsPanel } from "./pullRequest/ThreadPullRequestsPanel";
import {
deriveAgentPanelModel,
foldSubagentActivities,
@@ -4127,6 +4129,12 @@ export default function ChatView(props: ChatViewProps) {
if (!activeThreadRef) return;
useRightPanelStore.getState().open(activeThreadRef, "agents");
}, [activeThreadRef]);
const supportsThreadPullRequests =
serverConfig?.environment.capabilities.threadPullRequests === true;
const addPullRequestsSurface = useCallback(() => {
if (!activeThreadRef || !supportsThreadPullRequests) return;
useRightPanelStore.getState().open(activeThreadRef, "pull-requests");
}, [activeThreadRef, supportsThreadPullRequests]);
const openFileSurface = useCallback(
(relativePath: string) => {
if (!activeThreadRef || !activeProject) return;
@@ -5375,9 +5383,16 @@ export default function ChatView(props: ChatViewProps) {
: resolveThreadReferenceCopyTarget({
threadId: activeThreadId,
openPanelPullRequestUrl,
pullRequests: activeThreadMetadata?.pullRequests,
linkedPullRequestUrl: linkedThreadPullRequest?.url ?? null,
}),
[activeThreadId, isServerThread, linkedThreadPullRequest?.url, openPanelPullRequestUrl],
[
activeThreadId,
isServerThread,
activeThreadMetadata?.pullRequests,
linkedThreadPullRequest?.url,
openPanelPullRequestUrl,
],
);
const copyActiveThreadReference = useCallback(() => {
const target = activeThreadReferenceCopyTarget;
@@ -8037,11 +8052,12 @@ export default function ChatView(props: ChatViewProps) {
// reader's feet. A link the agent wrote can open any other one here, and that one has to be
// checkable out like it is anywhere else.
<PullRequestDetailPanel
key={`${renderedRightPanelSurface.repository}#${renderedRightPanelSurface.number}`}
key={`${renderedRightPanelSurface.host ?? ""}:${renderedRightPanelSurface.repository}#${renderedRightPanelSurface.number}`}
environmentId={activeThread.environmentId}
threadRef={activeThreadRef}
reference={{
projectId: renderedRightPanelSurface.projectId as ProjectId,
...(renderedRightPanelSurface.host ? { host: renderedRightPanelSurface.host } : {}),
repository: renderedRightPanelSurface.repository,
number: renderedRightPanelSurface.number,
}}
@@ -8062,7 +8078,14 @@ export default function ChatView(props: ChatViewProps) {
: "page"
}
composerDraftTarget={composerDraftTarget}
onBack={
activeThreadRef !== null && supportsThreadPullRequests
? addPullRequestsSurface
: undefined
}
/>
) : renderedRightPanelSurface?.kind === "pull-requests" && activeThreadRef ? (
<ThreadPullRequestsPanel threadRef={activeThreadRef} />
) : renderedRightPanelSurface?.kind === "agents" ? (
<AgentsPanel
model={agentPanelModel}
@@ -8620,12 +8643,14 @@ export default function ChatView(props: ChatViewProps) {
onAddDiff={addDiffSurface}
onAddFiles={addFilesSurface}
onAddPullRequest={addPullRequestSurface}
onAddPullRequests={addPullRequestsSurface}
onAddAgents={addAgentsSurface}
browserAvailable={isPreviewSupportedInRuntime()}
terminalAvailable={activeProject !== null}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
pullRequestAvailable={pullRequestSurfaceAvailable}
pullRequestsAvailable={isServerThread && supportsThreadPullRequests}
agentsAvailable
liveAgentCount={agentPanelModel.liveCount}
>
@@ -8670,12 +8695,14 @@ export default function ChatView(props: ChatViewProps) {
onAddDiff={addDiffSurface}
onAddFiles={addFilesSurface}
onAddPullRequest={addPullRequestSurface}
onAddPullRequests={addPullRequestsSurface}
onAddAgents={addAgentsSurface}
browserAvailable={isPreviewSupportedInRuntime()}
terminalAvailable={activeProject !== null}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
pullRequestAvailable={pullRequestSurfaceAvailable}
pullRequestsAvailable={isServerThread && supportsThreadPullRequests}
agentsAvailable
liveAgentCount={agentPanelModel.liveCount}
>
@@ -8684,6 +8711,7 @@ export default function ChatView(props: ChatViewProps) {
</RightPanelSheet>
) : null}
<LinkPullRequestDialogHost />
{expandedImage && (
<ExpandedImageDialog
key={expandedImageKey(expandedImage)}
@@ -149,6 +149,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
branch: null,
worktreePath: null,
checkpoints: [],
pullRequests: [],
activities: [],
...overrides,
};
+38 -1
View File
@@ -1,5 +1,7 @@
"use client";
import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility";
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
import {
canCreateProjectInEnvironment,
@@ -43,6 +45,7 @@ import {
FileSearchIcon,
FolderIcon,
FolderPlusIcon,
GitPullRequestArrowIcon,
LinkIcon,
MessageSquareIcon,
PaletteIcon,
@@ -80,7 +83,7 @@ import { sourceControlEnvironment } from "../state/sourceControl";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
import { useProjects, useThreadShells } from "../state/entities";
import { useProjects, useServerConfigs, useThreadShells } from "../state/entities";
import { useThreadSearch } from "../state/queries";
import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";
import {
@@ -148,6 +151,7 @@ import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons"
import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
import { ProjectFavicon } from "./ProjectFavicon";
import { ProjectFilePicker } from "./files/ProjectFilePicker";
import { openLinkPullRequestDialog } from "./pullRequest/LinkPullRequestDialog";
import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog";
import { toggleThemeEditorForTheme } from "./settings/themeEditorStore";
import { searchSettings, SETTINGS_SECTION_LABELS } from "./settings/settingsSearch";
@@ -605,12 +609,16 @@ function OpenCommandPaletteDialog(props: {
? scopeThreadRef(activeThread.environmentId, activeThread.id)
: null;
const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(referenceThreadRef);
const activeThreadServerConfig = useServerConfigs().get(
activeThread?.environmentId ?? ("" as EnvironmentId),
);
const activeThreadReferenceCopyTarget =
referenceThreadRef === null || (pathname === "/pull-requests" && !openPanelPullRequestUrl)
? null
: resolveThreadReferenceCopyTarget({
threadId: referenceThreadRef.threadId,
openPanelPullRequestUrl,
pullRequests: activeThread?.pullRequests,
linkedPullRequestUrl:
activeThread?.linkedPullRequest?.url ?? activeThread?.branchPullRequest?.url ?? null,
});
@@ -1591,6 +1599,35 @@ function OpenCommandPaletteDialog(props: {
});
}
if (
activeThread !== null &&
threadPullRequestLinkMode(activeThreadServerConfig?.environment.capabilities) !== "unsupported"
) {
const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id);
actionItems.push({
kind: "action",
value: "action:link-pull-request",
searchTerms: ["link", "pull request", "pr", "attach", "stack"],
title: "Link pull request to thread",
icon: <GitPullRequestArrowIcon className={ITEM_ICON_CLASS} />,
run: async () => {
openLinkPullRequestDialog(threadRef);
},
});
if (activeThreadServerConfig?.environment.capabilities.threadPullRequests === true) {
actionItems.push({
kind: "action",
value: "action:open-thread-pull-requests",
searchTerms: ["pull requests", "linked", "stack", "prs"],
title: "Show linked pull requests",
icon: <GitPullRequestArrowIcon className={ITEM_ICON_CLASS} />,
run: async () => {
useRightPanelStore.getState().open(threadRef, "pull-requests");
},
});
}
}
actionItems.push({
kind: "action",
value: "action:open-file-picker",
@@ -1351,6 +1351,9 @@ export default function GitActionsControl({
...(commitMessage ? { commitMessage } : {}),
...(featureBranch ? { featureBranch } : {}),
...(filePaths ? { filePaths } : {}),
// A pull request the action opens is linked to the thread it ran beside. Drafts
// have no server thread yet, so there is nothing to link to.
...(activeServerThread ? { threadId: activeServerThread.id } : {}),
onProgress: applyProgressEvent,
});
+45 -4
View File
@@ -1,3 +1,10 @@
import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
import { GitPullRequestIcon } from "lucide-react";
import { LinkBranchPullRequestButton } from "./pullRequest/LinkBranchPullRequestButton";
import {
resolveThreadCurrentPullRequestLink,
visibleThreadPullRequests,
} from "@t3tools/shared/threadPullRequests";
import { Spinner } from "~/components/ui/spinner";
import {
ArchiveIcon,
@@ -465,10 +472,16 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
});
const linkedPullRequestStatus = useLinkedThreadPullRequest(
thread.environmentId,
thread.linkedPullRequest ?? thread.branchPullRequest,
thread.linkedPullRequest,
leaseLiveStatus,
thread.pullRequests,
thread.branchPullRequest,
);
const pr = linkedPullRequestStatus?.pr ?? null;
const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
const currentLinkedPr = supportsMultiplePullRequests
? resolveThreadCurrentPullRequestLink(thread.pullRequests)
: null;
const prStatus = prStatusIndicator(pr, linkedPullRequestStatus?.sourceControlProvider);
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning;
@@ -579,17 +592,26 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
);
const handlePrClick = useCallback(
(event: React.MouseEvent<HTMLAnchorElement>) => {
if (!prStatus) return;
const url = prStatus?.url ?? currentLinkedPr?.url;
if (!url) return;
const openedInRightPanel = openPrLink(
event,
prStatus.url,
url,
openPullRequestsInRightPanel ? threadRef : undefined,
);
if (openedInRightPanel && openPullRequestsInRightPanel && !isActive) {
navigateToThread(threadRef);
}
},
[isActive, navigateToThread, openPrLink, openPullRequestsInRightPanel, prStatus, threadRef],
[
isActive,
navigateToThread,
openPrLink,
openPullRequestsInRightPanel,
prStatus,
currentLinkedPr,
threadRef,
],
);
const handleRenameInputRef = useCallback(
(element: HTMLInputElement | null) => {
@@ -729,6 +751,25 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
</TooltipPopup>
</Tooltip>
)}
{!pr && currentLinkedPr ? (
<a
href={currentLinkedPr.url}
target="_blank"
rel="noopener noreferrer"
onPointerDown={(event) => event.stopPropagation()}
onClick={handlePrClick}
className="text-muted-foreground"
aria-label={`PR #${currentLinkedPr.number}, status pending`}
>
<GitPullRequestIcon className="size-3" />
</a>
) : null}
{pr &&
(supportsMultiplePullRequests
? visibleThreadPullRequests(thread.pullRequests).length === 0
: thread.linkedPullRequest == null) ? (
<LinkBranchPullRequestButton threadRef={threadRef} url={pr.url} />
) : null}
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
{renamingThreadKey === threadKey ? (
<input
@@ -1,9 +1,11 @@
import { EnvironmentId, type ThreadPullRequestLink } from "@t3tools/contracts";
import type { DesktopPreviewFavicon, PreviewSessionSnapshot } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
import {
RightPanelTabs,
resolvePullRequestTabLink,
shouldOpenDefaultBrowserProfileFromMenuClick,
surfaceShortcutActionForKey,
surfaceShortcutTargetsTypingContext,
@@ -117,6 +119,7 @@ function renderTabs(
onAddBrowserInProfile={() => undefined}
onAddTerminal={() => undefined}
onAddPullRequest={() => undefined}
onAddPullRequests={() => undefined}
onAddDiff={() => undefined}
onAddFiles={() => undefined}
onAddAgents={() => undefined}
@@ -126,6 +129,7 @@ function renderTabs(
diffAvailable={false}
filesAvailable={false}
pullRequestAvailable={false}
pullRequestsAvailable={false}
agentsAvailable={false}
>
<div>content</div>
@@ -278,3 +282,47 @@ describe("tabMuteMenuItem", () => {
});
});
});
describe("pull request tab snapshots", () => {
const environmentId = EnvironmentId.make("local");
const link: ThreadPullRequestLink = {
host: "github.com",
repository: "acme/api",
number: 7,
url: "https://github.com/acme/api/pull/7",
source: "manual",
linkedAt: "2026-01-01T00:00:00Z",
stack: null,
snapshot: null,
};
it("keeps unknown linked state authoritative and scopes matches to environment and host", () => {
const threads = [{ environmentId, pullRequests: [link] }];
expect(resolvePullRequestTabLink(threads, environmentId, "github.com", link)).toBe(link);
expect(
resolvePullRequestTabLink(threads, EnvironmentId.make("remote"), "github.com", link),
).toBeUndefined();
expect(
resolvePullRequestTabLink(threads, environmentId, "github.enterprise.test", link),
).toBeUndefined();
});
it("uses the newest snapshot when several threads link the same PR", () => {
const snapshot = {
state: "merged" as const,
title: "API",
headBranch: "api",
baseBranch: "main",
isDraft: false,
updatedAt: null,
syncedAt: "2026-02-01T00:00:00Z",
};
const newer = { ...link, snapshot };
expect(
resolvePullRequestTabLink(
[{ environmentId, pullRequests: [link, newer] }],
environmentId,
"github.com",
link,
),
).toBe(newer);
});
});
+97 -3
View File
@@ -1,3 +1,10 @@
import { pullRequestHostOf, type SourceControlProviderKind } from "@t3tools/contracts";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { useProjects, useServerConfigs, useThreadShells } from "~/state/entities";
import {
threadPullRequestKeysEqual,
visibleThreadPullRequests,
} from "@t3tools/shared/threadPullRequests";
import type {
ContextMenuItem,
EnvironmentId,
@@ -14,6 +21,7 @@ import {
FileDiff,
Files,
GitPullRequest,
GitPullRequestArrow,
Globe2,
Plus,
TerminalSquare,
@@ -104,12 +112,14 @@ interface RightPanelTabsProps {
onAddDiff: () => void;
onAddFiles: () => void;
onAddPullRequest: () => void;
onAddPullRequests: () => void;
onAddAgents: () => void;
browserAvailable: boolean;
terminalAvailable: boolean;
diffAvailable: boolean;
filesAvailable: boolean;
pullRequestAvailable: boolean;
pullRequestsAvailable: boolean;
agentsAvailable: boolean;
pullRequestStatusSeeds?: Readonly<Record<string, PullRequestTabStatusSeed>>;
/** Running + waiting subagents; badges the Agents card in the empty state. */
@@ -139,6 +149,7 @@ const SURFACE_DISABLED_REASONS = {
files: "Files are only available when a project is open.",
diff: "Diff is only available for server threads in Git repositories.",
pullRequest: "This thread's branch has no pull request yet.",
pullRequests: "Linked pull requests are only available for server threads.",
agents: "Agents are only available from a thread.",
} as const;
@@ -161,6 +172,7 @@ const SURFACE_UNAVAILABLE_HINTS = {
files: "Available when a project is open.",
diff: "Available for Git repositories.",
pullRequest: "No pull request on this branch yet.",
pullRequests: "Available for server threads.",
agents: "Available from a thread.",
} as const;
@@ -298,12 +310,14 @@ function RightPanelEmptyState(props: {
onAddDiff: () => void;
onAddFiles: () => void;
onAddPullRequest: () => void;
onAddPullRequests: () => void;
onAddAgents: () => void;
browserAvailable: boolean;
terminalAvailable: boolean;
diffAvailable: boolean;
filesAvailable: boolean;
pullRequestAvailable: boolean;
pullRequestsAvailable: boolean;
agentsAvailable: boolean;
liveAgentCount: number;
}) {
@@ -361,6 +375,16 @@ function RightPanelEmptyState(props: {
onClick: props.onAddPullRequest,
badgeCount: 0,
},
{
label: "Linked pull requests",
description: "Every pull request this thread has linked, stacks included.",
icon: GitPullRequestArrow,
shortcut: "L",
available: props.pullRequestsAvailable,
disabledReason: SURFACE_UNAVAILABLE_HINTS.pullRequests,
onClick: props.onAddPullRequests,
badgeCount: 0,
},
{
label: "Agents",
description: "Follow subagents and workflows.",
@@ -602,6 +626,8 @@ function surfaceTitle(
);
case "pull-request":
return `#${surface.number}`;
case "pull-requests":
return "Pull requests";
case "agents":
return "Agents";
case "preview": {
@@ -683,11 +709,42 @@ function SurfaceIcon({
seed={pullRequestStatusSeeds?.[surface.id]}
/>
);
case "pull-requests":
return <GitPullRequestArrow className="size-3 shrink-0" />;
case "agents":
return <Bot className="size-3 shrink-0" />;
}
}
export function resolvePullRequestTabLink(
threads: readonly Pick<EnvironmentThreadShell, "environmentId" | "pullRequests">[],
environmentId: EnvironmentId | null,
host: string | null,
reference: { repository: string; number: number },
) {
if (environmentId === null || host === null) return undefined;
let newest: EnvironmentThreadShell["pullRequests"][number] | undefined;
for (const thread of threads) {
if (thread.environmentId !== environmentId) continue;
for (const link of visibleThreadPullRequests(thread.pullRequests)) {
if (
!threadPullRequestKeysEqual(link, {
host,
repository: reference.repository,
number: reference.number,
})
)
continue;
if (
newest === undefined ||
(link.snapshot?.syncedAt ?? "") > (newest.snapshot?.syncedAt ?? "")
)
newest = link;
}
}
return newest;
}
function PullRequestSurfaceIcon({
surface,
environmentId,
@@ -699,13 +756,36 @@ function PullRequestSurfaceIcon({
}) {
const resolvedEnvironmentId =
(surface.environmentId as EnvironmentId | undefined) ?? environmentId;
const detail = useEnvironmentQuery(
const projects = useProjects();
const threads = useThreadShells();
const project = projects.find(
(entry) => entry.environmentId === resolvedEnvironmentId && entry.id === surface.projectId,
);
const identity = project?.repositoryIdentity;
const host =
surface.host ??
(identity?.provider
? pullRequestHostOf(identity, identity.provider as SourceControlProviderKind)
: null);
const configs = useServerConfigs();
const capabilities =
resolvedEnvironmentId === null
? undefined
: configs.get(resolvedEnvironmentId)?.environment.capabilities;
const linkedSnapshot =
capabilities?.threadPullRequests === true
? (resolvePullRequestTabLink(threads, resolvedEnvironmentId, host, surface)?.snapshot ?? null)
: null;
const detail = useEnvironmentQuery(
resolvedEnvironmentId === null || capabilities?.pullRequests !== true || linkedSnapshot !== null
? null
: pullRequestEnvironment.detail({
environmentId: resolvedEnvironmentId,
input: {
projectId: surface.projectId as ProjectId,
...(capabilities?.threadPullRequests === true && surface.host !== undefined
? { host: surface.host }
: {}),
repository: surface.repository,
number: surface.number,
},
@@ -714,11 +794,15 @@ function PullRequestSurfaceIcon({
// Only state and draft reach the tab. A list seed cannot know mergeability, so feeding the
// full detail would flip an open tab to the conflict glyph the moment its read lands.
const status =
detail === null ? (seed ?? null) : { state: detail.state, isDraft: detail.isDraft };
linkedSnapshot !== null
? linkedSnapshot
: detail === null
? (seed ?? null)
: { state: detail.state, isDraft: detail.isDraft };
if (status === null) {
return <GitPullRequest className="size-3 shrink-0 text-muted-foreground" />;
}
const presentation = resolvePullRequestState(status);
const presentation = resolvePullRequestState({ state: status.state, isDraft: status.isDraft });
return <presentation.Icon className={cn("size-3 shrink-0", presentation.toneClassName)} />;
}
@@ -806,6 +890,14 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
disabledReason: SURFACE_DISABLED_REASONS.pullRequest,
onClick: props.onAddPullRequest,
},
{
label: "Linked pull requests",
icon: GitPullRequestArrow,
shortcut: "L",
available: props.pullRequestsAvailable,
disabledReason: SURFACE_DISABLED_REASONS.pullRequests,
onClick: props.onAddPullRequests,
},
{
label: "Agents",
icon: Bot,
@@ -1250,12 +1342,14 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
onAddDiff={props.onAddDiff}
onAddFiles={props.onAddFiles}
onAddPullRequest={props.onAddPullRequest}
onAddPullRequests={props.onAddPullRequests}
onAddAgents={props.onAddAgents}
browserAvailable={props.browserAvailable}
terminalAvailable={props.terminalAvailable}
diffAvailable={props.diffAvailable}
filesAvailable={props.filesAvailable}
pullRequestAvailable={props.pullRequestAvailable}
pullRequestsAvailable={props.pullRequestsAvailable}
agentsAvailable={props.agentsAvailable}
liveAgentCount={props.liveAgentCount}
/>
@@ -2133,6 +2133,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
branch: null,
worktreePath: null,
checkpoints: [],
pullRequests: [],
activities: [],
...overrides,
};
+114 -11
View File
@@ -1,3 +1,9 @@
import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
import { LinkBranchPullRequestButton } from "./pullRequest/LinkBranchPullRequestButton";
import {
resolveThreadCurrentPullRequestLink,
visibleThreadPullRequests,
} from "@t3tools/shared/threadPullRequests";
import { useAtomValue } from "@effect/atom-react";
import * as Schema from "effect/Schema";
import {
@@ -70,6 +76,7 @@ import {
} from "react";
import { useParams, useRouter } from "@tanstack/react-router";
import { useRightPanelStore } from "../rightPanelStore";
import {
isAtomCommandInterrupted,
settlePromise,
@@ -185,8 +192,12 @@ import {
import { SidebarDragLifecycle, SidebarPointerSensor } from "./Sidebar.pointer";
import { createSidebarListMotion } from "./Sidebar.motion";
import {
PR_STATE_COLOR_CLASS,
ThreadPullRequestBadgeIcon,
ThreadPullRequestsMiniList,
ThreadWorktreeIndicator,
prStatusIndicator,
resolveThreadPullRequestBadge,
settledPrHoverColorClass,
terminalStatusFromRunningIds,
type TerminalStatusIndicator,
@@ -209,7 +220,7 @@ import {
} from "../providerInstances";
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { Button } from "./ui/button";
import { Button, InlineButton } from "./ui/button";
import { Input } from "./ui/input";
import {
Combobox,
@@ -330,6 +341,7 @@ function SidebarThreadTooltip({
terminalProcessCount: number;
}) {
const driverKind = providerEntry?.driverKind ?? null;
const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
return (
<TooltipPopup
side="right"
@@ -411,6 +423,11 @@ function SidebarThreadTooltip({
</div>
) : null}
</div>
{supportsMultiplePullRequests && thread.pullRequests.length > 0 ? (
<div className="border-t border-border/60 pt-2 pl-0.5 text-xs text-muted-foreground">
<ThreadPullRequestsMiniList pullRequests={thread.pullRequests} />
</div>
) : null}
</div>
</TooltipPopup>
);
@@ -1047,8 +1064,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
const gitCwd = thread.worktreePath ?? props.project?.workspaceRoot ?? null;
const linkedPullRequestStatus = useLinkedThreadPullRequest(
thread.environmentId,
thread.linkedPullRequest ?? thread.branchPullRequest,
thread.linkedPullRequest,
leaseLiveStatus,
thread.pullRequests,
thread.branchPullRequest,
);
const gitStatus = useEnvironmentQuery(
leaseLiveStatus && (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
@@ -1063,6 +1082,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
gitStatus.data,
);
const pr = linkedPullRequestStatus?.pr ?? null;
const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
const currentLinkedPr = supportsMultiplePullRequests
? resolveThreadCurrentPullRequestLink(thread.pullRequests)
: null;
// Same semantics as the legacy sidebar (never-visited counts as read):
// switching sidebars must not light up every historical thread as unread.
@@ -1339,17 +1362,26 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
}, [showSnoozeButton]);
const handlePrClick = useCallback(
(event: ReactMouseEvent<HTMLAnchorElement>) => {
if (!pr?.url) return;
const url = pr?.url ?? currentLinkedPr?.url;
if (!url) return;
const openedInRightPanel = openPrLink(
event,
pr.url,
url,
openPullRequestsInRightPanel ? threadRef : undefined,
);
if (openedInRightPanel && openPullRequestsInRightPanel && !props.isActive) {
onThreadActivate(threadRef);
}
},
[onThreadActivate, openPrLink, openPullRequestsInRightPanel, pr, props.isActive, threadRef],
[
onThreadActivate,
openPrLink,
openPullRequestsInRightPanel,
pr,
currentLinkedPr,
props.isActive,
threadRef,
],
);
// All sidebar rows share one surface model. Live threads used to look
@@ -1456,10 +1488,43 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
</span>
);
// A real link so cmd/ctrl+click and middle-click open the host in the
// browser. A plain click still opens T3's pull request view.
// One badge shape for every thread: the glyph says stack or not, the number is the current
// pull request, and "+N" counts the others behind it. A real link so cmd/ctrl+click and
// middle-click open the host in the browser; a plain click opens T3's pull request view.
const prBadgeShape = supportsMultiplePullRequests
? resolveThreadPullRequestBadge(thread.pullRequests)
: null;
const prBadgeClassName = (state: "open" | "merged" | "closed", colorClass: string) =>
cn(
// Sidebar chrome follows the interface font; tabular digits keep the number from
// reflowing as PR states stream in. A border rather than text-decoration, so the line
// runs under the glyph as well as the number.
"text-xs tabular-nums",
variant === "slim" && variantAction === "unsettle"
? props.isActive
? "text-secondary-label"
: cn("text-secondary-label transition-colors", settledPrHoverColorClass(state))
: colorClass,
);
const handlePrStackClick = useCallback(() => {
useRightPanelStore.getState().open(threadRef, "pull-requests");
if (!props.isActive) onThreadActivate(threadRef);
}, [onThreadActivate, props.isActive, threadRef]);
const prBadge =
prStatus && pr ? (
prBadgeShape?.kind === "stack" ? (
// A stack is one thing with N layers; naming one of them would misrepresent it, so the
// badge counts layers and opens the thread's pull-requests surface.
<InlineButton
underline
onPointerDown={(event) => event.stopPropagation()}
onClick={handlePrStackClick}
className={prBadgeClassName(prBadgeShape.state, PR_STATE_COLOR_CLASS[prBadgeShape.state])}
aria-label={`Stack of ${prBadgeShape.layers} pull requests, ${prBadgeShape.state}`}
>
<ThreadPullRequestBadgeIcon icon="stack" />
{prBadgeShape.layers}
</InlineButton>
) : prStatus && pr ? (
<a
href={pr.url}
target="_blank"
@@ -1469,14 +1534,38 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
className={cn(
// Sidebar chrome follows the interface font; tabular digits keep the
// number from reflowing as PR states stream in.
"shrink-0 text-xs tabular-nums hover:underline",
"inline-flex shrink-0 items-center gap-0.5 whitespace-nowrap text-xs tabular-nums hover:underline",
variant === "slim" && variantAction === "unsettle"
? cn("text-secondary-label transition-colors", settledPrHoverClass)
: prStatus.colorClass,
)}
aria-label={prStatus.tooltip}
aria-label={
prBadgeShape && prBadgeShape.kind === "pull-request" && prBadgeShape.others > 0
? `${prStatus.tooltip}, and ${prBadgeShape.others} more linked`
: prStatus.tooltip
}
>
#{pr.number}
<ThreadPullRequestBadgeIcon icon="pull-request" />
{pr.number}
{prBadgeShape && prBadgeShape.others > 0 ? (
<span className="opacity-70">+{prBadgeShape.others}</span>
) : null}
</a>
) : currentLinkedPr ? (
<a
href={currentLinkedPr.url}
target="_blank"
rel="noopener noreferrer"
onPointerDown={(event) => event.stopPropagation()}
onClick={handlePrClick}
className="inline-flex shrink-0 items-center gap-0.5 text-xs tabular-nums text-muted-foreground hover:underline"
aria-label={`PR #${currentLinkedPr.number}, status pending`}
>
<ThreadPullRequestBadgeIcon icon="pull-request" />
{currentLinkedPr.number}
{prBadgeShape?.kind === "pull-request" && prBadgeShape.others > 0 ? (
<span>+{prBadgeShape.others}</span>
) : null}
</a>
) : null;
const terminalStatusIcon = terminalStatus ? (
@@ -1589,6 +1678,13 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
remain visible AND clickable while the row is hovered. Only
the time/jump label yields to the settle affordance. */}
{prBadge}
{prBadge &&
pr &&
(supportsMultiplePullRequests
? visibleThreadPullRequests(thread.pullRequests).length === 0
: thread.linkedPullRequest == null) ? (
<LinkBranchPullRequestButton threadRef={threadRef} url={pr.url} />
) : null}
{sortable?.isDragging ? (
dragDestination
) : (
@@ -1889,6 +1985,13 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
)}
{terminalStatusIcon}
{prBadge}
{prBadge &&
pr &&
(supportsMultiplePullRequests
? visibleThreadPullRequests(thread.pullRequests).length === 0
: thread.linkedPullRequest == null) ? (
<LinkBranchPullRequestButton threadRef={threadRef} url={pr.url} />
) : null}
{diff ? (
<span className="shrink-0 font-mono">
<span className="text-emerald-600 dark:text-emerald-400">+{diff.insertions}</span>{" "}
@@ -1,8 +1,8 @@
import { ThreadId } from "@t3tools/contracts";
import { ThreadId, type ThreadPullRequestLink } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
import { ThreadWorktreeIndicator } from "./ThreadStatusIndicators";
import { ThreadWorktreeIndicator, linkedPullRequestSnapshotStatus } from "./ThreadStatusIndicators";
describe("ThreadWorktreeIndicator", () => {
it("renders the worktree folder and branch in an accessible label", () => {
@@ -37,3 +37,46 @@ describe("ThreadWorktreeIndicator", () => {
expect(markup).toBe("");
});
});
describe("linked pull request snapshots", () => {
const link: ThreadPullRequestLink = {
host: "gitlab.example.com",
repository: "acme/web",
number: 42,
url: "https://gitlab.example.com/acme/web/-/merge_requests/42",
source: "manual",
linkedAt: "2026-01-01T00:00:00Z",
stack: null,
snapshot: null,
};
it("keeps unsynced links unknown", () => {
expect(linkedPullRequestSnapshotStatus(link)).toBeNull();
});
it("uses the snapshot state and branches with the linked identity", () => {
const result = linkedPullRequestSnapshotStatus({
...link,
snapshot: {
state: "merged",
title: "Change",
headBranch: "feature",
baseBranch: "main",
isDraft: false,
updatedAt: "2026-01-02T00:00:00Z",
syncedAt: "2026-01-03T00:00:00Z",
},
});
expect(result).toEqual({
pr: {
number: 42,
url: link.url,
title: "Change",
state: "merged",
isDraft: false,
headRef: "feature",
baseRef: "main",
updatedAt: "2026-01-02T00:00:00Z",
},
sourceControlProvider: { kind: "gitlab", name: "gitlab", baseUrl: "" },
});
});
});
@@ -1,25 +1,35 @@
import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
import { pullRequestDetailToVcsStatus } from "@t3tools/client-runtime/state/pull-requests";
import {
type EnvironmentId,
resolveEnvironmentMachineKind,
type EnvironmentId,
type ThreadLinkedPullRequest,
type ThreadPullRequestLink,
type VcsStatusResult,
} from "@t3tools/contracts";
import { FolderGit2Icon, TerminalIcon } from "lucide-react";
import {
resolveThreadCurrentPullRequestLink,
resolveThreadPullRequestChains,
visibleThreadPullRequests,
} from "@t3tools/shared/threadPullRequests";
import { FolderGit2Icon, GitPullRequestArrowIcon, LayersIcon, TerminalIcon } from "lucide-react";
import { useMemo } from "react";
import { cn } from "../lib/utils";
import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
import { parseChangeRequestUrl } from "../lib/openPullRequestLink";
import { useEnvironmentQuery } from "../state/query";
import { linkedPullRequestDetailAtom, useSharedPullRequestSummary } from "../state/pullRequests";
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
import { useUiStateStore } from "../uiStateStore";
import { resolveChangeRequestPresentation } from "../sourceControlPresentation";
import { resolveThreadStatusPill, type ThreadStatusPill } from "./Sidebar.logic";
import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation";
import type { SidebarThreadSummary } from "../types";
import { formatWorktreePathForDisplay } from "../worktreeCleanup";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { pullRequestListLines } from "./pullRequest/pullRequestListLines";
import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation";
export interface PrStatusIndicator {
label: string;
@@ -43,42 +53,151 @@ export interface LinkedThreadPullRequestStatus {
readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
}
/** Keep cached summaries visible when an offscreen row stops live queries. */
/** Linked badges use persisted snapshots; only branch and legacy fallbacks lease summary reads. */
export function useLinkedThreadPullRequest(
environmentId: EnvironmentId | null,
linkedPullRequest: ThreadLinkedPullRequest | null | undefined,
enabled = true,
pullRequests?: ReadonlyArray<ThreadPullRequestLink>,
branchPullRequest?: ThreadLinkedPullRequest | null,
): LinkedThreadPullRequestStatus | null {
const supportsLinks = useSupportsMultiplePullRequests(environmentId);
const current = useMemo(
() => (supportsLinks ? resolveThreadCurrentPullRequestLink(pullRequests ?? []) : null),
[pullRequests, supportsLinks],
);
const fallback =
current === null ? ((!supportsLinks ? linkedPullRequest : null) ?? branchPullRequest) : null;
const host = fallback == null ? undefined : parseChangeRequestUrl(fallback.url)?.host;
const reference =
fallback == null ? null : { ...fallback, ...(host === undefined ? {} : { host }) };
const queried = useEnvironmentQuery(
!enabled || environmentId === null || linkedPullRequest == null
!enabled || environmentId === null || reference === null
? null
: linkedPullRequestDetailAtom({
environmentId,
input: {
projectId: linkedPullRequest.projectId,
repository: linkedPullRequest.repository,
number: linkedPullRequest.number,
},
}),
: linkedPullRequestDetailAtom({ environmentId, input: reference }),
).data;
const detail = useSharedPullRequestSummary(environmentId, linkedPullRequest ?? null, queried);
const detail = useSharedPullRequestSummary(environmentId, reference, queried);
return useMemo(
return useMemo(() => {
if (current !== null) return linkedPullRequestSnapshotStatus(current);
return detail === null
? null
: {
pr: pullRequestDetailToVcsStatus(detail),
sourceControlProvider: { kind: detail.provider, name: detail.provider, baseUrl: "" },
};
}, [current, detail]);
}
export function linkedPullRequestSnapshotStatus(
link: ThreadPullRequestLink,
): LinkedThreadPullRequestStatus | null {
const snapshot = link.snapshot;
if (snapshot === null) return null;
const kind = link.url.includes("/-/merge_requests/")
? "gitlab"
: link.url.includes("/pullrequest/")
? "azure-devops"
: link.url.includes("/pull-requests/")
? "bitbucket"
: "github";
return {
pr: {
number: link.number,
url: link.url,
title: snapshot.title,
state: snapshot.state,
isDraft: snapshot.isDraft,
headRef: snapshot.headBranch,
baseRef: snapshot.baseBranch,
...(snapshot.updatedAt === null ? {} : { updatedAt: snapshot.updatedAt }),
},
sourceControlProvider: { kind, name: kind, baseUrl: "" },
};
}
export {
resolveThreadPullRequestBadge,
type ThreadPullRequestBadge,
} from "@t3tools/shared/threadPullRequests";
/** The glyph a row's badge wears: the layers icon for a stack, the pull-request one otherwise. */
export function ThreadPullRequestBadgeIcon({
icon,
className,
}: {
icon: "stack" | "pull-request";
className?: string | undefined;
}) {
const Icon = icon === "stack" ? LayersIcon : GitPullRequestArrowIcon;
return <Icon aria-hidden className={cn("size-3 shrink-0", className)} />;
}
/**
* A miniature of the pull-requests panel for the thread tooltip: same order, same indentation,
* so the hover answers "what is in here" without opening the surface.
*/
export function ThreadPullRequestsMiniList({
pullRequests,
}: {
pullRequests: ReadonlyArray<ThreadPullRequestLink>;
}) {
const lines = useMemo(
() =>
detail === null
? null
: {
pr: pullRequestDetailToVcsStatus(detail),
sourceControlProvider: {
kind: detail.provider,
name: detail.provider,
baseUrl: "",
},
},
[detail],
pullRequestListLines(resolveThreadPullRequestChains(visibleThreadPullRequests(pullRequests))),
[pullRequests],
);
if (lines.length === 0) return null;
return (
<ul className="flex flex-col gap-1">
{lines.map((line) => {
const snapshot = line.link.snapshot;
const presentation =
snapshot === null
? null
: resolvePullRequestState({ state: snapshot.state, isDraft: snapshot.isDraft });
return (
<li
key={`${line.link.host}/${line.link.repository}#${line.link.number}`}
className="flex min-w-0 items-center gap-2"
// Capped like the panel: past a few layers the indent only repeats "still in the
// stack", and sixteen of them would walk the titles off the popover.
style={{ paddingLeft: `${Math.min(line.depth, 3) * 0.75}rem` }}
>
{presentation ? (
<presentation.Icon
aria-hidden
className={cn("size-3 shrink-0", presentation.toneClassName)}
/>
) : (
<GitPullRequestArrowIcon
aria-hidden
className="size-3 shrink-0 stroke-muted-foreground"
/>
)}
<span className="shrink-0 font-mono tabular-nums">#{line.link.number}</span>
<span className="min-w-0 truncate text-foreground/75">
{snapshot?.title ?? line.link.repository}
</span>
{line.stack ? (
<span className="ml-auto shrink-0 pl-1 text-[10px]">
{line.stack.kind === "native" ? "stack" : "chain"} · {line.stack.size}
</span>
) : null}
</li>
);
})}
</ul>
);
}
/** The ink each pull-request state wears in the sidebar, shared by the number and stack badges. */
export const PR_STATE_COLOR_CLASS: Record<NonNullable<ThreadPr>["state"], string> = {
open: "text-emerald-600 dark:text-emerald-300/90",
merged: "text-violet-600 dark:text-violet-300/90",
closed: "text-red-600 dark:text-red-300/90",
};
export function settledPrHoverColorClass(
state: NonNullable<ThreadPr>["state"],
isDraft = false,
@@ -282,7 +401,10 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
);
const pullRequest = useLinkedThreadPullRequest(
thread.environmentId,
thread.linkedPullRequest ?? thread.branchPullRequest,
thread.linkedPullRequest,
true,
thread.pullRequests,
thread.branchPullRequest,
);
const pr = pullRequest?.pr ?? null;
const prStatus = prStatusIndicator(pr, pullRequest?.sourceControlProvider);
@@ -293,7 +415,12 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
},
});
if (!prStatus && !threadStatus) {
const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
const pendingLink =
pr === null && supportsMultiplePullRequests
? resolveThreadCurrentPullRequestLink(thread.pullRequests)
: null;
if (!prStatus && !threadStatus && !pendingLink) {
return null;
}
@@ -316,6 +443,12 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
</TooltipPopup>
</Tooltip>
) : null}
{pendingLink ? (
<GitPullRequestArrowIcon
className="size-3 text-muted-foreground"
aria-label={`PR #${pendingLink.number}, status pending`}
/>
) : null}
{threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
</span>
);
@@ -390,6 +390,7 @@ describe("streaming row projection", () => {
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
pullRequests: [],
worktreePath: null,
latestTurn: {
...initial.input.latestTurn,
@@ -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,
);
+21
View File
@@ -23,6 +23,7 @@ const buttonVariants = cva(
"icon-lg": "size-10 sm:size-9",
"icon-micro":
"size-5 rounded-sm p-0 before:rounded-[calc(var(--radius-sm)-1px)] [&_svg:not([class*='size-'])]:size-3",
"icon-tiny": "size-4 p-0 [&_svg:not([class*='size-'])]:size-3",
"icon-sm": "size-8 sm:size-7",
"icon-xl":
"size-11 sm:size-10 [&_svg:not([class*='size-'])]:size-5 sm:[&_svg:not([class*='size-'])]:size-4.5",
@@ -85,3 +86,23 @@ function Button({ className, variant, size, render, ...props }: ButtonProps) {
}
export { Button, buttonVariants };
/** An inline action that keeps the geometry of surrounding text or a graph node. */
export function InlineButton({
className,
underline = false,
...props
}: React.ComponentProps<"button"> & { underline?: boolean }) {
return (
<button
type="button"
data-slot="inline-button"
className={cn(
"inline-flex shrink-0 cursor-pointer items-center gap-0.5 whitespace-nowrap focus-visible:outline-2 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-64",
underline && "border-b border-transparent hover:border-current",
className,
)}
{...props}
/>
);
}
@@ -11,6 +11,7 @@ import { selectActiveRightPanelSurface, useRightPanelStore } from "../rightPanel
import { useProject } from "../state/entities";
import { pullRequestEnvironment } from "../state/pullRequests";
import { useEnvironmentQuery } from "../state/query";
import { useSupportsMultiplePullRequests } from "./useSupportsMultiplePullRequests";
export function useOpenPanelPullRequestUrl(threadRef: ScopedThreadRef | null) {
const surface = useRightPanelStore((state) =>
@@ -20,6 +21,7 @@ export function useOpenPanelPullRequestUrl(threadRef: ScopedThreadRef | null) {
const environmentId = reference?.environmentId
? EnvironmentId.make(reference.environmentId)
: threadRef?.environmentId;
const supportsMultiplePullRequests = useSupportsMultiplePullRequests(environmentId ?? null);
const project = useProject(
reference && environmentId
? scopeProjectRef(environmentId, ProjectId.make(reference.projectId))
@@ -31,6 +33,9 @@ export function useOpenPanelPullRequestUrl(threadRef: ScopedThreadRef | null) {
environmentId,
input: {
projectId: ProjectId.make(reference.projectId),
...(supportsMultiplePullRequests && reference.host !== undefined
? { host: reference.host }
: {}),
repository: reference.repository,
number: reference.number,
},
+104
View File
@@ -0,0 +1,104 @@
import { useMemo } from "react";
import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
import type {
EnvironmentId,
ScopedThreadRef,
ThreadLinkedPullRequest,
ThreadPullRequestLink,
} from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import {
planThreadPullRequestMutation,
threadPullRequestLinkMode,
} from "@t3tools/client-runtime/thread-pull-request-compatibility";
import {
threadPullRequestKeysEqual,
visibleThreadPullRequests,
} from "@t3tools/shared/threadPullRequests";
import {
findProjectForChangeRequest,
findProjectOnChangeRequestHost,
matchesLinkedPullRequestUrl,
parseChangeRequestUrl,
} from "~/lib/openPullRequestLink";
import { useProjects, useServerConfigs } from "~/state/entities";
import { threadEnvironment } from "~/state/threads";
import { useAtomCommand } from "~/state/use-atom-command";
/** Routes link actions through the command advertised by this environment. */
export function usePullRequestLinking(environmentId: EnvironmentId | null | undefined) {
const configs = useServerConfigs();
const projects = useProjects();
const capabilities =
environmentId == null ? undefined : configs.get(environmentId)?.environment.capabilities;
const mode = threadPullRequestLinkMode(capabilities);
const link = useAtomCommand(threadEnvironment.linkPullRequest, { reportFailure: false });
const unlink = useAtomCommand(threadEnvironment.unlinkPullRequest, { reportFailure: false });
const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false });
return useMemo(() => {
const environmentProjects = projects.filter(
(project) => project.environmentId === environmentId,
);
const canLink = (url: string) => {
const parsed = parseChangeRequestUrl(url);
if (parsed === null || mode === "unsupported") return false;
return (
(mode === "multiple" ? findProjectOnChangeRequestHost : findProjectForChangeRequest)(
environmentProjects,
parsed,
) !== undefined
);
};
const isLinked = (
thread: {
readonly pullRequests?: readonly ThreadPullRequestLink[];
readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
} | null,
url: string,
) => {
if (thread === null || mode === "unsupported") return false;
if (mode !== "multiple")
return (
thread.linkedPullRequest != null &&
matchesLinkedPullRequestUrl(thread.linkedPullRequest, url)
);
const parsed = parseChangeRequestUrl(url);
return (
parsed !== null &&
visibleThreadPullRequests(thread.pullRequests ?? []).some((entry) =>
threadPullRequestKeysEqual(entry, parsed),
)
);
};
const changeLink = async (threadRef: ScopedThreadRef, url: string, linked: boolean) => {
const parsed = parseChangeRequestUrl(url);
if (parsed === null || threadRef.environmentId !== environmentId || (linked && !canLink(url)))
throw new Error("The pull request is not available in this environment.");
const legacyProject = findProjectForChangeRequest(environmentProjects, parsed);
const mutation = planThreadPullRequestMutation({
capabilities,
threadId: threadRef.threadId,
reference: { ...parsed, url },
legacyProjectId: legacyProject?.id ?? null,
legacyRepository:
sourceControlRepositorySelector(legacyProject?.repositoryIdentity) ?? undefined,
linked,
});
if (mutation === null)
throw new Error("This environment does not support linking this pull request.");
const result = await (mutation.type === "thread.meta.update"
? updateMetadata({ environmentId: threadRef.environmentId, input: mutation.input })
: mutation.type === "thread.pull-request.link"
? link({ environmentId: threadRef.environmentId, input: mutation.input })
: unlink({ environmentId: threadRef.environmentId, input: mutation.input }));
if (result._tag === "Failure") {
if (isAtomCommandInterrupted(result)) throw new Error("Link update interrupted.");
throw squashAtomCommandFailure(result);
}
};
return { mode, canLink, isLinked, changeLink };
}, [capabilities, environmentId, link, mode, projects, unlink, updateMetadata]);
}
@@ -0,0 +1,10 @@
import type { EnvironmentId } from "@t3tools/contracts";
import { useServerConfigs } from "~/state/entities";
export function useSupportsMultiplePullRequests(environmentId: EnvironmentId | null): boolean {
const configs = useServerConfigs();
return (
environmentId !== null &&
configs.get(environmentId)?.environment.capabilities.threadPullRequests === true
);
}
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test";
import {
changeRequestRepositoryUrl,
findProjectForChangeRequest,
findProjectOnChangeRequestHost,
gitHubPullRequestBrowserUrl,
matchesLinkedPullRequestUrl,
parseChangeRequestUrl,
@@ -295,6 +296,81 @@ describe("parseChangeRequestUrl", () => {
});
});
describe("findProjectOnChangeRequestHost", () => {
const project = (id: string, identity: Record<string, unknown>) =>
({ id, repositoryIdentity: identity }) as never;
const frontend = project("frontend", {
canonicalKey: "github.com/acme/frontend",
provider: "github",
owner: "acme",
name: "frontend",
});
const backend = project("backend", {
canonicalKey: "github.com/acme/backend",
provider: "github",
owner: "acme",
name: "backend",
});
it.each([
"ssh.dev.azure.com/v3/org-a/project/web",
"vs-ssh.visualstudio.com/v3/org-a/project/web",
"org-a.visualstudio.com/defaultcollection/project/_git/web",
"dev.azure.com/org-a/project/_git/web",
])("matches Azure browser references against %s", (canonicalKey) => {
const checkout = project("azure", {
canonicalKey,
provider: "azure-devops",
displayName: canonicalKey.split("/").slice(1).join("/"),
});
const reference = { host: "dev.azure.com", repository: "org-a/project/_git/web", number: 42 };
expect(findProjectForChangeRequest([checkout], reference)).toBe(checkout);
expect(findProjectOnChangeRequestHost([checkout], reference)).toBe(checkout);
expect(
findProjectOnChangeRequestHost([checkout], {
...reference,
repository: "org-b/project/_git/web",
}),
).toBeUndefined();
expect(
findProjectOnChangeRequestHost([checkout], {
...reference,
repository: "org-a/other-project/_git/web",
}),
).toBeUndefined();
});
it("prefers the project checked out from the link's own repository", () => {
expect(
findProjectOnChangeRequestHost([frontend, backend], {
host: "github.com",
repository: "acme/backend",
number: 7,
}),
).toBe(backend);
});
it("lends any project on the host to a repository nobody has checked out", () => {
expect(
findProjectOnChangeRequestHost([frontend], {
host: "github.com",
repository: "acme/backend",
number: 7,
}),
).toBe(frontend);
});
it("finds nothing on a host nothing is checked out from", () => {
expect(
findProjectOnChangeRequestHost([frontend], {
host: "gitlab.com",
repository: "acme/backend",
number: 7,
}),
).toBeUndefined();
});
});
describe("findProjectForChangeRequest", () => {
const project = (identity: Record<string, unknown>) =>
({ id: "p1", repositoryIdentity: identity }) as never;
+76 -182
View File
@@ -1,13 +1,13 @@
import type {
EnvironmentId,
RepositoryIdentity,
ScopedThreadRef,
ThreadLinkedPullRequest,
} from "@t3tools/contracts";
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
import { useNavigate } from "@tanstack/react-router";
import { type MouseEvent, useCallback } from "react";
import { pullRequestHostOf, type SourceControlProviderKind } from "@t3tools/contracts";
import { parseChangeRequestUrl, type ChangeRequestLink } from "@t3tools/shared/changeRequestUrl";
import {
canonicalRepositoryKey,
sourceControlRepositorySelector,
} from "@t3tools/shared/sourceControl";
import { useOpenLink } from "../browser/useOpenLink";
import { stackedThreadToast, toastManager } from "../components/ui/toast";
@@ -17,176 +17,14 @@ import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { useProjects, useServerConfigs } from "../state/entities";
import { usePrimaryEnvironmentId } from "../state/environments";
/** Builds a GitHub URL that remains available when the pull request API cannot be read. */
export function gitHubPullRequestBrowserUrl(
identity: RepositoryIdentity | null | undefined,
repository: string,
number: number,
): string | null {
if (identity?.provider !== "github" || !Number.isSafeInteger(number) || number < 1) return null;
const repositoryPath = repository.split("/");
if (
repositoryPath.length !== 2 ||
repositoryPath.some((segment) => segment.length === 0 || segment === "." || segment === "..")
) {
return null;
}
let origin: string | null = null;
try {
const remoteUrl = new URL(identity.locator.remoteUrl.trim());
if (remoteUrl.protocol === "http:" || remoteUrl.protocol === "https:") {
origin = remoteUrl.origin;
}
} catch {
// SCP-style remotes are read from their normalized identity below.
}
const hostname = identity.canonicalKey.split("/")[0];
if (origin === null && !hostname) return null;
try {
const url = new URL(origin ?? `https://${hostname}`);
url.pathname = `/${repositoryPath.join("/")}/pull/${number}`;
return url.toString();
} catch {
return null;
}
}
/**
* A change request the page can open, named the way the page names one: the host below which the
* repository is addressed, the repository path as that host writes it, and the number.
*
* The two strings are what `pullRequestHostOf` and the project's `repositoryIdentity` produce
* from a git remote — lower case, no port, the full path below the host — because the page matches
* a link against those. Anything else opens nothing.
*/
export interface ChangeRequestLink {
readonly host: string;
readonly repository: string;
readonly number: number;
}
/** The host itself, one of its subdomains, or an install named after the provider. */
function isHostOf(hostname: string, apex: string, label?: string): boolean {
if (hostname === apex || hostname.endsWith(`.${apex}`)) return true;
return label !== undefined && hostname.startsWith(`${label}.`);
}
/**
* The repository and number behind a change request URL on a host the page can read, or null for
* anything else — an issue, a commit, a repository root, a host this cannot tell apart from an
* ordinary link. Null means the system browser, so a doubtful match is worse than no match: it
* takes the reader out of their browser and into a page that cannot find the change request.
*
* Each host is recognised by the path shape it alone uses, guarded by a hostname it could
* plausibly be served from, since self-hosted installs are named whatever their admin chose:
* GitLab's `/-/` marker is unique enough to trust on any hostname, while `/pull/` is generic
* enough that it is only believed from a GitHub-ish host.
*/
export function parseChangeRequestUrl(targetUrl: string): ChangeRequestLink | null {
let url: URL;
try {
url = new URL(targetUrl);
} catch {
return null;
}
// `javascript:`, `mailto:` and friends have no host to speak of and nothing to open.
if (url.protocol !== "https:" && url.protocol !== "http:") return null;
// Nothing here tries to tell a lookalike hostname from a real one — `github.com.evil.test`,
// `github.com-evil.test` and the rest are an open set, and blocking spellings of it costs real
// hosts (`gitlab.com.br` is a registrable domain, not a disguise). What a claim is worth is
// decided where it is used: only a link matching a repository this workspace has checked out
// opens the page, and everything else stays the ordinary link it was.
const host = url.hostname.toLowerCase();
// GitHub, and any Enterprise install: /{owner}/{repo}/pull/{n}
if (isHostOf(host, "github.com", "github")) {
const match = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(url.pathname);
return claim(host, match);
}
// GitLab, self-hosted included: /{group}/[{subgroup}/...]{repo}/-/merge_requests/{n}. The `/-/`
// separator is GitLab's own, so the hostname is not asked about.
const gitlab = /^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
if (gitlab) return claim(host, gitlab);
// Bitbucket Cloud: /{workspace}/{repo}/pull-requests/{n}
if (isHostOf(host, "bitbucket.org", "bitbucket")) {
const match = /^\/([^/]+\/[^/]+)\/pull-requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
return claim(host, match);
}
// Azure DevOps, both the current host and the per-organisation one it replaced. `_git` is part
// of the repository path there, as it is in the remote URL the identity is read from.
if (isHostOf(host, "dev.azure.com") || host.endsWith(".visualstudio.com")) {
const match = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u.exec(url.pathname);
return claim(host, match);
}
return null;
}
/**
* The pull-request URL a GitHub-style `#123` autolink might name. GitHub writes every bare
* reference through `/issues/`, including pull requests, so this only builds a candidate: the
* caller must successfully read it as a pull request before treating it as one.
*/
export function pullRequestCandidateUrlFromReferenceAutolink(targetUrl: string): string | null {
let url: URL;
try {
url = new URL(targetUrl);
} catch {
return null;
}
if (
(url.protocol !== "https:" && url.protocol !== "http:") ||
!isHostOf(url.hostname.toLowerCase(), "github.com", "github")
) {
return null;
}
const match = /^\/([^/]+\/[^/]+)\/issues\/(\d+)(?:\/|$)/u.exec(url.pathname);
if (match?.[1] === undefined || match[2] === undefined) return null;
url.pathname = `/${match[1]}/pull/${match[2]}`;
return url.toString();
}
/** Match a stored PR without requiring its project to remain available. */
export function matchesLinkedPullRequestUrl(
linkedPullRequest: ThreadLinkedPullRequest,
targetUrl: string,
): boolean {
const linked = parseChangeRequestUrl(linkedPullRequest.url);
const target = parseChangeRequestUrl(targetUrl);
return (
linked !== null &&
target !== null &&
linked.host === target.host &&
linked.repository === target.repository &&
linked.number === target.number
);
}
/** The repository root behind a recognised change-request URL, without PR-specific state. */
export function changeRequestRepositoryUrl(targetUrl: string): string | null {
const changeRequest = parseChangeRequestUrl(targetUrl);
if (changeRequest === null) return null;
const url = new URL(targetUrl);
const repositoryPath =
/^(.*?)\/-\/merge_requests\/\d+(?:\/|$)/iu.exec(url.pathname)?.[1] ??
/^(.*?)(?:\/pull\/\d+|\/-\/merge_requests\/\d+|\/pull-requests\/\d+|\/pullrequest\/\d+)(?:\/|$)/iu.exec(
url.pathname,
)?.[1];
if (!repositoryPath) return null;
url.pathname = repositoryPath;
url.search = "";
url.hash = "";
return url.toString();
}
function claim(host: string, match: RegExpExecArray | null): ChangeRequestLink | null {
const repository = match?.[1];
const number = Number(match?.[2]);
return repository && Number.isSafeInteger(number) && number > 0
? { host, repository: repository.toLowerCase(), number }
: null;
}
export {
parseChangeRequestUrl,
type ChangeRequestLink,
gitHubPullRequestBrowserUrl,
pullRequestCandidateUrlFromReferenceAutolink,
matchesLinkedPullRequestUrl,
changeRequestRepositoryUrl,
} from "@t3tools/shared/changeRequestUrl";
/**
* Returns a click handler that opens a pull request URL in the system browser.
@@ -210,6 +48,12 @@ export function findProjectForChangeRequest(
if (!identity) return false;
const kind = identity.provider as SourceControlProviderKind | undefined;
if (kind === undefined) return false;
if (kind === "azure-devops") {
return (
canonicalRepositoryKey(identity.canonicalKey.toLowerCase()) ===
canonicalRepositoryKey(`${link.host}/${link.repository}`.toLowerCase())
);
}
const repository =
identity.displayName ??
(identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null);
@@ -221,6 +65,36 @@ export function findProjectForChangeRequest(
});
}
/**
* Any project checked out from the link's host. Thread links are host-level, so a pull request
* from a repository nobody has checked out is still linkable as long as one project on that
* host can lend the server its credentials. The link's own project, when it exists, comes first.
*/
export function findProjectOnChangeRequestHost(
projects: ReadonlyArray<EnvironmentProject>,
link: ChangeRequestLink,
): EnvironmentProject | undefined {
const own = findProjectForChangeRequest(projects, link);
if (own !== undefined) return own;
// Azure CLI reads use the checkout's organization and project, not host-wide credentials.
if (
canonicalRepositoryKey(`${link.host}/${link.repository}`.toLowerCase()).startsWith(
"dev.azure.com/",
)
)
return undefined;
return projects.find((project) => {
const identity = project.repositoryIdentity;
const kind = identity?.provider as SourceControlProviderKind | undefined;
return (
identity != null &&
kind !== undefined &&
kind !== "azure-devops" &&
pullRequestHostOf(identity, kind) === link.host.toLowerCase()
);
});
}
/**
* Opens a change request link on the page, and says whether it did. Anything else — another
* organisation's repository, a host nothing here is checked out from, a link that merely looks
@@ -284,8 +158,25 @@ export function useOpenChangeRequestLink(
Number(right.environmentId === primaryEnvironmentId) -
Number(left.environmentId === primaryEnvironmentId),
);
const project = findProjectForChangeRequest(projects, parsed);
const exactProject = findProjectForChangeRequest(projects, parsed);
const project =
exactProject ??
(resolvedPanelRef
? findProjectOnChangeRequestHost(
projects.filter(
(candidate) =>
serverConfigs.get(candidate.environmentId)?.environment.capabilities
.threadPullRequests === true,
),
parsed,
)
: undefined);
if (project === undefined || !reads(project.environmentId)) return false;
const repository =
serverConfigs.get(project.environmentId)?.environment.capabilities.threadPullRequests ===
true
? parsed.repository
: (sourceControlRepositorySelector(project.repositoryIdentity) ?? parsed.repository);
event.preventDefault();
event.stopPropagation();
if (resolvedPanelRef) {
@@ -295,9 +186,12 @@ export function useOpenChangeRequestLink(
? {}
: { environmentId: project.environmentId }),
projectId: project.id,
// The identity's own spelling, not the one read out of the URL: the panel asks the
// provider for this repository, while matching a link only ever compares lower case.
repository: project.repositoryIdentity?.displayName ?? parsed.repository,
...(serverConfigs.get(project.environmentId)?.environment.capabilities
.threadPullRequests === true
? { host: parsed.host }
: {}),
repository,
url: targetUrl,
number: parsed.number,
});
if (!resolvedThreadRef) {
@@ -307,7 +201,7 @@ export function useOpenChangeRequestLink(
...previous,
involvement: previous.involvement ?? "all",
state: previous.state ?? "all",
repository: project.repositoryIdentity?.displayName ?? parsed.repository,
repository,
number: parsed.number,
selectedProjectId: project.id,
selectedEnvironmentId: project.environmentId,
@@ -324,7 +218,7 @@ export function useOpenChangeRequestLink(
// Every state, so the pull request being opened is also in the list behind it whether
// it is open, merged or closed.
state: "all",
repository: parsed.repository,
repository,
number: parsed.number,
selectedProjectId: project.id,
// Named so the page opens the right one of two servers holding this project.
+1
View File
@@ -34,6 +34,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
branch: null,
worktreePath: null,
checkpoints: [],
pullRequests: [],
activities: [],
...overrides,
};
+12
View File
@@ -605,6 +605,18 @@ describe("rightPanelStore", () => {
expect(state.surfaces[1]).not.toHaveProperty("url");
});
it("keeps matching repository and number on different hosts as separate tabs", () => {
const first = { projectId: "project-a", repository: "acme/api", number: 7, host: "github.com" };
const second = { ...first, host: "github.example.com" };
useRightPanelStore.getState().openPullRequest(refA, first);
useRightPanelStore.getState().openPullRequest(refA, second);
const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);
expect(state.surfaces).toEqual([pullRequestSurface(first), pullRequestSurface(second)]);
expect(pullRequestSurfaceId({ ...first, host: "GITHUB.COM" })).toBe(
pullRequestSurfaceId(first),
);
});
it("keeps one pull request read from two servers as two tabs", () => {
const local = {
environmentId: "local",
+12 -1
View File
@@ -26,6 +26,7 @@ const RIGHT_PANEL_KINDS = [
"preview",
"terminal",
"pull-request",
"pull-requests",
"agents",
] as const;
export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
@@ -68,10 +69,13 @@ export type RightPanelSurface =
*/
environmentId?: string;
projectId: string;
host?: string;
repository: string;
number: number;
url?: string;
}
/** The thread's linked pull requests, one singleton tab beside any number of `pull-request` tabs. */
| { id: "pull-requests"; kind: "pull-requests" }
| { id: "agents"; kind: "agents" };
const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
@@ -124,6 +128,7 @@ interface RightPanelStoreState {
target: {
environmentId?: string;
projectId: string;
host?: string;
repository: string;
number: number;
url?: string;
@@ -169,6 +174,8 @@ const singletonSurface = (
return { id: "diff", kind };
case "files":
return { id: "files", kind };
case "pull-requests":
return { id: "pull-requests", kind };
case "agents":
return { id: "agents", kind };
}
@@ -213,6 +220,7 @@ export type PullRequestSurface = Extract<RightPanelSurface, { kind: "pull-reques
export function pullRequestSurfaceId(target: {
environmentId?: string;
projectId: string;
host?: string;
repository: string;
number: number;
}): PullRequestSurface["id"] {
@@ -220,12 +228,14 @@ export function pullRequestSurfaceId(target: {
// servers is two tabs rather than one tab that changes its mind about which server it is on.
const scope =
target.environmentId === undefined ? "" : `${encodeURIComponent(target.environmentId)}:`;
return `pull-request:${scope}${encodeURIComponent(target.projectId)}:${encodeURIComponent(target.repository)}:${target.number}`;
const host = target.host === undefined ? "" : `${encodeURIComponent(target.host.toLowerCase())}:`;
return `pull-request:${scope}${encodeURIComponent(target.projectId)}:${host}${encodeURIComponent(target.repository)}:${target.number}`;
}
export function pullRequestSurface(target: {
environmentId?: string;
projectId: string;
host?: string;
repository: string;
number: number;
url?: string;
@@ -235,6 +245,7 @@ export function pullRequestSurface(target: {
kind: "pull-request",
...(target.environmentId === undefined ? {} : { environmentId: target.environmentId }),
projectId: target.projectId,
...(typeof target.host === "string" ? { host: target.host.toLowerCase() } : {}),
repository: target.repository,
number: target.number,
...(typeof target.url === "string" ? { url: target.url } : {}),
@@ -1923,12 +1923,14 @@ function PullRequestsRouteView() {
onAddDiff={() => undefined}
onAddFiles={() => undefined}
onAddPullRequest={() => undefined}
onAddPullRequests={() => undefined}
onAddAgents={() => undefined}
browserAvailable={false}
terminalAvailable={false}
diffAvailable={false}
filesAvailable={false}
pullRequestAvailable={false}
pullRequestsAvailable={false}
agentsAvailable={false}
liveAgentCount={0}
pullRequestStatusSeeds={listedPullRequestTabStatuses}
+3
View File
@@ -2,6 +2,7 @@ import { useAtomValue } from "@effect/atom-react";
import {
createLinkedPullRequestSummaryAtomFamily,
createPullRequestEnvironmentAtoms,
createPullRequestStackAtomFamily,
} from "@t3tools/client-runtime/state/pull-requests";
import type {
EnvironmentId,
@@ -58,6 +59,7 @@ export function useSharedPullRequestSummary(
: JSON.stringify([
environmentId,
reference.projectId,
reference.host?.toLowerCase() ?? null,
reference.repository.toLowerCase(),
reference.number,
]);
@@ -72,6 +74,7 @@ export function useSharedPullRequestSummary(
}, [atom, current, environmentId]);
return newestPullRequestSummary(current, observed);
}
export const pullRequestStackAtom = createPullRequestStackAtomFamily(connectionAtomRuntime);
export interface EnvironmentQueryTarget<Input> {
readonly environmentId: EnvironmentId;
@@ -218,6 +218,7 @@ export function useGitStackedAction(scope: SourceControlActionScope) {
commitMessage?: string;
featureBranch?: boolean;
filePaths?: string[];
threadId?: ThreadId;
onProgress?: (event: GitActionProgressEvent) => void;
}) => {
if (resolveScope(scope) === null) {
@@ -237,6 +238,7 @@ export function useGitStackedAction(scope: SourceControlActionScope) {
...(input.commitMessage ? { commitMessage: input.commitMessage } : {}),
...(input.featureBranch ? { featureBranch: true } : {}),
...(input.filePaths?.length ? { filePaths: input.filePaths } : {}),
...(input.threadId !== undefined ? { threadId: input.threadId } : {}),
...(input.onProgress ? { onProgress: input.onProgress } : {}),
});
},
+1
View File
@@ -21,6 +21,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
session: null,
messages: [],
checkpoints: [],
pullRequests: [],
activities: [],
proposedPlans: [],
createdAt: "2026-02-13T00:00:00.000Z",