TypeScript
fix(web): open GitHub pull requests in browser when loading fails (#8507)
Theo Browne7068e86f76e9
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsxindex 731a3acecef..b7826d4f9a5 100644--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx@@ -51,7 +51,7 @@ import {import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";import { useNewThreadHandler } from "~/hooks/useHandleNewThread";import { useCopyToClipboard, writeTextToClipboard } from "~/hooks/useCopyToClipboard";-import { changeRequestRepositoryUrl } from "~/lib/openPullRequestLink";+import { changeRequestRepositoryUrl, gitHubPullRequestBrowserUrl } from "~/lib/openPullRequestLink";import { usePreparePullRequestThreadAction } from "~/lib/sourceControlActions";import { cn } from "~/lib/utils";import { readLocalApi } from "~/localApi";@@ -590,6 +590,12 @@ export function PullRequestDetailPanel({const newThread = useNewThreadHandler();const { environments } = useEnvironments();const projects = useProjects();+ const unavailableGitHubUrl = useMemo(() => {+ const identity = projects.find(+ (project) => project.id === reference.projectId && project.environmentId === environmentId,+ )?.repositoryIdentity;+ return gitHubPullRequestBrowserUrl(identity, reference.repository, reference.number);+ }, [environmentId, projects, reference.number, reference.projectId, reference.repository]);// Beside a thread there is nothing to pick: the hand-offs land in that thread's composer, and// the thread is already on one server's copy of the branch.const pickableEnvironments = useMemo(@@ -1906,7 +1912,11 @@ export function PullRequestDetailPanel({}}>{detailQuery.error && !detail ? (- <PullRequestsUnavailableState error={detailQuery.error} onRetry={refreshDetail} />+ <PullRequestsUnavailableState+ error={detailQuery.error}+ onRetry={refreshDetail}+ {...(unavailableGitHubUrl ? { gitHubUrl: unavailableGitHubUrl } : {})}+ />) : detail ? (<>{mountedTabs.has("summary") ? (diff --git a/apps/web/src/components/pullRequest/PullRequestsUnavailableState.test.tsx b/apps/web/src/components/pullRequest/PullRequestsUnavailableState.test.tsxindex 1c7c8b6df1f..12136adbc63 100644--- a/apps/web/src/components/pullRequest/PullRequestsUnavailableState.test.tsx+++ b/apps/web/src/components/pullRequest/PullRequestsUnavailableState.test.tsx@@ -1,4 +1,5 @@import { isValidElement, type ReactElement, type ReactNode } from "react";+import { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it } from "vite-plus/test";import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";@@ -25,8 +26,48 @@ describe("PullRequestsUnavailableState", () => {});it("retains the retry for transient load failures", () => {- expect(- textOf(PullRequestsUnavailableState({ error: "GitHub did not answer.", onRetry: () => {} })),- ).toContain("Retry");+ const html = renderToStaticMarkup(+ <PullRequestsUnavailableState+ error="GitHub did not answer."+ onRetry={() => {}}+ gitHubUrl="https://github.com/pingdotgg/t3code/pull/42"+ />,+ );++ expect(html).toContain("Retry");+ expect(html).toContain("Open on GitHub");+ expect(html).toContain('href="https://github.com/pingdotgg/t3code/pull/42"');+ expect(html).toContain('target="_blank"');+ expect(html).toContain('rel="noopener noreferrer"');+ });++ it("can offer the browser without offering a retry", () => {+ const html = renderToStaticMarkup(+ <PullRequestsUnavailableState+ error="This server cannot read the pull request."+ gitHubUrl="https://github.com/pingdotgg/t3code/pull/9"+ />,+ );++ expect(html).toContain("Open on GitHub");+ expect(html).not.toContain("Retry");+ });++ it("can offer a retry without offering GitHub", () => {+ const html = renderToStaticMarkup(+ <PullRequestsUnavailableState error="The host did not answer." onRetry={() => {}} />,+ );++ expect(html).toContain("Retry");+ expect(html).not.toContain("Open on GitHub");+ });++ it("renders no action content without a retry or browser target", () => {+ const html = renderToStaticMarkup(+ <PullRequestsUnavailableState error="This project has no known remote." />,+ );++ expect(html).not.toContain('data-slot="empty-content"');+ expect(html).not.toContain("href=");});});diff --git a/apps/web/src/components/pullRequest/PullRequestsUnavailableState.tsx b/apps/web/src/components/pullRequest/PullRequestsUnavailableState.tsxindex 05bc08040e7..70f5c845d2c 100644--- a/apps/web/src/components/pullRequest/PullRequestsUnavailableState.tsx+++ b/apps/web/src/components/pullRequest/PullRequestsUnavailableState.tsx@@ -1,4 +1,4 @@-import { GitPullRequestIcon, RefreshCwIcon } from "lucide-react";+import { ExternalLinkIcon, GitPullRequestIcon, RefreshCwIcon } from "lucide-react";import { Button } from "../ui/button";import {@@ -14,10 +14,12 @@ export function PullRequestsUnavailableState({title = "Could not load pull requests",error,onRetry,+ gitHubUrl,}: {title?: string;error: string;onRetry?: () => void;+ gitHubUrl?: string;}) {return (<Empty className="px-4 py-16 md:px-4">@@ -30,12 +32,24 @@ export function PullRequestsUnavailableState({shows its message rather than trying to infer one from the failure text. */}<EmptyDescription>{error}</EmptyDescription></EmptyHeader>- {onRetry ? (- <EmptyContent>- <Button size="sm" variant="outline" onClick={onRetry}>- <RefreshCwIcon className="size-3.5" />- Retry- </Button>+ {onRetry || gitHubUrl ? (+ <EmptyContent className="flex-row flex-wrap justify-center gap-2">+ {onRetry ? (+ <Button size="sm" variant="outline" onClick={onRetry}>+ <RefreshCwIcon className="size-3.5" />+ Retry+ </Button>+ ) : null}+ {gitHubUrl ? (+ <Button+ size="sm"+ variant="outline"+ render={<a href={gitHubUrl} target="_blank" rel="noopener noreferrer" />}+ >+ <ExternalLinkIcon aria-hidden className="size-3.5" />+ Open on GitHub+ </Button>+ ) : null}</EmptyContent>) : null}</Empty>diff --git a/apps/web/src/lib/openPullRequestLink.test.ts b/apps/web/src/lib/openPullRequestLink.test.tsindex c783f0fcc76..bd8cfe3d72d 100644--- a/apps/web/src/lib/openPullRequestLink.test.ts+++ b/apps/web/src/lib/openPullRequestLink.test.ts@@ -3,13 +3,114 @@ import { describe, expect, it, vi } from "vite-plus/test";import {changeRequestRepositoryUrl,findProjectForChangeRequest,+ gitHubPullRequestBrowserUrl,matchesLinkedPullRequestUrl,openPullRequestLink,parseChangeRequestUrl,PullRequestLinkOpenError,shouldOpenPullRequestExternally,} from "./openPullRequestLink";-import { ProjectId } from "@t3tools/contracts";+import { ProjectId, type RepositoryIdentity } from "@t3tools/contracts";++function repositoryIdentity(+ provider: string,+ canonicalKey: string,+ remoteUrl: string,+): RepositoryIdentity {+ return {+ canonicalKey,+ provider,+ locator: { source: "git-remote", remoteName: "origin", remoteUrl },+ };+}++describe("gitHubPullRequestBrowserUrl", () => {+ it("uses the requested GitHub repository instead of the project's default repository", () => {+ const identity = repositoryIdentity(+ "github",+ "github.com/acme/default",+ "https://github.com/acme/default.git",+ );++ expect(gitHubPullRequestBrowserUrl(identity, "acme/other", 42)).toBe(+ "https://github.com/acme/other/pull/42",+ );+ });++ it("preserves a custom GitHub HTTP origin without its credentials", () => {+ const identity = repositoryIdentity(+ "github",+ "github.acme.test/team/default",+ "http://[email protected]:8443/team/default.git",+ );++ expect(gitHubPullRequestBrowserUrl(identity, "platform/api", 7)).toBe(+ "http://github.acme.test:8443/platform/api/pull/7",+ );+ });++ it.each([+ {+ name: "SSH",+ remoteUrl: "[email protected]:team/default.git",+ },+ {+ name: "git protocol",+ remoteUrl: "git://github.acme.test/team/default.git",+ },+ ])("uses the normalized host for a $name remote", ({ remoteUrl }) => {+ const identity = repositoryIdentity("github", "github.acme.test/team/default", remoteUrl);++ expect(gitHubPullRequestBrowserUrl(identity, "platform/api", 9)).toBe(+ "https://github.acme.test/platform/api/pull/9",+ );+ });++ it("returns null for missing or invalid GitHub data", () => {+ expect(gitHubPullRequestBrowserUrl(null, "acme/repository", 1)).toBeNull();+ expect(+ gitHubPullRequestBrowserUrl(+ repositoryIdentity("github", "github.com/acme/repository", "https://github.com/a/b"),+ "acme",+ 1,+ ),+ ).toBeNull();+ expect(+ gitHubPullRequestBrowserUrl(+ repositoryIdentity("github", "github.com/acme/repository", "https://github.com/a/b"),+ "../repository",+ 1,+ ),+ ).toBeNull();+ expect(+ gitHubPullRequestBrowserUrl(+ repositoryIdentity("github", "github.com/acme/repository", "https://github.com/a/b"),+ "acme/repository",+ 0,+ ),+ ).toBeNull();+ expect(+ gitHubPullRequestBrowserUrl(+ repositoryIdentity("github", "bad host/acme/repository", "not a remote"),+ "acme/repository",+ 1,+ ),+ ).toBeNull();+ });++ it.each(["gitlab", "bitbucket", "azure-devops", "unknown"])(+ "does not build a fallback for %s",+ (provider) => {+ expect(+ gitHubPullRequestBrowserUrl(+ repositoryIdentity(provider, "github.com/acme/repository", "https://github.com/a/b"),+ "acme/repository",+ 1,+ ),+ ).toBeNull();+ },+ );+});describe("changeRequestRepositoryUrl", () => {it("preserves repository path casing", () => {diff --git a/apps/web/src/lib/openPullRequestLink.ts b/apps/web/src/lib/openPullRequestLink.tsindex 22ee2938a03..810956c5279 100644--- a/apps/web/src/lib/openPullRequestLink.ts+++ b/apps/web/src/lib/openPullRequestLink.ts@@ -1,6 +1,7 @@import type {EnvironmentId,LocalApi,+ RepositoryIdentity,ScopedThreadRef,ThreadLinkedPullRequest,} from "@t3tools/contracts";@@ -53,6 +54,42 @@ export async function openPullRequestLink(}}+/** 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.diff --git a/docs/user/source-control.md b/docs/user/source-control.mdindex 916536bbe73..3aa856cf992 100644--- a/docs/user/source-control.md+++ b/docs/user/source-control.md@@ -42,6 +42,8 @@ T3 Code works with the platforms your team already uses:- While working in a thread, open linked reviews in the same compact right-panel tabs withoutleaving the conversation- Open the review directly in your browser with one click+- If T3 Code cannot load a GitHub pull request, including when GitHub rate limits requests, use+ **Open on GitHub** in the error view- Command-click (Control-click on Windows and Linux) a pull request number in the sidebar to open it in your browser instead of in T3 Code- Check out a teammate's branch to review code locally