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

@@ -183,20 +183,37 @@ afterEach(() => {
});
layer("GitHubPullRequestCli.layer", (it) => {
it.effect("reads linked pull request status through one narrow request", () =>
it.effect("reads linked pull request status with the overview fields in one request", () =>
Effect.gen(function* () {
mockedGetPullRequest.mockReturnValueOnce(
Effect.succeed({
number: 7,
title: "Reuse the summary",
url: "https://github.com/acme/web/pull/7",
baseRefName: "main",
headRefName: "feat/summary",
state: "merged",
closedAt: "2026-08-23T10:00:00Z",
mergedAt: "2026-08-23T10:00:00Z",
updatedAt: "2026-08-24T12:34:56.000Z",
}),
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({
number: 7,
title: "Reuse the summary",
url: "https://github.com/acme/web/pull/7",
author: { login: "octocat", name: "Octo Cat" },
baseRefName: "main",
headRefName: "feat/summary",
state: "OPEN",
isDraft: false,
mergeable: "MERGEABLE",
reviewDecision: "APPROVED",
additions: 12,
deletions: 3,
changedFiles: 2,
createdAt: "2026-08-20T00:00:00.000Z",
updatedAt: "2026-08-24T12:34:56.000Z",
reviewRequests: [],
labels: [],
statusCheckRollup: [
{ __typename: "CheckRun", status: "COMPLETED", conclusion: "SUCCESS", name: "ci" },
],
body: "",
}),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
@@ -207,23 +224,207 @@ layer("GitHubPullRequestCli.layer", (it) => {
number: 7,
});
assert.deepStrictEqual(summary, {
number: 7,
title: "Reuse the summary",
url: "https://github.com/acme/web/pull/7",
headBranch: "feat/summary",
baseBranch: "main",
state: "merged",
closedAt: "2026-08-23T10:00:00Z",
mergedAt: "2026-08-23T10:00:00Z",
updatedAt: "2026-08-24T12:34:56.000Z",
});
expect(mockedGetPullRequest).toHaveBeenCalledOnce();
expect(mockedGetPullRequest).toHaveBeenCalledWith({
assert.deepStrictEqual(
{
number: summary.number,
state: summary.state,
headBranch: summary.headBranch,
isDraft: summary.isDraft,
author: summary.author?.login,
additions: summary.additions,
deletions: summary.deletions,
changedFiles: summary.changedFiles,
reviewDecision: summary.reviewDecision,
checksState: summary.checksState,
mergeability: summary.mergeability,
},
{
number: 7,
state: "open",
headBranch: "feat/summary",
isDraft: false,
author: "octocat",
additions: 12,
deletions: 3,
changedFiles: 2,
reviewDecision: "approved",
checksState: "passing",
mergeability: "mergeable",
},
);
expect(mockedExecute).toHaveBeenCalledOnce();
expect(mockedExecute.mock.calls[0]?.[0]?.args).toEqual([
"pr",
"view",
"7",
"--repo",
"github.com/acme/web",
"--json",
expect.stringContaining("statusCheckRollup"),
]);
expect(mockedGetPullRequest).not.toHaveBeenCalled();
}),
);
it.effect("reads the stack a pull request is in through the stacks preview, on its host", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
id: 42,
number: 3,
url: "https://api.github.com/repos/acme/web/stacks/3",
base: { ref: "main" },
pull_requests: [
{
number: 6,
head: { ref: "feat/one" },
state: "closed",
merged_at: "2026-09-02",
},
{ number: 7, head: { ref: "feat/two" }, state: "open", merged_at: null },
],
},
]),
),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const stack = yield* cli.getPullRequestStack({
cwd: "/w",
reference: "https://github.com/acme/web/pull/7",
repository: "acme/web",
host: "ghe.example.com",
number: 7,
});
expect(mockedExecute).not.toHaveBeenCalled();
assert.deepStrictEqual(stack, {
id: "42",
number: 3,
url: "https://api.github.com/repos/acme/web/stacks/3",
base: "main",
layers: [
{ number: 6, headBranch: "feat/one", state: "merged" },
{ number: 7, headBranch: "feat/two", state: "open" },
],
});
assert.deepStrictEqual(callAt(0).args, [
"api",
"--hostname",
"ghe.example.com",
"repos/acme/web/stacks?pull_request=7",
]);
}),
);
it.effect("reads an empty stacks listing as not stacked", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const stack = yield* cli.getPullRequestStack({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
});
assert.isNull(stack);
}),
);
it.effect("reads a host that refuses the stacks preview as not stacked", () =>
Effect.gen(function* () {
// The CLI classifies a missing preview endpoint as not found.
mockedExecute.mockReturnValueOnce(
Effect.fail(
new GitHubCli.GitHubPullRequestNotFoundError({
command: "gh",
cwd: "/w",
cause: new Error("HTTP 404: Not Found (https://api.github.com/repos/acme/web/stacks)"),
}),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const stack = yield* cli.getPullRequestStack({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
});
assert.isNull(stack);
}),
);
it.effect("does not read a signed-out gh as an unstacked pull request", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
Effect.fail(
new GitHubCli.GitHubCliAuthenticationError({
command: "gh",
cwd: "/w",
cause: new Error("gh auth login"),
}),
),
);
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const error = yield* Effect.flip(
cli.getPullRequestStack({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
}),
);
assert.strictEqual(error._tag, "GitHubCliAuthenticationError");
}),
);
it.effect("preserves transient stack failures instead of reporting no stack", () =>
Effect.gen(function* () {
const failure = new GitHubCli.GitHubCliCommandError({
command: "gh",
cwd: "/w",
cause: new Error("HTTP 503"),
});
mockedExecute.mockReturnValueOnce(Effect.fail(failure));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const error = yield* Effect.flip(
cli.getPullRequestStack({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
}),
);
assert.strictEqual(error, failure);
}),
);
it.effect("reports a stacks answer it cannot read against the stack read", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output('[{"id":42}]')));
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
const error = yield* Effect.flip(
cli.getPullRequestStack({
cwd: "/w",
repository: "acme/web",
host: "github.com",
number: 7,
}),
);
assert.strictEqual(error._tag, "GitHubPullRequestReadError");
if (error._tag !== "GitHubPullRequestReadError") return;
assert.strictEqual(error.operation, "getPullRequestStack");
}),
);
@@ -39,6 +39,7 @@ import {
decodePullRequestListJson,
decodePullRequestNodeIdJson,
decodePullRequestSearchJson,
decodePullRequestStacksJson,
decodePullRequestStatsJson,
decodeReactionSubjectScopeJson,
decodeRepositoryAccessJson,
@@ -84,6 +85,7 @@ import {
type GitHubPullRequestHead,
type GitHubPullRequestListItem,
type GitHubPullRequestSearchItem,
type GitHubPullRequestStack,
type GitHubReviewThreadComments,
type GitHubRepositoryAccess,
type GitHubWorkflowRunApproval,
@@ -91,7 +93,7 @@ import {
type GitHubReviewThreadPage,
type GitHubViewerAccess,
} from "./gitHubPullRequestJson.ts";
import type { ProviderListCursor } from "./PullRequestProvider.ts";
import type { ProviderChangeRequestSummary, ProviderListCursor } from "./PullRequestProvider.ts";
/**
* Names the read that produced unusable output, so a failure reports the call it came from
@@ -460,21 +462,7 @@ export class GitHubPullRequestCli extends Context.Service<
readonly repository: string;
readonly host: string;
readonly number: number;
}) => Effect.Effect<
{
readonly number: number;
readonly title: string;
readonly url: string;
readonly headBranch: string;
readonly baseBranch: string;
readonly state: "open" | "closed" | "merged";
readonly isDraft?: boolean;
readonly closedAt?: string | null;
readonly mergedAt?: string | null;
readonly updatedAt: string;
},
GitHubPullRequestCliError
>;
}) => Effect.Effect<ProviderChangeRequestSummary, GitHubPullRequestCliError>;
readonly getPullRequestDetail: (input: {
readonly cwd: string;
@@ -494,6 +482,17 @@ export class GitHubPullRequestCli extends Context.Service<
readonly isCrossRepository: true;
}) => Effect.Effect<ReadonlyArray<GitHubWorkflowRunApproval>, GitHubPullRequestCliError>;
/**
* The host-native stack this pull request is in, or null when it is in none — which is also
* the answer for a host that refuses the stacks preview altogether.
*/
readonly getPullRequestStack: (input: {
readonly cwd: string;
readonly repository: string;
readonly host: string;
readonly number: number;
}) => Effect.Effect<GitHubPullRequestStack | null, GitHubPullRequestCliError>;
/**
* How far the branch trails its base, and whether this viewer may update it. Its own read
* because the comparison needs the head ref the detail answers with — a fork's branch is not
@@ -807,8 +806,8 @@ function matchesFilters(
viewer: string,
): boolean {
if (filters === undefined) return true;
const labels = item.labels.map((label) => label.name.trim().toLowerCase());
const holds = (label: string) => labels.includes(label.trim().toLowerCase());
const labels = new Set(item.labels.map((label) => label.name.trim().toLowerCase()));
const holds = (label: string) => labels.has(label.trim().toLowerCase());
return (
(filters.draft === undefined || item.isDraft === (filters.draft === "only")) &&
(filters.review === undefined ||
@@ -1630,41 +1629,94 @@ export const make = Effect.gen(function* () {
).pipe(Effect.map((results) => results.flat()));
},
// One `gh pr view` either way; asking for the detail fields costs nothing extra and hands
// the thread overview its author, diff stat, review decision and checks in the same read.
getPullRequestSummary: (input) =>
github
.getPullRequest({
.execute({
cwd: input.cwd,
reference: `https://${input.host}/${input.repository}/pull/${input.number}`,
args: [
"pr",
"view",
String(input.number),
...repositoryArgs(input),
"--json",
PULL_REQUEST_DETAIL_JSON_FIELDS,
],
})
.pipe(
Effect.flatMap((summary) =>
summary.updatedAt === undefined
? Effect.fail(
new GitHubPullRequestUpdatedAtUnavailableError({
command: "gh",
cwd: input.cwd,
repository: input.repository,
number: input.number,
}),
)
: Effect.succeed({
number: summary.number,
title: summary.title,
url: summary.url,
headBranch: summary.headRefName,
baseBranch: summary.baseRefName,
state: summary.state ?? "open",
...(summary.isDraft === true ? { isDraft: true } : {}),
closedAt: summary.closedAt ?? null,
mergedAt: summary.mergedAt ?? null,
updatedAt: summary.updatedAt,
Effect.flatMap((result) => {
const decoded = decodePullRequestDetailJson(result.stdout.trim());
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubPullRequestReadError({
command: "gh",
cwd: input.cwd,
operation: "getPullRequestSummary",
cause: decoded.failure,
}),
),
);
}
const detail = decoded.success;
return Effect.succeed({
number: detail.number,
title: detail.title,
url: detail.url,
headBranch: detail.headBranch,
baseBranch: detail.baseBranch,
state: detail.state,
updatedAt: detail.updatedAt,
closedAt: detail.closedAt ?? null,
mergedAt: detail.mergedAt ?? null,
isDraft: detail.isDraft,
author: detail.author,
additions: detail.additions,
deletions: detail.deletions,
changedFiles: detail.changedFiles,
reviewDecision: detail.reviewDecision,
checksState: detail.checksState,
mergeability: detail.mergeability,
});
}),
),
getPullRequestDetail,
listWorkflowRunsRequiringApproval,
getPullRequestStack: (input) => {
const { owner, name } = parseRepositorySelector(input.repository);
return github
.execute({
cwd: input.cwd,
args: [
"api",
"--hostname",
input.host,
`repos/${owner}/${name}/stacks?pull_request=${input.number}`,
],
})
.pipe(
Effect.flatMap((result) => {
const decoded = decodePullRequestStacksJson(result.stdout.trim());
return Result.isSuccess(decoded)
? Effect.succeed(decoded.success)
: Effect.fail(
new GitHubPullRequestReadError({
command: "gh",
cwd: input.cwd,
operation: "getPullRequestStack",
cause: decoded.failure,
}),
);
}),
// Hosts without the stacks preview return 404. Other failures must preserve the
// previously synced stack and let the caller retry.
Effect.catchTags({
GitHubPullRequestNotFoundError: () => Effect.succeed(null),
}),
);
},
getPullRequestBaseComparison: (input) => {
const { owner, name } = parseRepositorySelector(input.repository);
return graphqlRead({
@@ -25,6 +25,7 @@ it.effect("uses one narrow read for a linked pull request summary", () =>
baseBranch: "main",
state: "open" as const,
updatedAt: "2026-08-24T12:34:56.000Z",
author: { login: "octocat", name: null, avatarUrl: null },
};
}),
}),
@@ -42,6 +43,66 @@ it.effect("uses one narrow read for a linked pull request summary", () =>
expect(summary.state).toBe("open");
expect(summaryReads).toBe(1);
// The author's avatar comes from the login-shaped URL, not a second request.
expect(summary.author?.avatarUrl).toBe("https://github.com/octocat.png?size=80");
}),
);
it.effect("declares host-native stacks and passes the one the CLI reads through", () =>
Effect.gen(function* () {
const stack = {
id: "42",
number: 3,
url: "https://github.com/acme/web/stacks/3",
base: "main",
layers: [
{ number: 6, headBranch: "feat/one", state: "merged" as const },
{ number: 7, headBranch: "feat/two", state: "open" as const },
],
};
const provider = yield* make.pipe(
Effect.provide(
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
getPullRequestStack: (input) => Effect.succeed(input.number === 7 ? stack : null),
}),
),
);
expect(provider.capabilities.stacks).toBe(true);
const readStack = provider.getChangeRequestStack;
if (readStack === undefined) return yield* Effect.die("stack read was not implemented");
const ref = { cwd: "/w", repository: "acme/web", host: "github.com" };
expect(yield* readStack({ ...ref, number: 7 })).toEqual(stack);
expect(yield* readStack({ ...ref, number: 8 })).toBeNull();
}),
);
it.effect("reports a failed stack read against its own operation", () =>
Effect.gen(function* () {
const provider = yield* make.pipe(
Effect.provide(
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
getPullRequestStack: () =>
Effect.fail(
new GitHubPullRequestCli.GitHubPullRequestReadError({
command: "gh",
cwd: "/w",
operation: "getPullRequestStack",
cause: new Error("unreadable"),
}),
),
}),
),
);
const readStack = provider.getChangeRequestStack;
if (readStack === undefined) return yield* Effect.die("stack read was not implemented");
const error = yield* Effect.flip(
readStack({ cwd: "/w", repository: "acme/web", host: "github.com", number: 7 }),
);
expect(error.operation).toBe("getChangeRequestStack");
expect(error.reason).toBe("failed");
}),
);
@@ -47,6 +47,7 @@ const CAPABILITIES: PullRequestCapabilities = {
},
reviewers: { request: true, listCandidates: true },
edit: { changeRequest: true, comment: true },
stacks: true,
labels: true,
};
@@ -292,7 +293,20 @@ export const make = Effect.gen(function* () {
.pipe(Effect.mapError(fail("listChangeRequestStats"))),
getChangeRequestSummary: (input) =>
cli.getPullRequestSummary(input).pipe(Effect.mapError(fail("getChangeRequestSummary"))),
cli.getPullRequestSummary(input).pipe(
// `gh pr view` names the author without an avatar; the login-shaped URL every user
// has stands in, without the second request the listing spends on it.
Effect.map((summary) => ({
...summary,
...(summary.author === undefined
? {}
: { author: withAvatar(summary.author, new Map(), input.host) }),
})),
Effect.mapError(fail("getChangeRequestSummary")),
),
getChangeRequestStack: (input) =>
cli.getPullRequestStack(input).pipe(Effect.mapError(fail("getChangeRequestStack"))),
getChangeRequest: (input) =>
Effect.all(
@@ -103,6 +103,34 @@ export interface ProviderChangeRequestSummary {
readonly closedAt?: string | null;
readonly mergedAt?: string | null;
readonly updatedAt: string;
/** Overview fields, present where the host's single read returns them at no extra cost. */
readonly author?: PullRequestActor | null | undefined;
readonly additions?: number | undefined;
readonly deletions?: number | undefined;
readonly changedFiles?: number | undefined;
readonly reviewDecision?: PullRequestReviewDecision | null | undefined;
readonly checksState?: PullRequestChecksState | null | undefined;
readonly mergeability?: PullRequestMergeability | undefined;
}
/** One layer of a host-native stack, bottom to top order is the array's. */
export interface ProviderChangeRequestStackLayer {
readonly number: number;
readonly headBranch: string;
readonly state: PullRequestState;
}
/**
* A host-native stack: an ordered set of change requests the host itself merges and retargets as
* a unit. Only GitHub offers one today; the neutral shape lets the sync reactor and the UI stay
* ignorant of which host said so.
*/
export interface ProviderChangeRequestStack {
readonly id: string;
readonly number: number;
readonly url: string;
readonly base: string;
readonly layers: ReadonlyArray<ProviderChangeRequestStackLayer>;
}
export interface ProviderChangeRequestPage {
@@ -331,6 +359,14 @@ export interface PullRequestProviderApi {
input: ProviderRepositoryRef & { readonly number: number },
) => Effect.Effect<ProviderChangeRequestSummary, PullRequestProviderError>;
/**
* The host-native stack a change request belongs to, or null when it is not stacked. Optional
* because most hosts have no such object; the service derives chains from base branches there.
*/
readonly getChangeRequestStack?: (
input: ProviderRepositoryRef & { readonly number: number },
) => Effect.Effect<ProviderChangeRequestStack | null, PullRequestProviderError>;
/** Comments, line threads, and commits, kept off the critical path for the core detail. */
readonly getChangeRequestActivity: (
input: ProviderRepositoryRef & { readonly number: number },
@@ -32,6 +32,7 @@ function project(input: {
readonly repository?: string;
readonly provider?: string;
readonly host?: string;
readonly remoteUrl?: string;
}): OrchestrationProjectShell {
// The host defaults from the provider, so a fixture only names one when the point of the
// test is two hosts of the same kind.
@@ -47,7 +48,7 @@ function project(input: {
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: `https://${host}/${input.repository}.git`,
remoteUrl: input.remoteUrl ?? `https://${host}/${input.repository}.git`,
},
provider: input.provider ?? "github",
displayName: input.repository,
@@ -470,7 +471,7 @@ it.effect("uses a provider's raw cursor advance when it consumed malformed rows"
// Keyed by the selector Azure is actually asked with, which is the repository's own name.
assert.deepStrictEqual(result.nextCursors, {
"dev.azure.com web": "2026-07-02T00:00:00Z|4|7",
"dev.azure.com dev.azure.com/acme/web": "2026-07-02T00:00:00Z|4|7",
});
}),
);
@@ -1563,6 +1564,247 @@ it.effect("refuses a repository that does not belong to the requested project",
}),
);
it.effect("reads a host-native stack through the provider and null where it has none", () =>
Effect.gen(function* () {
const service = yield* makeService({
projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
providers: [
fakeProvider("github", {
getChangeRequestStack: () =>
Effect.succeed({
id: "9",
number: 3,
url: "https://github.com/acme/web/stacks/3",
base: "main",
layers: [
{ number: 7, headBranch: "a", state: "open" as const },
{ number: 8, headBranch: "b", state: "open" as const },
],
}),
}),
],
});
const stack = yield* service.stack({
projectId: "p1" as ProjectId,
repository: "acme/web",
number: 7,
});
assert.deepStrictEqual(
stack?.layers.map((layer) => layer.number),
[7, 8],
);
const withoutStacks = yield* makeService({
projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
providers: [fakeProvider("github")],
});
assert.isNull(
yield* withoutStacks.stack({
projectId: "p1" as ProjectId,
repository: "acme/web",
number: 7,
}),
);
}),
);
it.effect("routes a hosted reference to another repository through a project on that host", () =>
Effect.gen(function* () {
const seen: Array<{ cwd: string; repository: string; host: string }> = [];
const service = yield* makeService({
projects: [
project({ id: "frontend", title: "web", workspaceRoot: "/web", repository: "acme/web" }),
],
providers: [
fakeProvider("github", {
getChangeRequestSummary: (input) =>
Effect.sync(() => {
seen.push({ cwd: input.cwd, repository: input.repository, host: input.host });
return changeRequest(7, "2026-07-02T00:00:00Z");
}),
}),
],
});
const summary = yield* service.summary(
{ projectId: "frontend" as ProjectId, host: "github.com", repository: "acme/api", number: 7 },
{ recoverTransientFailure: false },
);
assert.strictEqual(summary.number, 7);
assert.deepStrictEqual(seen, [{ cwd: "/web", repository: "acme/api", host: "github.com" }]);
}),
);
it.effect("routes Azure reads and writes through the requested organization's checkout", () =>
Effect.gen(function* () {
const seen: string[] = [];
const service = yield* makeService({
projects: ["org-a", "org-b"].map((organization) =>
project({
id: organization,
title: organization,
workspaceRoot: `/${organization}`,
repository: `${organization}/project/_git/web`,
provider: "azure-devops",
host: "dev.azure.com",
}),
),
providers: [
fakeProvider("azure-devops", {
getChangeRequestSummary: (input) =>
Effect.sync(() => {
seen.push(`read ${input.cwd} ${input.repository}`);
return changeRequest(7, "2026-07-02T00:00:00Z");
}),
runAction: (input) =>
Effect.sync(() => {
seen.push(`write ${input.cwd} ${input.repository}`);
}),
}),
],
});
const reference = {
projectId: "org-a" as ProjectId,
host: "dev.azure.com",
repository: "org-b/project/_git/web",
number: 7,
};
yield* service.summary(reference, { recoverTransientFailure: false });
yield* service.runAction({ ...reference, action: "merge" });
assert.deepStrictEqual(seen, ["read /org-b web", "write /org-b web", "read /org-b web"]);
}),
);
for (const checkout of [
{
host: "ssh.dev.azure.com",
repository: "v3/org-b/project/web",
remoteUrl: "[email protected]:v3/org-b/project/web",
},
{
host: "vs-ssh.visualstudio.com",
repository: "v3/org-b/project/web",
remoteUrl: "[email protected]:v3/org-b/project/web",
},
{
host: "org-b.visualstudio.com",
repository: "DefaultCollection/project/_git/web",
remoteUrl: "https://org-b.visualstudio.com/DefaultCollection/project/_git/web",
},
]) {
it.effect(`routes Azure URL reads and writes through a ${checkout.host} checkout`, () =>
Effect.gen(function* () {
const seen: string[] = [];
const target = project({
id: "target",
title: "target",
workspaceRoot: "/target",
provider: "azure-devops",
...checkout,
});
const service = yield* makeService({
projects: [
...["org-a/project/_git/web", "org-b/other-project/_git/web"].map((repository) =>
project({
id: repository,
title: repository,
workspaceRoot: `/${repository}`,
provider: "azure-devops",
host: "dev.azure.com",
repository,
}),
),
target,
],
providers: [
fakeProvider("azure-devops", {
getChangeRequestSummary: (input) =>
Effect.sync(() => {
seen.push(`read ${input.cwd} ${input.repository}`);
return changeRequest(7, "2026-07-02T00:00:00Z");
}),
runAction: (input) =>
Effect.sync(() => {
seen.push(`write ${input.cwd} ${input.repository}`);
}),
}),
],
});
const reference = {
projectId: "org-a/project/_git/web" as ProjectId,
host: "dev.azure.com",
repository: "org-b/project/_git/web",
number: 7,
};
yield* service.summary(reference, { recoverTransientFailure: false });
yield* service.runAction({ ...reference, action: "merge" });
assert.deepStrictEqual(seen, ["read /target web", "write /target web", "read /target web"]);
}),
);
}
it.effect("refuses Azure cross-organization reads and writes without its checkout", () =>
Effect.gen(function* () {
const service = yield* makeService({
projects: [
project({
id: "org-a",
title: "org-a",
workspaceRoot: "/org-a",
repository: "org-a/project/_git/web",
provider: "azure-devops",
host: "dev.azure.com",
}),
],
providers: [
fakeProvider("azure-devops", {
getChangeRequestSummary: () => Effect.die("must not read the wrong organization"),
runAction: () => Effect.die("must not modify the wrong organization"),
}),
],
});
const reference = {
projectId: "org-a" as ProjectId,
host: "dev.azure.com",
repository: "org-b/project/_git/web",
number: 7,
};
const readError = yield* Effect.flip(
service.summary(reference, { recoverTransientFailure: false }),
);
const writeError = yield* Effect.flip(service.runAction({ ...reference, action: "close" }));
assert.strictEqual(readError._tag, "PullRequestUnavailableError");
assert.strictEqual(writeError._tag, "PullRequestUnavailableError");
}),
);
it.effect("refuses a hosted reference when nothing is checked out from that host", () =>
Effect.gen(function* () {
const service = yield* makeService({
projects: [
project({ id: "frontend", title: "web", workspaceRoot: "/web", repository: "acme/web" }),
],
providers: [fakeProvider("github")],
});
const error = yield* service
.summary(
{
projectId: "frontend" as ProjectId,
host: "gitlab.com",
repository: "acme/api",
number: 7,
},
{ recoverTransientFailure: false },
)
.pipe(Effect.flip);
assert.strictEqual(error._tag, "PullRequestUnavailableError");
}),
);
it.effect("refuses a diff on a host that cannot produce one", () =>
Effect.gen(function* () {
const service = yield* makeService({
@@ -3377,6 +3619,48 @@ it.effect("does not ask the host again for a linked summary it already holds", (
}),
);
it.effect(
"opening detail preserves enriched linked summaries and updates draft and diff fields",
() =>
Effect.gen(function* () {
const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
const service = yield* makeService({
projects: [
project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
],
providers: [
fakeProvider("github", {
getChangeRequestSummary: () =>
Effect.succeed({
...changeRequest(1, "2026-07-02T00:00:00Z"),
isDraft: true,
reviewDecision: "approved",
checksState: "passing",
}),
getChangeRequest: () =>
Effect.succeed({
...hostedChangeRequest("body", 14),
deletions: 3,
changedFiles: 5,
mergeability: "conflicting",
}),
}),
],
});
yield* service.summary(reference);
const detail = yield* service.detail(reference);
const summary = yield* service.summary(reference);
assert.strictEqual(summary.isDraft, false);
assert.deepStrictEqual(summary.author, detail.author);
assert.strictEqual(summary.additions, 14);
assert.strictEqual(summary.deletions, 3);
assert.strictEqual(summary.changedFiles, 5);
assert.strictEqual(summary.mergeability, "conflicting");
assert.strictEqual(summary.reviewDecision, "approved");
assert.strictEqual(summary.checksState, "passing");
}),
);
it.effect("reuses an observed merged state for strict settlement reads", () =>
Effect.gen(function* () {
const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
@@ -3587,43 +3871,6 @@ it.effect("carries an armed auto-merge through to the detail, and silence as sil
}),
);
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 = PullRequestService.repositoryIdentityOf({
repositoryIdentity: {
provider: "azure-devops",
displayName: "contoso/payments/_git/checkout",
owner: "contoso",
name: "checkout",
},
} as never);
assert.strictEqual(selector, "checkout");
});
it("falls back to the path's last segment where an Azure identity has no name", () => {
const selector = PullRequestService.repositoryIdentityOf({
repositoryIdentity: {
provider: "azure-devops",
displayName: "contoso/payments/_git/checkout",
},
} as never);
assert.strictEqual(selector, "checkout");
});
it("keeps a GitLab identity's whole path, because a nested group is part of the name", () => {
const selector = PullRequestService.repositoryIdentityOf({
repositoryIdentity: {
provider: "gitlab",
displayName: "group/subgroup/service",
owner: "group",
name: "service",
},
} as never);
assert.strictEqual(selector, "group/subgroup/service");
});
it.effect("narrows the rows of a host that ignored the filters it was handed", () =>
Effect.gen(function* () {
const service = yield* makeService({
@@ -4137,3 +4384,40 @@ it.effect("names the signed-in account in the detail, and says nothing where the
assert.strictEqual(unnamed.viewer, undefined);
}),
);
it.effect("keeps Azure continuation cursors separate for repositories with the same name", () =>
Effect.gen(function* () {
const seen: string[] = [];
const service = yield* makeService({
projects: ["org-a", "org-b"].map((organization) =>
project({
id: organization,
title: organization,
workspaceRoot: `/${organization}`,
repository: `${organization}/project/_git/web`,
provider: "azure-devops",
host: "dev.azure.com",
}),
),
providers: [
fakeProvider("azure-devops", {
listChangeRequests: (input) =>
Effect.sync(() => {
seen.push(input.cwd);
return {
items: [changeRequest(7, "2026-07-02T00:00:00Z")],
truncated: true,
continues: true,
};
}),
}),
],
});
const first = yield* service.list({ state: "open" });
assert.lengthOf(Object.keys(first.nextCursors), 2);
const key = Object.keys(first.nextCursors).find((key) => key.includes("org-b"))!;
seen.length = 0;
yield* service.list({ state: "open", cursors: { [key]: first.nextCursors[key]! } });
assert.deepStrictEqual(seen, ["/org-b"]);
}),
);
+202 -59
View File
@@ -1,3 +1,7 @@
import {
canonicalRepositoryKey,
sourceControlRepositorySelector,
} from "@t3tools/shared/sourceControl";
import * as Cache from "effect/Cache";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
@@ -46,6 +50,7 @@ import {
type PullRequestLabelCandidateList,
type PullRequestLabelChangeInput,
type PullRequestSubmitReviewInput,
type PullRequestStack,
type PullRequestSummary,
type PullRequestThreadReplyInput,
type PullRequestThreadResolutionInput,
@@ -144,6 +149,13 @@ export class PullRequestService extends Context.Service<
input: PullRequestRef,
options?: { readonly recoverTransientFailure?: boolean },
) => Effect.Effect<PullRequestSummary, PullRequestError>;
/**
* The host-native stack the pull request belongs to, or null when it is not in one or the
* host keeps no such object. Cached like a summary; a stack changes about as often.
*/
readonly stack: (
input: PullRequestRef,
) => Effect.Effect<PullRequestStack | null, PullRequestError>;
readonly subscribeMerges: Effect.Effect<
Stream.Stream<PullRequestMergeEvent>,
never,
@@ -241,6 +253,7 @@ const LABEL_CHANGE_REFUSAL = "You need triage access on this repository to chang
/** A project this page can read: its remote is on a host with an implementation. */
interface SupportedProject {
readonly cursorKey: string;
readonly project: OrchestrationProjectShell;
readonly api: PullRequestProviderApi;
readonly repository: string;
@@ -453,7 +466,7 @@ function withRateLimitBackoff(
call: (...args: Args) => Effect.Effect<A, PullRequestProviderError>,
) => wrap(operation, call, true);
return {
const wrapped = {
kind: api.kind,
capabilities: api.capabilities,
getViewer: wrap("getViewer", api.getViewer),
@@ -474,6 +487,9 @@ function withRateLimitBackoff(
: {
getChangeRequestSummary: wrap("getChangeRequestSummary", api.getChangeRequestSummary),
}),
...(api.getChangeRequestStack === undefined
? {}
: { getChangeRequestStack: wrap("getChangeRequestStack", api.getChangeRequestStack) }),
getChangeRequestActivity: wrap("getChangeRequestActivity", api.getChangeRequestActivity),
...(api.getReviewThreadComments === undefined
? {}
@@ -506,30 +522,9 @@ function withRateLimitBackoff(
setReaction: interactive("setReaction", api.setReaction),
setThreadResolution: interactive("setThreadResolution", api.setThreadResolution),
};
}
/**
* 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 repositoryIdentityOf(project: OrchestrationProjectShell): string | null {
const identity = project.repositoryIdentity;
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;
// Optional provider methods must be forwarded too; returning the interface alone permits omissions.
return wrapped satisfies PullRequestProviderApi &
Record<Exclude<keyof PullRequestProviderApi, keyof typeof wrapped>, never>;
}
export const make = Effect.gen(function* () {
@@ -554,7 +549,11 @@ export const make = Effect.gen(function* () {
for (const project of projects) {
if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
const identity = project.repositoryIdentity;
if (identity?.provider !== "unknown" || repositoryIdentityOf(project) === null) continue;
if (
identity?.provider !== "unknown" ||
sourceControlRepositorySelector(project.repositoryIdentity) === null
)
continue;
const host = pullRequestHostOf(identity, "unknown");
// A legacy identity has no canonical host until its provider is refined, so it must reach
// the refinement before a host filter can decide whether it belongs in the result.
@@ -628,7 +627,7 @@ export const make = Effect.gen(function* () {
if (filter.projectIds !== undefined && !filter.projectIds.includes(project.id)) continue;
const identity = project.repositoryIdentity;
let kind = identity?.provider as SourceControlProviderKind | undefined;
const repository = repositoryIdentityOf(project);
const repository = sourceControlRepositorySelector(project.repositoryIdentity);
if (!identity || kind === undefined || repository === null) continue;
// Worktrees of one repository are separate projects; reading the remote once keeps
// the page from repeating every change request per local checkout. The host is part
@@ -647,7 +646,10 @@ export const make = Effect.gen(function* () {
if (roots === undefined) viewerRoots.set(host, [project.workspaceRoot]);
else if (!roots.includes(project.workspaceRoot)) roots.push(project.workspaceRoot);
}
const key = listCursorKey(host, repository);
const key = listCursorKey(
host,
kind === "azure-devops" ? identity.canonicalKey : repository,
);
if (seen.has(key)) continue;
seen.add(key);
if (api === null) {
@@ -657,6 +659,7 @@ export const make = Effect.gen(function* () {
continue;
}
supported.push({
cursorKey: key,
project,
api: withRateLimitBackoff(api, host, rateLimits),
repository,
@@ -667,16 +670,30 @@ export const make = Effect.gen(function* () {
}),
);
/**
* The project whose checkout and credentials serve a reference. The project's own
* repository is the default; a reference that names a `host` may instead point at any
* repository on that host. Prefer its own checkout; providers with explicit repository
* targeting can fall back to another checkout on the host. Azure derives its organization
* from the checkout, so it requires a matching repository.
*/
const requireProject = (ref: PullRequestRef): Effect.Effect<SupportedProject, PullRequestError> =>
listWorkspaceProjects({ projectId: ref.projectId }).pipe(
Effect.flatMap(({ supported }): Effect.Effect<SupportedProject, PullRequestError> => {
const match = supported[0];
if (!match) {
return Effect.fail(new PullRequestUnavailableError({ reason: "provider-unsupported" }));
const own = supported[0];
const repository = ref.repository.trim();
const host = ref.host?.trim().toLowerCase();
if (own !== undefined && own.repository.toLowerCase() === repository.toLowerCase()) {
// Hostless references only ever meant the project's own repository, and a hosted one
// naming it still is; either way the project serves itself.
if (host === undefined || host === own.host) return Effect.succeed(own);
}
// The repository travels through the client, so it is checked against the project's
// own remote rather than being handed to a provider verbatim.
if (match.repository.toLowerCase() !== ref.repository.trim().toLowerCase()) {
if (host === undefined) {
if (own === undefined) {
return Effect.fail(new PullRequestUnavailableError({ reason: "provider-unsupported" }));
}
// The repository travels through the client, so it is checked against the project's
// own remote rather than being handed to a provider verbatim.
return Effect.fail(
new PullRequestOperationError({
operation: "resolveRepository",
@@ -684,7 +701,39 @@ export const make = Effect.gen(function* () {
}),
);
}
return Effect.succeed(match);
const repositoryKey = canonicalRepositoryKey(`${host}/${repository}`.toLowerCase());
// Azure SSH and legacy clone hosts differ from the browser URL's host. Compare
// the complete repository identity before narrowing those checkouts by host.
return listWorkspaceProjects(
repositoryKey.startsWith("dev.azure.com/") ? {} : { host },
).pipe(
Effect.flatMap(({ supported }) => {
const onHost = supported.filter((candidate) => candidate.host === host);
const route =
supported.find(
(candidate) =>
candidate.api.kind === "azure-devops" &&
candidate.project.repositoryIdentity != null &&
canonicalRepositoryKey(
candidate.project.repositoryIdentity.canonicalKey.toLowerCase(),
) === repositoryKey,
) ??
onHost.find(
(candidate) =>
candidate.api.kind !== "azure-devops" &&
candidate.repository.toLowerCase() === repository.toLowerCase(),
) ??
onHost.find((candidate) => candidate.api.kind !== "azure-devops");
if (route === undefined) {
return Effect.fail(
new PullRequestUnavailableError({ reason: "provider-unsupported" }),
);
}
return Effect.succeed(
route.api.kind === "azure-devops" ? route : { ...route, repository },
);
}),
);
}),
);
@@ -829,8 +878,8 @@ export const make = Effect.gen(function* () {
viewer: string,
): boolean => {
if (filters === undefined) return true;
const labels = item.labels.map((label) => label.name.trim().toLowerCase());
const holds = (label: string) => labels.includes(label.trim().toLowerCase());
const labels = new Set(item.labels.map((label) => label.name.trim().toLowerCase()));
const holds = (label: string) => labels.has(label.trim().toLowerCase());
return (
(filters.draft === undefined || item.isDraft === (filters.draft === "only")) &&
// Judged on the provider row rather than the entry, because the two absences mean
@@ -949,9 +998,7 @@ export const make = Effect.gen(function* () {
const selected =
continuation === null
? projects
: projects.filter(({ host, repository }) =>
continuation.has(listCursorKey(host, repository)),
);
: projects.filter(({ cursorKey }) => continuation.has(cursorKey));
const readable = selected.filter(({ host }) => viewers[host] !== undefined);
// A host that could not be read still has projects, and they are absent from the list.
// Reporting them keeps "N repositories were unavailable" honest instead of dropping them.
@@ -993,7 +1040,7 @@ export const make = Effect.gen(function* () {
const limit = input.limit ?? DEFAULT_REPOSITORY_LIST_LIMIT;
const cursorOf = (project: SupportedProject): ListCursor | undefined =>
continuation?.get(listCursorKey(project.host, project.repository));
continuation?.get(project.cursorKey);
/**
* One repository asked on its own. What every host without a search across repositories
@@ -1002,7 +1049,7 @@ export const make = Effect.gen(function* () {
const readRepository = (project: SupportedProject): Effect.Effect<RepositoryBatch> => {
{
const viewer = viewers[project.host]!;
const key = listCursorKey(project.host, project.repository);
const key = project.cursorKey;
const cursor = cursorOf(project);
return project.api
.listChangeRequests({
@@ -1161,7 +1208,7 @@ export const make = Effect.gen(function* () {
!cursorHere.seenAt.includes(item.number),
);
return Effect.succeed({
key: listCursorKey(project.host, project.repository),
key: project.cursorKey,
entries: items
.filter((item) => matchesRowFilters(item, input.filters, viewer))
.map((item) => toEntry({ project, item, viewer })),
@@ -1254,17 +1301,67 @@ export const make = Effect.gen(function* () {
title: changeRequest.title,
url: changeRequest.url,
state: changeRequest.state,
...(changeRequest.isDraft === true ? { isDraft: true } : {}),
headBranch: changeRequest.headBranch,
baseBranch: changeRequest.baseBranch,
closedAt: changeRequest.closedAt ?? null,
mergedAt: changeRequest.mergedAt ?? null,
updatedAt: changeRequest.updatedAt,
...(changeRequest.isDraft === undefined ? {} : { isDraft: changeRequest.isDraft }),
...(changeRequest.author === undefined ? {} : { author: changeRequest.author }),
...(changeRequest.additions === undefined
? {}
: { additions: changeRequest.additions }),
...(changeRequest.deletions === undefined
? {}
: { deletions: changeRequest.deletions }),
...(changeRequest.changedFiles === undefined
? {}
: { changedFiles: changeRequest.changedFiles }),
...(changeRequest.reviewDecision === undefined
? {}
: { reviewDecision: changeRequest.reviewDecision }),
...(changeRequest.checksState === undefined
? {}
: { checksState: changeRequest.checksState }),
...(changeRequest.mergeability === undefined
? {}
: { mergeability: changeRequest.mergeability }),
})),
);
}),
);
const stackUncached: PullRequestService["Service"]["stack"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project) => {
const read = project.api.getChangeRequestStack;
if (read === undefined) return Effect.succeed(null);
return read({
cwd: project.project.workspaceRoot,
repository: project.repository,
host: project.host,
number: input.number,
}).pipe(
Effect.mapError(toPullRequestError("stack")),
Effect.map((stack): PullRequestStack | null =>
stack === null
? null
: {
id: stack.id,
number: stack.number,
url: stack.url,
base: stack.base,
layers: stack.layers.map((layer) => ({
number: layer.number,
headBranch: layer.headBranch,
state: layer.state,
})),
},
),
);
}),
);
const detailUncached: PullRequestService["Service"]["detail"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project) =>
@@ -1507,7 +1604,11 @@ export const make = Effect.gen(function* () {
})
.pipe(
Effect.mapError(toPullRequestError("runAction")),
Effect.as(project.repository),
Effect.as(
project.api.kind === "azure-devops"
? input.repository.trim()
: project.repository,
),
);
}),
);
@@ -2133,11 +2234,35 @@ export const make = Effect.gen(function* () {
let turnRefreshEpoch = 0;
const refEpochs = new Map<string, number>();
const REF_EPOCH_CAPACITY = 2_048;
const refScope = (ref: PullRequestRef) => `${ref.projectId} ${ref.repository} ${ref.number}`;
const refScope = (ref: PullRequestRef) =>
`${ref.projectId} ${ref.host?.toLowerCase() ?? ""} ${ref.repository.toLowerCase()} ${ref.number}`;
const refEpoch = (ref: PullRequestRef) =>
Math.max(turnRefreshEpoch, refEpochs.get(refScope(ref)) ?? 0);
// Keys carry the reference back out of the cache loader, so the slot layout is shared with
// `refOfCacheKey` rather than read positionally at every loader.
const refCacheKey = (ref: PullRequestRef) =>
JSON.stringify([refEpoch(ref), ref.projectId, ref.repository, ref.number]);
JSON.stringify([
refEpoch(ref),
ref.projectId,
ref.host?.toLowerCase() ?? null,
ref.repository.toLowerCase(),
ref.number,
]);
const refOfCacheKey = (key: string): PullRequestRef => {
const [, projectId, host, repository, number] = JSON.parse(key) as [
number,
string,
string | null,
string,
number,
];
return {
projectId,
...(host === null ? {} : { host }),
repository,
number,
} as PullRequestRef;
};
// Counts belong to a PR, not a filtered page. Background reads and filter changes reuse
// them; explicit refreshes, mutations, and turns strand old and in-flight results.
const statsCacheKey = (key: string) => JSON.stringify([listingsEpoch, key]);
@@ -2181,8 +2306,7 @@ export const make = Effect.gen(function* () {
const summaryCache = yield* Cache.makeWith(
(key: string) => {
const [, projectId, repository, number] = JSON.parse(key) as [number, string, string, number];
return summaryUncached({ projectId, repository, number } as PullRequestRef);
return summaryUncached(refOfCacheKey(key));
},
{
capacity: DETAIL_CACHE_CAPACITY,
@@ -2203,6 +2327,13 @@ export const make = Effect.gen(function* () {
);
};
const stackCache = yield* Cache.makeWith((key: string) => stackUncached(refOfCacheKey(key)), {
capacity: DETAIL_CACHE_CAPACITY,
timeToLive: (exit) => (Exit.isSuccess(exit) ? SUMMARY_CACHE_TTL : Duration.zero),
});
const stack: PullRequestService["Service"]["stack"] = (input) =>
Cache.get(stackCache, refCacheKey(input));
// Keys serialize positionally and parse back in the lookup, so the cache is the only holder
// of in-flight state: concurrent identical reads coalesce on the key into one host request.
// The continuation cursors are part of the key, entries sorted so one continuation is one
@@ -2283,8 +2414,7 @@ export const make = Effect.gen(function* () {
const detailCache = yield* Cache.makeWith(
(key: string) => {
const statsKey = statsCacheKey(key);
const [, projectId, repository, number] = JSON.parse(key) as [number, string, string, number];
return detailUncached({ projectId, repository, number } as PullRequestRef).pipe(
return detailUncached(refOfCacheKey(key)).pipe(
Effect.tap(
Effect.fn("PullRequestService.recordDetailStats")(function* (value: PullRequestDetail) {
recordStats(
@@ -2307,7 +2437,12 @@ export const make = Effect.gen(function* () {
timeToLive: (exit) => (Exit.isSuccess(exit) ? DETAIL_CACHE_TTL : Duration.zero),
},
);
const summaryFromDetail = (detail: PullRequestDetail): PullRequestSummary => ({
const summaryFromDetail = (
detail: PullRequestDetail,
previous: PullRequestSummary | undefined,
): PullRequestSummary => ({
// Detail does not carry review/check summaries. Keep the last summary observation.
...previous,
provider: detail.provider,
projectId: detail.projectId,
repository: detail.repository,
@@ -2315,7 +2450,12 @@ export const make = Effect.gen(function* () {
title: detail.title,
url: detail.url,
state: detail.state,
...(detail.isDraft === true ? { isDraft: true } : {}),
isDraft: detail.isDraft,
author: detail.author,
additions: detail.additions,
deletions: detail.deletions,
changedFiles: detail.changedFiles,
mergeability: detail.mergeability,
headBranch: detail.headBranch,
baseBranch: detail.baseBranch,
closedAt: detail.closedAt,
@@ -2338,7 +2478,7 @@ export const make = Effect.gen(function* () {
key,
Cache.get(detailCache, key).pipe(
Effect.tap((value) => {
const summary = summaryFromDetail(value);
const summary = summaryFromDetail(value, lastGoodSummary.peek(key));
return shouldReplaceHeldSummary(key, summary)
? lastGoodSummary.record(key, summary)
: Effect.void;
@@ -2350,8 +2490,7 @@ export const make = Effect.gen(function* () {
const activityCache = yield* Cache.makeWith(
(key: string) => {
const [, projectId, repository, number] = JSON.parse(key) as [number, string, string, number];
return activityUncached({ projectId, repository, number } as PullRequestRef);
return activityUncached(refOfCacheKey(key));
},
{
capacity: DETAIL_CACHE_CAPACITY,
@@ -2365,9 +2504,10 @@ export const make = Effect.gen(function* () {
const diffCache = yield* Cache.makeWith(
(key: string) => {
const [, projectId, repository, number, cursor, commit] = JSON.parse(key) as [
const [, projectId, host, repository, number, cursor, commit] = JSON.parse(key) as [
number,
string,
string | null,
string,
number,
string | null,
@@ -2375,6 +2515,7 @@ export const make = Effect.gen(function* () {
];
return diffUncached({
projectId,
...(host === null ? {} : { host }),
repository,
number,
...(cursor === null ? {} : { cursor }),
@@ -2385,7 +2526,7 @@ export const make = Effect.gen(function* () {
capacity: DIFF_CACHE_CAPACITY,
timeToLive: (exit, key) => {
if (!Exit.isSuccess(exit)) return Duration.zero;
const commit = (JSON.parse(key) as ReadonlyArray<unknown>)[5];
const commit = (JSON.parse(key) as ReadonlyArray<unknown>)[6];
return commit === null ? DIFF_CACHE_TTL : COMMIT_DIFF_CACHE_TTL;
},
},
@@ -2394,7 +2535,8 @@ export const make = Effect.gen(function* () {
const key = JSON.stringify([
refEpoch(input),
input.projectId,
input.repository,
input.host?.toLowerCase() ?? null,
input.repository.toLowerCase(),
input.number,
input.cursor ?? null,
input.commit ?? null,
@@ -2523,6 +2665,7 @@ export const make = Effect.gen(function* () {
list,
listStats,
summary,
stack,
subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
Effect.map((subscription) => Stream.fromSubscription(subscription)),
),
@@ -11,6 +11,7 @@ import {
decodePullRequestListJson,
decodePullRequestNodeIdJson,
decodePullRequestSearchJson,
decodePullRequestStacksJson,
decodeLabelCandidatesJson,
decodeRepositoryAccessJson,
decodeReviewerCandidatesJson,
@@ -1500,3 +1501,81 @@ describe("how far a branch trails its base", () => {
expect(Result.isSuccess(decodeBaseComparisonJson("{"))).toBe(false);
});
});
describe("host-native stack decoding", () => {
/** A stack as the preview lists it, bottom to top, with the fields it answers today. */
function stack(overrides: Record<string, unknown> = {}) {
return {
id: 42,
number: 3,
node_id: "STK_kwDO",
url: "https://api.github.com/repos/acme/web/stacks/3",
base: { ref: "main", sha: "abc" },
open: true,
created_at: "2026-09-01T00:00:00Z",
pull_requests: [
{
number: 10,
head: { ref: "feat/one" },
state: "closed",
merged_at: "2026-09-02T00:00:00Z",
},
{ number: 11, head: { ref: "feat/two" }, state: "open", merged_at: null },
{ number: 12, head: { ref: "feat/three" }, state: "closed", merged_at: null },
],
...overrides,
};
}
/** The one stack a listing answered with, which these reads all expect to find. */
function expectStack(overrides: Record<string, unknown> = {}) {
const decoded = expectSuccess(decodePullRequestStacksJson(JSON.stringify([stack(overrides)])));
if (decoded === null) throw new Error("expected a stack");
return decoded;
}
it("reads the first stack, bottom to top, with merged_at outranking state", () => {
expect(expectStack()).toEqual({
id: "42",
number: 3,
url: "https://api.github.com/repos/acme/web/stacks/3",
base: "main",
layers: [
{ number: 10, headBranch: "feat/one", state: "merged" },
{ number: 11, headBranch: "feat/two", state: "open" },
{ number: 12, headBranch: "feat/three", state: "closed" },
],
});
});
it("accepts a base named as a bare branch, which is what the preview started out sending", () => {
expect(expectStack({ base: "develop" }).base).toBe("develop");
});
it("prefers the page a person opens over the API URL, where the host reports one", () => {
expect(expectStack({ html_url: "https://github.com/acme/web/stacks/3" }).url).toBe(
"https://github.com/acme/web/stacks/3",
);
});
it("falls back to the node id, then the number, for a stack without an id", () => {
expect(expectStack({ id: undefined }).id).toBe("STK_kwDO");
expect(expectStack({ id: null, node_id: null }).id).toBe("3");
});
it("reads an empty listing as not stacked", () => {
expect(expectSuccess(decodePullRequestStacksJson("[]"))).toBeNull();
});
it("refuses a stack without a number or without its pull requests", () => {
expect(
Result.isSuccess(decodePullRequestStacksJson(JSON.stringify([stack({ number: undefined })]))),
).toBe(false);
expect(
Result.isSuccess(
decodePullRequestStacksJson(JSON.stringify([stack({ pull_requests: undefined })])),
),
).toBe(false);
expect(Result.isSuccess(decodePullRequestStacksJson("{"))).toBe(false);
});
});
@@ -2445,3 +2445,69 @@ export function decodePullRequestFilesJson(
omittedFileStats,
});
}
/** One pull request as the stacks API lists it: a number, a head, and whether it is done. */
const RawStackPullRequestSchema = Schema.Struct({
number: Schema.Int,
head: Schema.Struct({ ref: Schema.String }),
state: Schema.optional(Schema.NullOr(Schema.String)),
merged_at: Schema.optional(Schema.NullOr(Schema.String)),
});
/**
* A stack as `GET /repos/{owner}/{repo}/stacks` answers it, in a public preview whose shape may
* still move. Only what a stack is made of is required — where it lives, what it stands on, and
* its pull requests — and `base` is accepted both as the ref object the preview sends today and
* as the bare branch name it started out as.
*/
const RawStackSchema = Schema.Struct({
id: Schema.optional(Schema.NullOr(Schema.Union([Schema.Int, Schema.String]))),
number: Schema.Int,
node_id: Schema.optional(Schema.NullOr(Schema.String)),
url: Schema.String,
html_url: Schema.optional(Schema.NullOr(Schema.String)),
base: Schema.Union([Schema.String, Schema.Struct({ ref: Schema.String })]),
pull_requests: Schema.Array(RawStackPullRequestSchema),
});
const decodeStacks = decodeJsonResult(Schema.Array(RawStackSchema));
export interface GitHubPullRequestStackLayer {
readonly number: number;
readonly headBranch: string;
readonly state: PullRequestState;
}
export interface GitHubPullRequestStack {
readonly id: string;
readonly number: number;
readonly url: string;
readonly base: string;
/** Bottom to top, which is the order GitHub lists them in. */
readonly layers: ReadonlyArray<GitHubPullRequestStackLayer>;
}
/**
* The first stack of a `?pull_request=` listing, or null for an empty one: a pull request is in
* at most one stack, so the array is GitHub's way of saying "none" rather than a page.
*/
export function decodePullRequestStacksJson(
raw: string,
): Result.Result<GitHubPullRequestStack | null, DecodeFailure> {
const decoded = decodeStacks(raw);
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
const stack = decoded.success[0];
if (stack === undefined) return Result.succeed(null);
return Result.succeed({
id: stack.id == null ? (trimmed(stack.node_id) ?? String(stack.number)) : String(stack.id),
number: stack.number,
// The page a person opens where the preview reports one; the API URL is what it always has.
url: trimmed(stack.html_url) ?? stack.url,
base: typeof stack.base === "string" ? stack.base : stack.base.ref,
layers: stack.pull_requests.map((pullRequest) => ({
number: pullRequest.number,
headBranch: pullRequest.head.ref,
state: toState({ state: pullRequest.state, mergedAt: pullRequest.merged_at }),
})),
});
}
@@ -0,0 +1,117 @@
import { assert, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import { listLinkedPullRequestThreads } from "./linkedThreads.ts";
it.effect(
"finds active and archived threads for exactly one pull request, excluding deleted and dismissed links",
() =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const createdAt = "2026-09-01T00:00:00.000Z";
const archivedAt = "2026-09-03T00:00:00.000Z";
yield* sql`
INSERT INTO projection_projects (project_id, title, workspace_root, scripts_json, created_at, updated_at)
VALUES ('project-1', 'Project', '/tmp/project', '[]', ${createdAt}, ${createdAt})
`;
const fixtures = [
{
id: "azure",
host: "dev.azure.com",
repository: "org/project/_git/web",
number: 7,
source: "manual",
},
{
id: "other-org",
host: "dev.azure.com",
repository: "other/project/_git/web",
number: 7,
source: "manual",
},
{ id: "active", host: "github.com", repository: "acme/web", number: 7, source: "manual" },
{
id: "archived",
host: "github.com",
repository: "acme/web",
number: 7,
source: "created",
},
{ id: "deleted", host: "github.com", repository: "acme/web", number: 7, source: "manual" },
{
id: "dismissed",
host: "github.com",
repository: "acme/web",
number: 7,
source: "stack-dismissed",
},
{
id: "other-host",
host: "github.example.com",
repository: "acme/web",
number: 7,
source: "manual",
},
{
id: "other-repository",
host: "github.com",
repository: "acme/api",
number: 7,
source: "manual",
},
{
id: "other-number",
host: "github.com",
repository: "acme/web",
number: 8,
source: "manual",
},
];
for (const fixture of fixtures) {
yield* sql`
INSERT INTO projection_threads (
thread_id, project_id, title, model_selection_json, created_at, updated_at, archived_at, deleted_at
) VALUES (
${fixture.id}, 'project-1', ${fixture.id}, '{"instanceId":"codex","model":"gpt-5.4"}',
${createdAt}, ${fixture.id === "archived" ? archivedAt : createdAt},
${fixture.id === "archived" ? archivedAt : null},
${fixture.id === "deleted" ? archivedAt : null}
)
`;
yield* sql`
INSERT INTO projection_thread_pull_requests (thread_id, host, repository, number, url, source, linked_at)
VALUES (${fixture.id}, ${fixture.host}, ${fixture.repository}, ${fixture.number},
'https://github.com/acme/web/pull/7', ${fixture.source}, ${createdAt})
`;
}
expect(
(yield* listLinkedPullRequestThreads({
host: "org.visualstudio.com",
repository: "project/_git/web",
number: 7,
})).threads.map((thread) => thread.id),
).toEqual(["azure"]);
const result = yield* listLinkedPullRequestThreads({
host: "GitHub.Com",
repository: "ACME/WEB",
number: 7,
});
expect(result).toEqual({
threads: [
{ id: "archived", projectId: "project-1", title: "archived", archivedAt },
{ id: "active", projectId: "project-1", title: "active", archivedAt: null },
],
});
assert.deepStrictEqual(
yield* listLinkedPullRequestThreads({
host: "github.com",
repository: "acme/web",
number: 99,
}),
{ threads: [] },
);
}).pipe(Effect.provide(SqlitePersistenceMemory)),
);
@@ -0,0 +1,39 @@
import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
import {
PullRequestLinkedThreadsResult,
PullRequestOperationError,
type ThreadPullRequestKey,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
const decodeLinkedThreads = Schema.decodeUnknownEffect(PullRequestLinkedThreadsResult);
export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThreads")(
function* (input: ThreadPullRequestKey) {
const key = normalizeThreadPullRequestKey(input);
const sql = yield* SqlClient.SqlClient;
const threads = yield* sql`
SELECT t.thread_id AS id, t.project_id AS "projectId", t.title,
t.archived_at AS "archivedAt"
FROM projection_thread_pull_requests AS link
JOIN projection_threads AS t ON t.thread_id = link.thread_id
WHERE link.host = ${key.host.toLowerCase()}
AND link.repository = ${key.repository.toLowerCase()}
AND link.number = ${key.number}
AND link.source != 'stack-dismissed'
AND t.deleted_at IS NULL
ORDER BY t.updated_at DESC, t.thread_id ASC
`;
return yield* decodeLinkedThreads({ threads });
},
Effect.mapError(
(cause) =>
new PullRequestOperationError({
operation: "linkedThreads",
detail: "Could not load linked threads.",
cause,
}),
),
);
@@ -0,0 +1,46 @@
import { ProjectId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { pullRequestSyncKey } from "./pullRequestSyncKey.ts";
describe("pullRequestSyncKey", () => {
const reference = { projectId: ProjectId.make("project"), repository: "web", number: 7 };
it.each([
"dev.azure.com/org/project/_git/web",
"ssh.dev.azure.com/v3/org/project/web",
"vs-ssh.visualstudio.com/v3/org/project/web",
"org.visualstudio.com/defaultcollection/project/_git/web",
])("resolves hostless and checkout-host Azure references for %s", (canonicalKey) => {
const identity = {
canonicalKey,
provider: "azure-devops",
name: "web",
displayName: canonicalKey.split("/").slice(1).join("/"),
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: `https://${canonicalKey}`,
},
};
const expected = { host: "dev.azure.com", repository: "org/project/_git/web", number: 7 };
expect(pullRequestSyncKey(reference, identity)).toEqual(expected);
expect(
pullRequestSyncKey({ ...reference, host: canonicalKey.split("/")[0]! }, identity),
).toEqual(expected);
expect(pullRequestSyncKey({ ...reference, repository: "other" }, identity)).toBeNull();
expect(pullRequestSyncKey({ ...reference, host: "unrelated.test" }, identity)).toBeNull();
});
it("normalizes complete hosted aliases without requiring a checkout", () => {
expect(
pullRequestSyncKey({
...reference,
host: "org.visualstudio.com",
repository: "project/_git/web",
}),
).toEqual({ host: "dev.azure.com", repository: "org/project/_git/web", number: 7 });
expect(
pullRequestSyncKey({ ...reference, host: "github.com", repository: "acme/web" }),
).toEqual({ host: "github.com", repository: "acme/web", number: 7 });
expect(pullRequestSyncKey(reference)).toBeNull();
});
});
@@ -0,0 +1,44 @@
import {
pullRequestHostOf,
type PullRequestRef,
type RepositoryIdentity,
type SourceControlProviderKind,
type ThreadPullRequestKey,
} from "@t3tools/contracts";
import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
/** Convert checkout-scoped references to the host-level identity used by linked threads. */
export function pullRequestSyncKey(
reference: PullRequestRef,
identity?: RepositoryIdentity | null,
): ThreadPullRequestKey | null {
if (identity?.provider === "azure-devops" && !reference.repository.includes("/")) {
if (
reference.repository.toLowerCase() !==
sourceControlRepositorySelector(identity)?.toLowerCase() ||
(reference.host !== undefined &&
reference.host.toLowerCase() !== pullRequestHostOf(identity, "azure-devops"))
)
return null;
const [host, ...repository] = identity.canonicalKey.split("/");
if (!host || repository.length === 0) return null;
return normalizeThreadPullRequestKey({
host,
repository: repository.join("/"),
number: reference.number,
});
}
const host =
reference.host ??
(identity
? pullRequestHostOf(identity, identity.provider as SourceControlProviderKind)
: undefined);
return host === undefined
? null
: normalizeThreadPullRequestKey({
host,
repository: reference.repository,
number: reference.number,
});
}