feat(pull-requests): link multiple pull requests to threads (#10839)
This commit is contained in:
1 parent
383cc40f4d
commit
afb84898be
172 files changed
+12063
-914
No files matched your search
@@ -0,0 +1,142 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
changeRequestUrlFor,
|
||||
parseChangeRequestUrl,
|
||||
pullRequestCandidateUrlFromReferenceAutolink,
|
||||
siblingPullRequestUrl,
|
||||
} from "./changeRequestUrl.ts";
|
||||
|
||||
describe("parseChangeRequestUrl", () => {
|
||||
it("reads a GitHub pull request, lower-casing the repository", () => {
|
||||
expect(parseChangeRequestUrl("https://github.com/T3Tools/T3Code/pull/123")).toEqual({
|
||||
host: "github.com",
|
||||
repository: "t3tools/t3code",
|
||||
number: 123,
|
||||
});
|
||||
});
|
||||
|
||||
it("reads a pull request on a GitHub Enterprise host", () => {
|
||||
expect(parseChangeRequestUrl("https://github.acme.test/platform/api/pull/7")).toEqual({
|
||||
host: "github.acme.test",
|
||||
repository: "platform/api",
|
||||
number: 7,
|
||||
});
|
||||
});
|
||||
|
||||
it("reads a supported GitHub host with a middle DNS label", () => {
|
||||
expect(parseChangeRequestUrl("https://code.github.example.com/acme/web/pull/42")).toEqual({
|
||||
host: "code.github.example.com",
|
||||
repository: "acme/web",
|
||||
number: 42,
|
||||
});
|
||||
expect(
|
||||
pullRequestCandidateUrlFromReferenceAutolink(
|
||||
"https://code.github.example.com/acme/web/issues/42",
|
||||
),
|
||||
).toBe("https://code.github.example.com/acme/web/pull/42");
|
||||
});
|
||||
|
||||
it("reads a GitLab merge request on any host, nested groups and all", () => {
|
||||
expect(
|
||||
parseChangeRequestUrl("https://gitlab.com/t3tools/platform/t3code/-/merge_requests/42"),
|
||||
).toEqual({ host: "gitlab.com", repository: "t3tools/platform/t3code", number: 42 });
|
||||
expect(parseChangeRequestUrl("https://code.acme.test/team/project/-/merge_requests/9")).toEqual(
|
||||
{ host: "code.acme.test", repository: "team/project", number: 9 },
|
||||
);
|
||||
});
|
||||
|
||||
it("reads Bitbucket and both Azure DevOps URL forms", () => {
|
||||
expect(parseChangeRequestUrl("https://bitbucket.org/workspace/repo/pull-requests/5")).toEqual({
|
||||
host: "bitbucket.org",
|
||||
repository: "workspace/repo",
|
||||
number: 5,
|
||||
});
|
||||
expect(
|
||||
parseChangeRequestUrl("https://dev.azure.com/acme/platform/_git/t3code/pullrequest/17"),
|
||||
).toEqual({ host: "dev.azure.com", repository: "acme/platform/_git/t3code", number: 17 });
|
||||
expect(
|
||||
parseChangeRequestUrl("https://acme.visualstudio.com/platform/_git/t3code/pullrequest/17"),
|
||||
).toEqual({ host: "acme.visualstudio.com", repository: "platform/_git/t3code", number: 17 });
|
||||
});
|
||||
|
||||
it("survives trailing segments, a trailing slash and a query string", () => {
|
||||
expect(parseChangeRequestUrl("https://github.com/t3tools/t3code/pull/123/files?w=1")).toEqual({
|
||||
host: "github.com",
|
||||
repository: "t3tools/t3code",
|
||||
number: 123,
|
||||
});
|
||||
expect(parseChangeRequestUrl("https://github.com/t3tools/t3code/pull/123/")).toEqual({
|
||||
host: "github.com",
|
||||
repository: "t3tools/t3code",
|
||||
number: 123,
|
||||
});
|
||||
});
|
||||
|
||||
it("claims nothing it cannot be sure of", () => {
|
||||
for (const link of [
|
||||
"https://github.com/t3tools/t3code/issues/123",
|
||||
"https://github.com/t3tools/t3code/commit/0a1b2c3",
|
||||
"https://github.com/t3tools/t3code",
|
||||
"https://github.com/t3tools/t3code/pull/abc",
|
||||
"https://gitlab.com/t3tools/t3code/-/issues/12",
|
||||
"https://blog.example.test/2026/updates/pull/3",
|
||||
"javascript:alert(1)//github.com/t3tools/t3code/pull/1",
|
||||
"not a url",
|
||||
]) {
|
||||
expect(parseChangeRequestUrl(link), link).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("siblingPullRequestUrl", () => {
|
||||
it.each([
|
||||
["https://github.com/pull/1/pull/42/files", "https://github.com/pull/1/pull/43"],
|
||||
[
|
||||
"https://git.acme.test/team/merge_requests/1/repo/-/merge_requests/42/diffs",
|
||||
"https://git.acme.test/team/merge_requests/1/repo/-/merge_requests/43",
|
||||
],
|
||||
|
||||
["https://github.com/acme/web/pull/42#discussion_r123", "https://github.com/acme/web/pull/43"],
|
||||
["https://github.com/acme/web/pull/42/files?w=1", "https://github.com/acme/web/pull/43"],
|
||||
[
|
||||
"https://github.acme.test:8443/acme/web/pull/42/",
|
||||
"https://github.acme.test:8443/acme/web/pull/43",
|
||||
],
|
||||
[
|
||||
"https://git.acme.test/acme/web/-/merge_requests/42/diffs",
|
||||
"https://git.acme.test/acme/web/-/merge_requests/43",
|
||||
],
|
||||
[
|
||||
"https://bitbucket.org/acme/web/pull-requests/42",
|
||||
"https://bitbucket.org/acme/web/pull-requests/43",
|
||||
],
|
||||
[
|
||||
"https://dev.azure.com/acme/project/_git/web/pullrequest/42?view=files",
|
||||
"https://dev.azure.com/acme/project/_git/web/pullrequest/43",
|
||||
],
|
||||
])("builds a canonical sibling of %s", (url, expected) => {
|
||||
expect(siblingPullRequestUrl(url, 43)).toBe(expected);
|
||||
});
|
||||
it("rejects non-PR URLs and invalid numbers", () => {
|
||||
expect(siblingPullRequestUrl("https://github.com/acme/web/issues/42", 43)).toBeNull();
|
||||
expect(siblingPullRequestUrl("https://github.com/acme/web/pull/42", 0)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("changeRequestUrlFor", () => {
|
||||
it.each([
|
||||
["ssh.dev.azure.com", "v3/org/project/web"],
|
||||
["vs-ssh.visualstudio.com", "v3/org/project/web"],
|
||||
["org.visualstudio.com", "defaultcollection/project/_git/web"],
|
||||
["dev.azure.com", "org/project/_git/web"],
|
||||
])("builds a browser URL from the Azure remote %s/%s", (host, repository) => {
|
||||
const url = changeRequestUrlFor("azure-devops", host, repository, 42);
|
||||
expect(url).toBe("https://dev.azure.com/org/project/_git/web/pullrequest/42");
|
||||
expect(parseChangeRequestUrl(url!)).toEqual({
|
||||
host: "dev.azure.com",
|
||||
repository: "org/project/_git/web",
|
||||
number: 42,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,210 @@
|
||||
import type { RepositoryIdentity, ThreadLinkedPullRequest } from "@t3tools/contracts";
|
||||
import { canonicalRepositoryKey } from "./sourceControl.ts";
|
||||
|
||||
/**
|
||||
* A change request named the way a thread link 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 links are
|
||||
* matched against those. Anything else matches 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.split(".").includes(label);
|
||||
}
|
||||
|
||||
/**
|
||||
* The repository and number behind a change request URL on a host this can read, or null for
|
||||
* anything else — an issue, a commit, a repository root, a host this cannot tell apart from an
|
||||
* ordinary link. A doubtful match is worse than no match, so nothing here guesses.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* Nothing here tries to tell a lookalike hostname from a real one — `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). What a claim is worth is decided where it is used.
|
||||
*/
|
||||
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;
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** The web URL a host writes for a change request; null when the host shape is unknown. */
|
||||
export function changeRequestUrlFor(
|
||||
kind: string | null | undefined,
|
||||
host: string,
|
||||
repository: string,
|
||||
number: number,
|
||||
): string | null {
|
||||
switch (kind) {
|
||||
case "github":
|
||||
return `https://${host}/${repository}/pull/${number}`;
|
||||
case "gitlab":
|
||||
return `https://${host}/${repository}/-/merge_requests/${number}`;
|
||||
case "bitbucket":
|
||||
return `https://${host}/${repository}/pull-requests/${number}`;
|
||||
case "azure-devops":
|
||||
return `https://${canonicalRepositoryKey(`${host}/${repository}`.toLowerCase())}/pullrequest/${number}`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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:") ||
|
||||
!(
|
||||
url.hostname.toLowerCase() === "github.com" ||
|
||||
url.hostname.toLowerCase().endsWith(".github.com") ||
|
||||
url.hostname.toLowerCase().split(".").includes("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();
|
||||
}
|
||||
|
||||
export function siblingPullRequestUrl(url: string, number: number): string | null {
|
||||
const reference = parseChangeRequestUrl(url);
|
||||
if (reference === null || !Number.isSafeInteger(number) || number < 1) return null;
|
||||
const sibling = new URL(url);
|
||||
const route = /^\/(-\/merge_requests|pull|pull-requests|pullrequest)\/\d+(?:\/|$)/u.exec(
|
||||
sibling.pathname.slice(reference.repository.length + 1),
|
||||
)?.[1];
|
||||
if (route === undefined) return null;
|
||||
sibling.pathname = `/${reference.repository}/${route}/${number}`;
|
||||
sibling.search = "";
|
||||
sibling.hash = "";
|
||||
return sibling.toString();
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
sourceControlRepositorySelector,
|
||||
detectSourceControlProviderFromRemoteUrl,
|
||||
getChangeRequestTerminologyForKind,
|
||||
isSshRemoteUrl,
|
||||
@@ -160,3 +161,34 @@ describe("isSshRemoteUrl", () => {
|
||||
expect(isSshRemoteUrl("[email protected]/project/repo")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it("names an Azure DevOps repository by its own name, not its project path", () => {
|
||||
// `az repos pr list --repository` takes a name and detects the organisation and project from
|
||||
// the checkout; the recorded `org/project/_git/repo` path is refused, and the repository then
|
||||
// reads as unavailable on the page.
|
||||
const selector = sourceControlRepositorySelector({
|
||||
provider: "azure-devops",
|
||||
displayName: "contoso/payments/_git/checkout",
|
||||
owner: "contoso",
|
||||
name: "checkout",
|
||||
});
|
||||
expect(selector).toBe("checkout");
|
||||
});
|
||||
|
||||
it("falls back to the path's last segment where an Azure identity has no name", () => {
|
||||
const selector = sourceControlRepositorySelector({
|
||||
provider: "azure-devops",
|
||||
displayName: "contoso/payments/_git/checkout",
|
||||
});
|
||||
expect(selector).toBe("checkout");
|
||||
});
|
||||
|
||||
it("keeps a GitLab identity's whole path, because a nested group is part of the name", () => {
|
||||
const selector = sourceControlRepositorySelector({
|
||||
provider: "gitlab",
|
||||
displayName: "group/subgroup/service",
|
||||
owner: "group",
|
||||
name: "service",
|
||||
});
|
||||
expect(selector).toBe("group/subgroup/service");
|
||||
});
|
||||
@@ -1,4 +1,8 @@
|
||||
import type { SourceControlProviderInfo, SourceControlProviderKind } from "@t3tools/contracts";
|
||||
import type {
|
||||
RepositoryIdentity,
|
||||
SourceControlProviderInfo,
|
||||
SourceControlProviderKind,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export interface ChangeRequestPresentation {
|
||||
readonly icon: "github" | "gitlab" | "azure-devops" | "bitbucket" | "change-request";
|
||||
@@ -234,3 +238,43 @@ export function detectSourceControlProviderFromRemoteUrl(
|
||||
baseUrl: toBaseUrl(host),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The provider-native repository selector. `displayName` is the full path below the host, which
|
||||
* is what nested GitLab groups need; owner/name is the two-segment fallback for identities
|
||||
* recorded before that field existed.
|
||||
*
|
||||
* Azure DevOps is the exception: `az repos pr list --repository` takes a repository name, and
|
||||
* takes the organisation and project from the checkout it detects — so the recorded
|
||||
* `org/project/_git/repo` path is refused outright and the whole repository reads as
|
||||
* unavailable. Its name is the last segment, which is what this hands over.
|
||||
*
|
||||
* One function because everything downstream is keyed by what it answers: the rows' own
|
||||
* `repository`, the per-repository cursors, and the detail and diff reads a row leads to.
|
||||
*/
|
||||
export function sourceControlRepositorySelector(
|
||||
identity:
|
||||
| Pick<RepositoryIdentity, "provider" | "displayName" | "owner" | "name">
|
||||
| null
|
||||
| undefined,
|
||||
): string | null {
|
||||
if (!identity) return null;
|
||||
if (identity.provider === "azure-devops") {
|
||||
const segments = (identity.displayName ?? "").split("/").filter((part) => part !== "_git");
|
||||
return identity.name || segments.at(-1) || null;
|
||||
}
|
||||
if (identity.displayName) return identity.displayName;
|
||||
return identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null;
|
||||
}
|
||||
|
||||
export function canonicalRepositoryKey(key: string): string {
|
||||
return key
|
||||
.replace(
|
||||
/^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,
|
||||
"dev.azure.com/$1/$2/_git/$3",
|
||||
)
|
||||
.replace(
|
||||
/^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,
|
||||
"dev.azure.com/$1/$2/_git/$3",
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
import type { ThreadPullRequestLink, ThreadPullRequestSnapshot } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
legacyLinkedPullRequestOf,
|
||||
legacyThreadPullRequestKey,
|
||||
resolveThreadCurrentPullRequest,
|
||||
resolveThreadPullRequestChains,
|
||||
resolveThreadPullRequestBadge,
|
||||
threadPullRequestKeysEqual,
|
||||
} from "./threadPullRequests.ts";
|
||||
|
||||
function snapshot(input: Partial<ThreadPullRequestSnapshot> = {}): ThreadPullRequestSnapshot {
|
||||
return {
|
||||
state: "open",
|
||||
title: "Change",
|
||||
headBranch: "feature",
|
||||
baseBranch: "main",
|
||||
isDraft: false,
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
syncedAt: "2026-01-01T00:00:00.000Z",
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function link(
|
||||
number: number,
|
||||
input: Partial<Omit<ThreadPullRequestLink, "number">> = {},
|
||||
): ThreadPullRequestLink {
|
||||
return {
|
||||
host: "github.com",
|
||||
repository: "pingdotgg/t3code",
|
||||
number,
|
||||
url: `https://github.com/pingdotgg/t3code/pull/${number}`,
|
||||
source: "manual",
|
||||
linkedAt: `2026-01-01T00:00:${String(number).padStart(2, "0")}.000Z`,
|
||||
snapshot: null,
|
||||
stack: null,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
describe("threadPullRequestKeysEqual", () => {
|
||||
it("ignores host and repository case", () => {
|
||||
expect(
|
||||
threadPullRequestKeysEqual(
|
||||
{ host: "GitHub.com", repository: "PingDotGG/t3code", number: 1 },
|
||||
{ host: "github.com", repository: "pingdotgg/t3code", number: 1 },
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
threadPullRequestKeysEqual(
|
||||
{ host: "github.com", repository: "pingdotgg/t3code", number: 1 },
|
||||
{ host: "gitlab.com", repository: "pingdotgg/t3code", number: 1 },
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadCurrentPullRequest", () => {
|
||||
it("returns null with no visible links", () => {
|
||||
expect(resolveThreadCurrentPullRequest([])).toBeNull();
|
||||
expect(resolveThreadCurrentPullRequest([link(1, { source: "stack-dismissed" })])).toBeNull();
|
||||
});
|
||||
|
||||
it("treats an unsynced link as open", () => {
|
||||
expect(resolveThreadCurrentPullRequest([link(1)])).toMatchObject({
|
||||
kind: "single",
|
||||
link: { number: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers the single open link over terminal ones", () => {
|
||||
const current = resolveThreadCurrentPullRequest([
|
||||
link(1, { snapshot: snapshot({ state: "merged" }) }),
|
||||
link(2, { snapshot: snapshot({ state: "open" }) }),
|
||||
link(3, { snapshot: snapshot({ state: "closed" }) }),
|
||||
]);
|
||||
expect(current).toMatchObject({ kind: "single", link: { number: 2 } });
|
||||
});
|
||||
|
||||
it("reports a stack when several links are open and puts the highest layer on top", () => {
|
||||
const stack = {
|
||||
kind: "native" as const,
|
||||
id: "s1",
|
||||
number: 1,
|
||||
url: "https://github.com/pingdotgg/t3code/stacks/1",
|
||||
base: "main",
|
||||
layers: [
|
||||
{ number: 10, headBranch: "a", state: "open" as const },
|
||||
{ number: 11, headBranch: "b", state: "open" as const },
|
||||
],
|
||||
};
|
||||
const current = resolveThreadCurrentPullRequest([
|
||||
link(11, { snapshot: snapshot(), stack }),
|
||||
link(10, { snapshot: snapshot(), stack }),
|
||||
]);
|
||||
expect(current).toMatchObject({ kind: "stack", top: { number: 11 } });
|
||||
if (current?.kind === "stack") {
|
||||
expect(current.open.map((entry) => entry.number)).toEqual([11, 10]);
|
||||
}
|
||||
});
|
||||
|
||||
it("orders an open set without stack data by most recent link", () => {
|
||||
const current = resolveThreadCurrentPullRequest([link(1), link(2)]);
|
||||
expect(current).toMatchObject({ kind: "stack", top: { number: 2 } });
|
||||
});
|
||||
|
||||
it("falls back to the most recently updated terminal link", () => {
|
||||
const current = resolveThreadCurrentPullRequest([
|
||||
link(1, { snapshot: snapshot({ state: "merged", updatedAt: "2026-01-03T00:00:00.000Z" }) }),
|
||||
link(2, { snapshot: snapshot({ state: "closed", updatedAt: "2026-01-02T00:00:00.000Z" }) }),
|
||||
]);
|
||||
expect(current).toMatchObject({ kind: "single", link: { number: 1 } });
|
||||
});
|
||||
});
|
||||
|
||||
describe("legacyLinkedPullRequestOf", () => {
|
||||
const identity = {
|
||||
canonicalKey: "github.com/pingdotgg/t3code",
|
||||
provider: "github",
|
||||
displayName: "pingdotgg/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "https://github.com/pingdotgg/t3code.git",
|
||||
},
|
||||
};
|
||||
it("projects only links the owning project can route without a host", () => {
|
||||
expect(legacyLinkedPullRequestOf([link(7)], "project-1" as never, identity)).toEqual({
|
||||
projectId: "project-1",
|
||||
repository: "pingdotgg/t3code",
|
||||
number: 7,
|
||||
url: "https://github.com/pingdotgg/t3code/pull/7",
|
||||
});
|
||||
expect(legacyLinkedPullRequestOf([], "project-1" as never, identity)).toBeNull();
|
||||
});
|
||||
it.each([
|
||||
{
|
||||
host: "github.enterprise.test",
|
||||
url: "https://github.enterprise.test/pingdotgg/t3code/pull/7",
|
||||
},
|
||||
{ repository: "acme/other", url: "https://github.com/acme/other/pull/7" },
|
||||
])("omits an unsafe legacy route %j", (foreign) => {
|
||||
expect(
|
||||
legacyLinkedPullRequestOf([link(7, foreign)], "project-1" as never, identity),
|
||||
).toBeNull();
|
||||
expect(
|
||||
legacyLinkedPullRequestOf([link(7, foreign), link(8)], "project-1" as never, identity)
|
||||
?.number,
|
||||
).toBe(8);
|
||||
});
|
||||
it.each([
|
||||
"dev.azure.com/org-a/project/_git/web",
|
||||
"ssh.dev.azure.com/v3/org-a/project/web",
|
||||
"org-a.visualstudio.com/DefaultCollection/project/_git/web",
|
||||
])("projects Azure links through the legacy selector for %s", (canonicalKey) => {
|
||||
const azureIdentity = {
|
||||
...identity,
|
||||
provider: "azure-devops",
|
||||
canonicalKey,
|
||||
displayName: canonicalKey.slice(canonicalKey.indexOf("/") + 1),
|
||||
name: "web",
|
||||
};
|
||||
const own = link(7, {
|
||||
host: "dev.azure.com",
|
||||
repository: "org-a/project/_git/web",
|
||||
url: "https://dev.azure.com/org-a/project/_git/web/pullrequest/7",
|
||||
});
|
||||
const foreign = link(7, {
|
||||
host: "dev.azure.com",
|
||||
repository: "web",
|
||||
url: "https://dev.azure.com/org-b/project/_git/web/pullrequest/7",
|
||||
linkedAt: "2026-01-02T00:00:00.000Z",
|
||||
});
|
||||
for (const repository of ["web", "org-a/project/_git/web"]) {
|
||||
expect(
|
||||
legacyLinkedPullRequestOf(
|
||||
[{ ...own, repository }, foreign],
|
||||
"project-1" as never,
|
||||
azureIdentity,
|
||||
),
|
||||
).toEqual({ projectId: "project-1", repository: "web", number: 7, url: own.url });
|
||||
}
|
||||
expect(legacyLinkedPullRequestOf([foreign], "project-1" as never, azureIdentity)).toBeNull();
|
||||
expect(legacyThreadPullRequestKey({ ...own, repository: "web" })).toEqual({
|
||||
host: "dev.azure.com",
|
||||
repository: "org-a/project/_git/web",
|
||||
number: 7,
|
||||
});
|
||||
expect(
|
||||
threadPullRequestKeysEqual(own, {
|
||||
host: "org-a.visualstudio.com",
|
||||
repository: "DefaultCollection/project/_git/web",
|
||||
number: 7,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
it("does not guess when the project identity is unavailable", () => {
|
||||
expect(legacyLinkedPullRequestOf([link(7)], "project-1" as never, null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadPullRequestChains", () => {
|
||||
it("chains links by base → head within a repository, bottom to top", () => {
|
||||
const chains = resolveThreadPullRequestChains([
|
||||
link(3, { snapshot: snapshot({ headBranch: "c", baseBranch: "b" }) }),
|
||||
link(1, { snapshot: snapshot({ headBranch: "a", baseBranch: "main" }) }),
|
||||
link(2, { snapshot: snapshot({ headBranch: "b", baseBranch: "a" }) }),
|
||||
link(9, { snapshot: snapshot({ headBranch: "solo", baseBranch: "main" }) }),
|
||||
]);
|
||||
expect(chains.map((chain) => [chain.kind, chain.layers.map((layer) => layer.number)])).toEqual([
|
||||
["derived", [1, 2, 3]],
|
||||
["derived", [9]],
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses the native stack order when the host provides one", () => {
|
||||
const stack = {
|
||||
kind: "native" as const,
|
||||
id: "s1",
|
||||
number: 1,
|
||||
url: "https://github.com/pingdotgg/t3code/stacks/1",
|
||||
base: "main",
|
||||
layers: [
|
||||
{ number: 5, headBranch: "a", state: "merged" as const },
|
||||
{ number: 6, headBranch: "b", state: "open" as const },
|
||||
],
|
||||
};
|
||||
const chains = resolveThreadPullRequestChains([
|
||||
link(6, { snapshot: snapshot({ headBranch: "b", baseBranch: "main" }), stack }),
|
||||
link(5, {
|
||||
snapshot: snapshot({ state: "merged", headBranch: "a", baseBranch: "main" }),
|
||||
stack,
|
||||
}),
|
||||
link(8),
|
||||
]);
|
||||
expect(chains.map((chain) => [chain.kind, chain.layers.map((layer) => layer.number)])).toEqual([
|
||||
["native", [5, 6]],
|
||||
["derived", [8]],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("chain selection and badge state", () => {
|
||||
it.each(["open", "merged", "closed"] as const)(
|
||||
"targets the top of a derived %s chain despite a later bottom update and link",
|
||||
(state) => {
|
||||
const bottom = link(2, {
|
||||
snapshot: snapshot({ state, headBranch: "base", updatedAt: "2026-02-01T00:00:00.000Z" }),
|
||||
});
|
||||
const top = link(1, {
|
||||
snapshot: snapshot({ state, headBranch: "top", baseBranch: "base" }),
|
||||
});
|
||||
expect(resolveThreadCurrentPullRequest([bottom, top])).toMatchObject(
|
||||
state === "open"
|
||||
? { kind: "stack", top: { number: 1 }, open: [top, bottom] }
|
||||
: { kind: "single", link: { number: 1 } },
|
||||
);
|
||||
expect(resolveThreadPullRequestBadge([bottom, top])).toEqual({
|
||||
kind: "stack",
|
||||
layers: 2,
|
||||
state,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the top native layer after completion and treats an unsynced layer as open", () => {
|
||||
const stack = {
|
||||
kind: "native" as const,
|
||||
id: "native-1",
|
||||
number: 1,
|
||||
url: "https://github.com/pingdotgg/t3code/stacks/1",
|
||||
base: "main",
|
||||
layers: [
|
||||
{ number: 2, headBranch: "base", state: "merged" as const },
|
||||
{ number: 1, headBranch: "top", state: "merged" as const },
|
||||
],
|
||||
};
|
||||
const bottom = link(2, {
|
||||
stack,
|
||||
snapshot: snapshot({ state: "merged", updatedAt: "2026-02-01T00:00:00.000Z" }),
|
||||
});
|
||||
const top = link(1, { stack, snapshot: snapshot({ state: "merged" }) });
|
||||
expect(resolveThreadCurrentPullRequest([bottom, top])).toMatchObject({
|
||||
kind: "single",
|
||||
link: { number: 1 },
|
||||
});
|
||||
expect(resolveThreadPullRequestBadge([bottom, { ...top, snapshot: null }])).toEqual({
|
||||
kind: "stack",
|
||||
layers: 2,
|
||||
state: "open",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses aggregate state and distinguishes unrelated work from a stack", () => {
|
||||
const bottom = link(1, { snapshot: snapshot({ state: "merged", headBranch: "base" }) });
|
||||
const top = link(2, { snapshot: snapshot({ state: "closed", baseBranch: "base" }) });
|
||||
expect(resolveThreadPullRequestBadge([bottom, top])).toEqual({
|
||||
kind: "stack",
|
||||
layers: 2,
|
||||
state: "closed",
|
||||
});
|
||||
expect(resolveThreadPullRequestBadge([bottom, top, link(3)])).toEqual({
|
||||
kind: "pull-request",
|
||||
others: 2,
|
||||
});
|
||||
expect(resolveThreadPullRequestBadge([link(3, { source: "stack-dismissed" })])).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps branch matching case-sensitive while ignoring repository case", () => {
|
||||
const bottom = link(1, {
|
||||
repository: "PingDotGG/T3code",
|
||||
snapshot: snapshot({ headBranch: "Base" }),
|
||||
});
|
||||
const top = link(2, { snapshot: snapshot({ headBranch: "top", baseBranch: "base" }) });
|
||||
expect(resolveThreadPullRequestChains([bottom, top])).toHaveLength(2);
|
||||
expect(
|
||||
resolveThreadPullRequestChains([
|
||||
bottom,
|
||||
{ ...top, snapshot: snapshot({ headBranch: "top", baseBranch: "Base" }) },
|
||||
])[0]?.layers,
|
||||
).toEqual([bottom, { ...top, snapshot: snapshot({ headBranch: "top", baseBranch: "Base" }) }]);
|
||||
});
|
||||
|
||||
it("preserves cyclic links without presenting a guessed stack order", () => {
|
||||
const links = [
|
||||
link(1, { snapshot: snapshot({ headBranch: "a", baseBranch: "b" }) }),
|
||||
link(2, { snapshot: snapshot({ headBranch: "b", baseBranch: "a" }) }),
|
||||
];
|
||||
expect(resolveThreadPullRequestChains(links).map((chain) => chain.layers)).toEqual(
|
||||
links.map((entry) => [entry]),
|
||||
);
|
||||
expect(resolveThreadCurrentPullRequest(links)).toMatchObject({
|
||||
kind: "stack",
|
||||
top: { number: 2 },
|
||||
});
|
||||
expect(resolveThreadPullRequestBadge(links)).toEqual({ kind: "pull-request", others: 1 });
|
||||
});
|
||||
|
||||
it("does not guess a parent when a head branch was reused", () => {
|
||||
const links = [
|
||||
link(1, { snapshot: snapshot({ state: "merged", headBranch: "reused" }) }),
|
||||
link(2, { snapshot: snapshot({ headBranch: "reused" }) }),
|
||||
link(3, { snapshot: snapshot({ headBranch: "top", baseBranch: "reused" }) }),
|
||||
];
|
||||
expect(resolveThreadPullRequestChains(links).map((chain) => chain.layers)).toEqual(
|
||||
links.map((entry) => [entry]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,271 @@
|
||||
import type {
|
||||
RepositoryIdentity,
|
||||
SourceControlProviderKind,
|
||||
ThreadLinkedPullRequest,
|
||||
ThreadPullRequestKey,
|
||||
ThreadPullRequestLink,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { pullRequestHostOf } from "@t3tools/contracts";
|
||||
import { parseChangeRequestUrl } from "./changeRequestUrl.ts";
|
||||
import { canonicalRepositoryKey, sourceControlRepositorySelector } from "./sourceControl.ts";
|
||||
|
||||
/** Normalize stored link identity, including Azure's SSH and browser host aliases. */
|
||||
export function normalizeThreadPullRequestKey(key: ThreadPullRequestKey): ThreadPullRequestKey {
|
||||
const canonical = canonicalRepositoryKey(
|
||||
`${key.host.trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`,
|
||||
);
|
||||
const separator = canonical.indexOf("/");
|
||||
return {
|
||||
host: canonical.slice(0, separator),
|
||||
repository: canonical.slice(separator + 1),
|
||||
number: key.number,
|
||||
};
|
||||
}
|
||||
|
||||
/** Legacy Azure selectors omit the organization and project; recover those from the PR URL. */
|
||||
export function legacyThreadPullRequestKey(
|
||||
linked: Pick<ThreadLinkedPullRequest, "repository" | "number" | "url">,
|
||||
fallbackHost?: string,
|
||||
): ThreadPullRequestKey {
|
||||
const parsed = parseChangeRequestUrl(linked.url);
|
||||
if (parsed !== null && parsed.number === linked.number) {
|
||||
const canonical = canonicalRepositoryKey(`${parsed.host}/${parsed.repository}`);
|
||||
if (canonical.startsWith("dev.azure.com/")) {
|
||||
return normalizeThreadPullRequestKey(parsed);
|
||||
}
|
||||
}
|
||||
let host = fallbackHost;
|
||||
if (host === undefined) {
|
||||
try {
|
||||
host = new URL(linked.url).hostname;
|
||||
} catch {
|
||||
host = "unknown";
|
||||
}
|
||||
}
|
||||
return {
|
||||
host: host.trim().toLowerCase() || "unknown",
|
||||
repository: linked.repository.trim().toLowerCase(),
|
||||
number: linked.number,
|
||||
};
|
||||
}
|
||||
|
||||
/** Identity comparison for links: host-level, case-insensitive on host and repository. */
|
||||
export function threadPullRequestKeysEqual(
|
||||
left: ThreadPullRequestKey,
|
||||
right: ThreadPullRequestKey,
|
||||
): boolean {
|
||||
return threadPullRequestKeyOf(left) === threadPullRequestKeyOf(right);
|
||||
}
|
||||
|
||||
export function threadPullRequestKeyOf(key: ThreadPullRequestKey): string {
|
||||
const normalized = normalizeThreadPullRequestKey(key);
|
||||
return `${normalized.host}/${normalized.repository}#${normalized.number}`;
|
||||
}
|
||||
|
||||
/** Links a user should see. Tombstoned stack members stay in the array only so the
|
||||
* sync reactor does not re-add them. */
|
||||
export function visibleThreadPullRequests(
|
||||
links: ReadonlyArray<ThreadPullRequestLink>,
|
||||
): ReadonlyArray<ThreadPullRequestLink> {
|
||||
return links.filter((link) => link.source !== "stack-dismissed");
|
||||
}
|
||||
|
||||
function isOpen(link: ThreadPullRequestLink): boolean {
|
||||
// Unsynced links are treated as open: they were just linked, and hiding them
|
||||
// behind a terminal PR until the first sync would make the link look lost.
|
||||
return link.snapshot === null || link.snapshot.state === "open";
|
||||
}
|
||||
|
||||
function latestUpdatedAt(link: ThreadPullRequestLink): number {
|
||||
const value = link.snapshot?.updatedAt ?? link.linkedAt;
|
||||
const ms = Date.parse(value);
|
||||
return Number.isNaN(ms) ? 0 : ms;
|
||||
}
|
||||
|
||||
/** The single pull request a one-slot surface (sidebar badge, tab icon, copy link) shows. */
|
||||
export type ThreadCurrentPullRequest =
|
||||
| { readonly kind: "single"; readonly link: ThreadPullRequestLink }
|
||||
| {
|
||||
readonly kind: "stack";
|
||||
readonly open: ReadonlyArray<ThreadPullRequestLink>;
|
||||
/** Highest layer of the open set; the one "View PR" and copy-link target. */
|
||||
readonly top: ThreadPullRequestLink;
|
||||
};
|
||||
|
||||
/**
|
||||
* Prefer open work and the highest open layer within a chain. A completed chain still
|
||||
* points at its top; unrelated terminal links use the most recently updated request.
|
||||
*/
|
||||
export function resolveThreadCurrentPullRequest(
|
||||
links: ReadonlyArray<ThreadPullRequestLink>,
|
||||
): ThreadCurrentPullRequest | null {
|
||||
const visible = visibleThreadPullRequests(links);
|
||||
if (visible.length === 0) return null;
|
||||
const open = visible.filter(isOpen);
|
||||
if (open.length === 1) return { kind: "single", link: open[0]! };
|
||||
const chains = resolveThreadPullRequestChains(visible);
|
||||
if (open.length > 1) {
|
||||
const openChains = chains
|
||||
.map((chain) => chain.layers.toReversed().filter(isOpen))
|
||||
.filter((layers) => layers.length > 0)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
Math.max(...right.map((link) => Date.parse(link.linkedAt))) -
|
||||
Math.max(...left.map((link) => Date.parse(link.linkedAt))),
|
||||
);
|
||||
const ordered = openChains.flat();
|
||||
return { kind: "stack", open: ordered, top: ordered[0]! };
|
||||
}
|
||||
if (chains.length === 1) {
|
||||
return { kind: "single", link: chains[0]!.layers.at(-1)! };
|
||||
}
|
||||
const terminal = [...visible].sort(
|
||||
(left, right) => latestUpdatedAt(right) - latestUpdatedAt(left),
|
||||
);
|
||||
return { kind: "single", link: terminal[0]! };
|
||||
}
|
||||
|
||||
/** The one link a legacy `linkedPullRequest` consumer should see, or null. */
|
||||
export function resolveThreadCurrentPullRequestLink(
|
||||
links: ReadonlyArray<ThreadPullRequestLink>,
|
||||
): ThreadPullRequestLink | null {
|
||||
const current = resolveThreadCurrentPullRequest(links);
|
||||
if (current === null) return null;
|
||||
return current.kind === "single" ? current.link : current.top;
|
||||
}
|
||||
|
||||
/** Legacy clients can only route links belonging to the thread's own repository. */
|
||||
export function legacyLinkedPullRequestOf(
|
||||
links: ReadonlyArray<ThreadPullRequestLink>,
|
||||
projectId: ThreadLinkedPullRequest["projectId"],
|
||||
identity: RepositoryIdentity | null | undefined,
|
||||
): ThreadLinkedPullRequest | null {
|
||||
if (!identity) return null;
|
||||
const host = pullRequestHostOf(identity, identity.provider as SourceControlProviderKind);
|
||||
const repository = sourceControlRepositorySelector(identity);
|
||||
if (repository === null) return null;
|
||||
const azureKey =
|
||||
identity.provider === "azure-devops"
|
||||
? canonicalRepositoryKey(identity.canonicalKey.toLowerCase())
|
||||
: null;
|
||||
const link = resolveThreadCurrentPullRequestLink(
|
||||
links.filter((link) => {
|
||||
if (azureKey !== null) {
|
||||
const key = legacyThreadPullRequestKey(link, link.host);
|
||||
return canonicalRepositoryKey(`${key.host}/${key.repository}`) === azureKey;
|
||||
}
|
||||
return (
|
||||
link.host.toLowerCase() === host.toLowerCase() &&
|
||||
link.repository.toLowerCase() === repository.toLowerCase()
|
||||
);
|
||||
}),
|
||||
);
|
||||
if (link === null) return null;
|
||||
return {
|
||||
projectId,
|
||||
repository: azureKey === null ? link.repository : repository,
|
||||
number: link.number,
|
||||
url: link.url,
|
||||
};
|
||||
}
|
||||
|
||||
export interface ThreadPullRequestChain {
|
||||
readonly kind: "native" | "derived";
|
||||
/** Bottom to top. */
|
||||
readonly layers: ReadonlyArray<ThreadPullRequestLink>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups a thread's links into stacks. Native stacks come from the host and win; the rest
|
||||
* are chained by matching one link's base branch to another's head branch within the same
|
||||
* repository. A link that chains to nothing is a one-layer chain.
|
||||
*/
|
||||
export function resolveThreadPullRequestChains(
|
||||
links: ReadonlyArray<ThreadPullRequestLink>,
|
||||
): ReadonlyArray<ThreadPullRequestChain> {
|
||||
const visible = visibleThreadPullRequests(links);
|
||||
const chains: Array<ThreadPullRequestChain> = [];
|
||||
const placed = new Set<string>();
|
||||
|
||||
const nativeStacks = new Map<string, Array<ThreadPullRequestLink>>();
|
||||
for (const link of visible) {
|
||||
if (link.stack === null) continue;
|
||||
const stackKey = `${link.host.toLowerCase()}/${link.repository.toLowerCase()}#stack:${link.stack.id}`;
|
||||
const members = nativeStacks.get(stackKey) ?? [];
|
||||
members.push(link);
|
||||
nativeStacks.set(stackKey, members);
|
||||
}
|
||||
for (const members of nativeStacks.values()) {
|
||||
const order = new Map(members[0]!.stack!.layers.map((layer, index) => [layer.number, index]));
|
||||
members.sort((left, right) => (order.get(left.number) ?? 0) - (order.get(right.number) ?? 0));
|
||||
for (const member of members) placed.add(threadPullRequestKeyOf(member));
|
||||
chains.push({ kind: "native", layers: members });
|
||||
}
|
||||
|
||||
const remaining = visible.filter((link) => !placed.has(threadPullRequestKeyOf(link)));
|
||||
const branchKey = (link: ThreadPullRequestLink, branch: string) =>
|
||||
`${link.host.toLowerCase()}/${link.repository.toLowerCase()}:${branch}`;
|
||||
// Reused head names cannot identify a parent unambiguously.
|
||||
const byHead = new Map<string, ThreadPullRequestLink | null>();
|
||||
for (const link of remaining) {
|
||||
if (link.snapshot === null) continue;
|
||||
const key = branchKey(link, link.snapshot.headBranch);
|
||||
byHead.set(key, byHead.has(key) ? null : link);
|
||||
}
|
||||
const hasChild = new Set<string>();
|
||||
for (const link of remaining) {
|
||||
if (link.snapshot === null) continue;
|
||||
const parent = byHead.get(branchKey(link, link.snapshot.baseBranch));
|
||||
if (parent != null && parent !== link) hasChild.add(threadPullRequestKeyOf(parent));
|
||||
}
|
||||
// Walk from each top (a link nothing builds on) down its base chain.
|
||||
for (const top of remaining) {
|
||||
if (hasChild.has(threadPullRequestKeyOf(top))) continue;
|
||||
const layers: Array<ThreadPullRequestLink> = [];
|
||||
let cursor: ThreadPullRequestLink | undefined = top;
|
||||
while (cursor !== undefined && !placed.has(threadPullRequestKeyOf(cursor))) {
|
||||
placed.add(threadPullRequestKeyOf(cursor));
|
||||
layers.unshift(cursor);
|
||||
cursor =
|
||||
cursor.snapshot === null
|
||||
? undefined
|
||||
: (byHead.get(branchKey(cursor, cursor.snapshot.baseBranch)) ?? undefined);
|
||||
}
|
||||
if (layers.length > 0) chains.push({ kind: "derived", layers });
|
||||
}
|
||||
// Cycles have no top. Keep those links visible without inventing a stack order.
|
||||
for (const link of remaining) {
|
||||
if (!placed.has(threadPullRequestKeyOf(link))) {
|
||||
chains.push({ kind: "derived", layers: [link] });
|
||||
}
|
||||
}
|
||||
return chains;
|
||||
}
|
||||
|
||||
export type ThreadPullRequestBadge =
|
||||
| {
|
||||
readonly kind: "stack";
|
||||
readonly layers: number;
|
||||
readonly state: "open" | "closed" | "merged";
|
||||
}
|
||||
| { readonly kind: "pull-request"; readonly others: number };
|
||||
|
||||
/** Aggregate a single chain's state; unrelated links show a count beside the current PR. */
|
||||
export function resolveThreadPullRequestBadge(
|
||||
pullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined,
|
||||
): ThreadPullRequestBadge | null {
|
||||
const visible = visibleThreadPullRequests(pullRequests ?? []);
|
||||
if (visible.length === 0) return null;
|
||||
const chains = resolveThreadPullRequestChains(visible);
|
||||
if (visible.length > 1 && chains.length === 1) {
|
||||
const states = visible.map((link) => link.snapshot?.state ?? "open");
|
||||
const state = states.includes("open")
|
||||
? "open"
|
||||
: states.every((entry) => entry === "merged")
|
||||
? "merged"
|
||||
: "closed";
|
||||
return { kind: "stack", layers: visible.length, state };
|
||||
}
|
||||
return { kind: "pull-request", others: visible.length - 1 };
|
||||
}
|
||||
@@ -1,13 +1,26 @@
|
||||
import type { ThreadPullRequestLink } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveThreadReferenceCopyTarget } from "./threadReference.ts";
|
||||
|
||||
const crossRepositoryPullRequest: ThreadPullRequestLink = {
|
||||
host: "github.com",
|
||||
repository: "other/repo",
|
||||
number: 42,
|
||||
url: "https://github.com/other/repo/pull/42",
|
||||
source: "manual",
|
||||
linkedAt: "2026-01-01T00:00:00.000Z",
|
||||
snapshot: null,
|
||||
stack: null,
|
||||
};
|
||||
|
||||
describe("resolveThreadReferenceCopyTarget", () => {
|
||||
it("does not copy another reference while the open panel URL is unavailable", () => {
|
||||
expect(
|
||||
resolveThreadReferenceCopyTarget({
|
||||
threadId: "thread-1",
|
||||
openPanelPullRequestUrl: null,
|
||||
pullRequests: [crossRepositoryPullRequest],
|
||||
linkedPullRequestUrl: "https://github.com/t3/pr/12",
|
||||
}),
|
||||
).toBeNull();
|
||||
@@ -18,6 +31,7 @@ describe("resolveThreadReferenceCopyTarget", () => {
|
||||
resolveThreadReferenceCopyTarget({
|
||||
threadId: "thread-1",
|
||||
openPanelPullRequestUrl: "https://github.com/t3/pr/14",
|
||||
pullRequests: [crossRepositoryPullRequest],
|
||||
linkedPullRequestUrl: "https://github.com/t3/pr/12",
|
||||
}),
|
||||
).toMatchObject({
|
||||
@@ -27,6 +41,58 @@ describe("resolveThreadReferenceCopyTarget", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.each([null, "https://github.com/t3/pr/12"])(
|
||||
"copies a native cross-repository link before the fallback URL %s",
|
||||
(linkedPullRequestUrl) => {
|
||||
expect(
|
||||
resolveThreadReferenceCopyTarget({
|
||||
threadId: "thread-1",
|
||||
pullRequests: [crossRepositoryPullRequest],
|
||||
linkedPullRequestUrl,
|
||||
}),
|
||||
).toMatchObject({
|
||||
kind: "pull-request",
|
||||
value: crossRepositoryPullRequest.url,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("copies the highest open stack layer instead of the first link", () => {
|
||||
const stack: NonNullable<ThreadPullRequestLink["stack"]> = {
|
||||
kind: "native",
|
||||
id: "stack-1",
|
||||
number: 1,
|
||||
url: "https://github.com/other/repo/stacks/1",
|
||||
base: "main",
|
||||
layers: [
|
||||
{ number: 42, headBranch: "first", state: "open" },
|
||||
{ number: 43, headBranch: "second", state: "open" },
|
||||
],
|
||||
};
|
||||
const top = {
|
||||
...crossRepositoryPullRequest,
|
||||
number: 43,
|
||||
url: "https://github.com/other/repo/pull/43",
|
||||
stack,
|
||||
};
|
||||
expect(
|
||||
resolveThreadReferenceCopyTarget({
|
||||
threadId: "thread-1",
|
||||
pullRequests: [{ ...crossRepositoryPullRequest, stack }, top],
|
||||
}),
|
||||
).toMatchObject({ kind: "pull-request", value: top.url });
|
||||
});
|
||||
|
||||
it("uses the fallback URL when native links are dismissed", () => {
|
||||
expect(
|
||||
resolveThreadReferenceCopyTarget({
|
||||
threadId: "thread-1",
|
||||
pullRequests: [{ ...crossRepositoryPullRequest, source: "stack-dismissed" }],
|
||||
linkedPullRequestUrl: "https://github.com/t3/pr/12",
|
||||
}),
|
||||
).toMatchObject({ kind: "pull-request", value: "https://github.com/t3/pr/12" });
|
||||
});
|
||||
|
||||
it("uses the thread pull request when no panel is open", () => {
|
||||
expect(
|
||||
resolveThreadReferenceCopyTarget({
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import type { ThreadPullRequestLink } from "@t3tools/contracts";
|
||||
|
||||
import { resolveThreadCurrentPullRequestLink } from "./threadPullRequests.ts";
|
||||
|
||||
export interface ThreadReferenceCopyTarget {
|
||||
readonly kind: "pull-request" | "thread";
|
||||
readonly value: string;
|
||||
@@ -10,10 +14,14 @@ export function resolveThreadReferenceCopyTarget(input: {
|
||||
readonly threadId: string;
|
||||
/** Undefined means no PR panel; null means its URL is not available yet. */
|
||||
readonly openPanelPullRequestUrl?: string | null | undefined;
|
||||
readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
|
||||
readonly linkedPullRequestUrl?: string | null;
|
||||
}): ThreadReferenceCopyTarget | null {
|
||||
if (input.openPanelPullRequestUrl === null) return null;
|
||||
const pullRequestUrl = input.openPanelPullRequestUrl ?? input.linkedPullRequestUrl;
|
||||
const pullRequestUrl =
|
||||
input.openPanelPullRequestUrl ??
|
||||
resolveThreadCurrentPullRequestLink(input.pullRequests ?? [])?.url ??
|
||||
input.linkedPullRequestUrl;
|
||||
return pullRequestUrl
|
||||
? {
|
||||
kind: "pull-request",
|
||||
|
||||
Reference in new issue
Block a user