Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(web): pull request surfaces — filters & qualifiers, all-server listing, update branch, reactions, in-place editing, smarter diffs (#6039)

Bilal Bakrb28f9bf0a1bd
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index 34853209d..36f348d63 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -58,10 +58,13 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.pullRequestsActivity]: AuthOrchestrationReadScope,
[WS_METHODS.pullRequestsDiffFileContents]: AuthOrchestrationReadScope,
[WS_METHODS.pullRequestsRunAction]: AuthOrchestrationOperateScope,
+ [WS_METHODS.pullRequestsUpdate]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsComment]: AuthOrchestrationOperateScope,
+ [WS_METHODS.pullRequestsUpdateComment]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsSubmitReview]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsReplyToThread]: AuthOrchestrationOperateScope,
[WS_METHODS.pullRequestsSetThreadResolution]: AuthOrchestrationOperateScope,
+ [WS_METHODS.pullRequestsSetReaction]: AuthOrchestrationOperateScope,
// Read scope like the reads it un-caches: refreshing is part of reading, and a read-only
// client pressing refresh must not be told it may not look again.
[WS_METHODS.pullRequestsInvalidate]: AuthOrchestrationReadScope,
diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts
index 7cc252d3b..a5f8fa659 100644
--- a/apps/server/src/git/GitManager.test.ts
+++ b/apps/server/src/git/GitManager.test.ts
@@ -9,8 +9,10 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
+import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
+import * as References from "effect/References";
import * as Scope from "effect/Scope";
import { ChildProcessSpawner } from "effect/unstable/process";
import { expect } from "vite-plus/test";
@@ -1386,6 +1388,58 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
+ it.effect("status logs actionable provider detail without exposing the upstream cause", () =>
+ Effect.gen(function* () {
+ const repoDir = yield* makeTempDir("t3code-git-manager-");
+ yield* initRepo(repoDir);
+ yield* runGit(repoDir, ["checkout", "-b", "feature/status-rate-limited"]);
+ const remoteDir = yield* createBareRemote();
+ yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
+ yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-rate-limited"]);
+
+ const upstreamCause = "GraphQL rate limit for user ID 51714798 and token secret-value";
+ const { manager } = yield* makeManager({
+ ghScenario: {
+ failWith: new GitHubCli.GitHubCliRateLimitError({
+ command: "gh",
+ cwd: repoDir,
+ cause: new Error(upstreamCause),
+ }),
+ },
+ });
+ const logs: Array<{ message: string; annotations: Record<string, unknown> }> = [];
+ const logger = Logger.make<unknown, void>(({ fiber, message }) => {
+ logs.push({
+ message: String(message),
+ annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
+ });
+ });
+
+ const status = yield* manager
+ .status({ cwd: repoDir })
+ .pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
+
+ expect(status.pr).toBeNull();
+ const warning = logs.find((entry) => entry.message.includes("PR lookup failed"));
+ expect(warning?.annotations).toMatchObject({
+ operation: "lookupStatusPr",
+ branch: "feature/status-rate-limited",
+ errorTag: "SourceControlProviderError",
+ provider: "github",
+ providerOperation: "listChangeRequests",
+ providerCommand: "gh",
+ errorDetail:
+ "GitHub API rate limit exceeded. Run `gh api rate_limit` to inspect the quota and reset time.",
+ });
+ const loggedText = [
+ warning?.message ?? "",
+ ...Object.values(warning?.annotations ?? {}).map(String),
+ ].join("\n");
+ expect(loggedText).not.toContain(upstreamCause);
+ expect(loggedText).not.toContain("secret-value");
+ }),
+ );
+
it.effect("status keeps the last known PR when a later lookup fails", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts
index b4d1240c6..bed5a8839 100644
--- a/apps/server/src/git/GitManager.ts
+++ b/apps/server/src/git/GitManager.ts
@@ -12,6 +12,7 @@ import * as Option from "effect/Option";
import * as Order from "effect/Order";
import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
+import * as Schema from "effect/Schema";
import {
GitActionProgressEvent,
GitActionProgressPhase,
@@ -28,6 +29,7 @@ import {
type VcsStatusRemoteResult,
VcsStatusResult,
ModelSelection,
+ SourceControlProviderError,
type SourceControlWritingStyleSettings,
} from "@t3tools/contracts";
import {
@@ -113,6 +115,7 @@ const PR_LOOKUP_CACHE_TTL = Duration.minutes(2);
const PR_LOOKUP_FAILURE_BASE_TTL = Duration.seconds(20);
const PR_LOOKUP_FAILURE_MAX_TTL = Duration.minutes(15);
const PR_LOOKUP_CACHE_CAPACITY = 2_048;
+const isSourceControlProviderError = Schema.is(SourceControlProviderError);
/**
* How long a failed PR lookup is cached, given the number of consecutive
@@ -1048,6 +1051,14 @@ export const make = Effect.gen(function* () {
typeof error === "object" && error !== null && "_tag" in error
? String(error._tag)
: typeof error,
+ ...(isSourceControlProviderError(error)
+ ? {
+ provider: error.provider,
+ providerOperation: error.operation,
+ providerCommand: error.command ?? "unknown",
+ errorDetail: error.detail,
+ }
+ : {}),
}),
Effect.andThen(resolveBranchHeadContext(cwd, details)),
Effect.map((headContext) =>
diff --git a/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.test.ts b/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.test.ts
index b52b6d497..5baf18a1f 100644
--- a/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.test.ts
+++ b/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.test.ts
@@ -342,7 +342,40 @@ layer("AzureDevOpsPullRequestCli.layer", (it) => {
}),
);
+ it.effect("stores the squash choice with an auto-completion, as a merge now does", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
+ const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
+
+ yield* cli.runPullRequestAction({
+ cwd: "/w",
+ number: 42,
+ action: "enable-auto-merge",
+ mergeMethod: "squash",
+ });
+
+ expect(argsOfCall(0)).toEqual([
+ "repos",
+ "pr",
+ "update",
+ "--detect",
+ "true",
+ "--id",
+ "42",
+ "--auto-complete",
+ "true",
+ "--squash",
+ "true",
+ "--only-show-errors",
+ "--output",
+ "json",
+ ]);
+ }),
+ );
+
it.effect.each([
+ { action: "enable-auto-merge", expected: ["--auto-complete", "true", "--squash", "false"] },
+ { action: "disable-auto-merge", expected: ["--auto-complete", "false"] },
{ action: "draft", expected: ["--draft", "true"] },
{ action: "ready", expected: ["--draft", "false"] },
{ action: "close", expected: ["--status", "abandoned"] },
@@ -370,6 +403,79 @@ layer("AzureDevOpsPullRequestCli.layer", (it) => {
}),
);
+ it.effect.each([
+ { name: "a title", rewrite: { title: "Add the page" }, expected: ["--title=Add the page"] },
+ {
+ name: "a description",
+ rewrite: { body: "Why the page changed" },
+ expected: ["--description=Why the page changed"],
+ },
+ {
+ name: "both",
+ rewrite: { title: "Add the page", body: "Why the page changed" },
+ expected: ["--title=Add the page", "--description=Why the page changed"],
+ },
+ ] as const)("rewrites $name, sending nothing it was not given", ({ rewrite, expected }) =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
+ const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
+
+ yield* cli.updatePullRequest({ cwd: "/w", number: 42, ...rewrite });
+
+ expect(argsOfCall(0)).toEqual([
+ "repos",
+ "pr",
+ "update",
+ "--detect",
+ "true",
+ "--id",
+ "42",
+ ...expected,
+ "--only-show-errors",
+ "--output",
+ "json",
+ ]);
+ }),
+ );
+
+ it.effect("sends a description that starts with a dash as one value, not as a flag", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
+ const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
+
+ yield* cli.updatePullRequest({
+ cwd: "/w",
+ number: 42,
+ body: "- rewrote the page\n- kept the rest",
+ });
+
+ // One argument, so the leading dash of an ordinary bullet list never reaches az as a flag,
+ // and the whole text stays together where `--description` would otherwise take several.
+ expect(argsOfCall(0)).toContain("--description=- rewrote the page\n- kept the rest");
+ }),
+ );
+
+ it.effect("rewrites through the provider, which says it takes one", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
+ const provider = yield* AzureDevOpsPullRequestProvider.make;
+
+ // False for a remark because nothing here can post one, so there is none to rewrite.
+ expect(provider.capabilities.edit).toEqual({ changeRequest: true, comment: false });
+ assert.isDefined(provider.updateChangeRequest);
+ yield* provider.updateChangeRequest({
+ cwd: "/w",
+ repository: "web",
+ host: "dev.azure.com",
+ number: 42,
+ title: "Add the page",
+ });
+
+ expect(argsOfCall(0)).toContain("--title=Add the page");
+ expect(argsOfCall(0)).not.toContain("--description");
+ }),
+ );
+
it.effect("reads the conversation through the REST API, pinned to a version", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
diff --git a/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.ts b/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.ts
index 43f929163..549a172b3 100644
--- a/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.ts
+++ b/apps/server/src/pullRequest/AzureDevOpsPullRequestCli.ts
@@ -159,6 +159,14 @@ export class AzureDevOpsPullRequestCli extends Context.Service<
readonly mergeMethod?: PullRequestMergeMethod;
}) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
+ /** Rewrites the pull request's own words, through the same command that moves it. */
+ readonly updatePullRequest: (input: {
+ readonly cwd: string;
+ readonly number: number;
+ readonly title?: string | undefined;
+ readonly body?: string | undefined;
+ }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
+
/**
* Adds reviewers to a pull request, or takes them off it. `az repos pr reviewer` is the whole
* of what Azure offers here: it adds and removes named identities, and has no counterpart that
@@ -212,12 +220,21 @@ function actionArgs(
switch (action) {
case "merge":
return ["--status", "completed", "--squash", mergeMethod === "squash" ? "true" : "false"];
+ // Auto-complete is Azure's own name for it: the pull request stays active and Azure completes
+ // it once its policies pass. The squash choice is stored with it, as it is for a merge now.
+ case "enable-auto-merge":
+ return ["--auto-complete", "true", "--squash", mergeMethod === "squash" ? "true" : "false"];
+ case "disable-auto-merge":
+ return ["--auto-complete", "false"];
case "ready":
return ["--draft", "false"];
case "draft":
return ["--draft", "true"];
case "close":
return ["--status", "abandoned"];
+ // Never reached: this host does not declare the action, so nothing offers it.
+ case "update-branch":
+ return [];
case "reopen":
return ["--status", "active"];
}
@@ -481,6 +498,29 @@ export const make = Effect.gen(function* () {
],
})
.pipe(Effect.asVoid),
+
+ updatePullRequest: (input) =>
+ azure
+ .execute({
+ cwd: input.cwd,
+ args: [
+ "repos",
+ "pr",
+ "update",
+ ...detectArgs,
+ "--id",
+ String(input.number),
+ // One argument rather than a flag and a value beside it: a description usually opens
+ // with a bullet, and az reads a dash in the next argv slot as a flag of its own.
+ // `--description` also takes several strings, and this keeps the whole text as one.
+ ...(input.title === undefined ? [] : [`--title=${input.title}`]),
+ ...(input.body === undefined ? [] : [`--description=${input.body}`]),
+ "--only-show-errors",
+ "--output",
+ "json",
+ ],
+ })
+ .pipe(Effect.asVoid),
});
});
diff --git a/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.test.ts b/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.test.ts
index cce581ce6..51d8f74bb 100644
--- a/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.test.ts
+++ b/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.test.ts
@@ -9,7 +9,15 @@ describe("azure devops viewer permissions", () => {
// and an unknown permission is granted rather than guessed away. Azure refuses the ones it
// will not allow, at the moment they are taken, in words this could not have written.
expect(AZURE_DEVOPS_VIEWER_PERMISSIONS).toEqual({
- actions: ["merge", "ready", "draft", "close", "reopen"],
+ actions: [
+ "merge",
+ "ready",
+ "draft",
+ "close",
+ "reopen",
+ "enable-auto-merge",
+ "disable-auto-merge",
+ ],
// False because the host itself cannot post one, not because this viewer may not.
comment: false,
resolve: false,
diff --git a/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.ts b/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.ts
index 5d8f7a093..5607b0cd4 100644
--- a/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.ts
+++ b/apps/server/src/pullRequest/AzureDevOpsPullRequestProvider.ts
@@ -18,11 +18,20 @@ const CAPABILITIES: PullRequestCapabilities = {
// Reading a conversation is a plain REST read, but posting one is not something this can
// claim without having run it, so the composer stays hidden.
comment: false,
- actions: ["merge", "ready", "draft", "close", "reopen"],
+ actions: [
+ "merge",
+ "ready",
+ "draft",
+ "close",
+ "reopen",
+ "enable-auto-merge",
+ "disable-auto-merge",
+ ],
// Azure squashes as a completion option; it has no rebase strategy of its own.
mergeMethods: ["merge", "squash"],
// `az repos pr list` filters by status, creator, reviewer and branch, and by no text at all.
search: false,
+ reactions: false,
// With no patch to show there are no lines to write against, so nothing here is offered.
review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
// `az repos pr reviewer add` and `remove` name identities, and nothing anywhere in `az repos`
@@ -30,6 +39,10 @@ const CAPABILITIES: PullRequestCapabilities = {
// different service with its own permissions. So the page takes a name here rather than being
// handed a menu built out of a guess.
reviewers: { request: true, listCandidates: false },
+ // A new title and description travel on the same `az repos pr update` that moves a pull request.
+ // Rewriting a remark is false for the same reason posting one is: this cannot put a remark on
+ // Azure DevOps at all, so there is nothing here it could rewrite either.
+ edit: { changeRequest: true, comment: false },
};
/**
@@ -153,6 +166,7 @@ export const make = Effect.gen(function* () {
checks: [],
mergeCapabilities: { merge: true, squash: true, rebase: false },
viewerPermissions: AZURE_DEVOPS_VIEWER_PERMISSIONS,
+ autoMergeEnabled: pullRequest.autoMergeEnabled,
}),
),
),
@@ -206,6 +220,16 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("runAction"))),
+ updateChangeRequest: (input) =>
+ cli
+ .updatePullRequest({
+ cwd: input.cwd,
+ number: input.number,
+ title: input.title,
+ body: input.body,
+ })
+ .pipe(Effect.mapError(fail("updateChangeRequest"))),
+
// Never called: `capabilities.reviewers.listCandidates` is false, and the service refuses the
// list without it.
listReviewerCandidates: () =>
@@ -240,6 +264,8 @@ export const make = Effect.gen(function* () {
replyToThread: () => unsupported("replyToThread"),
setThreadResolution: () => unsupported("setThreadResolution"),
+
+ setReaction: () => unsupported("setReaction"),
};
return provider;
diff --git a/apps/server/src/pullRequest/BitbucketPullRequestApi.test.ts b/apps/server/src/pullRequest/BitbucketPullRequestApi.test.ts
index 1248b3969..f57bb67a4 100644
--- a/apps/server/src/pullRequest/BitbucketPullRequestApi.test.ts
+++ b/apps/server/src/pullRequest/BitbucketPullRequestApi.test.ts
@@ -510,6 +510,74 @@ layer("BitbucketPullRequestApi.layer", (it) => {
}),
);
+ it.effect("rewrites a title alone, without touching anything else", () =>
+ Effect.gen(function* () {
+ mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
+ const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
+
+ yield* api.updateChangeRequest({ repository: "acme/web", number: 7, title: "A new title" });
+
+ const call = callAt(0);
+ expect(call.method).toBe("PUT");
+ expect(call.url).toBe("/repositories/acme/web/pullrequests/7");
+ // Bitbucket's PUT is a partial update, so a field left out of the body is left as it was.
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ expect(JSON.parse(call.body ?? "")).toEqual({ title: "A new title" });
+ }),
+ );
+
+ it.effect("leaves out the half of the pull request it was not asked about", () =>
+ Effect.gen(function* () {
+ mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
+ const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
+
+ yield* api.updateChangeRequest({ repository: "acme/web", number: 7, body: "New body." });
+
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ expect(JSON.parse(callAt(0).body ?? "")).toEqual({ description: "New body." });
+ }),
+ );
+
+ it.effect("writes both fields when both were rewritten", () =>
+ Effect.gen(function* () {
+ mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
+ const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
+
+ yield* api.updateChangeRequest({
+ repository: "acme/web",
+ number: 7,
+ title: "A new title",
+ body: "New body.",
+ });
+
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ expect(JSON.parse(callAt(0).body ?? "")).toEqual({
+ title: "A new title",
+ description: "New body.",
+ });
+ }),
+ );
+
+ it.effect("rewrites a comment where it stands, whichever kind it is", () =>
+ Effect.gen(function* () {
+ mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
+ const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
+
+ yield* api.updateComment({
+ repository: "acme/web",
+ number: 7,
+ commentId: "10",
+ body: "Edited.",
+ });
+
+ expect(callAt(0)).toMatchObject({
+ method: "PUT",
+ url: "/repositories/acme/web/pullrequests/7/comments/10",
+ body: '{"content":{"raw":"Edited."}}',
+ });
+ }),
+ );
+
it.effect("fails the read when Bitbucket answers with something unreadable", () =>
Effect.gen(function* () {
mockedRequest.mockReturnValueOnce(
diff --git a/apps/server/src/pullRequest/BitbucketPullRequestApi.ts b/apps/server/src/pullRequest/BitbucketPullRequestApi.ts
index 7c0a7d117..a20d4aaaa 100644
--- a/apps/server/src/pullRequest/BitbucketPullRequestApi.ts
+++ b/apps/server/src/pullRequest/BitbucketPullRequestApi.ts
@@ -222,12 +222,26 @@ export class BitbucketPullRequestApi extends Context.Service<
readonly mergeMethod?: PullRequestMergeMethod;
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
+ readonly updateChangeRequest: (input: {
+ readonly repository: string;
+ readonly number: number;
+ readonly title?: string | undefined;
+ readonly body?: string | undefined;
+ }) => Effect.Effect<void, BitbucketPullRequestApiError>;
+
readonly comment: (input: {
readonly repository: string;
readonly number: number;
readonly body: string;
}) => Effect.Effect<void, BitbucketPullRequestApiError>;
+ readonly updateComment: (input: {
+ readonly repository: string;
+ readonly number: number;
+ readonly commentId: string;
+ readonly body: string;
+ }) => Effect.Effect<void, BitbucketPullRequestApiError>;
+
readonly submitReview: (input: {
readonly repository: string;
readonly number: number;
@@ -701,6 +715,24 @@ export const make = Effect.gen(function* () {
.pipe(Effect.asVoid);
}),
+ updateChangeRequest: (input) =>
+ withRepository(input.repository, (path) =>
+ // Only the words this call rewrites travel in the body: as `setReviewerRequest` above
+ // relies on, Bitbucket's PUT is a partial update, so any field left out is left as it
+ // was — sending `reviewers` back here would overwrite a change another user made to it
+ // between this call being issued and the request landing.
+ bitbucket
+ .request({
+ method: "PUT",
+ url: `${path}/pullrequests/${input.number}`,
+ body: JSON.stringify({
+ ...(input.title === undefined ? {} : { title: input.title }),
+ ...(input.body === undefined ? {} : { description: input.body }),
+ }),
+ })
+ .pipe(Effect.asVoid),
+ ),
+
comment: (input) =>
withRepository(input.repository, (path) =>
bitbucket
@@ -713,6 +745,21 @@ export const make = Effect.gen(function* () {
.pipe(Effect.asVoid),
),
+ updateComment: (input) =>
+ withRepository(input.repository, (path) =>
+ bitbucket
+ .request({
+ // Bitbucket keeps a pull request's remarks and its line comments in the one
+ // collection, so this endpoint rewrites either kind.
+ method: "PUT",
+ url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
+ input.commentId,
+ )}`,
+ body: JSON.stringify({ content: { raw: input.body } }),
+ })
+ .pipe(Effect.asVoid),
+ ),
+
submitReview: (input) =>
withRepository(input.repository, (path) =>
Effect.gen(function* () {
diff --git a/apps/server/src/pullRequest/BitbucketPullRequestProvider.ts b/apps/server/src/pullRequest/BitbucketPullRequestProvider.ts
index 8a0ea9806..00e558588 100644
--- a/apps/server/src/pullRequest/BitbucketPullRequestProvider.ts
+++ b/apps/server/src/pullRequest/BitbucketPullRequestProvider.ts
@@ -19,6 +19,9 @@ const CAPABILITIES: PullRequestCapabilities = {
actions: ["merge", "close"],
mergeMethods: ["merge", "squash", "rebase"],
search: true,
+ // Bitbucket Cloud's API exposes no reaction on a pull request or on a comment, so none is
+ // read and none is offered.
+ reactions: false,
review: {
inlineComment: true,
reply: true,
@@ -26,6 +29,7 @@ const CAPABILITIES: PullRequestCapabilities = {
verdicts: ["comment", "approve", "request-changes"],
},
reviewers: { request: true, listCandidates: true },
+ edit: { changeRequest: true, comment: true },
};
/**
@@ -249,11 +253,31 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("runAction"))),
+ updateChangeRequest: (input) =>
+ api
+ .updateChangeRequest({
+ repository: input.repository,
+ number: input.number,
+ title: input.title,
+ body: input.body,
+ })
+ .pipe(Effect.mapError(fail("updateChangeRequest"))),
+
comment: (input) =>
api
.comment({ repository: input.repository, number: input.number, body: input.body })
.pipe(Effect.mapError(fail("comment"))),
+ updateComment: (input) =>
+ api
+ .updateComment({
+ repository: input.repository,
+ number: input.number,
+ commentId: input.commentId,
+ body: input.body,
+ })
+ .pipe(Effect.mapError(fail("updateComment"))),
+
submitReview: (input) =>
api
.submitReview({
@@ -275,6 +299,17 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("replyToThread"))),
+ // Never called: `capabilities.reactions` is false, and the service refuses without it.
+ setReaction: () =>
+ Effect.fail(
+ new PullRequestProviderError({
+ provider: "bitbucket",
+ operation: "setReaction",
+ reason: "failed",
+ detail: "Bitbucket does not support reactions.",
+ }),
+ ),
+
setThreadResolution: (input) =>
api
.setCommentResolution({
diff --git a/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts b/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts
index bf7e8951a..848c4cd5e 100644
--- a/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts
+++ b/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts
@@ -5,6 +5,7 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
+import { BASE_COMPARISON_GRAPHQL_QUERY } from "./gitHubPullRequestJson.ts";
const mockedExecute = vi.fn<GitHubCli.GitHubCli["Service"]["execute"]>();
@@ -551,6 +552,206 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
+ it.effect("carries the further narrowings into the search as qualifiers", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ yield* cli.listPullRequests({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ state: "open",
+ involvement: "all",
+ viewer: "bilal",
+ limit: 10,
+ filters: {
+ draft: "hide",
+ review: "changes-requested",
+ checks: "failing",
+ labels: [["needs design"], ['quo"te']],
+ excludedLabels: ["wip"],
+ author: "octocat",
+ },
+ });
+
+ // Quotes around anything a reader typed, and the one character that could end a quoted
+ // value early dropped rather than escaped.
+ expect(searchOfCall(0)).toBe(
+ 'label:"needs design" label:"quote" -label:"wip" author:"octocat" draft:false ' +
+ "review:changes_requested status:failure sort:updated-desc",
+ );
+ }),
+ );
+
+ it.effect('resolves an author filter of "me" to the viewer, not the literal word', () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ yield* cli.listPullRequests({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ state: "open",
+ involvement: "all",
+ viewer: "bilal",
+ limit: 10,
+ filters: { author: "me" },
+ });
+
+ expect(searchOfCall(0)).toBe('author:"bilal" sort:updated-desc');
+ }),
+ );
+
+ it.effect("sends one label qualifier per group, its names joined the way GitHub ors them", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ yield* cli.listPullRequests({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ state: "open",
+ involvement: "all",
+ viewer: "bilal",
+ limit: 10,
+ filters: { labels: [["size:S", "size:XS"], ["bug"]] },
+ });
+
+ // One qualifier satisfied by either size, and a second one that must hold as well.
+ expect(searchOfCall(0)).toBe('label:"size:S","size:XS" label:"bug" sort:updated-desc');
+ expect(callAt(0).args).toContain('label:"size:S","size:XS" label:"bug" sort:updated-desc');
+ }),
+ );
+
+ it.effect(
+ "falls back for a repository the index does not cover under a checks filter, keeping only the matching rows",
+ () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
+ mockedExecute.mockReturnValueOnce(
+ Effect.succeed(
+ output(
+ pullRequests(2, 1, (number) => ({
+ statusCheckRollup:
+ number === 1
+ ? [{ name: "lint", status: "COMPLETED", conclusion: "SUCCESS" }]
+ : [{ name: "test", status: "COMPLETED", conclusion: "FAILURE" }],
+ })),
+ ),
+ ),
+ );
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ const batch = yield* cli.listPullRequests({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ state: "open",
+ involvement: "all",
+ viewer: "bilal",
+ limit: 10,
+ filters: { checks: "passing" },
+ });
+
+ // The fallback's rows carry `checksState` exactly as a search's rows do, so `checks` is
+ // now a filter the fallback judges itself, the same as `draft`: an empty search answer
+ // under it is still ambiguous, and the row picked out afterwards is the one whose own
+ // `checksState` reads "passing".
+ expect(searchOfCall(1)).toBeUndefined();
+ assert.deepStrictEqual(
+ batch.items.map((item) => item.number),
+ [1],
+ );
+ }),
+ );
+
+ it.effect("fails a checks filter for a row whose checks are still pending", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
+ mockedExecute.mockReturnValueOnce(
+ Effect.succeed(
+ output(
+ pullRequests(1, 1, () => ({
+ statusCheckRollup: [{ name: "build", status: "IN_PROGRESS" }],
+ })),
+ ),
+ ),
+ );
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ const batch = yield* cli.listPullRequests({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ state: "open",
+ involvement: "all",
+ viewer: "bilal",
+ limit: 10,
+ filters: { checks: "passing" },
+ });
+
+ // Pending equals neither "passing" nor "failing", so it satisfies neither filter value —
+ // the same row would also be dropped by `checks: "failing"`.
+ assert.deepStrictEqual(batch.items, []);
+ }),
+ );
+
+ it.effect(
+ "falls back for a repository the index does not cover even under a judgeable filter",
+ () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
+ mockedExecute.mockReturnValueOnce(
+ Effect.succeed(output(pullRequests(2, 1, (number) => ({ isDraft: number === 1 })))),
+ );
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ const batch = yield* cli.listPullRequests({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ state: "open",
+ involvement: "all",
+ viewer: "bilal",
+ limit: 10,
+ filters: { draft: "hide" },
+ });
+
+ // `draft` is a filter the fallback can judge over its own rows just as search judges it,
+ // so an empty search answer under it alone is still ambiguous between "nothing matches"
+ // and "this repository is not indexed" — and the fallback applies the filter itself,
+ // keeping only the non-draft row.
+ expect(searchOfCall(1)).toBeUndefined();
+ expect(batch.items.map((item) => item.number)).toEqual([2]);
+ }),
+ );
+
+ it.effect("carries the further narrowings into a batched search", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(searchPage([])));
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ yield* cli.searchPullRequests({
+ cwd: "/w",
+ host: "github.com",
+ repositories: ["acme/web"],
+ state: "open",
+ involvement: "all",
+ viewer: "bilal",
+ limit: 10,
+ filters: { draft: "only", review: "none", labels: [["bug"]] },
+ });
+
+ assert.strictEqual(
+ searchQueryOfCall(0),
+ 'is:pr is:open label:"bug" draft:true review:none sort:updated-desc repo:acme/web',
+ );
+ }),
+ );
+
it.effect("quotes a search, so it cannot add a qualifier or a flag of its own", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
@@ -819,6 +1020,40 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
+ it.effect("updates a stale branch with a merge commit unless asked to rebase", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("")));
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ yield* cli.runPullRequestAction({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ action: "update-branch",
+ });
+ // GitHub's own default, and `gh`'s: a merge commit unless the rebase flag says otherwise.
+ expect(callAt(0).args).toEqual(["pr", "update-branch", "7", "--repo", "github.com/acme/web"]);
+
+ yield* cli.runPullRequestAction({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ action: "update-branch",
+ updateMethod: "rebase",
+ });
+ expect(callAt(1).args).toEqual([
+ "pr",
+ "update-branch",
+ "7",
+ "--repo",
+ "github.com/acme/web",
+ "--rebase",
+ ]);
+ }),
+ );
+
it.effect("merges with the strategy it was asked for", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("")));
@@ -844,6 +1079,74 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
+ it.effect("arms auto-merge with the same strategy a merge would have used", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("")));
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ yield* cli.runPullRequestAction({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ action: "enable-auto-merge",
+ mergeMethod: "squash",
+ });
+ expect(callAt(0).args).toEqual([
+ "pr",
+ "merge",
+ "7",
+ "--repo",
+ "github.com/acme/web",
+ "--auto",
+ "--squash",
+ ]);
+
+ // No strategy asked for is GitHub's own default, exactly as it is for a merge now.
+ yield* cli.runPullRequestAction({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ action: "enable-auto-merge",
+ });
+ expect(callAt(1).args).toEqual([
+ "pr",
+ "merge",
+ "7",
+ "--repo",
+ "github.com/acme/web",
+ "--auto",
+ "--merge",
+ ]);
+ }),
+ );
+
+ it.effect("takes auto-merge back off without naming a strategy", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("")));
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ yield* cli.runPullRequestAction({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ action: "disable-auto-merge",
+ mergeMethod: "squash",
+ });
+
+ expect(callAt(0).args).toEqual([
+ "pr",
+ "merge",
+ "7",
+ "--repo",
+ "github.com/acme/web",
+ "--disable-auto",
+ ]);
+ }),
+ );
+
it.effect("returns a pull request to draft by undoing ready", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(output("")));
@@ -1406,6 +1709,279 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
+ it.effect("confirms a given subject belongs to the named pull request, then reacts to it", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(
+ Effect.succeed(
+ output(
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ JSON.stringify({
+ data: {
+ repository: { pullRequest: { id: "PR_kwDOA" } },
+ node: { id: "IC_1", pullRequest: { id: "PR_kwDOA" } },
+ },
+ }),
+ ),
+ ),
+ );
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ yield* cli.setReaction({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ subjectId: "IC_1",
+ content: "heart",
+ reacted: true,
+ });
+
+ assert.strictEqual(mockedExecute.mock.calls.length, 2);
+ const scopeCheck = callAt(0).args;
+ expect(scopeCheck).toContain("owner=acme");
+ expect(scopeCheck).toContain("name=web");
+ expect(scopeCheck).toContain("number=7");
+ expect(scopeCheck).toContain("subjectId=IC_1");
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ const request = JSON.parse(callAt(1).stdin ?? "") as {
+ query: string;
+ variables: Record<string, string>;
+ };
+ expect(request.query).toContain("addReaction(");
+ expect(request.variables).toEqual({ subjectId: "IC_1", content: "HEART" });
+ }),
+ );
+
+ it.effect("refuses a given subject that belongs to a different pull request", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(
+ Effect.succeed(
+ output(
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ JSON.stringify({
+ data: {
+ repository: { pullRequest: { id: "PR_thisOne" } },
+ // A comment on pull request #99 of a different repository, named as though it
+ // belonged to #7 here.
+ node: { id: "IC_99", pullRequest: { id: "PR_someOtherOne" } },
+ },
+ }),
+ ),
+ ),
+ );
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ const error = yield* Effect.flip(
+ cli.setReaction({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ subjectId: "IC_99",
+ content: "heart",
+ reacted: true,
+ }),
+ );
+
+ assert.strictEqual(error._tag, "GitHubSubjectScopeError");
+ // Refused before any mutation was sent.
+ assert.strictEqual(mockedExecute.mock.calls.length, 1);
+ }),
+ );
+
+ it.effect("looks up the pull request's own node id when no subject was given", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(
+ Effect.succeed(
+ output(
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ JSON.stringify({ data: { repository: { pullRequest: { id: "PR_kwDOA" } } } }),
+ ),
+ ),
+ );
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ yield* cli.setReaction({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ content: "rocket",
+ reacted: true,
+ });
+
+ assert.strictEqual(mockedExecute.mock.calls.length, 2);
+ const lookup = callAt(0).args;
+ expect(lookup).toContain("owner=acme");
+ expect(lookup).toContain("name=web");
+ expect(lookup).toContain("number=7");
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ const request = JSON.parse(callAt(1).stdin ?? "") as {
+ query: string;
+ variables: Record<string, string>;
+ };
+ expect(request.query).toContain("addReaction(");
+ expect(request.variables).toEqual({ subjectId: "PR_kwDOA", content: "ROCKET" });
+ }),
+ );
+
+ it.effect("takes a reaction back through the remove mutation", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(
+ Effect.succeed(
+ output(
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ JSON.stringify({
+ data: {
+ repository: { pullRequest: { id: "PR_kwDOA" } },
+ node: { id: "IC_1", pullRequest: { id: "PR_kwDOA" } },
+ },
+ }),
+ ),
+ ),
+ );
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ yield* cli.setReaction({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ subjectId: "IC_1",
+ content: "heart",
+ reacted: false,
+ });
+
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ const request = JSON.parse(callAt(1).stdin ?? "") as { query: string };
+ expect(request.query).toContain("removeReaction(");
+ }),
+ );
+
+ it.effect("rewrites only the words a request named", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(
+ Effect.succeed(
+ output(
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ JSON.stringify({ data: { repository: { pullRequest: { id: "PR_kwDOA" } } } }),
+ ),
+ ),
+ );
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+ const rewrite = (fields: { readonly title?: string; readonly body?: string }) =>
+ cli.updatePullRequest({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ ...fields,
+ });
+
+ yield* rewrite({ title: "A better title" });
+ yield* rewrite({ body: "A better description." });
+ yield* rewrite({ title: "Both", body: "at once." });
+
+ // Each rewrite looks the pull request's node id up first, then mutates.
+ const variablesAt = (index: number) =>
+ (JSON.parse(callAt(index).stdin ?? "") as { variables: Record<string, string> }).variables;
+ expect(variablesAt(1)).toEqual({ pullRequestId: "PR_kwDOA", title: "A better title" });
+ expect(variablesAt(3)).toEqual({
+ pullRequestId: "PR_kwDOA",
+ body: "A better description.",
+ });
+ expect(variablesAt(5)).toEqual({
+ pullRequestId: "PR_kwDOA",
+ title: "Both",
+ body: "at once.",
+ });
+ // The reader's own words, so they travel the way every other body does.
+ expect(callAt(5).args.join(" ")).not.toContain("at once.");
+ }),
+ );
+
+ it.effect("rewrites a remark through the mutation its kind needs", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(
+ Effect.succeed(
+ output(
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ JSON.stringify({
+ data: {
+ repository: { pullRequest: { id: "PR_kwDOA" } },
+ node: { id: "IC_1", pullRequest: { id: "PR_kwDOA" } },
+ },
+ }),
+ ),
+ ),
+ );
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+ const rewrite = (kind: "issue-comment" | "review-comment") =>
+ cli.updateComment({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ commentId: "IC_1",
+ kind,
+ body: "Reworded.",
+ });
+
+ yield* rewrite("issue-comment");
+ yield* rewrite("review-comment");
+
+ const parse = (index: number) =>
+ JSON.parse(callAt(index).stdin ?? "") as {
+ query: string;
+ variables: Record<string, string>;
+ };
+ expect(callAt(0).args).toContain("subjectId=IC_1");
+ expect(parse(1).query).toContain("updateIssueComment(");
+ expect(parse(1).variables).toEqual({ commentId: "IC_1", body: "Reworded." });
+ expect(parse(3).query).toContain("updatePullRequestReviewComment(");
+ expect(parse(3).variables).toEqual({ commentId: "IC_1", body: "Reworded." });
+ }),
+ );
+
+ it.effect("refuses a comment that belongs to a different pull request", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(
+ Effect.succeed(
+ output(
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ JSON.stringify({
+ data: {
+ repository: { pullRequest: { id: "PR_thisOne" } },
+ node: { id: "IC_99", pullRequest: { id: "PR_someOtherOne" } },
+ },
+ }),
+ ),
+ ),
+ );
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ const error = yield* Effect.flip(
+ cli.updateComment({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ commentId: "IC_99",
+ kind: "issue-comment",
+ body: "Reworded.",
+ }),
+ );
+
+ assert.strictEqual(error._tag, "GitHubSubjectScopeError");
+ expect(error.message).toContain("updateComment");
+ // Refused before any mutation was sent.
+ assert.strictEqual(mockedExecute.mock.calls.length, 1);
+ }),
+ );
+
it.effect("fails the read when gh returns something unreadable", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output('{"message":"not found"}')));
@@ -1472,7 +2048,7 @@ layer("GitHubPullRequestCli.layer", (it) => {
expect(detail.body).toBe("Core body");
expect(activity.author?.login).toBe("octocat");
expect(callAt(0).args.at(-1)).toBe(
- "number,title,url,author,headRefName,baseRefName,state,isDraft,mergeable,additions,deletions,createdAt,updatedAt,mergedAt,reviewRequests,labels,body,changedFiles,closedAt,statusCheckRollup",
+ "number,title,url,author,headRefName,baseRefName,state,isDraft,mergeable,reviewDecision,additions,deletions,createdAt,updatedAt,mergedAt,reviewRequests,labels,statusCheckRollup,body,changedFiles,closedAt,headRepositoryOwner,autoMergeRequest",
);
expect(callAt(1).args.at(-1)).toBe("author,comments,reviews,commits");
}),
@@ -1634,6 +2210,58 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
+ it.effect("sends the base comparison's variables as gh flags, not as bare words", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(
+ Effect.succeed(
+ output(
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ JSON.stringify({
+ data: {
+ repository: {
+ pullRequest: {
+ viewerCanUpdateBranch: true,
+ baseRef: { compare: { behindBy: 4 } },
+ },
+ },
+ },
+ }),
+ ),
+ ),
+ );
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ const comparison = yield* cli.getPullRequestBaseComparison({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ headRef: "fork:feat/page",
+ });
+
+ // The tuples are flattened straight into argv, so a variable without its flag is a
+ // positional argument gh refuses outright.
+ const args = callAt(0).args;
+ expect(args).toEqual([
+ "api",
+ "graphql",
+ "--hostname",
+ "github.com",
+ "-f",
+ "owner=acme",
+ "-f",
+ "name=web",
+ "-F",
+ "number=7",
+ "-f",
+ "headRef=fork:feat/page",
+ "-f",
+ `query=${BASE_COMPARISON_GRAPHQL_QUERY}`,
+ ]);
+ expect(comparison).toEqual({ behindBy: 4, viewerCanUpdate: true });
+ }),
+ );
+
it.effect("reads the viewer's role off the same call as the merge settings", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(
diff --git a/apps/server/src/pullRequest/GitHubPullRequestCli.ts b/apps/server/src/pullRequest/GitHubPullRequestCli.ts
index 392fac856..27402c211 100644
--- a/apps/server/src/pullRequest/GitHubPullRequestCli.ts
+++ b/apps/server/src/pullRequest/GitHubPullRequestCli.ts
@@ -3,22 +3,29 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
-import type {
- PullRequestAction,
- PullRequestActor,
- PullRequestInvolvement,
- PullRequestListState,
- PullRequestMergeMethod,
- PullRequestReviewCommentDraft,
- PullRequestReviewVerdict,
- PullRequestReviewerCandidateList,
- PullRequestReviewerKind,
- PullRequestThreadComment,
+import {
+ resolvePullRequestAuthorFilter,
+ type PullRequestAction,
+ type PullRequestActor,
+ type PullRequestInvolvement,
+ type PullRequestListFilters,
+ type PullRequestListState,
+ type PullRequestMergeMethod,
+ type PullRequestOmittedFileStat,
+ type PullRequestReaction,
+ type PullRequestReactionContent,
+ type PullRequestReviewCommentDraft,
+ type PullRequestReviewVerdict,
+ type PullRequestReviewerCandidateList,
+ type PullRequestReviewerKind,
+ type PullRequestThreadComment,
+ type PullRequestUpdateMethod,
} from "@t3tools/contracts";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import {
ACTOR_AVATARS_GRAPHQL_QUERY,
+ ADD_REACTION_GRAPHQL_MUTATION,
buildReviewSubmissionJson,
buildReviewerRequestJson,
decodeActorAvatarsJson,
@@ -26,10 +33,13 @@ import {
decodePullRequestDetailJson,
decodePullRequestFilesJson,
decodePullRequestListJson,
+ decodePullRequestNodeIdJson,
decodePullRequestSearchJson,
decodePullRequestStatsJson,
+ decodeReactionSubjectScopeJson,
decodeRepositoryAccessJson,
decodeReviewerCandidatesJson,
+ decodeReviewDismissalsJson,
decodeReviewThreadCommentsJson,
decodeReviewThreadsJson,
buildPullRequestStatsGraphQlQuery,
@@ -37,18 +47,29 @@ import {
pullRequestSearchGraphQlQuery,
PULL_REQUEST_SEARCH_MAX_ROWS,
PULL_REQUEST_ACTIVITY_JSON_FIELDS,
+ BASE_COMPARISON_GRAPHQL_QUERY,
+ decodeBaseComparisonJson,
PULL_REQUEST_DETAIL_JSON_FIELDS,
PULL_REQUEST_LIST_JSON_FIELDS,
+ PULL_REQUEST_NODE_ID_GRAPHQL_QUERY,
+ REACTION_SUBJECT_PULL_REQUEST_GRAPHQL_QUERY,
+ REMOVE_REACTION_GRAPHQL_MUTATION,
+ gitHubReactionContent,
REPOSITORY_ACCESS_JSON_FIELDS,
RESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION,
REVIEWER_CANDIDATES_GRAPHQL_QUERY,
REVIEW_THREAD_COMMENTS_GRAPHQL_QUERY,
+ REVIEW_DISMISSALS_GRAPHQL_QUERY,
REVIEW_THREAD_REPLY_GRAPHQL_MUTATION,
REVIEW_THREADS_GRAPHQL_QUERY,
reviewThreadConversation,
UNRESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION,
+ UPDATE_ISSUE_COMMENT_GRAPHQL_MUTATION,
+ UPDATE_PULL_REQUEST_GRAPHQL_MUTATION,
+ UPDATE_REVIEW_COMMENT_GRAPHQL_MUTATION,
VIEWER_PERMISSIONS_GRAPHQL_QUERY,
decodeViewerPermissionsJson,
+ type GitHubBaseComparison,
type GitHubPullRequestDetail,
type GitHubPullRequestActivity,
type GitHubPullRequestListItem,
@@ -199,6 +220,24 @@ export class GitHubRepositorySelectorError extends Schema.TaggedErrorClass<GitHu
}
}
+/** Not a decode failure: the reader named a subject this pull request never handed out. */
+export class GitHubSubjectScopeError extends Schema.TaggedErrorClass<GitHubSubjectScopeError>()(
+ "GitHubSubjectScopeError",
+ {
+ command: Schema.Literal("gh"),
+ cwd: Schema.String,
+ operation: Schema.String,
+ },
+) {
+ get detail(): string {
+ return "The named subject did not belong to the named pull request.";
+ }
+
+ override get message(): string {
+ return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
+ }
+}
+
export type GitHubPullRequestCliError =
| GitHubCli.GitHubCliError
| GitHubPullRequestReadError
@@ -207,6 +246,7 @@ export type GitHubPullRequestCliError =
| GitHubDiffRevisionsUnavailableError
| GitHubDiffFileContentsUnavailableError
| GitHubRepositorySelectorError
+ | GitHubSubjectScopeError
| GitHubViewerLoginUnavailableError;
/** A large pull request can produce a multi-megabyte patch; past this it is truncated. */
@@ -270,6 +310,8 @@ export interface GitHubPullRequestDiffSlice {
readonly truncated: boolean;
/** Where the next slice starts, or null once the patch is whole. */
readonly nextCursor: string | null;
+ /** GitHub's own counts for the files whose hunks it withheld from this slice. */
+ readonly omittedFileStats?: ReadonlyArray<PullRequestOmittedFileStat>;
}
export class GitHubPullRequestCli extends Context.Service<
@@ -291,6 +333,8 @@ export class GitHubPullRequestCli extends Context.Service<
readonly query?: string | undefined;
/** Where to carry on from, as a `updated:` qualifier on the same search. */
readonly cursor?: ProviderListCursor | undefined;
+ /** Further narrowings, as qualifiers on the search and as a local pass on the fallback. */
+ readonly filters?: PullRequestListFilters | undefined;
}) => Effect.Effect<GitHubPullRequestListBatch, GitHubPullRequestCliError>;
/**
@@ -309,6 +353,7 @@ export class GitHubPullRequestCli extends Context.Service<
readonly limit: number;
readonly query?: string | undefined;
readonly cursor?: ProviderListCursor | undefined;
+ readonly filters?: PullRequestListFilters | undefined;
}) => Effect.Effect<GitHubPullRequestSearchBatch, GitHubPullRequestCliError>;
/** The line counts the search leaves out, for rows already on the page. */
@@ -328,6 +373,20 @@ export class GitHubPullRequestCli extends Context.Service<
readonly number: number;
}) => Effect.Effect<GitHubPullRequestDetail, 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
+ * addressable in the base repository by name alone.
+ */
+ readonly getPullRequestBaseComparison: (input: {
+ readonly cwd: string;
+ readonly repository: string;
+ readonly host: string;
+ readonly number: number;
+ /** Qualified `owner:branch`, which is the only form a fork's head resolves under. */
+ readonly headRef: string;
+ }) => Effect.Effect<GitHubBaseComparison, GitHubPullRequestCliError>;
+
readonly getPullRequestActivity: (input: {
readonly cwd: string;
readonly repository: string;
@@ -418,6 +477,7 @@ export class GitHubPullRequestCli extends Context.Service<
readonly number: number;
readonly action: PullRequestAction;
readonly mergeMethod?: PullRequestMergeMethod;
+ readonly updateMethod?: PullRequestUpdateMethod;
}) => Effect.Effect<void, GitHubPullRequestCliError>;
readonly commentOnPullRequest: (input: {
@@ -453,6 +513,47 @@ export class GitHubPullRequestCli extends Context.Service<
readonly threadId: string;
readonly resolved: boolean;
}) => Effect.Effect<void, GitHubPullRequestCliError>;
+
+ /**
+ * Adds a reaction to a remark, or takes it back. `subjectId` is any node GitHub calls
+ * reactable — a comment, a review, or the pull request itself, which is looked up here
+ * because nothing in the conversation names it. A given `subjectId` is confirmed to belong
+ * to this pull request before the mutation runs, since nothing else ties the two together.
+ */
+ readonly setReaction: (input: {
+ readonly cwd: string;
+ readonly repository: string;
+ readonly host: string;
+ readonly number: number;
+ readonly subjectId?: string | undefined;
+ readonly content: PullRequestReactionContent;
+ readonly reacted: boolean;
+ }) => Effect.Effect<void, GitHubPullRequestCliError>;
+
+ /** Rewrites the pull request's own words, leaving whichever of the two was not given. */
+ readonly updatePullRequest: (input: {
+ readonly cwd: string;
+ readonly repository: string;
+ readonly host: string;
+ readonly number: number;
+ readonly title?: string | undefined;
+ readonly body?: string | undefined;
+ }) => Effect.Effect<void, GitHubPullRequestCliError>;
+
+ /**
+ * Rewrites a remark. `commentId` is trusted to be whatever node it names, so it is confirmed
+ * to belong to this pull request before the mutation runs, the way a reaction subject is.
+ * Whether the remark is the reader's to rewrite is GitHub's own answer, not one asked here.
+ */
+ readonly updateComment: (input: {
+ readonly cwd: string;
+ readonly repository: string;
+ readonly host: string;
+ readonly number: number;
+ readonly commentId: string;
+ readonly kind: "issue-comment" | "review-comment";
+ readonly body: string;
+ }) => Effect.Effect<void, GitHubPullRequestCliError>;
}
>()("t3/pullRequest/GitHubPullRequestCli") {}
@@ -501,6 +602,76 @@ function searchPhrase(query: string): string {
return `"${query.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
}
+/** GitHub's own spelling of a review state, which is not the contract's. */
+const REVIEW_QUALIFIERS = {
+ approved: "approved",
+ "changes-requested": "changes_requested",
+ "review-required": "required",
+ none: "none",
+} as const;
+
+/**
+ * The extra narrowings as GitHub search qualifiers. Values a reader typed are quoted, and the
+ * one character that could end the quoted value early is dropped rather than escaped: no GitHub
+ * label or login holds a double quote, so there is nothing to preserve and everything to lose.
+ */
+function qualifierValue(value: string): string {
+ return `"${value.replaceAll('"', "").trim()}"`;
+}
+
+function filterQualifiers(
+ filters: PullRequestListFilters | undefined,
+ viewer: string,
+): ReadonlyArray<string> {
+ if (filters === undefined) return [];
+ return [
+ // One qualifier per group, its names joined by commas — GitHub's own OR.
+ ...(filters.labels ?? []).flatMap((group) =>
+ group.length === 0 ? [] : [`label:${group.map(qualifierValue).join(",")}`],
+ ),
+ ...(filters.excludedLabels ?? []).map((label) => `-label:${qualifierValue(label)}`),
+ ...(filters.author === undefined
+ ? []
+ : [`author:${qualifierValue(resolvePullRequestAuthorFilter(filters.author, viewer))}`]),
+ ...(filters.draft === undefined ? [] : [`draft:${filters.draft === "only"}`]),
+ ...(filters.review === undefined ? [] : [`review:${REVIEW_QUALIFIERS[filters.review]}`]),
+ ...(filters.checks === undefined
+ ? []
+ : [`status:${filters.checks === "passing" ? "success" : "failure"}`]),
+ ];
+}
+
+/**
+ * The same narrowings over a row that has already arrived, for the search-free fallback. Every
+ * listed row now carries its own `checksState`, so `checks` is judged the way `review` is: by
+ * equality against the row's field. Unlike `review`, `checks` has no `"none"` value to catch an
+ * absent state on purpose — a row with no checks configured, or whose checks are still `pending`,
+ * equals neither `"passing"` nor `"failing"` and so fails both, the same as a row search would
+ * not have surfaced for `status:success` or `status:failure`.
+ */
+function matchesFilters(
+ item: GitHubPullRequestListItem,
+ filters: PullRequestListFilters | undefined,
+ 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());
+ return (
+ (filters.draft === undefined || item.isDraft === (filters.draft === "only")) &&
+ (filters.review === undefined ||
+ (filters.review === "none"
+ ? item.reviewDecision === null
+ : item.reviewDecision === filters.review)) &&
+ (filters.checks === undefined || item.checksState === filters.checks) &&
+ (filters.labels === undefined || filters.labels.every((group) => group.some(holds))) &&
+ (filters.excludedLabels === undefined || !filters.excludedLabels.some(holds)) &&
+ (filters.author === undefined ||
+ item.author?.login.toLowerCase() ===
+ resolvePullRequestAuthorFilter(filters.author, viewer).toLowerCase())
+ );
+}
+
function involvementArgs(input: {
readonly state: PullRequestListState;
readonly involvement: PullRequestInvolvement;
@@ -513,6 +684,7 @@ function involvementArgs(input: {
* cannot use search at all and takes whatever order `gh pr list` answers in.
*/
readonly sorted: boolean;
+ readonly filters?: PullRequestListFilters | undefined;
}): ReadonlyArray<string> {
// `--state closed` includes merged pull requests, so the Closed tab additionally excludes
// them through search; `--author` and `review-requested:` are GitHub's own filters. `gh`
@@ -531,6 +703,7 @@ function involvementArgs(input: {
// sharing one instant are ordinary and the caller drops the ones it has already sent —
// asking for strictly older would lose the rest of them instead.
...(input.cursor === undefined ? [] : [`updated:<=${input.cursor.updatedBefore}`]),
+ ...filterQualifiers(input.filters, input.viewer),
// `gh pr list` answers newest-created first, which is not the order the page reads rows in
// and not an order a continuation can carry on from: a change request opened last year and
// touched this morning belongs at the top of the list and at the front of the first slice.
@@ -550,6 +723,7 @@ function matchesUnsortedListing(
readonly state: PullRequestListState;
readonly involvement: PullRequestInvolvement;
readonly viewer: string;
+ readonly filters?: PullRequestListFilters | undefined;
},
): boolean {
const matchesState = input.state === "all" || item.state === input.state;
@@ -560,7 +734,7 @@ function matchesUnsortedListing(
? item.author?.login.toLowerCase() === viewer
: item.hasTeamReviewRequest ||
item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer));
- return matchesState && matchesInvolvement;
+ return matchesState && matchesInvolvement && matchesFilters(item, input.filters, input.viewer);
}
/** What a repository selector may hold before it goes into a search as itself. */
@@ -587,6 +761,7 @@ function searchQuery(input: {
readonly viewer: string;
readonly query?: string | undefined;
readonly cursor?: ProviderListCursor | undefined;
+ readonly filters?: PullRequestListFilters | undefined;
}): string | null {
if (input.repositories.length === 0) return null;
const repositories = input.repositories.map((repository) => repository.trim());
@@ -603,6 +778,7 @@ function searchQuery(input: {
...(query.length === 0 ? [] : [searchPhrase(query)]),
// Inclusive, and de-duplicated by the caller, for the reason the per-repository read gives.
...(input.cursor === undefined ? [] : [`updated:<=${input.cursor.updatedBefore}`]),
+ ...filterQualifiers(input.filters, input.viewer),
// The order the page reads its rows in, and the only order a continuation can carry on from.
"sort:updated-desc",
...repositories.map((repository) => `repo:${repository}`),
@@ -621,10 +797,20 @@ function cursorVariable(cursor: string | null): readonly [string, string] {
function actionArgs(
action: PullRequestAction,
mergeMethod: PullRequestMergeMethod | undefined,
+ updateMethod: PullRequestUpdateMethod | undefined,
): ReadonlyArray<string> {
switch (action) {
case "merge":
return ["merge", `--${mergeMethod ?? "merge"}`];
+ // `--auto` arms the same command instead of running it, and still needs the strategy: GitHub
+ // stores the strategy with the standing instruction rather than choosing one at merge time.
+ case "enable-auto-merge":
+ return ["merge", "--auto", `--${mergeMethod ?? "merge"}`];
+ case "disable-auto-merge":
+ return ["merge", "--disable-auto"];
+ // `gh` updates with a merge commit unless asked to rebase, which is GitHub's own default.
+ case "update-branch":
+ return ["update-branch", ...(updateMethod === "rebase" ? ["--rebase"] : [])];
case "ready":
return ["ready"];
case "draft":
@@ -639,6 +825,62 @@ function actionArgs(
export const make = Effect.gen(function* () {
const github = yield* GitHubCli.GitHubCli;
+ /**
+ * The pull request's own node id, which is what a mutation against the pull request itself is
+ * addressed by: a reaction on its description, or a rewrite of its words.
+ */
+ const pullRequestNodeId = (input: {
+ readonly cwd: string;
+ readonly repository: string;
+ readonly host: string;
+ readonly number: number;
+ readonly operation: string;
+ }) => {
+ const { owner, name } = parseRepositorySelector(input.repository);
+ return graphqlRead({
+ cwd: input.cwd,
+ host: input.host,
+ operation: input.operation,
+ variables: [
+ ["-f", `owner=${owner}`],
+ ["-f", `name=${name}`],
+ ["-F", `number=${input.number}`],
+ ],
+ query: PULL_REQUEST_NODE_ID_GRAPHQL_QUERY,
+ decode: decodePullRequestNodeIdJson,
+ });
+ };
+
+ /**
+ * Whether a client-given subject actually belongs to the pull request the request names. A
+ * subject id is trusted to be whatever node it names, and that node can hang off any pull
+ * request on the host — so the mutation itself would write wherever the id actually belongs,
+ * not wherever the request says it does, unless this confirms the two agree first.
+ */
+ const subjectBelongsToPullRequest = (input: {
+ readonly cwd: string;
+ readonly repository: string;
+ readonly host: string;
+ readonly number: number;
+ readonly subjectId: string;
+ readonly operation: string;
+ }) => {
+ const { owner, name } = parseRepositorySelector(input.repository);
+ return graphqlRead({
+ cwd: input.cwd,
+ host: input.host,
+ operation: input.operation,
+ variables: [
+ ["-f", `owner=${owner}`],
+ ["-f", `name=${name}`],
+ ["-F", `number=${input.number}`],
+ ["-f", `subjectId=${input.subjectId}`],
+ ],
+ query: REACTION_SUBJECT_PULL_REQUEST_GRAPHQL_QUERY,
+ decode: decodeReactionSubjectScopeJson,
+ });
+ };
+
// `gh` resolves a bare `owner/repo` against whichever host it defaults to, which is
// github.com. Naming the host makes a GitHub Enterprise repository resolve to its own
// install rather than to a same-named repository on github.com.
@@ -796,6 +1038,9 @@ export const make = Effect.gen(function* () {
patch: decoded.success.patch,
truncated: decoded.success.truncated,
nextCursor: morePages ? String(input.page + 1) : null,
+ ...(decoded.success.omittedFileStats.length === 0
+ ? {}
+ : { omittedFileStats: decoded.success.omittedFileStats }),
});
}),
);
@@ -977,10 +1222,15 @@ export const make = Effect.gen(function* () {
// repository's whole list, which is every row the reader did not search for. The fallback
// is for a repository the index does not cover, and a listing with no text to match is the
// only place an empty answer can mean that.
- const searched = (input.query?.trim().length ?? 0) > 0;
+ // Every filter is a qualifier `matchesFilters` can judge over the fallback's own rows just
+ // as well as search judges them over its own, so carrying them into the fallback answers
+ // the same read rather than a wider one. Free text is the one thing the fallback cannot
+ // judge locally — it lists rows, it does not search their text — so a query still rules
+ // the fallback out: an empty answer under one is already the answer.
+ const hasQuery = (input.query?.trim().length ?? 0) > 0;
return read(true).pipe(
Effect.flatMap((batch) =>
- batch.items.length === 0 && input.cursor === undefined && !searched
+ batch.items.length === 0 && input.cursor === undefined && !hasQuery
? read(false)
: Effect.succeed(batch),
),
@@ -1085,6 +1335,23 @@ export const make = Effect.gen(function* () {
}),
),
+ getPullRequestBaseComparison: (input) => {
+ const { owner, name } = parseRepositorySelector(input.repository);
+ return graphqlRead({
+ cwd: input.cwd,
+ host: input.host,
+ operation: "getPullRequestBaseComparison",
+ variables: [
+ ["-f", `owner=${owner}`],
+ ["-f", `name=${name}`],
+ ["-F", `number=${input.number}`],
+ ["-f", `headRef=${input.headRef}`],
+ ],
+ query: BASE_COMPARISON_GRAPHQL_QUERY,
+ decode: decodeBaseComparisonJson,
+ });
+ },
+
getPullRequestActivity: (input) =>
github
.execute({
@@ -1216,8 +1483,12 @@ export const make = Effect.gen(function* () {
{ readonly additions: number; readonly deletions: number }
>();
let reviewers: ReadonlyArray<PullRequestActor> = [];
+ let reactions: GitHubReviewThreadPage["reactions"] = [];
+ const reactionsById = new Map<string, ReadonlyArray<PullRequestReaction>>();
let commits: GitHubReviewThreadPage["commits"] = [];
let viewer: GitHubReviewThreadPage["viewer"] = { canUpdate: true, didAuthor: false };
+ const dismissalsByReviewId = new Map<string, string>();
+ let dismissalCursor: string | null = null;
let cursor: string | null = null;
let page = 0;
do {
@@ -1229,14 +1500,46 @@ export const make = Effect.gen(function* () {
// first one already carries all of them.
if (page === 0) {
reviewers = read.reviewers;
+ reactions = read.reactions;
+ for (const [id, entry] of read.reactionsById) reactionsById.set(id, entry);
commits = read.commits;
viewer = read.viewer;
+ for (const [id, message] of read.dismissalsByReviewId)
+ dismissalsByReviewId.set(id, message);
+ dismissalCursor = read.nextDismissalCursor;
for (const [oid, stat] of read.commitStats) commitStats.set(oid, stat);
}
cursor = read.nextCursor;
page += 1;
} while (cursor !== null && page < REVIEW_THREAD_PAGES);
+ // Almost never entered: the embedded page already holds every dismissal a pull request
+ // ordinarily accrues. Followed so a review whose event fell past that page still finds
+ // its reason.
+ let dismissalPage = 0;
+ while (dismissalCursor !== null && dismissalPage < REVIEW_THREAD_PAGES) {
+ const read: {
+ readonly dismissalsByReviewId: ReadonlyMap<string, string>;
+ readonly nextCursor: string | null;
+ } = yield* graphqlRead({
+ cwd: input.cwd,
+ host: input.host,
+ operation: "listReviewThreadComments",
+ variables: [
+ ["-f", `owner=${owner}`],
+ ["-f", `name=${name}`],
+ ["-F", `number=${input.number}`],
+ ["-f", `cursor=${dismissalCursor}`],
+ ],
+ query: REVIEW_DISMISSALS_GRAPHQL_QUERY,
+ decode: decodeReviewDismissalsJson,
+ });
+ for (const [id, message] of read.dismissalsByReviewId)
+ dismissalsByReviewId.set(id, message);
+ dismissalCursor = read.nextCursor;
+ dismissalPage += 1;
+ }
+
// Only the threads GitHub said were unfinished cost a request; the rest arrived whole
// with the page they were listed on.
const finished = yield* Effect.forEach(
@@ -1264,11 +1567,14 @@ export const make = Effect.gen(function* () {
const reviewThreads = finished.map((entry) => entry.thread);
return {
comments: reviewThreadConversation(reviewThreads),
+ dismissalsByReviewId,
reviewThreads,
// GitHub's own count of each thread, so the number the page shows is the host's even
// where a bound kept some of the words on GitHub.
commentCount: finished.reduce((total, entry) => total + entry.commentCount, 0),
truncated: cursor !== null || finished.some((entry) => entry.truncated),
+ reactions,
+ reactionsById,
reviewers,
avatarsByLogin,
commitStats,
@@ -1396,7 +1702,11 @@ export const make = Effect.gen(function* () {
},
runPullRequestAction: (input) => {
- const [subcommand, ...flags] = actionArgs(input.action, input.mergeMethod);
+ const [subcommand, ...flags] = actionArgs(
+ input.action,
+ input.mergeMethod,
+ input.updateMethod,
+ );
return github
.execute({
cwd: input.cwd,
@@ -1467,6 +1777,91 @@ export const make = Effect.gen(function* () {
: UNRESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION,
variables: { threadId: input.threadId },
}),
+
+ setReaction: (input) => {
+ const givenSubjectId = input.subjectId;
+ const subjectId =
+ givenSubjectId === undefined
+ ? pullRequestNodeId({ ...input, operation: "setReaction" })
+ : subjectBelongsToPullRequest({
+ ...input,
+ subjectId: givenSubjectId,
+ operation: "setReaction",
+ }).pipe(
+ Effect.flatMap((belongs) =>
+ belongs
+ ? Effect.succeed(givenSubjectId)
+ : Effect.fail(
+ new GitHubSubjectScopeError({
+ command: "gh",
+ cwd: input.cwd,
+ operation: "setReaction",
+ }),
+ ),
+ ),
+ );
+ return subjectId.pipe(
+ Effect.flatMap((subjectId) =>
+ graphql({
+ cwd: input.cwd,
+ host: input.host,
+ query: input.reacted ? ADD_REACTION_GRAPHQL_MUTATION : REMOVE_REACTION_GRAPHQL_MUTATION,
+ variables: { subjectId, content: gitHubReactionContent(input.content) },
+ }),
+ ),
+ );
+ },
+
+ updatePullRequest: (input) =>
+ pullRequestNodeId({ ...input, operation: "updatePullRequest" }).pipe(
+ Effect.flatMap((pullRequestId) =>
+ graphql({
+ cwd: input.cwd,
+ host: input.host,
+ query: UPDATE_PULL_REQUEST_GRAPHQL_MUTATION,
+ // A field the caller did not name is left out of the request entirely, so GitHub
+ // keeps the words that are there rather than being asked for an empty one.
+ variables: {
+ pullRequestId,
+ ...(input.title === undefined ? {} : { title: input.title }),
+ ...(input.body === undefined ? {} : { body: input.body }),
+ },
+ }),
+ ),
+ ),
+
+ updateComment: (input) =>
+ subjectBelongsToPullRequest({
+ cwd: input.cwd,
+ repository: input.repository,
+ host: input.host,
+ number: input.number,
+ subjectId: input.commentId,
+ operation: "updateComment",
+ }).pipe(
+ Effect.flatMap((belongs) =>
+ belongs
+ ? Effect.succeed(input.commentId)
+ : Effect.fail(
+ new GitHubSubjectScopeError({
+ command: "gh",
+ cwd: input.cwd,
+ operation: "updateComment",
+ }),
+ ),
+ ),
+ Effect.flatMap((commentId) =>
+ graphql({
+ cwd: input.cwd,
+ host: input.host,
+ query:
+ input.kind === "issue-comment"
+ ? UPDATE_ISSUE_COMMENT_GRAPHQL_MUTATION
+ : UPDATE_REVIEW_COMMENT_GRAPHQL_MUTATION,
+ variables: { commentId, body: input.body },
+ }),
+ ),
+ ),
});
});
diff --git a/apps/server/src/pullRequest/GitHubPullRequestProvider.test.ts b/apps/server/src/pullRequest/GitHubPullRequestProvider.test.ts
index 453ac31df..13098ce38 100644
--- a/apps/server/src/pullRequest/GitHubPullRequestProvider.test.ts
+++ b/apps/server/src/pullRequest/GitHubPullRequestProvider.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
+import type { PullRequestReaction } from "@t3tools/contracts";
import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
import { gitHubViewerPermissions, loginAvatarUrl, make } from "./GitHubPullRequestProvider.ts";
@@ -9,7 +10,16 @@ import type { GitHubReviewThreadComments } from "./gitHubPullRequestJson.ts";
describe("gitHubViewerPermissions", () => {
it("offers everything to a viewer who can write to the repository", () => {
expect(gitHubViewerPermissions({ canWrite: true, canUpdate: true, didAuthor: false })).toEqual({
- actions: ["merge", "ready", "draft", "close", "reopen"],
+ // Arming a merge for later is the merge, so it travels with it.
+ actions: [
+ "merge",
+ "enable-auto-merge",
+ "disable-auto-merge",
+ "ready",
+ "draft",
+ "close",
+ "reopen",
+ ],
comment: true,
resolve: true,
verdicts: ["comment", "approve", "request-changes"],
@@ -34,7 +44,7 @@ describe("gitHubViewerPermissions", () => {
it("keeps an author's own pull request theirs to close, with read access and no more", () => {
expect(gitHubViewerPermissions({ canWrite: false, canUpdate: true, didAuthor: true })).toEqual({
- // Merging is the one thing writing is needed for; the rest an author may do.
+ // Merging is the one thing writing is needed for, now or later; the rest an author may do.
actions: ["ready", "draft", "close", "reopen"],
comment: true,
resolve: true,
@@ -71,17 +81,20 @@ describe("gitHubViewerPermissions", () => {
title: "Pull request 7",
url: "https://github.com/acme/web/pull/7",
author: null,
+ headRepositoryOwner: null,
headBranch: "feat/page",
baseBranch: "main",
state: "open",
isDraft: false,
mergeability: "mergeable",
+ reviewDecision: null,
additions: 1,
deletions: 1,
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
reviewRequestLogins: [],
hasTeamReviewRequest: false,
+ checksState: null,
labels: [],
body: "",
changedFiles: 1,
@@ -104,6 +117,101 @@ describe("gitHubViewerPermissions", () => {
);
});
+describe("getViewerPermissions", () => {
+ const openDetail = {
+ authorId: null,
+ number: 7,
+ title: "Pull request 7",
+ url: "https://github.com/acme/web/pull/7",
+ author: null,
+ headRepositoryOwner: "acme",
+ headBranch: "feat/page",
+ baseBranch: "main",
+ state: "open" as const,
+ isDraft: false,
+ mergeability: "mergeable" as const,
+ reviewDecision: null,
+ additions: 1,
+ deletions: 1,
+ createdAt: "2026-07-01T00:00:00Z",
+ updatedAt: "2026-07-02T00:00:00Z",
+ reviewRequestLogins: [],
+ hasTeamReviewRequest: false,
+ checksState: null,
+ labels: [],
+ body: "",
+ changedFiles: 1,
+ mergedAt: null,
+ closedAt: null,
+ checks: [],
+ comments: [],
+ commits: [],
+ };
+
+ const layerWithComparison = (
+ comparison: Effect.Effect<{
+ readonly behindBy: number | null;
+ readonly viewerCanUpdate: boolean;
+ }>,
+ ) =>
+ Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
+ getPullRequestDetail: () => Effect.succeed(openDetail),
+ getPullRequestBaseComparison: () => comparison,
+ getViewerAccess: () => Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
+ });
+
+ it.effect("offers update-branch when the comparison grants it", () =>
+ Effect.gen(function* () {
+ const provider = yield* make;
+ const permissions = yield* provider.getViewerPermissions({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ });
+
+ expect(permissions.actions).toContain("update-branch");
+ expect(permissions.updateMethods).toEqual(["merge", "rebase"]);
+ }).pipe(
+ Effect.provide(layerWithComparison(Effect.succeed({ behindBy: 3, viewerCanUpdate: true }))),
+ ),
+ );
+
+ it.effect("withholds update-branch when the comparison cannot be read", () =>
+ Effect.gen(function* () {
+ const provider = yield* make;
+ const permissions = yield* provider.getViewerPermissions({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ });
+
+ expect(permissions.actions).not.toContain("update-branch");
+ expect(permissions.updateMethods).toBeUndefined();
+ // The rest of the answer survives a comparison nobody could make.
+ expect(permissions.actions).toContain("merge");
+ }).pipe(
+ Effect.provide(
+ Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
+ getPullRequestDetail: () => Effect.succeed(openDetail),
+ getPullRequestBaseComparison: () =>
+ Effect.fail(
+ new GitHubPullRequestCli.GitHubPullRequestReadError({
+ command: "gh",
+ cwd: "/w",
+ operation: "getPullRequestBaseComparison",
+ cause: new Error("unreadable"),
+ }),
+ ),
+ getViewerAccess: () =>
+ Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
+ }),
+ ),
+ ),
+ );
+});
+
describe("getChangeRequest commits", () => {
const baseDetail = {
authorId: null,
@@ -122,6 +230,7 @@ describe("getChangeRequest commits", () => {
updatedAt: "2026-07-02T00:00:00Z",
reviewRequestLogins: [],
hasTeamReviewRequest: false,
+ checksState: null,
labels: [],
body: "",
changedFiles: 1,
@@ -133,9 +242,12 @@ describe("getChangeRequest commits", () => {
const baseThreadComments = {
comments: [],
+ dismissalsByReviewId: new Map<string, string>(),
reviewThreads: [],
commentCount: 0,
truncated: false,
+ reactions: [],
+ reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
reviewers: [],
avatarsByLogin: new Map<string, string>(),
commitStats: new Map<string, { readonly additions: number; readonly deletions: number }>(),
@@ -200,6 +312,122 @@ describe("getChangeRequest commits", () => {
);
});
+describe("getChangeRequestActivity dismissed reviews", () => {
+ const dismissedReview = (body: string) => ({
+ id: "PRR_1",
+ kind: "review" as const,
+ author: null,
+ body,
+ createdAt: "2026-07-03T00:00:00Z",
+ url: null,
+ path: null,
+ reviewState: "DISMISSED",
+ });
+ const threadComments: GitHubReviewThreadComments = {
+ comments: [],
+ dismissalsByReviewId: new Map([["PRR_1", "Dismissing prior approval to re-evaluate 9b66581"]]),
+ reviewThreads: [],
+ commentCount: 0,
+ truncated: false,
+ reactions: [],
+ reactionsById: new Map(),
+ reviewers: [],
+ avatarsByLogin: new Map(),
+ commitStats: new Map(),
+ commits: [],
+ viewer: { canUpdate: true, didAuthor: false },
+ };
+ const layerFor = (body: string) =>
+ Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
+ getPullRequestActivity: () =>
+ Effect.succeed({ author: null, comments: [dismissedReview(body)], commits: [] }),
+ listReviewThreadComments: () => Effect.succeed(threadComments),
+ });
+ const readActivity = Effect.gen(function* () {
+ const provider = yield* make;
+ return yield* provider.getChangeRequestActivity({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ });
+ });
+
+ it.effect("fills a marker-only dismissed review with the timeline's reason", () =>
+ // Macroscope's approvals carry only an HTML comment, which markdown renders as nothing —
+ // an empty-string check misses them and the card opens onto nothing.
+ readActivity.pipe(
+ Effect.map((activity) => {
+ expect(activity.comments[0]?.body).toBe("Dismissing prior approval to re-evaluate 9b66581");
+ }),
+ Effect.provide(layerFor("<!-- Macroscope (Approvability) review body marker -->")),
+ ),
+ );
+
+ it.effect("keeps the words of a dismissed review that has its own", () =>
+ readActivity.pipe(
+ Effect.map((activity) => {
+ expect(activity.comments[0]?.body).toBe("These findings still stand.");
+ }),
+ Effect.provide(layerFor("These findings still stand.")),
+ ),
+ );
+});
+
+describe("editing", () => {
+ const rewrites: Array<unknown> = [];
+
+ it.effect("hands a rewrite to the CLI as the request named it", () =>
+ Effect.gen(function* () {
+ const provider = yield* make;
+
+ expect(provider.capabilities.edit).toEqual({ changeRequest: true, comment: true });
+ yield* provider.updateChangeRequest!({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ title: "A better title",
+ });
+ yield* provider.updateComment!({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ commentId: "IC_1",
+ kind: "review-comment",
+ body: "Reworded.",
+ });
+
+ expect(rewrites).toEqual([
+ {
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ title: "A better title",
+ },
+ {
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ commentId: "IC_1",
+ kind: "review-comment",
+ body: "Reworded.",
+ },
+ ]);
+ }).pipe(
+ Effect.provide(
+ Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
+ updatePullRequest: (input) => Effect.sync(() => void rewrites.push(input)),
+ updateComment: (input) => Effect.sync(() => void rewrites.push(input)),
+ }),
+ ),
+ ),
+ );
+});
+
describe("loginAvatarUrl", () => {
it("serves a user's picture from the host they belong to", () => {
expect(loginAvatarUrl("octocat", "github.com")).toBe("https://github.com/octocat.png?size=80");
diff --git a/apps/server/src/pullRequest/GitHubPullRequestProvider.ts b/apps/server/src/pullRequest/GitHubPullRequestProvider.ts
index b77c20a54..57d18e8ab 100644
--- a/apps/server/src/pullRequest/GitHubPullRequestProvider.ts
+++ b/apps/server/src/pullRequest/GitHubPullRequestProvider.ts
@@ -2,6 +2,7 @@ import * as Effect from "effect/Effect";
import type {
PullRequestActor,
PullRequestCapabilities,
+ PullRequestReaction,
PullRequestViewerPermissions,
} from "@t3tools/contracts";
@@ -17,9 +18,20 @@ import type { GitHubViewerAccess } from "./gitHubPullRequestJson.ts";
const CAPABILITIES: PullRequestCapabilities = {
diff: true,
comment: true,
- actions: ["merge", "ready", "draft", "close", "reopen"],
+ actions: [
+ "merge",
+ "ready",
+ "draft",
+ "close",
+ "reopen",
+ "update-branch",
+ "enable-auto-merge",
+ "disable-auto-merge",
+ ],
mergeMethods: ["merge", "squash", "rebase"],
+ updateMethods: ["merge", "rebase"],
search: true,
+ reactions: true,
review: {
inlineComment: true,
reply: true,
@@ -27,6 +39,7 @@ const CAPABILITIES: PullRequestCapabilities = {
verdicts: ["comment", "approve", "request-changes"],
},
reviewers: { request: true, listCandidates: true },
+ edit: { changeRequest: true, comment: true },
};
/**
@@ -49,8 +62,13 @@ const CAPABILITIES: PullRequestCapabilities = {
export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequestViewerPermissions {
return {
actions: [
- ...(access.canWrite ? (["merge"] as const) : []),
+ // Arming a merge and taking the arming back are the merge, deferred: whoever may not
+ // merge here may not leave an instruction to merge later either.
+ ...(access.canWrite ? (["merge", "enable-auto-merge", "disable-auto-merge"] as const) : []),
...(access.canUpdate ? (["ready", "draft", "close", "reopen"] as const) : []),
+ // Whether this viewer may update the branch is GitHub's own answer, read with the
+ // comparison; without it the action is offered to nobody rather than to everybody.
+ ...(access.canUpdateBranch === true ? (["update-branch"] as const) : []),
],
comment: true,
resolve: access.canWrite || access.didAuthor,
@@ -59,6 +77,7 @@ export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequest
// leaves them commenting, which is what an author has to say about their own change anyway.
verdicts: access.didAuthor ? (["comment"] as const) : CAPABILITIES.review.verdicts,
requestReviewers: access.canWrite,
+ ...(access.canUpdateBranch === true ? { updateMethods: CAPABILITIES.updateMethods } : {}),
};
}
@@ -98,6 +117,10 @@ export function loginAvatarUrl(login: string, host: string): string | null {
return /^[a-z0-9][a-z0-9-]{0,38}$/iu.test(login) ? `https://${host}/${login}.png?size=80` : null;
}
+/** True where markdown would render nothing: whitespace, or only HTML comments. */
+const rendersEmpty = (body: string): boolean =>
+ body.replace(/<!--[\s\S]*?-->/g, "").trim().length === 0;
+
export const make = Effect.gen(function* () {
const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
@@ -129,6 +152,7 @@ export const make = Effect.gen(function* () {
limit: input.limit,
query: input.query,
cursor: input.cursor,
+ filters: input.filters,
})
.pipe(
Effect.mapError(fail("listChangeRequests")),
@@ -172,6 +196,7 @@ export const make = Effect.gen(function* () {
limit: input.limit,
query: input.query,
cursor: input.cursor,
+ filters: input.filters,
})
.pipe(
Effect.mapError(fail("listChangeRequestsAcross")),
@@ -196,7 +221,24 @@ export const make = Effect.gen(function* () {
getChangeRequest: (input) =>
Effect.all(
[
- cli.getPullRequestDetail(input),
+ cli.getPullRequestDetail(input).pipe(
+ Effect.flatMap((pullRequest) =>
+ // Only an open pull request can be behind anything worth saying so about, and only
+ // one whose head repository is known can be compared at all. A comparison that
+ // fails is left unknown: the banner is an offer, never a blocker.
+ pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null
+ ? Effect.succeed({ pullRequest, comparison: null })
+ : cli
+ .getPullRequestBaseComparison({
+ ...input,
+ headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,
+ })
+ .pipe(
+ Effect.map((comparison) => ({ pullRequest, comparison })),
+ Effect.orElseSucceed(() => ({ pullRequest, comparison: null })),
+ ),
+ ),
+ ),
cli.getRepositoryAccess({
cwd: input.cwd,
repository: input.repository,
@@ -210,15 +252,27 @@ export const make = Effect.gen(function* () {
).pipe(
Effect.mapError(fail("getChangeRequest")),
Effect.map(
- ([pullRequest, repository, viewerAccess]): ProviderChangeRequestDetail => ({
- ...pullRequest,
- reviewers: pullRequest.reviewRequestLogins.map((login) => ({
+ ([detail, repository, viewerAccess]): ProviderChangeRequestDetail => ({
+ ...detail.pullRequest,
+ reviewers: detail.pullRequest.reviewRequestLogins.map((login) => ({
login,
name: null,
avatarUrl: null,
})),
mergeCapabilities: repository.mergeCapabilities,
- viewerPermissions: gitHubViewerPermissions(viewerAccess),
+ viewerPermissions: gitHubViewerPermissions({
+ ...viewerAccess,
+ canUpdateBranch: detail.comparison?.viewerCanUpdate === true,
+ }),
+ baseComparison:
+ detail.comparison === null || detail.comparison.behindBy === null
+ ? "unknown"
+ : detail.comparison.behindBy > 0
+ ? "behind"
+ : "up-to-date",
+ ...(detail.comparison?.behindBy == null
+ ? {}
+ : { behindBy: detail.comparison.behindBy }),
}),
),
),
@@ -232,6 +286,9 @@ export const make = Effect.gen(function* () {
cli.listReviewThreadComments(input).pipe(
Effect.orElseSucceed(() => ({
comments: [],
+ dismissalsByReviewId: new Map<string, string>(),
+ reactions: [],
+ reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
reviewThreads: [],
commentCount: 0,
truncated: true,
@@ -253,6 +310,7 @@ export const make = Effect.gen(function* () {
([pullRequest, reviewThreads]): ProviderChangeRequestActivity => ({
author: withAvatar(pullRequest.author, reviewThreads.avatarsByLogin, input.host),
reviewers: reviewThreads.reviewers,
+ reactions: reviewThreads.reactions,
commits: (reviewThreads.commits.length > 0
? reviewThreads.commits
: pullRequest.commits
@@ -266,7 +324,20 @@ export const make = Effect.gen(function* () {
comments: [...pullRequest.comments, ...reviewThreads.comments]
.map((comment) => ({
...comment,
+ // GitHub keeps the dismissal reason on the timeline event, not on the review,
+ // so a dismissed review with nothing visible of its own reads its words from
+ // there. "Visible" and not "empty": bot reviews often carry only an HTML
+ // marker comment, which markdown renders as nothing.
+ body:
+ comment.kind === "review" &&
+ comment.reviewState?.toUpperCase() === "DISMISSED" &&
+ rendersEmpty(comment.body)
+ ? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
+ : comment.body,
author: withAvatar(comment.author, reviewThreads.avatarsByLogin, input.host),
+ // A comment out of `gh pr view --json` carries none of its own: that read
+ // reports no reaction at all, so they arrive from the GraphQL page by node id.
+ reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
}))
.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
// `gh pr view --json comments,reviews` follows GitHub's cursors itself, so those two
@@ -285,9 +356,34 @@ export const make = Effect.gen(function* () {
),
getViewerPermissions: (input) =>
- cli
- .getViewerAccess(input)
- .pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitHubViewerPermissions)),
+ Effect.all(
+ [
+ cli.getViewerAccess(input),
+ // Whether this viewer may update the branch is only on the comparison, and the
+ // comparison only resolves through the head ref the detail carries. A failure here
+ // withholds that one action rather than the whole answer, the way the detail path
+ // leaves the banner unknown.
+ cli.getPullRequestDetail(input).pipe(
+ Effect.flatMap((pullRequest) =>
+ pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null
+ ? Effect.succeed(false)
+ : cli
+ .getPullRequestBaseComparison({
+ ...input,
+ headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,
+ })
+ .pipe(Effect.map((comparison) => comparison.viewerCanUpdate === true)),
+ ),
+ Effect.orElseSucceed(() => false),
+ ),
+ ],
+ { concurrency: 2 },
+ ).pipe(
+ Effect.mapError(fail("getViewerPermissions")),
+ Effect.map(([access, canUpdateBranch]) =>
+ gitHubViewerPermissions({ ...access, canUpdateBranch }),
+ ),
+ ),
getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
@@ -318,11 +414,37 @@ export const make = Effect.gen(function* () {
number: input.number,
action: input.action,
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
+ ...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
})
.pipe(Effect.mapError(fail("runAction"))),
+ updateChangeRequest: (input) =>
+ cli
+ .updatePullRequest({
+ cwd: input.cwd,
+ repository: input.repository,
+ host: input.host,
+ number: input.number,
+ ...(input.title === undefined ? {} : { title: input.title }),
+ ...(input.body === undefined ? {} : { body: input.body }),
+ })
+ .pipe(Effect.mapError(fail("updateChangeRequest"))),
+
comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
+ updateComment: (input) =>
+ cli
+ .updateComment({
+ cwd: input.cwd,
+ repository: input.repository,
+ host: input.host,
+ number: input.number,
+ commentId: input.commentId,
+ kind: input.kind,
+ body: input.body,
+ })
+ .pipe(Effect.mapError(fail("updateComment"))),
+
submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
replyToThread: (input) =>
@@ -336,6 +458,19 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("replyToThread"))),
+ setReaction: (input) =>
+ cli
+ .setReaction({
+ cwd: input.cwd,
+ repository: input.repository,
+ host: input.host,
+ number: input.number,
+ ...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
+ content: input.content,
+ reacted: input.reacted,
+ })
+ .pipe(Effect.mapError(fail("setReaction"))),
+
setThreadResolution: (input) =>
cli
.setReviewThreadResolution({
diff --git a/apps/server/src/pullRequest/GitLabPullRequestCli.test.ts b/apps/server/src/pullRequest/GitLabPullRequestCli.test.ts
index 9bfad2648..c33e01c2d 100644
--- a/apps/server/src/pullRequest/GitLabPullRequestCli.test.ts
+++ b/apps/server/src/pullRequest/GitLabPullRequestCli.test.ts
@@ -414,6 +414,69 @@ layer("GitLabPullRequestCli.layer", (it) => {
}),
);
+ it.effect("arms auto-merge with the same strategy a merge would have used", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output("")));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.runMergeRequestAction({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ action: "enable-auto-merge",
+ mergeMethod: "squash",
+ });
+
+ expect(argsOfCall(0)).toEqual([
+ "mr",
+ "merge",
+ "7",
+ "--repo",
+ "acme/web",
+ "--auto-merge=true",
+ "--yes",
+ "--squash",
+ ]);
+ }),
+ );
+
+ it.effect("cancels an armed auto-merge through the API glab has no flag for", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.runMergeRequestAction({
+ cwd: "/w",
+ repository: "acme/platform/web",
+ number: 7,
+ action: "disable-auto-merge",
+ });
+
+ expect(argsOfCall(0)).toEqual([
+ "api",
+ "projects/acme%2Fplatform%2Fweb/merge_requests/7/cancel_merge_when_pipeline_succeeds",
+ "--method",
+ "POST",
+ ]);
+ }),
+ );
+
+ it.effect("brings a stale branch up to date by rebasing it, the only way GitLab has", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output("")));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.runMergeRequestAction({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ action: "update-branch",
+ });
+
+ expect(argsOfCall(0)).toEqual(["mr", "rebase", "7", "--repo", "acme/web"]);
+ }),
+ );
+
it.effect("moves a merge request back to draft through glab", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("")));
@@ -791,6 +854,21 @@ layer("GitLabPullRequestCli.layer", (it) => {
}),
);
+ it.effect("asks the detail read for the divergence GitLab withholds by default", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output('{"message":"404 Not Found"}')));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* Effect.ignore(
+ cli.getMergeRequestDetail({ cwd: "/w", repository: "acme/web", number: 7 }),
+ );
+
+ expect(argsOfCall(0)[1]).toBe(
+ "projects/acme%2Fweb/merge_requests/7?include_diverged_commits_count=true",
+ );
+ }),
+ );
+
it.effect("fails the read when GitLab returns something unreadable", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output('{"message":"404 Not Found"}')));
@@ -1008,6 +1086,89 @@ layer("GitLabPullRequestCli.layer", (it) => {
}),
);
+ it.effect("awards an emoji through a POST naming it, not a body", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.setReaction({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ content: "thumbs-up",
+ reacted: true,
+ });
+
+ assert.strictEqual(mockedExecute.mock.calls.length, 1);
+ expect(argsOfCall(0)).toEqual([
+ "api",
+ "projects/acme%2Fweb/merge_requests/7/award_emoji?name=thumbsup",
+ "--method",
+ "POST",
+ ]);
+ }),
+ );
+
+ it.effect("removes an award by listing them and deleting the reader's own id", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ Effect.succeed(output(JSON.stringify({ username: "bilal" }))),
+ );
+ mockedExecute.mockReturnValueOnce(
+ Effect.succeed(
+ output(
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ JSON.stringify([
+ { id: 5, name: "thumbsup", user: { username: "bilal" } },
+ { id: 6, name: "thumbsup", user: { username: "julius" } },
+ ]),
+ ),
+ ),
+ );
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.setReaction({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ content: "thumbs-up",
+ reacted: false,
+ });
+
+ assert.strictEqual(mockedExecute.mock.calls.length, 3);
+ expect(argsOfCall(2)).toEqual([
+ "api",
+ "projects/acme%2Fweb/merge_requests/7/award_emoji/5",
+ "--method",
+ "DELETE",
+ ]);
+ }),
+ );
+
+ it.effect("does nothing when the reader has no award of that name to take back", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ Effect.succeed(output(JSON.stringify({ username: "bilal" }))),
+ );
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.setReaction({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ content: "thumbs-up",
+ reacted: false,
+ });
+
+ // Nothing to delete: the reaction the caller asked to take back is already gone.
+ assert.strictEqual(mockedExecute.mock.calls.length, 2);
+ }),
+ );
+
it.effect("names a merge request with no diff revisions rather than calling it unreadable", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(
@@ -1141,4 +1302,99 @@ layer("GitLabPullRequestCli.layer", (it) => {
expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({ reviewer_ids: [5] });
}),
);
+
+ it.effect("rewrites a title without touching the description", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.updateMergeRequest({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ title: "A better title",
+ });
+
+ expect(argsOfCall(0)).toEqual([
+ "api",
+ "projects/acme%2Fweb/merge_requests/7",
+ "--method",
+ "PUT",
+ "--input",
+ "-",
+ "--header",
+ "Content-Type: application/json",
+ ]);
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ expect(JSON.parse(callAt(0).stdin ?? "")).toEqual({ title: "A better title" });
+ }),
+ );
+
+ it.effect("sends a rewritten body as GitLab's description, and nothing else", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.updateMergeRequest({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ description: "What this changes.",
+ });
+
+ // A title sent as an empty string would wipe the one the merge request already has.
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ expect(JSON.parse(callAt(0).stdin ?? "")).toEqual({ description: "What this changes." });
+ }),
+ );
+
+ it.effect("rewrites title and description together in one request", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.updateMergeRequest({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ title: "A better title",
+ description: "What this changes.",
+ });
+
+ assert.strictEqual(mockedExecute.mock.calls.length, 1);
+ // @effect-diagnostics-next-line preferSchemaOverJson:off
+ expect(JSON.parse(callAt(0).stdin ?? "")).toEqual({
+ title: "A better title",
+ description: "What this changes.",
+ });
+ }),
+ );
+
+ it.effect("rewrites a note in place through the note it names", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.updateNote({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ noteId: "42",
+ body: "true",
+ });
+
+ expect(argsOfCall(0)).toEqual([
+ "api",
+ "projects/acme%2Fweb/merge_requests/7/notes/42",
+ "--method",
+ "PUT",
+ "--input",
+ "-",
+ "--header",
+ "Content-Type: application/json",
+ ]);
+ // A JSON body, so a note rewritten to a literal `true` stays text.
+ expect(callAt(0).stdin).toBe('{"body":"true"}');
+ }),
+ );
});
diff --git a/apps/server/src/pullRequest/GitLabPullRequestCli.ts b/apps/server/src/pullRequest/GitLabPullRequestCli.ts
index 4cbb74d32..17c23bf86 100644
--- a/apps/server/src/pullRequest/GitLabPullRequestCli.ts
+++ b/apps/server/src/pullRequest/GitLabPullRequestCli.ts
@@ -11,6 +11,8 @@ import type {
PullRequestListState,
PullRequestMergeCapabilities,
PullRequestMergeMethod,
+ PullRequestReaction,
+ PullRequestReactionContent,
PullRequestReviewCommentDraft,
PullRequestReviewThread,
PullRequestReviewVerdict,
@@ -19,6 +21,8 @@ import type {
import * as GitLabCli from "../sourceControl/GitLabCli.ts";
import {
+ AWARD_EMOJI_GRAPHQL_QUERY,
+ decodeAwardEmojiJson,
decodeCommitDiffRefsJson,
decodeCommitsJson,
decodeDiffRefsJson,
@@ -27,9 +31,11 @@ import {
decodeMergeRequestDiffsJson,
decodeMergeRequestListJson,
decodeNotesJson,
+ decodeOwnAwardIdJson,
decodeProjectMergeCapabilitiesJson,
decodeProjectUsersJson,
decodeViewerJson,
+ gitLabAwardName,
type GitLabDiffRefs,
type GitLabMergeRequestDetail,
type GitLabMergeRequestListItem,
@@ -303,6 +309,15 @@ export class GitLabPullRequestCli extends Context.Service<
readonly mergeMethod?: PullRequestMergeMethod;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
+ /** Whichever of the two is given is sent. GitLab calls a merge request's body its description. */
+ readonly updateMergeRequest: (input: {
+ readonly cwd: string;
+ readonly repository: string;
+ readonly number: number;
+ readonly title?: string | undefined;
+ readonly description?: string | undefined;
+ }) => Effect.Effect<void, GitLabPullRequestCliError>;
+
readonly commentOnMergeRequest: (input: {
readonly cwd: string;
readonly repository: string;
@@ -310,6 +325,14 @@ export class GitLabPullRequestCli extends Context.Service<
readonly body: string;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
+ readonly updateNote: (input: {
+ readonly cwd: string;
+ readonly repository: string;
+ readonly number: number;
+ readonly noteId: string;
+ readonly body: string;
+ }) => Effect.Effect<void, GitLabPullRequestCliError>;
+
readonly listDiscussions: (input: {
readonly cwd: string;
readonly repository: string;
@@ -343,6 +366,32 @@ export class GitLabPullRequestCli extends Context.Service<
readonly discussionId: string;
readonly resolved: boolean;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
+
+ /** The awards on the merge request and on every note of it, keyed by the note's REST id. */
+ readonly listReactions: (input: {
+ readonly cwd: string;
+ readonly repository: string;
+ readonly number: number;
+ }) => Effect.Effect<
+ {
+ readonly reactions: ReadonlyArray<PullRequestReaction>;
+ readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
+ },
+ GitLabPullRequestCliError
+ >;
+
+ /**
+ * Awards an emoji, or takes the award back. `noteId` is a note of the merge request; absent
+ * awards the merge request itself, which is where its description's reactions live.
+ */
+ readonly setReaction: (input: {
+ readonly cwd: string;
+ readonly repository: string;
+ readonly number: number;
+ readonly noteId?: string | undefined;
+ readonly content: PullRequestReactionContent;
+ readonly reacted: boolean;
+ }) => Effect.Effect<void, GitLabPullRequestCliError>;
}
>()("t3/pullRequest/GitLabPullRequestCli") {}
@@ -412,12 +461,30 @@ function actionArgs(
...(mergeMethod === "squash" ? ["--squash"] : []),
...(mergeMethod === "rebase" ? ["--rebase"] : []),
];
+ // The same command with the flag the other way up: here the wait is the whole point, so
+ // glab is told to arm the merge rather than talked out of it.
+ case "enable-auto-merge":
+ return [
+ "merge",
+ "--auto-merge=true",
+ "--yes",
+ ...(mergeMethod === "squash" ? ["--squash"] : []),
+ ...(mergeMethod === "rebase" ? ["--rebase"] : []),
+ ];
+ // Never reached: taking the arming back has no `glab mr` command, so it goes to the API.
+ case "disable-auto-merge":
+ return [];
case "ready":
return ["update", "--ready"];
case "draft":
return ["update", "--draft"];
case "close":
return ["close"];
+ // A rebase, because GitLab has no other way to move a branch onto its target: there is no
+ // merge-the-target-in equivalent of GitHub's update button, which is why this host declares
+ // `rebase` alone and never has to read the method it was handed.
+ case "update-branch":
+ return ["rebase"];
case "reopen":
return ["reopen"];
}
@@ -819,7 +886,11 @@ export const make = Effect.gen(function* () {
}): Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError> =>
api({
cwd: input.cwd,
- path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
+ // How far behind the target branch this one is comes only when asked for by name, and it
+ // is asked for here rather than on a second read because it is the same merge request.
+ path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}?${query([
+ ["include_diverged_commits_count", "true"],
+ ])}`,
}).pipe(
Effect.flatMap((result) => {
const decoded = decodeMergeRequestDetailJson(result.stdout.trim());
@@ -862,26 +933,104 @@ export const make = Effect.gen(function* () {
}),
);
+ /** Where an award is written: a note of the merge request, or the merge request itself. */
+ const awardSubjectPath = (input: {
+ readonly repository: string;
+ readonly number: number;
+ readonly noteId?: string | undefined;
+ }) => {
+ const mergeRequest = `projects/${projectPath(input.repository)}/merge_requests/${input.number}`;
+ return input.noteId === undefined
+ ? `${mergeRequest}/award_emoji`
+ : `${mergeRequest}/notes/${encodeURIComponent(input.noteId)}/award_emoji`;
+ };
+
+ /**
+ * The awards on the merge request and its notes, a page of notes at a time. Bounded by the same
+ * count as the conversation itself: awards past the notes that were read belong to notes the
+ * page is not showing.
+ */
+ const awardsPage = (input: {
+ readonly cwd: string;
+ readonly repository: string;
+ readonly number: number;
+ readonly cursor: string | null;
+ readonly page: number;
+ readonly collected: {
+ readonly reactions: ReadonlyArray<PullRequestReaction>;
+ readonly reactionsByNoteId: Map<string, ReadonlyArray<PullRequestReaction>>;
+ } | null;
+ }): Effect.Effect<
+ {
+ readonly reactions: ReadonlyArray<PullRequestReaction>;
+ readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
+ },
+ GitLabPullRequestCliError
+ > =>
+ api({
+ cwd: input.cwd,
+ path: "graphql",
+ method: "POST",
+ stdin: JSON.stringify({
+ query: AWARD_EMOJI_GRAPHQL_QUERY,
+ variables: {
+ fullPath: input.repository,
+ iid: String(input.number),
+ cursor: input.cursor,
+ },
+ }),
+ }).pipe(
+ Effect.flatMap((result) => {
+ const decoded = decodeAwardEmojiJson(result.stdout.trim());
+ if (!Result.isSuccess(decoded)) {
+ return Effect.fail(
+ new GitLabMergeRequestReadError({
+ command: "glab",
+ cwd: input.cwd,
+ operation: "listReactions",
+ cause: decoded.failure,
+ }),
+ );
+ }
+ const collected = input.collected ?? {
+ reactions: decoded.success.reactions,
+ reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(),
+ };
+ for (const [id, reactions] of decoded.success.reactionsByNoteId)
+ collected.reactionsByNoteId.set(id, reactions);
+ return decoded.success.nextCursor === null || input.page >= CONVERSATION_PAGES
+ ? Effect.succeed(collected)
+ : awardsPage({
+ ...input,
+ cursor: decoded.success.nextCursor,
+ page: input.page + 1,
+ collected,
+ });
+ }),
+ );
+
+ const viewerUsername = (input: { readonly cwd: string }) =>
+ api({ cwd: input.cwd, path: "user" }).pipe(
+ Effect.flatMap((result): Effect.Effect<string, GitLabPullRequestCliError> => {
+ const decoded = decodeViewerJson(result.stdout.trim());
+ if (!Result.isSuccess(decoded)) {
+ return Effect.fail(
+ new GitLabMergeRequestReadError({
+ command: "glab",
+ cwd: input.cwd,
+ operation: "getViewerUsername",
+ cause: decoded.failure,
+ }),
+ );
+ }
+ return decoded.success === null
+ ? Effect.fail(new GitLabViewerUnavailableError({ command: "glab", cwd: input.cwd }))
+ : Effect.succeed(decoded.success);
+ }),
+ );
+
return GitLabPullRequestCli.of({
- getViewerUsername: (input) =>
- api({ cwd: input.cwd, path: "user" }).pipe(
- Effect.flatMap((result): Effect.Effect<string, GitLabPullRequestCliError> => {
- const decoded = decodeViewerJson(result.stdout.trim());
- if (!Result.isSuccess(decoded)) {
- return Effect.fail(
- new GitLabMergeRequestReadError({
- command: "glab",
- cwd: input.cwd,
- operation: "getViewerUsername",
- cause: decoded.failure,
- }),
- );
- }
- return decoded.success === null
- ? Effect.fail(new GitLabViewerUnavailableError({ command: "glab", cwd: input.cwd }))
- : Effect.succeed(decoded.success);
- }),
- ),
+ getViewerUsername: viewerUsername,
listMergeRequests: (input) => {
const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE);
@@ -893,6 +1042,44 @@ export const make = Effect.gen(function* () {
listNotes: (input) => notesPage({ ...input, page: 1, collected: [] }),
+ listReactions: (input) => awardsPage({ ...input, cursor: null, page: 1, collected: null }),
+
+ setReaction: (input) =>
+ Effect.gen(function* () {
+ const subject = awardSubjectPath(input);
+ if (input.reacted) {
+ yield* api({
+ cwd: input.cwd,
+ path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,
+ method: "POST",
+ });
+ return;
+ }
+ // GitLab deletes an award by its id and takes no emoji name there, so the reader's own
+ // award of that name is looked up first. Nothing to delete is success: the reaction the
+ // caller asked to take back is already gone.
+ const viewer = yield* viewerUsername({ cwd: input.cwd });
+ const listed = yield* api({ cwd: input.cwd, path: subject });
+ const own = decodeOwnAwardIdJson(listed.stdout.trim(), {
+ content: input.content,
+ viewer,
+ });
+ if (!Result.isSuccess(own)) {
+ return yield* new GitLabMergeRequestReadError({
+ command: "glab",
+ cwd: input.cwd,
+ operation: "setReaction",
+ cause: own.failure,
+ });
+ }
+ if (own.success === null) return;
+ yield* api({
+ cwd: input.cwd,
+ path: `${subject}/${own.success}`,
+ method: "DELETE",
+ });
+ }),
+
listCommits: (input) =>
api({
cwd: input.cwd,
@@ -1053,6 +1240,16 @@ export const make = Effect.gen(function* () {
),
runMergeRequestAction: (input) => {
+ // `glab mr merge` arms auto-merge and never disarms it, so the one direction the CLI has
+ // no flag for is asked of GitLab directly through the same `api` passthrough the rest of
+ // this module writes with.
+ if (input.action === "disable-auto-merge") {
+ return api({
+ cwd: input.cwd,
+ path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/cancel_merge_when_pipeline_succeeds`,
+ method: "POST",
+ }).pipe(Effect.asVoid);
+ }
const [subcommand, ...flags] = actionArgs(input.action, input.mergeMethod);
return gitlab
.execute({
@@ -1062,6 +1259,20 @@ export const make = Effect.gen(function* () {
.pipe(Effect.asVoid);
},
+ updateMergeRequest: (input) =>
+ api({
+ cwd: input.cwd,
+ path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
+ method: "PUT",
+ // Only the fields the caller asked to change: GitLab leaves out what it is not sent, and
+ // clears what it is sent empty — so a title corrected on its own must carry no
+ // description at all.
+ stdin: JSON.stringify({
+ ...(input.title === undefined ? {} : { title: input.title }),
+ ...(input.description === undefined ? {} : { description: input.description }),
+ }),
+ }).pipe(Effect.asVoid),
+
commentOnMergeRequest: (input) =>
api({
cwd: input.cwd,
@@ -1072,6 +1283,16 @@ export const make = Effect.gen(function* () {
stdin: JSON.stringify({ body: input.body }),
}).pipe(Effect.asVoid),
+ updateNote: (input) =>
+ api({
+ cwd: input.cwd,
+ path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes/${encodeURIComponent(
+ input.noteId,
+ )}`,
+ method: "PUT",
+ stdin: JSON.stringify({ body: input.body }),
+ }).pipe(Effect.asVoid),
+
listDiscussions: (input) => discussionsPage({ ...input, page: 1, collected: [] }),
submitReview: (input) =>
diff --git a/apps/server/src/pullRequest/GitLabPullRequestProvider.test.ts b/apps/server/src/pullRequest/GitLabPullRequestProvider.test.ts
index 55bbbe38d..5d36d58df 100644
--- a/apps/server/src/pullRequest/GitLabPullRequestProvider.test.ts
+++ b/apps/server/src/pullRequest/GitLabPullRequestProvider.test.ts
@@ -1,20 +1,36 @@
-import { describe, expect, it } from "vite-plus/test";
+import { assert, describe, expect, it, vi } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
-import { gitLabViewerPermissions } from "./GitLabPullRequestProvider.ts";
+import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
+import { gitLabViewerPermissions, make } from "./GitLabPullRequestProvider.ts";
describe("gitLabViewerPermissions", () => {
it("offers everything to a viewer GitLab says can merge", () => {
expect(gitLabViewerPermissions({ viewerCanMerge: true })).toEqual({
- actions: ["merge", "ready", "draft", "close", "reopen"],
+ // Arming a merge for later and taking the arming back answer to the same `can_merge`.
+ actions: [
+ "merge",
+ "ready",
+ "draft",
+ "close",
+ "reopen",
+ "update-branch",
+ "enable-auto-merge",
+ "disable-auto-merge",
+ ],
comment: true,
resolve: true,
verdicts: ["comment", "approve"],
// GitLab says nothing about who may set a reviewer, and an unreported permission is granted.
requestReviewers: true,
+ // Rebase and nothing else: GitLab cannot merge a target branch into a source branch, so
+ // offering the choice would be offering something no request could carry out.
+ updateMethods: ["rebase"],
});
});
- it("keeps merge from a viewer GitLab says cannot", () => {
+ it("keeps merge, now and later, from a viewer GitLab says cannot", () => {
// `user.can_merge` already accounts for the role, the approval rules and a protected target
// branch, so it is the one answer here that does not have to be inferred.
expect(gitLabViewerPermissions({ viewerCanMerge: false })).toEqual({
@@ -26,6 +42,12 @@ describe("gitLabViewerPermissions", () => {
});
});
+ it("names no way of updating a branch it will not let this viewer update", () => {
+ // The action and the strategy behind it go together: a button offered with nothing to press
+ // it with, or a strategy left standing next to a withheld button, is a half-refusal.
+ expect(gitLabViewerPermissions({ viewerCanMerge: false }).updateMethods).toBeUndefined();
+ });
+
it("treats an author with read access as any other reader, which is all GitLab says", () => {
// Its REST API names no relationship between the viewer and the merge request beyond
// `can_merge`, so the four an author keeps stay offered to everyone rather than being taken
@@ -38,3 +60,138 @@ describe("gitLabViewerPermissions", () => {
]);
});
});
+
+describe("getChangeRequest base freshness", () => {
+ const detail = {
+ number: 7,
+ title: "Merge request 7",
+ url: "https://gitlab.com/acme/web/-/merge_requests/7",
+ author: null,
+ headBranch: "feat/page",
+ baseBranch: "main",
+ state: "open" as const,
+ isDraft: false,
+ mergeability: "mergeable" as const,
+ additions: 0,
+ deletions: 0,
+ createdAt: "2026-07-01T00:00:00Z",
+ updatedAt: "2026-07-02T00:00:00Z",
+ reviewRequestLogins: [],
+ labels: [],
+ body: "",
+ changedFiles: 1,
+ mergedAt: null,
+ closedAt: null,
+ reviewers: [],
+ checks: [],
+ viewerCanMerge: true,
+ reviewerIds: [],
+ };
+
+ const readWith = (divergence: { readonly divergedCommits?: number }) =>
+ Effect.gen(function* () {
+ const provider = yield* make;
+ return yield* provider.getChangeRequest({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "gitlab.com",
+ number: 7,
+ });
+ }).pipe(
+ Effect.provide(
+ Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
+ getMergeRequestDetail: () => Effect.succeed({ ...detail, ...divergence }),
+ getProjectMergeCapabilities: () =>
+ Effect.succeed({ merge: true, squash: true, rebase: true }),
+ }),
+ ),
+ );
+
+ it.effect("reads a counted divergence as a branch that has fallen behind", () =>
+ Effect.gen(function* () {
+ const changeRequest = yield* readWith({ divergedCommits: 3 });
+
+ expect(changeRequest.baseComparison).toBe("behind");
+ expect(changeRequest.behindBy).toBe(3);
+ }),
+ );
+
+ it.effect("reads a divergence of none as a branch that is current", () =>
+ Effect.gen(function* () {
+ const changeRequest = yield* readWith({ divergedCommits: 0 });
+
+ expect(changeRequest.baseComparison).toBe("up-to-date");
+ expect(changeRequest.behindBy).toBe(0);
+ }),
+ );
+
+ it.effect("says nothing at all where GitLab counted nothing", () =>
+ Effect.gen(function* () {
+ // An install too old to answer has to leave the page silent rather than let it claim the
+ // branch is current, which is the one wrong thing this banner could say.
+ const changeRequest = yield* readWith({});
+
+ expect(changeRequest.baseComparison).toBe("unknown");
+ expect(changeRequest.behindBy).toBeUndefined();
+ }),
+ );
+});
+
+describe("rewriting what has already been said", () => {
+ const updateMergeRequest = vi.fn(() => Effect.void);
+ const updateNote = vi.fn(() => Effect.void);
+
+ const providerWith = make.pipe(
+ Effect.provide(
+ Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({ updateMergeRequest, updateNote }),
+ ),
+ );
+
+ it.effect("sends only the half of the merge request the reader rewrote", () =>
+ Effect.gen(function* () {
+ const provider = yield* providerWith;
+ assert.isDefined(provider.updateChangeRequest);
+
+ yield* provider.updateChangeRequest({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "gitlab.com",
+ number: 7,
+ body: "What this changes.",
+ });
+
+ // GitLab calls it the description, and the title stays out of the request entirely.
+ expect(updateMergeRequest).toHaveBeenCalledWith({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ description: "What this changes.",
+ });
+ }),
+ );
+
+ it.effect("rewrites a positioned comment through the same note as any other", () =>
+ Effect.gen(function* () {
+ const provider = yield* providerWith;
+ assert.isDefined(provider.updateComment);
+
+ yield* provider.updateComment({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "gitlab.com",
+ number: 7,
+ commentId: "42",
+ kind: "review-comment",
+ body: "Reworded.",
+ });
+
+ expect(updateNote).toHaveBeenCalledWith({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ noteId: "42",
+ body: "Reworded.",
+ });
+ }),
+ );
+});
diff --git a/apps/server/src/pullRequest/GitLabPullRequestProvider.ts b/apps/server/src/pullRequest/GitLabPullRequestProvider.ts
index 50396e27e..07edf08e5 100644
--- a/apps/server/src/pullRequest/GitLabPullRequestProvider.ts
+++ b/apps/server/src/pullRequest/GitLabPullRequestProvider.ts
@@ -1,5 +1,9 @@
import * as Effect from "effect/Effect";
-import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
+import type {
+ PullRequestCapabilities,
+ PullRequestReaction,
+ PullRequestViewerPermissions,
+} from "@t3tools/contracts";
import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
import {
@@ -12,10 +16,24 @@ import {
const CAPABILITIES: PullRequestCapabilities = {
diff: true,
comment: true,
- actions: ["merge", "ready", "draft", "close", "reopen"],
+ actions: [
+ "merge",
+ "ready",
+ "draft",
+ "close",
+ "reopen",
+ "update-branch",
+ "enable-auto-merge",
+ "disable-auto-merge",
+ ],
// GitLab offers all three, though a project settles on one; `mergeCapabilities` narrows it.
mergeMethods: ["merge", "squash", "rebase"],
+ // Rebase alone: GitLab moves a stale branch onto its target by replaying it, and has nothing
+ // that merges the target back in the way GitHub's update button can. Declaring only what it
+ // does is what lets a request to merge the target in be refused instead of quietly rebasing.
+ updateMethods: ["rebase"],
search: true,
+ reactions: true,
review: {
inlineComment: true,
reply: true,
@@ -25,8 +43,21 @@ const CAPABILITIES: PullRequestCapabilities = {
verdicts: ["comment", "approve"],
},
reviewers: { request: true, listCandidates: true },
+ edit: { changeRequest: true, comment: true },
};
+/**
+ * The actions `user.can_merge` answers for. Rebasing writes to the source branch rather than to
+ * the target, so it is not literally the same permission — but GitLab reports nothing narrower,
+ * and someone it will not let land this change has no business rewriting its branch either.
+ */
+const MERGE_ACTIONS: ReadonlySet<string> = new Set([
+ "merge",
+ "update-branch",
+ "enable-auto-merge",
+ "disable-auto-merge",
+]);
+
/**
* What the signed-in account may do here. GitLab answers exactly one of these questions per
* viewer, on the merge request itself: `user.can_merge`, which is why merging is the only thing
@@ -45,11 +76,16 @@ export function gitLabViewerPermissions(input: {
readonly viewerCanMerge: boolean;
}): PullRequestViewerPermissions {
return {
- actions: CAPABILITIES.actions.filter((action) => action !== "merge" || input.viewerCanMerge),
+ // Arming the merge and taking the arming back are the merge, deferred, so they answer to
+ // the same `can_merge` the merge itself does.
+ actions: CAPABILITIES.actions.filter(
+ (action) => !MERGE_ACTIONS.has(action) || input.viewerCanMerge,
+ ),
comment: true,
resolve: true,
verdicts: CAPABILITIES.review.verdicts,
requestReviewers: true,
+ ...(input.viewerCanMerge ? { updateMethods: CAPABILITIES.updateMethods } : {}),
};
}
@@ -114,6 +150,17 @@ export const make = Effect.gen(function* () {
...mergeRequest,
mergeCapabilities,
viewerPermissions: gitLabViewerPermissions(mergeRequest),
+ // A GitLab too old to count the divergence says nothing here rather than "up to
+ // date": the banner is worth missing, and a wrong all-clear is not worth showing.
+ baseComparison:
+ mergeRequest.divergedCommits === undefined
+ ? "unknown"
+ : mergeRequest.divergedCommits > 0
+ ? "behind"
+ : "up-to-date",
+ ...(mergeRequest.divergedCommits === undefined
+ ? {}
+ : { behindBy: mergeRequest.divergedCommits }),
}),
),
),
@@ -128,19 +175,37 @@ export const make = Effect.gen(function* () {
cli
.listDiscussions(input)
.pipe(Effect.orElseSucceed(() => ({ threads: [], truncated: true }))),
+ // The notes endpoint carries no award of any kind, so they are read alongside it. A
+ // failed read costs the conversation its reactions rather than its words.
+ cli.listReactions(input).pipe(
+ Effect.orElseSucceed(() => ({
+ reactions: [] as ReadonlyArray<PullRequestReaction>,
+ reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(),
+ })),
+ ),
],
- { concurrency: 3 },
+ { concurrency: 4 },
).pipe(
Effect.mapError(fail("getChangeRequestActivity")),
Effect.map(
- ([notes, commits, discussions]): ProviderChangeRequestActivity => ({
- comments: notes.comments,
+ ([notes, commits, discussions, awards]): ProviderChangeRequestActivity => ({
+ reactions: awards.reactions,
+ comments: notes.comments.map((comment) => ({
+ ...comment,
+ reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
+ })),
// GitLab reports no count of its own, so the walk's own total is the host's: the
// notes endpoint carries every comment on the merge request, including the ones
// written under a discussion, and it is read until GitLab runs out.
commentCount: notes.comments.length,
commentsTruncated: notes.truncated || discussions.truncated,
- reviewThreads: discussions.threads,
+ reviewThreads: discussions.threads.map((thread) => ({
+ ...thread,
+ comments: thread.comments.map((comment) => ({
+ ...comment,
+ reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
+ })),
+ })),
commits,
}),
),
@@ -188,8 +253,32 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("runAction"))),
+ updateChangeRequest: (input) =>
+ cli
+ .updateMergeRequest({
+ cwd: input.cwd,
+ repository: input.repository,
+ number: input.number,
+ ...(input.title === undefined ? {} : { title: input.title }),
+ ...(input.body === undefined ? {} : { description: input.body }),
+ })
+ .pipe(Effect.mapError(fail("updateChangeRequest"))),
+
comment: (input) => cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))),
+ // The kind is not read: every comment this provider hands out, positioned or not, carries a
+ // plain REST note id, and one endpoint rewrites both.
+ updateComment: (input) =>
+ cli
+ .updateNote({
+ cwd: input.cwd,
+ repository: input.repository,
+ number: input.number,
+ noteId: input.commentId,
+ body: input.body,
+ })
+ .pipe(Effect.mapError(fail("updateComment"))),
+
submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
replyToThread: (input) =>
@@ -203,6 +292,18 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("replyToThread"))),
+ setReaction: (input) =>
+ cli
+ .setReaction({
+ cwd: input.cwd,
+ repository: input.repository,
+ number: input.number,
+ ...(input.subjectId === undefined ? {} : { noteId: input.subjectId }),
+ content: input.content,
+ reacted: input.reacted,
+ })
+ .pipe(Effect.mapError(fail("setReaction"))),
+
setThreadResolution: (input) =>
cli
.setDiscussionResolution({
diff --git a/apps/server/src/pullRequest/PullRequestProvider.ts b/apps/server/src/pullRequest/PullRequestProvider.ts
index 34ec28b41..6356d593b 100644
--- a/apps/server/src/pullRequest/PullRequestProvider.ts
+++ b/apps/server/src/pullRequest/PullRequestProvider.ts
@@ -3,22 +3,30 @@ import * as Schema from "effect/Schema";
import type {
PullRequestAction,
PullRequestActor,
+ PullRequestBaseComparison,
PullRequestCapabilities,
+ PullRequestChecksState,
PullRequestCheck,
PullRequestComment,
PullRequestCommit,
PullRequestInvolvement,
PullRequestLabel,
+ PullRequestListFilters,
PullRequestListState,
PullRequestMergeCapabilities,
PullRequestMergeMethod,
PullRequestMergeability,
+ PullRequestOmittedFileStat,
+ PullRequestReaction,
+ PullRequestReactionContent,
PullRequestReviewCommentDraft,
+ PullRequestReviewDecision,
PullRequestReviewThread,
PullRequestReviewVerdict,
PullRequestReviewerCandidateList,
PullRequestReviewerKind,
PullRequestState,
+ PullRequestUpdateMethod,
PullRequestViewerPermissions,
SourceControlProviderKind,
} from "@t3tools/contracts";
@@ -64,6 +72,10 @@ export interface ProviderChangeRequest {
/** Accounts with a review requested. Team-level requests are excluded by each provider. */
readonly reviewRequestLogins: ReadonlyArray<string>;
readonly labels: ReadonlyArray<PullRequestLabel>;
+ /** Absent from a host that does not summarise its reviews, which is every host but GitHub. */
+ readonly reviewDecision?: PullRequestReviewDecision | null | undefined;
+ /** Absent from a host that reports no check rollup on its listings. */
+ readonly checksState?: PullRequestChecksState | null | undefined;
}
export interface ProviderChangeRequestPage {
@@ -140,6 +152,11 @@ export interface ProviderChangeRequestDetail extends ProviderChangeRequest {
readonly checks: ReadonlyArray<PullRequestCheck>;
readonly mergeCapabilities: PullRequestMergeCapabilities;
readonly viewerPermissions: PullRequestViewerPermissions;
+ /** Absent from a host that cannot compare the branch with its base, which is most of them. */
+ readonly baseComparison?: PullRequestBaseComparison;
+ readonly behindBy?: number;
+ /** Absent from a host that does not report whether it is armed to merge this on its own. */
+ readonly autoMergeEnabled?: boolean;
}
/** The conversation-shaped half of a detail, loaded after the core can already render. */
@@ -158,6 +175,8 @@ export interface ProviderChangeRequestActivity {
readonly commentsTruncated: boolean;
readonly reviewThreads: ReadonlyArray<PullRequestReviewThread>;
readonly commits: ReadonlyArray<PullRequestCommit>;
+ /** The change request's own reactions, from a host that has them. */
+ readonly reactions?: ReadonlyArray<PullRequestReaction>;
}
export interface ProviderDiffSlice {
@@ -165,6 +184,8 @@ export interface ProviderDiffSlice {
/** Something in this slice could not be shown, as opposed to there being more slices. */
readonly truncated: boolean;
readonly nextCursor: string | null;
+ /** The host's own counts for the files whose hunks it withheld from this slice. */
+ readonly omittedFileStats?: ReadonlyArray<PullRequestOmittedFileStat>;
}
export interface ProviderDiffFileContents {
@@ -216,6 +237,12 @@ export interface PullRequestProviderApi {
* asks for the first slice, which is every listing that has not been continued.
*/
readonly cursor?: ProviderListCursor | undefined;
+ /**
+ * Further narrowings, which a host applies as far as it can and ignores the rest of —
+ * an unnarrowed page is a wider answer rather than a wrong one, and the caller narrows
+ * what it gets for the fields a row carries.
+ */
+ readonly filters?: PullRequestListFilters | undefined;
},
) => Effect.Effect<ProviderChangeRequestPage, PullRequestProviderError>;
@@ -244,6 +271,7 @@ export interface PullRequestProviderApi {
readonly limit: number;
readonly query?: string | undefined;
readonly cursor?: ProviderListCursor | undefined;
+ readonly filters?: PullRequestListFilters | undefined;
}) => Effect.Effect<ProviderBatchedChangeRequestPage, PullRequestProviderError>;
/**
@@ -314,7 +342,23 @@ export interface PullRequestProviderApi {
input: ProviderRepositoryRef & {
readonly number: number;
readonly action: PullRequestAction;
+ /** Meaningful for `merge` and `enable-auto-merge`; absent takes the host's own default. */
readonly mergeMethod?: PullRequestMergeMethod;
+ /** Only meaningful for `update-branch`; absent takes the host's own default. */
+ readonly updateMethod?: PullRequestUpdateMethod;
+ },
+ ) => Effect.Effect<void, PullRequestProviderError>;
+
+ /**
+ * Rewrites the change request's own words. Only called when `capabilities.edit.changeRequest`
+ * is true, and never with both fields absent — the caller refuses that before it gets here,
+ * because a host asked to change nothing answers differently on each of them.
+ */
+ readonly updateChangeRequest?: (
+ input: ProviderRepositoryRef & {
+ readonly number: number;
+ readonly title?: string | undefined;
+ readonly body?: string | undefined;
},
) => Effect.Effect<void, PullRequestProviderError>;
@@ -322,6 +366,23 @@ export interface PullRequestProviderApi {
input: ProviderRepositoryRef & { readonly number: number; readonly body: string },
) => Effect.Effect<void, PullRequestProviderError>;
+ /**
+ * Rewrites a remark somebody already posted. Only called when `capabilities.edit.comment` is
+ * true, with an id exactly as the conversation carried it.
+ *
+ * Whether this remark is the reader's to rewrite is the host's own answer: no read here can
+ * settle it, since access can be taken away between the conversation being read and the
+ * rewrite being sent, and a host refuses a stranger's remark with a sentence saying so.
+ */
+ readonly updateComment?: (
+ input: ProviderRepositoryRef & {
+ readonly number: number;
+ readonly commentId: string;
+ readonly kind: "issue-comment" | "review-comment";
+ readonly body: string;
+ },
+ ) => Effect.Effect<void, PullRequestProviderError>;
+
/**
* Sends a whole review at once. Only called for a verdict the host declared in
* `capabilities.review.verdicts`, and with line comments only where it declared
@@ -376,6 +437,22 @@ export interface PullRequestProviderApi {
},
) => Effect.Effect<void, PullRequestProviderError>;
+ /**
+ * Adds a reaction, or takes it back. Only called when `capabilities.reactions` is true.
+ *
+ * `subjectId` is a remark's id as the conversation carried it; absent means the change request
+ * itself, whose reactions sit on its description. Whatever a host needs to address either of
+ * them is worked out here, because the id a conversation travels with is the one the reader has.
+ */
+ readonly setReaction: (
+ input: ProviderRepositoryRef & {
+ readonly number: number;
+ readonly subjectId?: string | undefined;
+ readonly content: PullRequestReactionContent;
+ readonly reacted: boolean;
+ },
+ ) => Effect.Effect<void, PullRequestProviderError>;
+
/** Only called when `capabilities.review.resolve` is true. */
readonly setThreadResolution: (
input: ProviderRepositoryRef & {
diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts
index 77a7118d9..243cfe06c 100644
--- a/apps/server/src/pullRequest/PullRequestService.test.ts
+++ b/apps/server/src/pullRequest/PullRequestService.test.ts
@@ -114,8 +114,10 @@ function fakeProvider(
actions: ["merge", "ready", "draft", "close", "reopen"],
mergeMethods: ["merge"],
search: true,
+ reactions: true,
review: FULL_REVIEW,
reviewers: FULL_REVIEWERS,
+ edit: { changeRequest: true, comment: true },
},
getViewer: () => Effect.succeed("bilal"),
// A viewer who may do everything the host can, so a test only narrows what it is about.
@@ -132,10 +134,13 @@ function fakeProvider(
getChangeRequestActivity: () => Effect.die("unused"),
getDiff: () => Effect.die("unused"),
runAction: () => Effect.void,
+ updateChangeRequest: () => Effect.void,
comment: () => Effect.void,
+ updateComment: () => Effect.void,
submitReview: () => Effect.void,
replyToThread: () => Effect.void,
setThreadResolution: () => Effect.void,
+ setReaction: () => Effect.void,
listReviewerCandidates: () => Effect.succeed({ candidates: [], truncated: false }),
setReviewerRequest: () => Effect.void,
...overrides,
@@ -435,8 +440,9 @@ it.effect("uses a provider's raw cursor advance when it consumed malformed rows"
const result = yield* service.list({ state: "open" });
+ // Keyed by the selector Azure is actually asked with, which is the repository's own name.
assert.deepStrictEqual(result.nextCursors, {
- "dev.azure.com acme/web": "2026-07-02T00:00:00Z|4|7",
+ "dev.azure.com web": "2026-07-02T00:00:00Z|4|7",
});
}),
);
@@ -945,6 +951,7 @@ it.effect("refuses an action the host never claimed it could run", () =>
actions: ["merge", "close"],
mergeMethods: ["merge"],
search: true,
+ reactions: true,
review: FULL_REVIEW,
reviewers: FULL_REVIEWERS,
},
@@ -1007,6 +1014,136 @@ it.effect("refuses an action this viewer may not take, and says what access it t
}),
);
+it.effect("gates arming a merge for later exactly as it gates merging now", () =>
+ Effect.gen(function* () {
+ let ranWith: { readonly action: string; readonly mergeMethod?: string } | null = null;
+ const service = yield* makeService({
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
+ providers: [
+ fakeProvider("github", {
+ capabilities: {
+ diff: true,
+ comment: true,
+ actions: ["merge", "close", "enable-auto-merge", "disable-auto-merge"],
+ mergeMethods: ["merge", "squash"],
+ search: true,
+ reactions: true,
+ review: FULL_REVIEW,
+ reviewers: FULL_REVIEWERS,
+ },
+ // This account may close the change request it opened, and nothing else here.
+ getViewerPermissions: () =>
+ Effect.succeed({
+ actions: ["close"],
+ comment: true,
+ resolve: true,
+ verdicts: ["comment", "approve", "request-changes"],
+ requestReviewers: false,
+ }),
+ runAction: (input) => {
+ ranWith = {
+ action: input.action,
+ ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
+ };
+ return Effect.void;
+ },
+ }),
+ ],
+ });
+ const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
+
+ const refused = yield* Effect.flip(
+ service.runAction({ ...reference, action: "enable-auto-merge", mergeMethod: "squash" }),
+ );
+ assert.strictEqual(refused._tag, "PullRequestOperationError");
+ assert.include(refused.message, "merged for you once it is ready");
+ assert.strictEqual(ranWith, null);
+
+ // The strategy is checked against the host for an armed merge too: a merge it performs
+ // later is still a merge, and one it cannot spell must not be passed on.
+ const wrongStrategy = yield* Effect.flip(
+ service.runAction({ ...reference, action: "enable-auto-merge", mergeMethod: "rebase" }),
+ );
+ assert.strictEqual(wrongStrategy._tag, "PullRequestOperationError");
+ assert.strictEqual(ranWith, null);
+ }),
+);
+
+it.effect("hands the host the strategy an armed merge was asked for", () =>
+ Effect.gen(function* () {
+ let ranWith: { readonly action: string; readonly mergeMethod?: string } | null = null;
+ const service = yield* makeService({
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
+ providers: [
+ fakeProvider("github", {
+ capabilities: {
+ diff: true,
+ comment: true,
+ actions: ["merge", "enable-auto-merge", "disable-auto-merge"],
+ mergeMethods: ["merge", "squash"],
+ search: true,
+ reactions: true,
+ review: FULL_REVIEW,
+ reviewers: FULL_REVIEWERS,
+ },
+ getViewerPermissions: () =>
+ Effect.succeed({
+ actions: ["merge", "enable-auto-merge", "disable-auto-merge"],
+ comment: true,
+ resolve: true,
+ verdicts: ["comment", "approve", "request-changes"],
+ requestReviewers: true,
+ }),
+ runAction: (input) => {
+ ranWith = {
+ action: input.action,
+ ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
+ };
+ return Effect.void;
+ },
+ }),
+ ],
+ });
+ const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
+
+ yield* service.runAction({ ...reference, action: "enable-auto-merge", mergeMethod: "squash" });
+ assert.deepStrictEqual(ranWith, { action: "enable-auto-merge", mergeMethod: "squash" });
+
+ yield* service.runAction({ ...reference, action: "disable-auto-merge" });
+ assert.deepStrictEqual(ranWith, { action: "disable-auto-merge" });
+ }),
+);
+
+it.effect("refuses an auto-merge the host never claimed, without asking it", () =>
+ Effect.gen(function* () {
+ let ran = false;
+ const service = yield* makeService({
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
+ providers: [
+ // Bitbucket's shape: it merges, and has nothing that merges later on its own.
+ fakeProvider("github", {
+ runAction: () => {
+ ran = true;
+ return Effect.void;
+ },
+ }),
+ ],
+ });
+
+ const error = yield* Effect.flip(
+ service.runAction({
+ projectId: "p1" as ProjectId,
+ repository: "acme/web",
+ number: 1,
+ action: "enable-auto-merge",
+ }),
+ );
+
+ assert.strictEqual(error._tag, "PullRequestOperationError");
+ assert.isFalse(ran);
+ }),
+);
+
it.effect("refuses to resolve a conversation this viewer may not, without asking the host", () =>
Effect.gen(function* () {
const service = yield* makeService({
@@ -1054,6 +1191,7 @@ it.effect("asks nobody what the viewer may do when the host cannot do it at all"
actions: ["merge", "close"],
mergeMethods: ["merge"],
search: true,
+ reactions: true,
review: FULL_REVIEW,
reviewers: FULL_REVIEWERS,
},
@@ -1092,6 +1230,7 @@ it.effect("refuses a comment on a host that cannot post one", () =>
actions: ["merge"],
mergeMethods: ["merge"],
search: true,
+ reactions: true,
review: FULL_REVIEW,
reviewers: FULL_REVIEWERS,
},
@@ -1271,6 +1410,7 @@ it.effect("refuses a diff on a host that cannot produce one", () =>
actions: ["merge", "close"],
mergeMethods: ["merge"],
search: true,
+ reactions: true,
review: FULL_REVIEW,
reviewers: FULL_REVIEWERS,
},
@@ -1330,6 +1470,7 @@ it.effect("refuses a verdict the host never claimed, without asking the provider
actions: ["merge"],
mergeMethods: ["merge"],
search: true,
+ reactions: true,
// GitLab's shape: it approves, and has nothing that rejects.
review: {
inlineComment: true,
@@ -1377,6 +1518,7 @@ it.effect("refuses line comments on a host that takes only a summary", () =>
actions: ["merge"],
mergeMethods: ["merge"],
search: true,
+ reactions: true,
review: { inlineComment: false, reply: false, resolve: false, verdicts: ["comment"] },
reviewers: FULL_REVIEWERS,
},
@@ -1454,6 +1596,7 @@ it.effect("refuses to resolve a conversation on a host that cannot", () =>
actions: ["merge"],
mergeMethods: ["merge"],
search: true,
+ reactions: true,
review: { inlineComment: true, reply: false, resolve: false, verdicts: ["comment"] },
reviewers: FULL_REVIEWERS,
},
@@ -1480,6 +1623,149 @@ it.effect("refuses to resolve a conversation on a host that cannot", () =>
}),
);
+it.effect("refuses to react on a host with no reactions", () =>
+ Effect.gen(function* () {
+ const service = yield* makeService({
+ projects: [
+ project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
+ ],
+ providers: [
+ fakeProvider("github", {
+ capabilities: {
+ diff: true,
+ comment: true,
+ actions: ["merge"],
+ mergeMethods: ["merge"],
+ search: true,
+ reactions: false,
+ review: FULL_REVIEW,
+ reviewers: FULL_REVIEWERS,
+ },
+ setReaction: () => Effect.die("must not be called"),
+ }),
+ ],
+ });
+
+ const error = yield* Effect.flip(
+ service.setReaction({
+ projectId: "p1" as ProjectId,
+ repository: "pingdotgg/t3code",
+ number: 1,
+ content: "heart",
+ reacted: true,
+ }),
+ );
+
+ assert.strictEqual(error._tag, "PullRequestOperationError");
+ }),
+);
+
+it.effect("refuses to react on a host whose capabilities omit reactions entirely", () =>
+ Effect.gen(function* () {
+ const service = yield* makeService({
+ projects: [
+ project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
+ ],
+ providers: [
+ fakeProvider("github", {
+ capabilities: {
+ diff: true,
+ comment: true,
+ actions: ["merge"],
+ mergeMethods: ["merge"],
+ search: true,
+ review: FULL_REVIEW,
+ reviewers: FULL_REVIEWERS,
+ },
+ setReaction: () => Effect.die("must not be called"),
+ }),
+ ],
+ });
+
+ const error = yield* Effect.flip(
+ service.setReaction({
+ projectId: "p1" as ProjectId,
+ repository: "pingdotgg/t3code",
+ number: 1,
+ content: "heart",
+ reacted: true,
+ }),
+ );
+
+ assert.strictEqual(error._tag, "PullRequestOperationError");
+ }),
+);
+
+it.effect("passes a reaction through with its subject id on a host that has them", () =>
+ Effect.gen(function* () {
+ let received: {
+ readonly subjectId: string | undefined;
+ readonly content: string;
+ readonly reacted: boolean;
+ } | null = null;
+ const service = yield* makeService({
+ projects: [
+ project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
+ ],
+ providers: [
+ fakeProvider("github", {
+ setReaction: (input) => {
+ received = {
+ subjectId: input.subjectId,
+ content: input.content,
+ reacted: input.reacted,
+ };
+ return Effect.void;
+ },
+ }),
+ ],
+ });
+
+ yield* service.setReaction({
+ projectId: "p1" as ProjectId,
+ repository: "pingdotgg/t3code",
+ number: 1,
+ subjectId: "IC_1",
+ content: "heart",
+ reacted: true,
+ });
+
+ assert.deepStrictEqual(received, { subjectId: "IC_1", content: "heart", reacted: true });
+ }),
+);
+
+it.effect("invalidates the cached activity after reacting, like the other mutations", () =>
+ Effect.gen(function* () {
+ let activityCalls = 0;
+ 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", {
+ getChangeRequestActivity: () => {
+ activityCalls += 1;
+ return Effect.succeed({
+ comments: [],
+ commentCount: 0,
+ commentsTruncated: false,
+ reviewThreads: [],
+ commits: [],
+ });
+ },
+ }),
+ ],
+ });
+
+ yield* service.activity(reference);
+ assert.strictEqual(activityCalls, 1);
+
+ yield* service.setReaction({ ...reference, content: "heart", reacted: true });
+ yield* service.activity(reference);
+
+ assert.strictEqual(activityCalls, 2);
+ }),
+);
+
it.effect("refuses an empty reply before it reaches the host", () =>
Effect.gen(function* () {
const service = yield* makeService({
@@ -1521,6 +1807,7 @@ it.effect("refuses a merge strategy the host does not offer", () =>
// Azure DevOps's shape: it squashes as a completion option and has no rebase.
mergeMethods: ["merge", "squash"],
search: true,
+ reactions: true,
review: FULL_REVIEW,
reviewers: FULL_REVIEWERS,
},
@@ -1704,6 +1991,7 @@ it.effect("refuses to ask for a review on a host that cannot, before any call is
actions: ["merge"],
mergeMethods: ["merge"],
search: true,
+ reactions: true,
review: FULL_REVIEW,
reviewers: { request: false, listCandidates: false },
},
@@ -1744,6 +2032,7 @@ it.effect("refuses the candidate list on a host that has no such list to give",
actions: ["merge"],
mergeMethods: ["merge"],
search: false,
+ reactions: true,
review: FULL_REVIEW,
// Azure's shape: it takes a reviewer, and names nobody who could be one.
reviewers: { request: true, listCandidates: false },
@@ -1910,6 +2199,45 @@ it.effect("answers a repeated listing from cache, and concurrent readers share o
}),
);
+it.effect("a listing narrowed to some projects is its own cache entry", () =>
+ Effect.gen(function* () {
+ const asked: ReadonlyArray<string>[] = [];
+ const service = yield* makeService({
+ projects: [
+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
+ project({ id: "p2", title: "docs", workspaceRoot: "/b", repository: "acme/docs" }),
+ ],
+ providers: [
+ fakeProvider("github", {
+ listChangeRequestsAcross: (input) => {
+ asked.push(input.repositories);
+ return Effect.succeed({
+ items: input.repositories.map((repository, index) =>
+ batchedChangeRequest(index + 1, repository, "2026-07-02T00:00:00Z"),
+ ),
+ truncated: false,
+ });
+ },
+ }),
+ ],
+ });
+
+ yield* service.list({ state: "open" });
+ const narrowed = yield* service.list({ state: "open", projectIds: ["p2" as ProjectId] });
+
+ // The narrowing is part of the key, so it reads its own scope instead of the wider answer.
+ assert.deepStrictEqual(asked, [["acme/web", "acme/docs"], ["acme/docs"]]);
+ assert.deepStrictEqual(
+ narrowed.entries.map((entry) => entry.repository),
+ ["acme/docs"],
+ );
+
+ // Asking again with the same narrowing, ordered differently, is still the same answer.
+ yield* service.list({ state: "open", projectIds: ["p2" as ProjectId] });
+ assert.strictEqual(asked.length, 2);
+ }),
+);
+
it.effect("an explicit invalidation makes the next listing ask the host again", () =>
Effect.gen(function* () {
let hostCalls = 0;
@@ -2370,3 +2698,597 @@ it.effect(
assert.strictEqual(activityCalls, 2);
}),
);
+
+it.effect("carries an armed auto-merge through to the detail, and silence as silence", () =>
+ Effect.gen(function* () {
+ const detailWith = (autoMergeEnabled: boolean | undefined) =>
+ Effect.gen(function* () {
+ const service = yield* makeService({
+ projects: [
+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
+ ],
+ providers: [
+ fakeProvider("github", {
+ getChangeRequest: () =>
+ Effect.succeed({
+ ...changeRequest(1, "2026-07-02T00:00:00Z"),
+ body: "",
+ changedFiles: 0,
+ mergedAt: null,
+ closedAt: null,
+ reviewers: [],
+ checks: [],
+ mergeCapabilities: { merge: true, squash: true, rebase: true },
+ viewerPermissions: {
+ actions: ["merge"],
+ comment: true,
+ resolve: true,
+ verdicts: ["comment", "approve", "request-changes"],
+ requestReviewers: true,
+ },
+ ...(autoMergeEnabled === undefined ? {} : { autoMergeEnabled }),
+ }),
+ }),
+ ],
+ });
+ return yield* service.detail({
+ projectId: "p1" as ProjectId,
+ repository: "acme/web",
+ number: 1,
+ });
+ });
+
+ assert.strictEqual((yield* detailWith(true)).autoMergeEnabled, true);
+ assert.strictEqual((yield* detailWith(false)).autoMergeEnabled, false);
+ // A host that says nothing leaves the field absent rather than claiming the merge is unarmed.
+ assert.isUndefined((yield* detailWith(undefined)).autoMergeEnabled);
+ }),
+);
+
+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({
+ projects: [
+ project({
+ id: "p1",
+ title: "web",
+ workspaceRoot: "/a",
+ repository: "acme/web",
+ provider: "gitlab",
+ }),
+ ],
+ providers: [
+ // Only GitHub narrows a listing for itself; every other host answers unnarrowed, and
+ // sending it a draft filter it quietly ignores used to put drafts on a filtered page.
+ fakeProvider("gitlab", {
+ listChangeRequests: () =>
+ Effect.succeed({
+ items: [
+ { ...changeRequest(1, "2026-07-02T00:00:00Z"), isDraft: true },
+ changeRequest(2, "2026-07-01T00:00:00Z"),
+ ],
+ truncated: false,
+ continues: false,
+ }),
+ }),
+ ],
+ });
+
+ const result = yield* service.list({ state: "open", filters: { draft: "hide" } });
+
+ assert.deepStrictEqual(
+ result.entries.map((entry) => entry.number),
+ [2],
+ );
+ }),
+);
+
+it.effect("keeps a row of a host that ignored the filters if any name of a label group holds", () =>
+ Effect.gen(function* () {
+ const sized = (number: number, updatedAt: string, ...names: ReadonlyArray<string>) => ({
+ ...changeRequest(number, updatedAt),
+ labels: names.map((name) => ({ name, color: null })),
+ });
+ const service = yield* makeService({
+ projects: [
+ project({
+ id: "p1",
+ title: "web",
+ workspaceRoot: "/a",
+ repository: "acme/web",
+ provider: "gitlab",
+ }),
+ ],
+ providers: [
+ fakeProvider("gitlab", {
+ listChangeRequests: () =>
+ Effect.succeed({
+ items: [
+ sized(1, "2026-07-04T00:00:00Z", "size:S", "bug"),
+ sized(2, "2026-07-03T00:00:00Z", "size:XS", "bug"),
+ sized(3, "2026-07-02T00:00:00Z", "size:L", "bug"),
+ sized(4, "2026-07-01T00:00:00Z", "size:S"),
+ ],
+ truncated: false,
+ continues: false,
+ }),
+ }),
+ ],
+ });
+
+ // Either size satisfies the first group; the second group is its own question, so the row
+ // carrying a size but no bug goes.
+ const result = yield* service.list({
+ state: "open",
+ filters: { labels: [["size:S", "size:XS"], ["bug"]] },
+ });
+
+ assert.deepStrictEqual(
+ result.entries.map((entry) => entry.number),
+ [1, 2],
+ );
+ }),
+);
+
+it.effect('resolves an author filter of "me" to the viewer before narrowing a host\'s rows', () =>
+ Effect.gen(function* () {
+ const service = yield* makeService({
+ projects: [
+ project({
+ id: "p1",
+ title: "web",
+ workspaceRoot: "/a",
+ repository: "acme/web",
+ provider: "gitlab",
+ }),
+ ],
+ providers: [
+ // Only GitHub narrows a listing for itself, so this fixture's "me" has to be resolved
+ // locally too — the same helper both call sites lean on.
+ fakeProvider("gitlab", {
+ listChangeRequests: () =>
+ Effect.succeed({
+ items: [
+ changeRequest(1, "2026-07-02T00:00:00Z"),
+ {
+ ...changeRequest(2, "2026-07-01T00:00:00Z"),
+ author: { login: "bilal", name: null, avatarUrl: null },
+ },
+ ],
+ truncated: false,
+ continues: false,
+ }),
+ }),
+ ],
+ });
+
+ const result = yield* service.list({ state: "open", filters: { author: "me" } });
+
+ assert.deepStrictEqual(
+ result.entries.map((entry) => entry.number),
+ [2],
+ );
+ }),
+);
+
+it.effect("refuses a way of updating a branch that the host or the viewer does not allow", () =>
+ Effect.gen(function* () {
+ let taken: string | null = null;
+ const service = yield* makeService({
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
+ providers: [
+ fakeProvider("github", {
+ capabilities: {
+ diff: true,
+ comment: true,
+ actions: ["merge", "close", "update-branch"],
+ mergeMethods: ["merge"],
+ // This host brings a stale branch up to date with a merge commit and nothing else.
+ updateMethods: ["merge"],
+ search: true,
+ reactions: true,
+ review: FULL_REVIEW,
+ reviewers: FULL_REVIEWERS,
+ },
+ getViewerPermissions: () =>
+ Effect.succeed({
+ actions: ["close", "update-branch"],
+ comment: true,
+ resolve: true,
+ verdicts: ["comment"],
+ requestReviewers: false,
+ updateMethods: ["merge"],
+ }),
+ runAction: (input) => {
+ taken = input.updateMethod ?? "default";
+ return Effect.void;
+ },
+ }),
+ ],
+ });
+ const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
+
+ // Asking for a rebase a host does not offer must fail rather than quietly merge instead.
+ const error = yield* Effect.flip(
+ service.runAction({ ...reference, action: "update-branch", updateMethod: "rebase" }),
+ );
+ assert.strictEqual(error._tag, "PullRequestOperationError");
+ assert.strictEqual(taken, null);
+
+ yield* service.runAction({ ...reference, action: "update-branch", updateMethod: "merge" });
+ assert.strictEqual(taken, "merge");
+ }),
+);
+
+it.effect("refuses to merge a target branch into a source branch on a host that only rebases", () =>
+ Effect.gen(function* () {
+ let taken = 0;
+ const service = yield* makeService({
+ projects: [
+ project({
+ id: "p1",
+ title: "on gitlab",
+ workspaceRoot: "/a",
+ repository: "group/project",
+ provider: "gitlab",
+ }),
+ ],
+ providers: [
+ fakeProvider("gitlab", {
+ capabilities: {
+ diff: true,
+ comment: true,
+ actions: ["merge", "close", "update-branch"],
+ mergeMethods: ["merge"],
+ // What GitLab declares: it replays the branch, and has no update that merges the
+ // target back in.
+ updateMethods: ["rebase"],
+ search: true,
+ reactions: true,
+ review: FULL_REVIEW,
+ reviewers: FULL_REVIEWERS,
+ },
+ getViewerPermissions: () =>
+ Effect.succeed({
+ actions: ["close", "update-branch"],
+ comment: true,
+ resolve: true,
+ verdicts: ["comment"],
+ requestReviewers: false,
+ updateMethods: ["rebase"],
+ }),
+ runAction: () => {
+ taken += 1;
+ return Effect.void;
+ },
+ }),
+ ],
+ });
+ const reference = { projectId: "p1" as ProjectId, repository: "group/project", number: 1 };
+
+ // A merge asked of a host that rebases must fail here rather than reach the provider, which
+ // would rebase instead and report the wrong thing as done.
+ const error = yield* Effect.flip(
+ service.runAction({ ...reference, action: "update-branch", updateMethod: "merge" }),
+ );
+ assert.strictEqual(error._tag, "PullRequestOperationError");
+ assert.strictEqual(taken, 0);
+
+ yield* service.runAction({ ...reference, action: "update-branch", updateMethod: "rebase" });
+ assert.strictEqual(taken, 1);
+ }),
+);
+
+it.effect("judges the review filter only on a host that summarises its reviews", () =>
+ Effect.gen(function* () {
+ const service = yield* makeService({
+ projects: [
+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
+ project({
+ id: "p2",
+ title: "on gitlab",
+ workspaceRoot: "/b",
+ repository: "group/project",
+ provider: "gitlab",
+ }),
+ ],
+ providers: [
+ // GitHub answers with the field on every row: null is "nobody has decided yet".
+ fakeProvider("github", {
+ listChangeRequests: () =>
+ Effect.succeed({
+ items: [
+ { ...changeRequest(1, "2026-07-02T00:00:00Z"), reviewDecision: null },
+ {
+ ...changeRequest(2, "2026-07-02T00:00:00Z"),
+ reviewDecision: "approved" as const,
+ },
+ ],
+ truncated: false,
+ continues: true,
+ }),
+ }),
+ // GitLab never supplies the field, so its rows are not the filter's to judge.
+ fakeProvider("gitlab", {
+ listChangeRequests: () =>
+ Effect.succeed({
+ items: [changeRequest(3, "2026-07-02T00:00:00Z")],
+ truncated: false,
+ continues: true,
+ }),
+ }),
+ ],
+ });
+
+ const none = yield* service.list({ state: "open", filters: { review: "none" } });
+ assert.deepStrictEqual(none.entries.map((entry) => entry.number).toSorted(), [1, 3]);
+
+ const approved = yield* service.list({ state: "open", filters: { review: "approved" } });
+ assert.deepStrictEqual(approved.entries.map((entry) => entry.number).toSorted(), [2, 3]);
+ }),
+);
+
+it.effect("sends only the words a rewrite carries", () =>
+ Effect.gen(function* () {
+ const received: Array<{ title?: string | undefined; body?: string | undefined }> = [];
+ 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", {
+ updateChangeRequest: (input) => {
+ received.push({ title: input.title, body: input.body });
+ return Effect.void;
+ },
+ }),
+ ],
+ });
+
+ yield* service.update({ ...reference, title: "A better title" });
+ yield* service.update({ ...reference, body: "" });
+ yield* service.update({ ...reference, title: "Both", body: "at once" });
+
+ assert.deepStrictEqual(received, [
+ { title: "A better title", body: undefined },
+ { title: undefined, body: "" },
+ { title: "Both", body: "at once" },
+ ]);
+ }),
+);
+
+it.effect("refuses a rewrite that changes nothing, before any call is made", () =>
+ Effect.gen(function* () {
+ const service = yield* makeService({
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
+ providers: [
+ fakeProvider("github", { updateChangeRequest: () => Effect.die("must not be called") }),
+ ],
+ });
+
+ const error = yield* Effect.flip(
+ service.update({ projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }),
+ );
+
+ assert.strictEqual(error._tag, "PullRequestOperationError");
+ assert.include(error.message, "Nothing was changed.");
+ }),
+);
+
+it.effect("refuses to rewrite anything on a host that never claimed it", () =>
+ Effect.gen(function* () {
+ const service = yield* makeService({
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
+ providers: [
+ fakeProvider("github", {
+ capabilities: {
+ diff: true,
+ comment: true,
+ actions: ["merge"],
+ mergeMethods: ["merge"],
+ search: true,
+ reactions: true,
+ review: FULL_REVIEW,
+ reviewers: FULL_REVIEWERS,
+ },
+ updateChangeRequest: () => Effect.die("must not be called"),
+ updateComment: () => Effect.die("must not be called"),
+ }),
+ ],
+ });
+ const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
+
+ const rewriteRefused = yield* Effect.flip(service.update({ ...reference, title: "New" }));
+ const commentRefused = yield* Effect.flip(
+ service.updateComment({
+ ...reference,
+ commentId: "IC_1",
+ kind: "issue-comment",
+ body: "New",
+ }),
+ );
+
+ assert.include(rewriteRefused.message, "cannot rewrite a change request.");
+ assert.include(commentRefused.message, "cannot rewrite a comment.");
+ }),
+);
+
+it.effect("passes a rewritten remark through with the id and kind it arrived under", () =>
+ Effect.gen(function* () {
+ let received: { id: string; kind: string; body: string } | null = null;
+ const service = yield* makeService({
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
+ providers: [
+ fakeProvider("github", {
+ updateComment: (input) => {
+ received = { id: input.commentId, kind: input.kind, body: input.body };
+ return Effect.void;
+ },
+ }),
+ ],
+ });
+
+ yield* service.updateComment({
+ projectId: "p1" as ProjectId,
+ repository: "acme/web",
+ number: 1,
+ commentId: "PRRC_1",
+ kind: "review-comment",
+ body: "Second thoughts",
+ });
+
+ assert.deepStrictEqual(received, {
+ id: "PRRC_1",
+ kind: "review-comment",
+ body: "Second thoughts",
+ });
+ }),
+);
+
+it.effect("refuses a remark rewritten into nothing but whitespace", () =>
+ Effect.gen(function* () {
+ const service = yield* makeService({
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
+ providers: [
+ fakeProvider("github", { updateComment: () => Effect.die("must not be called") }),
+ ],
+ });
+
+ const error = yield* Effect.flip(
+ service.updateComment({
+ projectId: "p1" as ProjectId,
+ repository: "acme/web",
+ number: 1,
+ commentId: "IC_1",
+ kind: "issue-comment",
+ body: " \n ",
+ }),
+ );
+
+ assert.include(error.message, "A comment cannot be empty.");
+ }),
+);
+
+it.effect("forgets the cached detail after a rewrite, like the other mutations", () =>
+ Effect.gen(function* () {
+ let coreCalls = 0;
+ 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", {
+ getChangeRequest: () => {
+ coreCalls += 1;
+ return Effect.succeed({
+ ...changeRequest(1, "2026-07-02T00:00:00Z"),
+ body: "",
+ changedFiles: 0,
+ mergedAt: null,
+ closedAt: null,
+ reviewers: [],
+ checks: [],
+ mergeCapabilities: { merge: true, squash: true, rebase: true },
+ viewerPermissions: {
+ actions: ["merge"],
+ comment: true,
+ resolve: true,
+ verdicts: ["comment", "approve", "request-changes"],
+ requestReviewers: true,
+ },
+ });
+ },
+ }),
+ ],
+ });
+
+ yield* service.detail(reference);
+ yield* service.update({ ...reference, title: "Renamed" });
+ yield* service.detail(reference);
+
+ assert.strictEqual(coreCalls, 2);
+ }),
+);
+
+it.effect("names the signed-in account in the detail, and says nothing where the host cannot", () =>
+ Effect.gen(function* () {
+ const detailFrom = (provider: PullRequestProviderApi) =>
+ Effect.gen(function* () {
+ const service = yield* makeService({
+ projects: [
+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
+ ],
+ providers: [provider],
+ });
+ return yield* service.detail({
+ projectId: "p1" as ProjectId,
+ repository: "acme/web",
+ number: 1,
+ });
+ });
+ const readable = fakeProvider("github", {
+ getChangeRequest: () =>
+ Effect.succeed({
+ ...changeRequest(1, "2026-07-02T00:00:00Z"),
+ body: "",
+ changedFiles: 0,
+ mergedAt: null,
+ closedAt: null,
+ reviewers: [],
+ checks: [],
+ mergeCapabilities: { merge: true, squash: true, rebase: true },
+ viewerPermissions: {
+ actions: ["merge"],
+ comment: true,
+ resolve: true,
+ verdicts: ["comment", "approve", "request-changes"],
+ requestReviewers: true,
+ },
+ }),
+ });
+
+ const named = yield* detailFrom(readable);
+ const unnamed = yield* detailFrom({
+ ...readable,
+ getViewer: () => Effect.fail(unusable("github", "unauthenticated")),
+ });
+
+ assert.strictEqual(named.viewer, "bilal");
+ assert.strictEqual(unnamed.viewer, undefined);
+ }),
+);
diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts
index adff1f837..f12f72bda 100644
--- a/apps/server/src/pullRequest/PullRequestService.ts
+++ b/apps/server/src/pullRequest/PullRequestService.ts
@@ -10,11 +10,13 @@ import {
PullRequestUnavailableError,
pullRequestHostOf,
pullRequestProviderRequirement,
+ resolvePullRequestAuthorFilter,
type OrchestrationProjectShell,
type PullRequestAction,
type PullRequestActionInput,
type PullRequestActivity,
type PullRequestCommentInput,
+ type PullRequestCommentUpdateInput,
type PullRequestDetail,
type PullRequestDiffFileContentsInput,
type PullRequestDiffFileContentsResult,
@@ -23,12 +25,14 @@ import {
type PullRequestDiffResult,
type PullRequestInvalidateInput,
type PullRequestListEntry,
+ type PullRequestListFilters,
type PullRequestListInput,
type PullRequestListProjectError,
type PullRequestListResult,
type PullRequestListStatsInput,
type PullRequestListStatsResult,
type PullRequestProviderSummary,
+ type PullRequestReactionInput,
type PullRequestRef,
type PullRequestReviewVerdict,
type PullRequestReviewerCandidateList,
@@ -36,6 +40,7 @@ import {
type PullRequestSubmitReviewInput,
type PullRequestThreadReplyInput,
type PullRequestThreadResolutionInput,
+ type PullRequestUpdateInput,
type SourceControlProviderInfo,
type SourceControlProviderKind,
} from "@t3tools/contracts";
@@ -134,7 +139,11 @@ export class PullRequestService extends Context.Service<
input: PullRequestDiffFileContentsInput,
) => Effect.Effect<PullRequestDiffFileContentsResult, PullRequestError>;
readonly runAction: (input: PullRequestActionInput) => Effect.Effect<void, PullRequestError>;
+ readonly update: (input: PullRequestUpdateInput) => Effect.Effect<void, PullRequestError>;
readonly comment: (input: PullRequestCommentInput) => Effect.Effect<void, PullRequestError>;
+ readonly updateComment: (
+ input: PullRequestCommentUpdateInput,
+ ) => Effect.Effect<void, PullRequestError>;
readonly submitReview: (
input: PullRequestSubmitReviewInput,
) => Effect.Effect<void, PullRequestError>;
@@ -144,6 +153,9 @@ export class PullRequestService extends Context.Service<
readonly setThreadResolution: (
input: PullRequestThreadResolutionInput,
) => Effect.Effect<void, PullRequestError>;
+ readonly setReaction: (
+ input: PullRequestReactionInput,
+ ) => Effect.Effect<void, PullRequestError>;
readonly reviewerCandidates: (
input: PullRequestRef,
) => Effect.Effect<PullRequestReviewerCandidateList, PullRequestError>;
@@ -174,8 +186,14 @@ const ACTION_ACCESS_REFUSALS: Record<PullRequestAction, string> = {
"You need write access on this repository, or to have opened this change request, to return it to a draft.",
close:
"You need write access on this repository, or to have opened this change request, to close it.",
+ "update-branch":
+ "You need write access on this repository, or to have opened this change request, to update its branch.",
reopen:
"You need write access on this repository, or to have opened this change request, to reopen it.",
+ "enable-auto-merge":
+ "You need write access on this repository to have it merged for you once it is ready.",
+ "disable-auto-merge":
+ "You need write access on this repository to stop it being merged for you once it is ready.",
};
/**
@@ -349,13 +367,25 @@ function toPullRequestError(
}
/**
- * The provider-native repository identity. `displayName` is the full path below the host, which
- * is what nested GitLab groups and Azure project paths need; owner/name is the two-segment
- * fallback for identities recorded before that field existed.
+ * 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.
*/
-function repositoryIdentityOf(project: OrchestrationProjectShell): string | null {
+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;
}
@@ -424,7 +454,7 @@ export const make = Effect.gen(function* () {
};
const listWorkspaceProjects = (
- filter: Pick<PullRequestListInput, "projectId" | "host">,
+ filter: Pick<PullRequestListInput, "projectId" | "projectIds" | "host">,
): Effect.Effect<WorkspaceProjects, PullRequestError> =>
projections.getShellSnapshot().pipe(
Effect.mapError(
@@ -450,6 +480,7 @@ export const make = Effect.gen(function* () {
const seen = new Set<string>();
for (const project of snapshot.projects) {
if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
+ 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);
@@ -603,6 +634,43 @@ export const make = Effect.gen(function* () {
{ concurrency: REPOSITORY_CONCURRENCY },
);
+ /**
+ * The narrowings a row can be judged by from its own fields, applied here rather than trusted
+ * to the host. Only GitHub is asked to narrow a listing for itself; every other provider
+ * answers unnarrowed, and without this pass a draft filter or a label filter would be sent,
+ * accepted and quietly ignored. Idempotent for the hosts that did narrow.
+ *
+ * `checks` is absent because no listed row carries its check state: that one filter is the
+ * host's alone, and a row nobody narrowed stays rather than being guessed at.
+ */
+ const matchesRowFilters = (
+ item: ProviderChangeRequest,
+ filters: PullRequestListFilters | undefined,
+ 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());
+ return (
+ (filters.draft === undefined || item.isDraft === (filters.draft === "only")) &&
+ // Judged on the provider row rather than the entry, because the two absences mean
+ // different things and the entry keeps only one of them: `null` is a host that summarises
+ // its reviews saying there is no decision yet, which is what "none" asks for, while
+ // `undefined` is a host that does not summarise at all — an unjudgeable row, left alone
+ // the way an unreadable check state is.
+ (filters.review === undefined ||
+ item.reviewDecision === undefined ||
+ (filters.review === "none"
+ ? item.reviewDecision === null
+ : item.reviewDecision === filters.review)) &&
+ (filters.labels === undefined || filters.labels.every((group) => group.some(holds))) &&
+ (filters.excludedLabels === undefined || !filters.excludedLabels.some(holds)) &&
+ (filters.author === undefined ||
+ item.author?.login.toLowerCase() ===
+ resolvePullRequestAuthorFilter(filters.author, viewer).toLowerCase())
+ );
+ };
+
const toEntry = (input: {
readonly project: SupportedProject;
readonly item: ProviderChangeRequest;
@@ -628,10 +696,16 @@ export const make = Effect.gen(function* () {
deletions: input.item.deletions,
createdAt: input.item.createdAt,
updatedAt: input.item.updatedAt,
+ ...(input.item.checksState === undefined || input.item.checksState === null
+ ? {}
+ : { checksState: input.item.checksState }),
viewerReviewRequested:
input.item.author?.login.toLowerCase() !== viewer &&
input.item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer),
labels: input.item.labels,
+ ...(input.item.reviewDecision === undefined || input.item.reviewDecision === null
+ ? {}
+ : { reviewDecision: input.item.reviewDecision }),
};
};
@@ -755,6 +829,7 @@ export const make = Effect.gen(function* () {
// Each host matches this its own way, and one that cannot match text at all
// answers unnarrowed rather than failing.
query: input.query,
+ filters: input.filters,
// Only the two fields a host can act on: which rows have already been sent at the
// boundary instant is this service's business, not a provider's.
...(cursor === undefined
@@ -778,7 +853,9 @@ export const make = Effect.gen(function* () {
);
return {
key,
- entries: items.map((item) => toEntry({ project, item, viewer })),
+ entries: items
+ .filter((item) => matchesRowFilters(item, input.filters, viewer))
+ .map((item) => toEntry({ project, item, viewer })),
errors: [],
truncated: page.truncated,
nextCursor:
@@ -836,6 +913,7 @@ export const make = Effect.gen(function* () {
viewer,
limit,
query: input.query,
+ filters: input.filters,
...(cursor === undefined
? {}
: { cursor: { updatedBefore: cursor.updatedBefore, delivered: cursor.delivered } }),
@@ -881,7 +959,9 @@ export const make = Effect.gen(function* () {
);
return Effect.succeed({
key: listCursorKey(project.host, project.repository),
- entries: items.map((item) => toEntry({ project, item, viewer })),
+ entries: items
+ .filter((item) => matchesRowFilters(item, input.filters, viewer))
+ .map((item) => toEntry({ project, item, viewer })),
errors: [],
truncated: page.truncated,
nextCursor:
@@ -939,51 +1019,72 @@ export const make = Effect.gen(function* () {
};
});
+ /**
+ * Who this project's host says the reader is. Shared with the listing's own lookup — the same
+ * ten-minute answer per host — so a page that has already listed anything pays nothing for it,
+ * and a host that cannot say leaves it null rather than failing the read it decorates.
+ */
+ const viewerOf = (project: SupportedProject): Effect.Effect<string | null> =>
+ resolveViewers([project], new Map()).pipe(Effect.map(([resolved]) => resolved?.viewer ?? null));
+
const detailUncached: PullRequestService["Service"]["detail"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project) =>
- project.api
- .getChangeRequest({
- cwd: project.project.workspaceRoot,
- repository: project.repository,
- host: project.host,
- number: input.number,
- })
- .pipe(
- Effect.mapError(toPullRequestError("detail")),
- Effect.map(
- (changeRequest): PullRequestDetail => ({
- provider: project.api.kind,
- capabilities: project.api.capabilities,
- projectId: project.project.id,
- projectTitle: project.project.title,
- workspaceRoot: project.project.workspaceRoot,
+ Effect.all(
+ [
+ project.api
+ .getChangeRequest({
+ cwd: project.project.workspaceRoot,
repository: project.repository,
- number: changeRequest.number,
- title: changeRequest.title,
- body: changeRequest.body,
- url: changeRequest.url,
- author: changeRequest.author,
- state: changeRequest.state,
- isDraft: changeRequest.isDraft,
- mergeability: changeRequest.mergeability,
- additions: changeRequest.additions,
- deletions: changeRequest.deletions,
- changedFiles: changeRequest.changedFiles,
- headBranch: changeRequest.headBranch,
- baseBranch: changeRequest.baseBranch,
- createdAt: changeRequest.createdAt,
- updatedAt: changeRequest.updatedAt,
- mergedAt: changeRequest.mergedAt,
- closedAt: changeRequest.closedAt,
- reviewers: changeRequest.reviewers,
- labels: changeRequest.labels,
- checks: changeRequest.checks,
- mergeCapabilities: changeRequest.mergeCapabilities,
- viewerPermissions: changeRequest.viewerPermissions,
- }),
- ),
+ host: project.host,
+ number: input.number,
+ })
+ .pipe(Effect.mapError(toPullRequestError("detail"))),
+ viewerOf(project),
+ ],
+ { concurrency: 2 },
+ ).pipe(
+ Effect.map(
+ ([changeRequest, viewer]): PullRequestDetail => ({
+ provider: project.api.kind,
+ capabilities: project.api.capabilities,
+ projectId: project.project.id,
+ projectTitle: project.project.title,
+ workspaceRoot: project.project.workspaceRoot,
+ repository: project.repository,
+ number: changeRequest.number,
+ title: changeRequest.title,
+ body: changeRequest.body,
+ url: changeRequest.url,
+ author: changeRequest.author,
+ state: changeRequest.state,
+ isDraft: changeRequest.isDraft,
+ mergeability: changeRequest.mergeability,
+ additions: changeRequest.additions,
+ deletions: changeRequest.deletions,
+ changedFiles: changeRequest.changedFiles,
+ headBranch: changeRequest.headBranch,
+ baseBranch: changeRequest.baseBranch,
+ createdAt: changeRequest.createdAt,
+ updatedAt: changeRequest.updatedAt,
+ mergedAt: changeRequest.mergedAt,
+ closedAt: changeRequest.closedAt,
+ reviewers: changeRequest.reviewers,
+ labels: changeRequest.labels,
+ checks: changeRequest.checks,
+ mergeCapabilities: changeRequest.mergeCapabilities,
+ viewerPermissions: changeRequest.viewerPermissions,
+ ...(viewer === null || viewer.trim().length === 0 ? {} : { viewer }),
+ ...(changeRequest.baseComparison === undefined
+ ? {}
+ : { baseComparison: changeRequest.baseComparison }),
+ ...(changeRequest.behindBy === undefined ? {} : { behindBy: changeRequest.behindBy }),
+ ...(changeRequest.autoMergeEnabled === undefined
+ ? {}
+ : { autoMergeEnabled: changeRequest.autoMergeEnabled }),
+ }),
),
+ ),
),
);
@@ -1008,6 +1109,7 @@ export const make = Effect.gen(function* () {
commentsTruncated: activity.commentsTruncated,
reviewThreads: activity.reviewThreads,
commits: activity.commits,
+ ...(activity.reactions === undefined ? {} : { reactions: activity.reactions }),
}),
),
),
@@ -1088,6 +1190,19 @@ export const make = Effect.gen(function* () {
}),
);
}
+ // The same for the way a stale branch is brought up to date: a host that only merges
+ // must not be asked to rebase and left to pick something else.
+ if (
+ input.updateMethod !== undefined &&
+ !(project.api.capabilities.updateMethods ?? []).includes(input.updateMethod)
+ ) {
+ return Effect.fail(
+ new PullRequestOperationError({
+ operation: "runAction",
+ detail: `This host cannot update a branch by ${input.updateMethod}.`,
+ }),
+ );
+ }
// What the host can do and what this account may ask of it are two questions, and both
// have to say yes. The second is asked last, because it costs a request and the checks
// above do not.
@@ -1101,6 +1216,17 @@ export const make = Effect.gen(function* () {
}),
);
}
+ if (
+ input.updateMethod !== undefined &&
+ !(viewer.updateMethods ?? []).includes(input.updateMethod)
+ ) {
+ return Effect.fail(
+ new PullRequestOperationError({
+ operation: "runAction",
+ detail: ACTION_ACCESS_REFUSALS["update-branch"],
+ }),
+ );
+ }
return project.api
.runAction({
cwd: project.project.workspaceRoot,
@@ -1109,6 +1235,7 @@ export const make = Effect.gen(function* () {
number: input.number,
action: input.action,
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
+ ...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
})
.pipe(Effect.mapError(toPullRequestError("runAction")));
}),
@@ -1162,6 +1289,76 @@ export const make = Effect.gen(function* () {
}),
);
+ /**
+ * Rewriting the change request's own words, and rewriting a remark, are both left to the host to
+ * allow or refuse. Neither is a question a permission read answers: every host lets the person
+ * who wrote something rewrite it whatever access they have otherwise, and none of them reports
+ * that as a permission — so a check here could only guess, and a wrong guess takes the control
+ * away from the one person certain to be allowed.
+ */
+ const update: PullRequestService["Service"]["update"] = (input) =>
+ requireProject(input).pipe(
+ Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
+ const rewrite = project.api.updateChangeRequest;
+ if (project.api.capabilities.edit?.changeRequest !== true || rewrite === undefined) {
+ return Effect.fail(
+ new PullRequestOperationError({
+ operation: "update",
+ detail: "This host cannot rewrite a change request.",
+ }),
+ );
+ }
+ if (input.title === undefined && input.body === undefined) {
+ return Effect.fail(
+ new PullRequestOperationError({
+ operation: "update",
+ detail: "Nothing was changed.",
+ }),
+ );
+ }
+ return rewrite({
+ cwd: project.project.workspaceRoot,
+ repository: project.repository,
+ host: project.host,
+ number: input.number,
+ ...(input.title === undefined ? {} : { title: input.title }),
+ ...(input.body === undefined ? {} : { body: input.body }),
+ }).pipe(Effect.mapError(toPullRequestError("update")));
+ }),
+ );
+
+ const updateComment: PullRequestService["Service"]["updateComment"] = (input) =>
+ (input.body.trim().length === 0
+ ? Effect.fail(
+ new PullRequestOperationError({
+ operation: "updateComment",
+ detail: "A comment cannot be empty.",
+ }),
+ )
+ : requireProject(input)
+ ).pipe(
+ Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
+ const rewrite = project.api.updateComment;
+ if (project.api.capabilities.edit?.comment !== true || rewrite === undefined) {
+ return Effect.fail(
+ new PullRequestOperationError({
+ operation: "updateComment",
+ detail: "This host cannot rewrite a comment.",
+ }),
+ );
+ }
+ return rewrite({
+ cwd: project.project.workspaceRoot,
+ repository: project.repository,
+ host: project.host,
+ number: input.number,
+ commentId: input.commentId,
+ kind: input.kind,
+ body: input.body,
+ }).pipe(Effect.mapError(toPullRequestError("updateComment")));
+ }),
+ );
+
const submitReview: PullRequestService["Service"]["submitReview"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
@@ -1297,6 +1494,36 @@ export const make = Effect.gen(function* () {
}),
);
+ /**
+ * Reacting is gated on the host alone. Every host with reactions takes one from whoever can read
+ * the change request, so there is no access left to check that reading it has not already
+ * settled.
+ */
+ const setReaction: PullRequestService["Service"]["setReaction"] = (input) =>
+ requireProject(input).pipe(
+ Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
+ if (project.api.capabilities.reactions !== true) {
+ return Effect.fail(
+ new PullRequestOperationError({
+ operation: "setReaction",
+ detail: "This host has no reactions.",
+ }),
+ );
+ }
+ return project.api
+ .setReaction({
+ cwd: project.project.workspaceRoot,
+ repository: project.repository,
+ host: project.host,
+ number: input.number,
+ ...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
+ content: input.content,
+ reacted: input.reacted,
+ })
+ .pipe(Effect.mapError(toPullRequestError("setReaction")));
+ }),
+ );
+
/**
* Who may be asked is only ever wanted by somebody about to ask, because the menu it fills is
* the one the request is made from. So the same permission guards both: a page that could open
@@ -1520,6 +1747,23 @@ export const make = Effect.gen(function* () {
refEpochs.set(scope, ++epochCounter);
};
+ /** The positional filter slot of a cache key, back as the record `listUncached` takes. */
+ const filtersOfKey = (
+ slots: ReadonlyArray<
+ string | ReadonlyArray<string> | ReadonlyArray<ReadonlyArray<string>> | null
+ >,
+ ): PullRequestListFilters => {
+ const [draft, review, checks, author, labels, excludedLabels] = slots;
+ return {
+ ...(typeof draft === "string" ? { draft: draft as "only" | "hide" } : {}),
+ ...(typeof review === "string" ? { review: review as PullRequestListFilters["review"] } : {}),
+ ...(typeof checks === "string" ? { checks: checks as PullRequestListFilters["checks"] } : {}),
+ ...(typeof author === "string" ? { author } : {}),
+ ...(Array.isArray(labels) ? { labels: labels as ReadonlyArray<ReadonlyArray<string>> } : {}),
+ ...(Array.isArray(excludedLabels) ? { excludedLabels } : {}),
+ };
+ };
+
// 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
@@ -1528,13 +1772,24 @@ export const make = Effect.gen(function* () {
(key: string) => {
// The parse undoes this module's own serialization, so the shapes are known exactly;
// the cast restores the branded field types JSON cannot carry.
- const [, state, involvement, projectId, host, limit, query, cursorEntries] = JSON.parse(
- key,
- ) as [
+ const [
+ ,
+ state,
+ involvement,
+ filters,
+ projectId,
+ projectIds,
+ host,
+ limit,
+ query,
+ cursorEntries,
+ ] = JSON.parse(key) as [
number,
string,
string | null,
+ ReadonlyArray<string | ReadonlyArray<string> | null> | null,
string | null,
+ ReadonlyArray<string> | null,
string | null,
number | null,
string | null,
@@ -1543,7 +1798,9 @@ export const make = Effect.gen(function* () {
return listUncached({
state,
...(involvement === null ? {} : { involvement }),
+ ...(filters === null ? {} : { filters: filtersOfKey(filters) }),
...(projectId === null ? {} : { projectId }),
+ ...(projectIds === null ? {} : { projectIds }),
...(host === null ? {} : { host }),
...(limit === null ? {} : { limit }),
...(query === null ? {} : { query }),
@@ -1564,7 +1821,20 @@ export const make = Effect.gen(function* () {
listingsEpoch,
input.state,
input.involvement ?? null,
+ // Positional so two identical filter sets key alike however their record was assembled.
+ input.filters === undefined
+ ? null
+ : [
+ input.filters.draft ?? null,
+ input.filters.review ?? null,
+ input.filters.checks ?? null,
+ input.filters.author ?? null,
+ input.filters.labels ?? null,
+ input.filters.excludedLabels ?? null,
+ ],
input.projectId ?? null,
+ // Sorted so the same narrowing keys alike however the caller ordered it.
+ input.projectIds === undefined ? null : [...input.projectIds].sort(),
input.host ?? null,
input.limit ?? null,
input.query ?? null,
@@ -1726,10 +1996,13 @@ export const make = Effect.gen(function* () {
diff,
diffFileContents,
runAction: invalidatedByMutation(runAction),
+ update: invalidatedByMutation(update),
comment: invalidatedByMutation(comment),
+ updateComment: invalidatedByMutation(updateComment),
submitReview: invalidatedByMutation(submitReview),
replyToThread: invalidatedByMutation(replyToThread),
setThreadResolution: invalidatedByMutation(setThreadResolution),
+ setReaction: invalidatedByMutation(setReaction),
// The candidate list is deliberately read fresh per menu-open, so it stays uncached.
reviewerCandidates,
requestReviewers: invalidatedByMutation(requestReviewers),
diff --git a/apps/server/src/pullRequest/azureDevOpsPullRequestJson.test.ts b/apps/server/src/pullRequest/azureDevOpsPullRequestJson.test.ts
index 3ac55cde1..a975c89f8 100644
--- a/apps/server/src/pullRequest/azureDevOpsPullRequestJson.test.ts
+++ b/apps/server/src/pullRequest/azureDevOpsPullRequestJson.test.ts
@@ -144,6 +144,21 @@ describe("decodePullRequestJson", () => {
]);
});
+ it("reads auto-complete from whoever armed it, and its absence as nobody", () => {
+ const armed = expectSuccess(
+ decodePullRequestJson(
+ asJson(pullRequest({ autoCompleteSetBy: { displayName: "Bilal Hassan" } })),
+ ),
+ );
+ expect(armed?.autoMergeEnabled).toBe(true);
+
+ // Azure leaves the field out entirely rather than sending it empty, so its absence is the
+ // whole of what it says about auto-complete being off.
+ expect(expectSuccess(decodePullRequestJson(asJson(pullRequest())))?.autoMergeEnabled).toBe(
+ false,
+ );
+ });
+
it("works out where the conversation lives from what Azure returned", () => {
const detail = expectSuccess(decodePullRequestJson(asJson(pullRequest())));
diff --git a/apps/server/src/pullRequest/azureDevOpsPullRequestJson.ts b/apps/server/src/pullRequest/azureDevOpsPullRequestJson.ts
index a51eef4f0..39ca4a551 100644
--- a/apps/server/src/pullRequest/azureDevOpsPullRequestJson.ts
+++ b/apps/server/src/pullRequest/azureDevOpsPullRequestJson.ts
@@ -35,6 +35,12 @@ const RawPullRequestSchema = Schema.Struct({
description: Schema.optional(Schema.NullOr(Schema.String)),
status: Schema.optional(Schema.NullOr(Schema.String)),
isDraft: Schema.optional(Schema.NullOr(Schema.Boolean)),
+ /**
+ * Who armed auto-complete, which is the only thing Azure says about it: the field carries an
+ * identity while the pull request is set to complete on its own, and Azure leaves it out
+ * entirely once nobody has. So its presence is the answer, and there is no third state.
+ */
+ autoCompleteSetBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
mergeStatus: Schema.optional(Schema.NullOr(Schema.String)),
createdBy: Schema.optional(Schema.NullOr(RawIdentitySchema)),
reviewers: Schema.optional(Schema.NullOr(Schema.Array(RawIdentitySchema))),
@@ -124,6 +130,8 @@ export interface AzureDevOpsPullRequest {
readonly reviewers: ReadonlyArray<PullRequestActor>;
/** Where this pull request's threads live, when Azure said enough to work it out. */
readonly threadsUrl: string | null;
+ /** Whether Azure is set to complete this on its own once its policies pass. */
+ readonly autoMergeEnabled: boolean;
}
function trimmed(value: string | null | undefined): string | null {
@@ -223,6 +231,7 @@ function toPullRequest(
reviewRequestLogins: reviewers.map((reviewer) => reviewer.login),
reviewers,
threadsUrl: toThreadsUrl(raw),
+ autoMergeEnabled: (raw.autoCompleteSetBy ?? null) !== null,
};
}
diff --git a/apps/server/src/pullRequest/bitbucketPullRequestJson.test.ts b/apps/server/src/pullRequest/bitbucketPullRequestJson.test.ts
index 81212949f..a348ac4b3 100644
--- a/apps/server/src/pullRequest/bitbucketPullRequestJson.test.ts
+++ b/apps/server/src/pullRequest/bitbucketPullRequestJson.test.ts
@@ -315,6 +315,22 @@ describe("decodeStatusesJson", () => {
expect(decoded.items[0]?.status).toBe(expected);
});
+
+ it("keeps two statuses that share a display name but have different keys", () => {
+ const decoded = expectSuccess(
+ decodeStatusesJson(
+ page([
+ { key: "build", name: "Pipeline", state: "SUCCESSFUL" },
+ { key: "deploy", name: "Pipeline", state: "FAILED" },
+ ]),
+ ),
+ );
+
+ expect(decoded.items.map((check) => [check.name, check.status])).toEqual([
+ ["build / Pipeline", "success"],
+ ["deploy / Pipeline", "failure"],
+ ]);
+ });
});
describe("decodeDiffstatJson", () => {
diff --git a/apps/server/src/pullRequest/bitbucketPullRequestJson.ts b/apps/server/src/pullRequest/bitbucketPullRequestJson.ts
index 697ab2bbb..b0711b8ff 100644
--- a/apps/server/src/pullRequest/bitbucketPullRequestJson.ts
+++ b/apps/server/src/pullRequest/bitbucketPullRequestJson.ts
@@ -18,6 +18,8 @@ import type {
import { TrimmedNonEmptyString } from "@t3tools/contracts";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
+import { dedupeChecks } from "./pullRequestChecks.ts";
+
/**
* Bitbucket's enums are decoded as plain strings and normalized here, in the same tolerant
* style as the GitHub and GitLab decoders: a new pull request state or build status must not
@@ -547,21 +549,33 @@ export function decodeStatusesJson(
if (!Result.isSuccess(decoded)) {
return Result.fail(decoded.failure);
}
- const checks: PullRequestCheck[] = [];
+ const checks: Array<{
+ readonly check: PullRequestCheck;
+ readonly workflowName: string | null;
+ readonly at: string | null;
+ }> = [];
for (const entry of decoded.success.values) {
const decodedStatus = decodeStatusEntry(entry);
if (Exit.isFailure(decodedStatus)) continue;
const status = decodedStatus.value;
const name = trimmed(status.name) ?? trimmed(status.key);
if (name === null) continue;
+ // Bitbucket re-uses a status key when a pipeline is run again, so the same check can appear
+ // twice on one page. Nothing decoded here says which copy is newer, so the later one wins,
+ // which is the order Bitbucket writes an update in. The key is kept as the workflow name so
+ // two different pipelines that display the same name are not folded into one.
checks.push({
- name,
- status: toBuildStatus(status.state),
- description: trimmed(status.description),
- url: trimmed(status.url),
+ check: {
+ name,
+ status: toBuildStatus(status.state),
+ description: trimmed(status.description),
+ url: trimmed(status.url),
+ },
+ workflowName: trimmed(status.key),
+ at: null,
});
}
- return Result.succeed({ items: checks, next: trimmed(decoded.success.next) });
+ return Result.succeed({ items: dedupeChecks(checks), next: trimmed(decoded.success.next) });
}
export interface BitbucketDiffStat {
diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts
index d3d9945da..a3c3524a6 100644
--- a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts
+++ b/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts
@@ -4,16 +4,20 @@ import { describe, expect, it } from "vite-plus/test";
import {
buildReviewSubmissionJson,
buildReviewerRequestJson,
+ decodeBaseComparisonJson,
decodePullRequestActivityJson,
decodePullRequestDetailJson,
decodePullRequestFilesJson,
decodePullRequestListJson,
+ decodePullRequestNodeIdJson,
+ decodePullRequestSearchJson,
decodeRepositoryAccessJson,
decodeReviewerCandidatesJson,
decodeReviewThreadCommentsJson,
decodeReviewThreadsJson,
decodeViewerPermissionsJson,
reviewThreadConversation,
+ REVIEW_THREADS_GRAPHQL_QUERY,
} from "./gitHubPullRequestJson.ts";
function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
@@ -67,6 +71,65 @@ describe("pull request list decoding", () => {
expect(entry?.reviewRequestLogins).toEqual(["octocat"]);
});
+ it("normalizes the review decision and reports nothing for one GitHub does not summarize", () => {
+ const batch = expectSuccess(
+ decodePullRequestListJson(
+ listJson([
+ { reviewDecision: "APPROVED" },
+ { reviewDecision: "CHANGES_REQUESTED" },
+ { reviewDecision: "REVIEW_REQUIRED" },
+ { reviewDecision: null },
+ ]),
+ ),
+ );
+ expect(batch.items.map((entry) => entry.reviewDecision)).toEqual([
+ "approved",
+ "changes-requested",
+ "review-required",
+ null,
+ ]);
+ });
+
+ it("rolls the head commit's checks up to the one word a row has space for", () => {
+ const batch = expectSuccess(
+ decodePullRequestListJson(
+ listJson([
+ // A failure outranks a run still going, and a completed run has to be read through its
+ // conclusion rather than its status.
+ {
+ statusCheckRollup: [
+ { name: "lint", status: "COMPLETED", conclusion: "SUCCESS" },
+ { name: "build", status: "IN_PROGRESS" },
+ { name: "test", status: "COMPLETED", conclusion: "FAILURE" },
+ ],
+ },
+ {
+ statusCheckRollup: [
+ { name: "lint", status: "COMPLETED", conclusion: "SUCCESS" },
+ { name: "build", status: "QUEUED" },
+ ],
+ },
+ { statusCheckRollup: [{ name: "lint", status: "COMPLETED", conclusion: "SUCCESS" }] },
+ // A commit status reports one `state` and no `status` at all.
+ { statusCheckRollup: [{ context: "ci/legacy", state: "ERROR" }] },
+ // Neither a pass, a failure nor a wait is no verdict rather than a green tick.
+ { statusCheckRollup: [{ name: "lint", status: "COMPLETED", conclusion: "SKIPPED" }] },
+ { statusCheckRollup: [] },
+ {},
+ ]),
+ ),
+ );
+ expect(batch.items.map((entry) => entry.checksState)).toEqual([
+ "failing",
+ "pending",
+ "passing",
+ "failing",
+ null,
+ null,
+ null,
+ ]);
+ });
+
it("skips malformed entries but still counts them, so paging does not stop early", () => {
const raw = `[${listJson([{}]).slice(1, -1)},{"number":"not-a-number"}]`;
const batch = expectSuccess(decodePullRequestListJson(raw));
@@ -75,6 +138,49 @@ describe("pull request list decoding", () => {
});
});
+describe("pull request search decoding", () => {
+ function searchJson(rollupStates: ReadonlyArray<string | null>): string {
+ return JSON.stringify({
+ data: {
+ search: {
+ pageInfo: { hasNextPage: false },
+ nodes: rollupStates.map((state, index) => ({
+ number: index + 1,
+ title: "Add the pull requests page",
+ url: "https://github.com/pingdotgg/t3code/pull/1",
+ headRefName: "feat/page",
+ baseRefName: "main",
+ createdAt: "2026-07-01T00:00:00Z",
+ updatedAt: "2026-07-02T00:00:00Z",
+ repository: { nameWithOwner: "pingdotgg/t3code" },
+ commits: {
+ nodes: [{ commit: { statusCheckRollup: state === null ? null : { state } } }],
+ },
+ })),
+ },
+ },
+ });
+ }
+
+ it("maps the rollup enum the search answers with onto the same three words", () => {
+ // The search asks GitHub for the verdict rather than the checks behind it, so this path sees
+ // one enum where the listing sees an array.
+ const batch = expectSuccess(
+ decodePullRequestSearchJson(
+ searchJson(["SUCCESS", "FAILURE", "ERROR", "PENDING", "EXPECTED", null]),
+ ),
+ );
+ expect(batch.items.map((entry) => entry.checksState)).toEqual([
+ "passing",
+ "failing",
+ "failing",
+ "pending",
+ "pending",
+ null,
+ ]);
+ });
+});
+
describe("pull request detail decoding", () => {
const detailJson = JSON.stringify({
number: 7,
@@ -117,6 +223,58 @@ describe("pull request detail decoding", () => {
]);
});
+ it("reads an auto-merge request as armed, its null as off and its absence as neither", () => {
+ const raw = JSON.parse(detailJson) as Record<string, unknown>;
+ const armed = (entry: Record<string, unknown>) =>
+ expectSuccess(decodePullRequestDetailJson(JSON.stringify({ ...raw, ...entry })))
+ .autoMergeEnabled;
+
+ expect(
+ armed({ autoMergeRequest: { enabledBy: { login: "octocat" }, mergeMethod: "SQUASH" } }),
+ ).toBe(true);
+ expect(armed({ autoMergeRequest: null })).toBe(false);
+ // `gh` not answering for the field at all is not GitHub saying the merge is unarmed.
+ expect(armed({})).toBeUndefined();
+ });
+
+ it("shows a re-running check once, as the run that is happening now", () => {
+ // What `statusCheckRollup` reports while a workflow is being re-run: the same check twice,
+ // the finished run and the one that replaced it, with no id to tell them apart.
+ const raw = JSON.parse(detailJson) as Record<string, unknown>;
+ const detail = expectSuccess(
+ decodePullRequestDetailJson(
+ JSON.stringify({
+ ...raw,
+ statusCheckRollup: [
+ {
+ __typename: "CheckRun",
+ name: "Prepare PR size config",
+ workflowName: "PR Size",
+ status: "COMPLETED",
+ conclusion: "SUCCESS",
+ startedAt: "2026-08-11T16:06:20Z",
+ completedAt: "2026-08-11T16:06:25Z",
+ },
+ {
+ __typename: "CheckRun",
+ name: "Prepare PR size config",
+ workflowName: "PR Size",
+ status: "IN_PROGRESS",
+ conclusion: "",
+ startedAt: "2026-08-11T17:01:04Z",
+ completedAt: "0001-01-01T00:00:00Z",
+ },
+ ],
+ }),
+ ),
+ );
+
+ expect(detail.checks.map((check) => [check.name, check.status])).toEqual([
+ ["Prepare PR size config", "pending"],
+ ]);
+ expect(detail.checksState).toBe("pending");
+ });
+
it("merges reviews with comments in time order and keeps a bodyless approval", () => {
const detail = expectSuccess(decodePullRequestActivityJson(detailJson));
// r2 approved without writing anything, which is still the event worth seeing.
@@ -461,6 +619,89 @@ describe("review thread decoding", () => {
});
});
+describe("reaction decoding", () => {
+ const commentWithGroups = (reactionGroups: ReadonlyArray<Record<string, unknown>>) =>
+ JSON.stringify({
+ data: {
+ node: {
+ comments: {
+ pageInfo: { hasNextPage: false, endCursor: null },
+ nodes: [{ id: "t1", body: "nice", createdAt: "2026-07-01T00:00:00Z", reactionGroups }],
+ },
+ },
+ },
+ });
+
+ it("keeps a named group, widens a group whose reactors were cut short, drops an unknown content and an empty group", () => {
+ const decoded = expectSuccess(
+ decodeReviewThreadCommentsJson(
+ commentWithGroups([
+ {
+ content: "THUMBS_UP",
+ viewerHasReacted: true,
+ reactors: { totalCount: 2, nodes: [{ login: "julius" }, { login: "bilal" }] },
+ },
+ // Not one of the eight the contract carries.
+ {
+ content: "PARTY_PARROT",
+ reactors: { totalCount: 1, nodes: [{ login: "hubot" }] },
+ },
+ // Nobody behind it, which GitHub still answers a group for.
+ { content: "HEART", reactors: { totalCount: 0, nodes: [] } },
+ // More reactors than the bounded read named, and no `viewerHasReacted` at all.
+ {
+ content: "ROCKET",
+ reactors: { totalCount: 140, nodes: [{ login: "a" }, { login: "b" }, { login: "c" }] },
+ },
+ ]),
+ ),
+ );
+
+ expect(decoded.comments[0]?.reactions).toEqual([
+ { content: "thumbs-up", count: 2, actors: ["julius", "bilal"], viewerHasReacted: true },
+ { content: "rocket", count: 140, actors: ["a", "b", "c"], viewerHasReacted: false },
+ ]);
+ });
+
+ it("leaves the viewer's own login out of actors, matched case-insensitively, while count still counts them", () => {
+ const decoded = expectSuccess(
+ decodeReviewThreadCommentsJson(
+ JSON.stringify({
+ data: {
+ viewer: { login: "Bilal" },
+ node: {
+ comments: {
+ pageInfo: { hasNextPage: false, endCursor: null },
+ nodes: [
+ {
+ id: "t1",
+ body: "nice",
+ createdAt: "2026-07-01T00:00:00Z",
+ reactionGroups: [
+ {
+ content: "HEART",
+ viewerHasReacted: true,
+ reactors: {
+ totalCount: 2,
+ nodes: [{ login: "bilal" }, { login: "julius" }],
+ },
+ },
+ ],
+ },
+ ],
+ },
+ },
+ },
+ }),
+ ),
+ );
+
+ expect(decoded.comments[0]?.reactions).toEqual([
+ { content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
+ ]);
+ });
+});
+
describe("repository access decoding", () => {
const repositoryJson = (viewerPermission?: string | null) =>
JSON.stringify({
@@ -618,6 +859,7 @@ describe("review thread decoding", () => {
body: "first",
createdAt: "2026-07-01T00:00:00Z",
url: "https://github.com/acme/web/pull/1#discussion_rc1",
+ reactions: [],
},
{
id: "c2",
@@ -625,6 +867,7 @@ describe("review thread decoding", () => {
body: "second",
createdAt: "2026-07-01T00:00:00Z",
url: "https://github.com/acme/web/pull/1#discussion_rc2",
+ reactions: [],
},
],
},
@@ -676,6 +919,101 @@ describe("review thread decoding", () => {
expect(reviewThreadConversation(threads).map((comment) => comment.id)).toEqual(["c4"]);
expect(threads).toHaveLength(1);
});
+
+ it("puts an issue comment's and a review's reactions in reactionsById, and the pull request's own in reactions", () => {
+ const result = expectSuccess(
+ decodeReviewThreadsJson(
+ threadsJson([], {
+ reactionGroups: [
+ {
+ content: "HEART",
+ viewerHasReacted: true,
+ reactors: { totalCount: 1, nodes: [{ login: "bilal" }] },
+ },
+ ],
+ comments: {
+ nodes: [
+ {
+ id: "c1",
+ reactionGroups: [
+ {
+ content: "THUMBS_UP",
+ reactors: { totalCount: 1, nodes: [{ login: "julius" }] },
+ },
+ ],
+ },
+ ],
+ },
+ reviews: {
+ nodes: [
+ {
+ id: "r1",
+ reactionGroups: [
+ { content: "EYES", reactors: { totalCount: 1, nodes: [{ login: "hubot" }] } },
+ ],
+ },
+ ],
+ },
+ }),
+ ),
+ );
+
+ expect(result.reactions).toEqual([
+ { content: "heart", count: 1, actors: ["bilal"], viewerHasReacted: true },
+ ]);
+ expect([...result.reactionsById]).toEqual([
+ ["c1", [{ content: "thumbs-up", count: 1, actors: ["julius"], viewerHasReacted: false }]],
+ ["r1", [{ content: "eyes", count: 1, actors: ["hubot"], viewerHasReacted: false }]],
+ ]);
+ });
+
+ it("leaves the viewer's own login out of the pull request's own reactions, matched case-insensitively, while count still counts them", () => {
+ const result = expectSuccess(
+ decodeReviewThreadsJson(
+ JSON.stringify({
+ data: {
+ viewer: { login: "Bilal" },
+ repository: {
+ pullRequest: {
+ reviewThreads: { totalCount: 0, nodes: [] },
+ reactionGroups: [
+ {
+ content: "HEART",
+ viewerHasReacted: true,
+ reactors: { totalCount: 2, nodes: [{ login: "bilal" }, { login: "julius" }] },
+ },
+ ],
+ },
+ },
+ },
+ }),
+ ),
+ );
+
+ expect(result.reactions).toEqual([
+ { content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
+ ]);
+ });
+});
+
+describe("decodePullRequestNodeIdJson", () => {
+ it("reads the pull request's own node id, which a reaction on its description is addressed by", () => {
+ expect(
+ expectSuccess(
+ decodePullRequestNodeIdJson(
+ JSON.stringify({ data: { repository: { pullRequest: { id: "PR_kwDOA" } } } }),
+ ),
+ ),
+ ).toBe("PR_kwDOA");
+ });
+});
+
+describe("REVIEW_THREADS_GRAPHQL_QUERY", () => {
+ it("asks for reactionGroups on the pull request itself, its comments, its reviews and each thread's comments", () => {
+ expect(REVIEW_THREADS_GRAPHQL_QUERY.match(/reactionGroups/g)).toHaveLength(4);
+ // The reviews connection is new: only reactions were ever wanted off it.
+ expect(REVIEW_THREADS_GRAPHQL_QUERY).toContain("reviews(first:");
+ });
});
describe("reviewer candidate decoding", () => {
@@ -957,3 +1295,45 @@ describe("decodePullRequestFilesJson", () => {
expect(result.truncated).toBe(false);
});
});
+
+describe("how far a branch trails its base", () => {
+ const comparison = (pullRequest: unknown) =>
+ JSON.stringify({ data: { repository: { pullRequest } } });
+
+ it("reads the commit count and whether this viewer may move the branch", () => {
+ const decoded = expectSuccess(
+ decodeBaseComparisonJson(
+ comparison({ viewerCanUpdateBranch: true, baseRef: { compare: { behindBy: 12 } } }),
+ ),
+ );
+ expect(decoded).toEqual({ behindBy: 12, viewerCanUpdate: true });
+ });
+
+ it("reads a current branch as nothing to do", () => {
+ expect(
+ expectSuccess(
+ decodeBaseComparisonJson(
+ comparison({ viewerCanUpdateBranch: false, baseRef: { compare: { behindBy: 0 } } }),
+ ),
+ ),
+ ).toEqual({ behindBy: 0, viewerCanUpdate: false });
+ });
+
+ it("answers unknown where the head could not be compared", () => {
+ // A pull request from a fork whose repository is gone, which GitHub answers with a null
+ // comparison beside a perfectly good pull request.
+ expect(
+ expectSuccess(
+ decodeBaseComparisonJson(comparison({ viewerCanUpdateBranch: true, baseRef: null })),
+ ).behindBy,
+ ).toBeNull();
+ expect(expectSuccess(decodeBaseComparisonJson(comparison(null)))).toEqual({
+ behindBy: null,
+ viewerCanUpdate: false,
+ });
+ });
+
+ it("refuses a body that is not the answer to this question", () => {
+ expect(Result.isSuccess(decodeBaseComparisonJson("{"))).toBe(false);
+ });
+});
diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.ts
index 8668d840c..e113b87d8 100644
--- a/apps/server/src/pullRequest/gitHubPullRequestJson.ts
+++ b/apps/server/src/pullRequest/gitHubPullRequestJson.ts
@@ -6,12 +6,17 @@ import type {
PullRequestActor,
PullRequestCheck,
PullRequestCheckStatus,
+ PullRequestChecksState,
PullRequestComment,
PullRequestCommit,
PullRequestLabel,
PullRequestMergeCapabilities,
+ PullRequestOmittedFileStat,
PullRequestMergeability,
+ PullRequestReaction,
+ PullRequestReactionContent,
PullRequestReviewCommentDraft,
+ PullRequestReviewDecision,
PullRequestReviewThread,
PullRequestReviewVerdict,
PullRequestReviewerCandidate,
@@ -22,6 +27,8 @@ import type {
} from "@t3tools/contracts";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
+import { dedupeChecks } from "./pullRequestChecks.ts";
+
/**
* Enum-ish GitHub CLI fields are decoded as plain strings and normalized here: a `gh`
* release that adds a conclusion or a review state must not fail the whole payload.
@@ -51,6 +58,27 @@ const RawReviewRequestSchema = Schema.Struct({
name: Schema.optional(Schema.NullOr(Schema.String)),
});
+const RawCheckSchema = Schema.Struct({
+ __typename: Schema.optional(Schema.String),
+ name: Schema.optional(Schema.NullOr(Schema.String)),
+ context: Schema.optional(Schema.NullOr(Schema.String)),
+ status: Schema.optional(Schema.NullOr(Schema.String)),
+ conclusion: Schema.optional(Schema.NullOr(Schema.String)),
+ state: Schema.optional(Schema.NullOr(Schema.String)),
+ description: Schema.optional(Schema.NullOr(Schema.String)),
+ detailsUrl: Schema.optional(Schema.NullOr(Schema.String)),
+ targetUrl: Schema.optional(Schema.NullOr(Schema.String)),
+ /**
+ * What tells two same-named checks apart, and which run of one is the newest. All three ride
+ * along with `statusCheckRollup` already — it is asked for as a whole field — so reading them
+ * costs no request. Empty for an app-provided check run, which belongs to no workflow, and
+ * absent entirely on a commit status, which is not a run at all.
+ */
+ workflowName: Schema.optional(Schema.NullOr(Schema.String)),
+ startedAt: Schema.optional(Schema.NullOr(Schema.String)),
+ completedAt: Schema.optional(Schema.NullOr(Schema.String)),
+});
+
const RawListItemSchema = Schema.Struct({
number: Schema.Int,
title: Schema.String,
@@ -61,6 +89,7 @@ const RawListItemSchema = Schema.Struct({
state: Schema.optional(Schema.NullOr(Schema.String)),
isDraft: Schema.optional(Schema.Boolean),
mergeable: Schema.optional(Schema.NullOr(Schema.String)),
+ reviewDecision: Schema.optional(Schema.NullOr(Schema.String)),
additions: Schema.optional(Schema.Int),
deletions: Schema.optional(Schema.Int),
createdAt: Schema.String,
@@ -68,6 +97,14 @@ const RawListItemSchema = Schema.Struct({
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
reviewRequests: Schema.optional(Schema.Array(RawReviewRequestSchema)),
labels: Schema.optional(Schema.Array(RawLabelSchema)),
+ /**
+ * Every check of the head commit, which is the only rollup `gh pr list --json` can give: there
+ * is no field for the one-word verdict. Measured against `pingdotgg/t3code`, asking for it costs
+ * 0.6s -> 7.9s at a hundred rows and 0.9s -> 2.1s at thirty, for 425 KB of checks a listing
+ * reduces to one word. The listing pays it because the alternative is a request per row; the
+ * cross-repository search below asks GitHub for the verdict itself instead.
+ */
+ statusCheckRollup: Schema.optional(Schema.NullOr(Schema.Array(RawCheckSchema))),
});
/**
@@ -85,6 +122,7 @@ const RawSearchItemSchema = Schema.Struct({
state: Schema.optional(Schema.NullOr(Schema.String)),
isDraft: Schema.optional(Schema.Boolean),
mergeable: Schema.optional(Schema.NullOr(Schema.String)),
+ reviewDecision: Schema.optional(Schema.NullOr(Schema.String)),
createdAt: Schema.String,
updatedAt: Schema.String,
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
@@ -113,6 +151,36 @@ const RawSearchItemSchema = Schema.Struct({
}),
),
),
+ /**
+ * GraphQL answers the rollup a listing actually wants — one enum for the head commit, rather
+ * than the whole check array `gh pr list --json` insists on. Measured at a hundred rows across
+ * this repository: 0.8s -> 3.0s and 15 KB, against 425 KB for the same verdict over `gh`.
+ */
+ commits: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({
+ nodes: Schema.optional(
+ Schema.NullOr(
+ Schema.Array(
+ Schema.NullOr(
+ Schema.Struct({
+ commit: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({
+ statusCheckRollup: Schema.optional(
+ Schema.NullOr(Schema.Struct({ state: Schema.String })),
+ ),
+ }),
+ ),
+ ),
+ }),
+ ),
+ ),
+ ),
+ ),
+ }),
+ ),
+ ),
});
const RawSearchSchema = Schema.Struct({
@@ -149,17 +217,109 @@ const RawStatsSchema = Schema.Struct({
),
});
-const RawCheckSchema = Schema.Struct({
- __typename: Schema.optional(Schema.String),
- name: Schema.optional(Schema.NullOr(Schema.String)),
- context: Schema.optional(Schema.NullOr(Schema.String)),
- status: Schema.optional(Schema.NullOr(Schema.String)),
- conclusion: Schema.optional(Schema.NullOr(Schema.String)),
- state: Schema.optional(Schema.NullOr(Schema.String)),
- description: Schema.optional(Schema.NullOr(Schema.String)),
- detailsUrl: Schema.optional(Schema.NullOr(Schema.String)),
- targetUrl: Schema.optional(Schema.NullOr(Schema.String)),
-});
+/** How many of a reaction's people the hover names before it counts the rest. */
+const REACTORS_PER_GROUP = 10;
+
+/**
+ * A reaction group as every reactable node reports it. `reactors` is bounded rather than paged:
+ * a hover says who reacted, and a hundred and forty names is a count, not a sentence.
+ */
+const REACTION_GROUPS_FIELDS = `reactionGroups {
+ content
+ viewerHasReacted
+ reactors(first: ${REACTORS_PER_GROUP}) {
+ totalCount
+ nodes {
+ ... on User { login }
+ ... on Bot { login }
+ ... on Organization { login }
+ ... on Mannequin { login }
+ }
+ }
+}`;
+
+/** GitHub's reaction names, which are the same eight the contract carries under other spellings. */
+const REACTION_CONTENT_BY_GITHUB: Readonly<Record<string, PullRequestReactionContent>> = {
+ THUMBS_UP: "thumbs-up",
+ THUMBS_DOWN: "thumbs-down",
+ LAUGH: "laugh",
+ HOORAY: "hooray",
+ CONFUSED: "confused",
+ HEART: "heart",
+ ROCKET: "rocket",
+ EYES: "eyes",
+};
+
+const GITHUB_REACTION_BY_CONTENT: Readonly<Record<PullRequestReactionContent, string>> = {
+ "thumbs-up": "THUMBS_UP",
+ "thumbs-down": "THUMBS_DOWN",
+ laugh: "LAUGH",
+ hooray: "HOORAY",
+ confused: "CONFUSED",
+ heart: "HEART",
+ rocket: "ROCKET",
+ eyes: "EYES",
+};
+
+export function gitHubReactionContent(content: PullRequestReactionContent): string {
+ return GITHUB_REACTION_BY_CONTENT[content];
+}
+
+const RawReactionGroupsSchema = Schema.optional(
+ Schema.NullOr(
+ Schema.Array(
+ Schema.Struct({
+ content: Schema.optional(Schema.NullOr(Schema.String)),
+ viewerHasReacted: Schema.optional(Schema.Boolean),
+ reactors: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({
+ totalCount: Schema.optional(Schema.Int),
+ nodes: Schema.optional(
+ Schema.NullOr(
+ Schema.Array(
+ Schema.NullOr(
+ Schema.Struct({ login: Schema.optional(Schema.NullOr(Schema.String)) }),
+ ),
+ ),
+ ),
+ ),
+ }),
+ ),
+ ),
+ }),
+ ),
+ ),
+);
+
+type RawReactionGroups = typeof RawReactionGroupsSchema.Type;
+
+/**
+ * The groups GitHub answered with, as the contract carries them. A group with nobody behind it is
+ * dropped: GitHub answers with a group per content it knows, including the ones nobody chose. The
+ * viewer's own login is left out of `actors` — the page names them "You" instead, and leaving it
+ * in would name them twice — but `count` still counts them along with everyone else.
+ */
+function toReactions(
+ groups: RawReactionGroups,
+ viewer: string | null,
+): ReadonlyArray<PullRequestReaction> {
+ const normalizedViewer = viewer?.toLowerCase() ?? null;
+ const reactions: PullRequestReaction[] = [];
+ for (const group of groups ?? []) {
+ const content = REACTION_CONTENT_BY_GITHUB[trimmed(group.content)?.toUpperCase() ?? ""];
+ if (content === undefined) continue;
+ const logins = (group.reactors?.nodes ?? []).flatMap((node) => trimmed(node?.login) ?? []);
+ const count = Math.max(group.reactors?.totalCount ?? logins.length, logins.length);
+ if (count <= 0) continue;
+ const actors =
+ normalizedViewer === null
+ ? logins
+ : logins.filter((login) => login.toLowerCase() !== normalizedViewer);
+ reactions.push({ content, count, actors, viewerHasReacted: group.viewerHasReacted === true });
+ }
+ return reactions;
+}
const RawCommentSchema = Schema.Struct({
id: Schema.String,
@@ -167,6 +327,8 @@ const RawCommentSchema = Schema.Struct({
body: Schema.optional(Schema.String),
createdAt: Schema.String,
url: Schema.optional(Schema.NullOr(Schema.String)),
+ /** Only ever present on a GraphQL read; `gh pr view --json` reports no reaction at all. */
+ reactionGroups: RawReactionGroupsSchema,
});
const RawReviewSchema = Schema.Struct({
@@ -196,10 +358,17 @@ const RawCommitSchema = Schema.Struct({
const RawDetailSchema = Schema.Struct({
...RawListItemSchema.fields,
+ /** Names the fork a pull request came from, which is what qualifies its head ref. */
+ headRepositoryOwner: Schema.optional(Schema.NullOr(Schema.Struct({ login: Schema.String }))),
body: Schema.optional(Schema.String),
changedFiles: Schema.optional(Schema.Int),
closedAt: Schema.optional(Schema.NullOr(Schema.String)),
- statusCheckRollup: Schema.optional(Schema.NullOr(Schema.Array(RawCheckSchema))),
+ /**
+ * The standing instruction to merge once GitHub's own requirements are met, which is an object
+ * describing who armed it and how, and a JSON null where nobody has. Nothing inside it is read:
+ * the question the page asks is whether one exists.
+ */
+ autoMergeRequest: Schema.optional(Schema.NullOr(Schema.Unknown)),
});
const RawActivitySchema = Schema.Struct({
@@ -234,6 +403,11 @@ const RawThreadCommentsSchema = Schema.Struct({
/** `gh pr view --json` cannot reach review threads, so they come from the GraphQL API. */
const RawReviewThreadsSchema = Schema.Struct({
data: Schema.Struct({
+ // Rides along in the same request: GitHub names who reacted but never says whether that is
+ // the reader, so the comparison is made here rather than paid for with a request of its own.
+ viewer: Schema.optional(
+ Schema.NullOr(Schema.Struct({ login: Schema.optional(Schema.NullOr(Schema.String)) })),
+ ),
repository: Schema.Struct({
pullRequest: Schema.Struct({
reviewThreads: Schema.Struct({
@@ -254,11 +428,32 @@ const RawReviewThreadsSchema = Schema.Struct({
}),
...RawViewerFieldsSchema.fields,
author: Schema.optional(Schema.NullOr(RawActorSchema)),
+ reactionGroups: RawReactionGroupsSchema,
comments: Schema.optional(
Schema.NullOr(
Schema.Struct({
nodes: Schema.Array(
- Schema.Struct({ author: Schema.optional(Schema.NullOr(RawActorSchema)) }),
+ Schema.Struct({
+ id: Schema.optional(Schema.NullOr(Schema.String)),
+ author: Schema.optional(Schema.NullOr(RawActorSchema)),
+ reactionGroups: RawReactionGroupsSchema,
+ }),
+ ),
+ }),
+ ),
+ ),
+ /**
+ * Reviews for their reactions alone: the words and the verdict arrive with
+ * `gh pr view --json reviews`, which reports no reaction of any kind.
+ */
+ reviews: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({
+ nodes: Schema.Array(
+ Schema.Struct({
+ id: Schema.optional(Schema.NullOr(Schema.String)),
+ reactionGroups: RawReactionGroupsSchema,
+ }),
),
}),
),
@@ -284,6 +479,23 @@ const RawReviewThreadsSchema = Schema.Struct({
}),
),
),
+ reviewDismissals: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({
+ pageInfo: Schema.optional(RawPageInfoSchema),
+ nodes: Schema.Array(
+ Schema.Struct({
+ dismissalMessage: Schema.optional(Schema.NullOr(Schema.String)),
+ review: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({ id: Schema.optional(Schema.NullOr(Schema.String)) }),
+ ),
+ ),
+ }),
+ ),
+ }),
+ ),
+ ),
commits: Schema.optional(
Schema.NullOr(
Schema.Struct({
@@ -384,9 +596,9 @@ export function decodeActorAvatarsJson(
}
export const PULL_REQUEST_LIST_JSON_FIELDS =
- "number,title,url,author,headRefName,baseRefName,state,isDraft,mergeable,additions,deletions,createdAt,updatedAt,mergedAt,reviewRequests,labels";
+ "number,title,url,author,headRefName,baseRefName,state,isDraft,mergeable,reviewDecision,additions,deletions,createdAt,updatedAt,mergedAt,reviewRequests,labels,statusCheckRollup";
-export const PULL_REQUEST_DETAIL_JSON_FIELDS = `${PULL_REQUEST_LIST_JSON_FIELDS},body,changedFiles,closedAt,statusCheckRollup`;
+export const PULL_REQUEST_DETAIL_JSON_FIELDS = `${PULL_REQUEST_LIST_JSON_FIELDS},body,changedFiles,closedAt,headRepositoryOwner,autoMergeRequest`;
export const PULL_REQUEST_ACTIVITY_JSON_FIELDS = "author,comments,reviews,commits";
/** GitHub's own ceiling on a connection page, which is what both thread reads ask for. */
@@ -429,12 +641,14 @@ export function pullRequestSearchGraphQlQuery(rows: number): string {
state
isDraft
mergeable
+ reviewDecision
createdAt
updatedAt
mergedAt
repository { nameWithOwner }
reviewRequests(first: 20) { nodes { requestedReviewer { ... on User { login } } } }
labels(first: 20) { nodes { name color } }
+ commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
}
}
}
@@ -461,6 +675,7 @@ export function pullRequestSearchGraphQlQuery(rows: number): string {
* wants, and stands in for the `gh` list wherever it came back non-empty.
*/
export const REVIEW_THREADS_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!, $cursor: String) {
+ viewer { login }
repository(owner: $owner, name: $name) {
pullRequest(number: $number) {
reviewThreads(first: ${GRAPHQL_PAGE_SIZE}, after: $cursor) {
@@ -476,14 +691,18 @@ export const REVIEW_THREADS_GRAPHQL_QUERY = `query($owner: String!, $name: Strin
comments(first: ${GRAPHQL_PAGE_SIZE}) {
totalCount
pageInfo { hasNextPage endCursor }
- nodes { id author { login avatarUrl } body createdAt url }
+ nodes { id author { login avatarUrl } body createdAt url ${REACTION_GROUPS_FIELDS} }
}
}
}
viewerCanUpdate
viewerDidAuthor
author { login avatarUrl }
- comments(first: ${GRAPHQL_PAGE_SIZE}) { nodes { author { login avatarUrl } } }
+ ${REACTION_GROUPS_FIELDS}
+ comments(first: ${GRAPHQL_PAGE_SIZE}) {
+ nodes { id author { login avatarUrl } ${REACTION_GROUPS_FIELDS} }
+ }
+ reviews(first: ${GRAPHQL_PAGE_SIZE}) { nodes { id ${REACTION_GROUPS_FIELDS} } }
reviewRequests(first: 50) {
nodes {
requestedReviewer {
@@ -495,6 +714,10 @@ export const REVIEW_THREADS_GRAPHQL_QUERY = `query($owner: String!, $name: Strin
latestReviews(first: 50) {
nodes { author { login avatarUrl } }
}
+ reviewDismissals: timelineItems(itemTypes: [REVIEW_DISMISSED_EVENT], first: ${GRAPHQL_PAGE_SIZE}) {
+ pageInfo { hasNextPage endCursor }
+ nodes { ... on ReviewDismissedEvent { dismissalMessage review { id } } }
+ }
commits(last: ${GRAPHQL_PAGE_SIZE}) {
nodes {
commit {
@@ -517,11 +740,12 @@ export const REVIEW_THREADS_GRAPHQL_QUERY = `query($owner: String!, $name: Strin
* GitHub makes necessary, and one no ordinary pull request ever provokes.
*/
export const REVIEW_THREAD_COMMENTS_GRAPHQL_QUERY = `query($threadId: ID!, $cursor: String) {
+ viewer { login }
node(id: $threadId) {
... on PullRequestReviewThread {
comments(first: ${GRAPHQL_PAGE_SIZE}, after: $cursor) {
pageInfo { hasNextPage endCursor }
- nodes { id author { login avatarUrl } body createdAt url }
+ nodes { id author { login avatarUrl } body createdAt url ${REACTION_GROUPS_FIELDS} }
}
}
}
@@ -529,6 +753,9 @@ export const REVIEW_THREAD_COMMENTS_GRAPHQL_QUERY = `query($threadId: ID!, $curs
const RawReviewThreadCommentsSchema = Schema.Struct({
data: Schema.Struct({
+ viewer: Schema.optional(
+ Schema.NullOr(Schema.Struct({ login: Schema.optional(Schema.NullOr(Schema.String)) })),
+ ),
/** Null for an id that names nothing the viewer can read, which is not a thread to page. */
node: Schema.NullOr(Schema.Struct({ comments: Schema.optional(RawThreadCommentsSchema) })),
}),
@@ -540,6 +767,84 @@ export const REVIEW_THREAD_REPLY_GRAPHQL_MUTATION = `mutation($threadId: ID!, $b
}
}`;
+/**
+ * The pull request's own node id, which is what a reaction on its description is addressed by.
+ * Read only when one is being written: the conversation carries an id for every remark in it, and
+ * the pull request is the one subject nothing in it names.
+ */
+export const PULL_REQUEST_NODE_ID_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
+ repository(owner: $owner, name: $name) { pullRequest(number: $number) { id } }
+}`;
+
+const RawPullRequestNodeIdSchema = Schema.Struct({
+ data: Schema.Struct({
+ repository: Schema.Struct({
+ pullRequest: Schema.Struct({ id: Schema.String }),
+ }),
+ }),
+});
+
+const decodePullRequestNodeId = decodeJsonResult(RawPullRequestNodeIdSchema);
+
+export function decodePullRequestNodeIdJson(raw: string): Result.Result<string, DecodeFailure> {
+ const decoded = decodePullRequestNodeId(raw);
+ return Result.isSuccess(decoded)
+ ? Result.succeed(decoded.success.data.repository.pullRequest.id)
+ : Result.fail(decoded.failure);
+}
+
+/**
+ * Where a client-given reaction subject actually hangs: the pull request itself, or the pull
+ * request an issue comment, a review comment, or a review belongs to. Read before a mutation
+ * reaches it, so a subject named for one pull request cannot react on another's behalf.
+ */
+export const REACTION_SUBJECT_PULL_REQUEST_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!, $subjectId: ID!) {
+ repository(owner: $owner, name: $name) { pullRequest(number: $number) { id } }
+ node(id: $subjectId) {
+ id
+ ... on IssueComment { pullRequest { id } }
+ ... on PullRequestReviewComment { pullRequest { id } }
+ ... on PullRequestReview { pullRequest { id } }
+ }
+}`;
+
+const RawReactionSubjectScopeSchema = Schema.Struct({
+ data: Schema.Struct({
+ repository: Schema.NullOr(
+ Schema.Struct({ pullRequest: Schema.NullOr(Schema.Struct({ id: Schema.String })) }),
+ ),
+ node: Schema.NullOr(
+ Schema.Struct({
+ id: Schema.String,
+ pullRequest: Schema.optional(Schema.Struct({ id: Schema.String })),
+ }),
+ ),
+ }),
+});
+
+const decodeReactionSubjectScope = decodeJsonResult(RawReactionSubjectScopeSchema);
+
+/**
+ * True when the subject named is the pull request itself, or hangs off it — false for anything
+ * else, including a subject or a pull request this host could not find.
+ */
+export function decodeReactionSubjectScopeJson(raw: string): Result.Result<boolean, DecodeFailure> {
+ const decoded = decodeReactionSubjectScope(raw);
+ if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
+ const expected = decoded.success.data.repository?.pullRequest?.id ?? null;
+ const node = decoded.success.data.node;
+ const actual = node === null ? null : (node.pullRequest?.id ?? node.id);
+ return Result.succeed(expected !== null && actual !== null && expected === actual);
+}
+
+export const ADD_REACTION_GRAPHQL_MUTATION = `mutation($subjectId: ID!, $content: ReactionContent!) {
+ addReaction(input: { subjectId: $subjectId, content: $content }) { reaction { content } }
+}`;
+
+export const REMOVE_REACTION_GRAPHQL_MUTATION = `mutation($subjectId: ID!, $content: ReactionContent!) {
+ removeReaction(input: { subjectId: $subjectId, content: $content }) { reaction { content } }
+}`;
+
export const RESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION = `mutation($threadId: ID!) {
resolveReviewThread(input: { threadId: $threadId }) { thread { isResolved } }
}`;
@@ -548,6 +853,31 @@ export const UNRESOLVE_REVIEW_THREAD_GRAPHQL_MUTATION = `mutation($threadId: ID!
unresolveReviewThread(input: { threadId: $threadId }) { thread { isResolved } }
}`;
+/**
+ * Rewrites the pull request's own words. Both are nullable so that one document serves a change
+ * to the title, to the description, or to the two together: a variable the request does not send
+ * puts no entry in the input at all, which leaves that field as it was rather than clearing it.
+ */
+export const UPDATE_PULL_REQUEST_GRAPHQL_MUTATION = `mutation($pullRequestId: ID!, $title: String, $body: String) {
+ updatePullRequest(input: { pullRequestId: $pullRequestId, title: $title, body: $body }) {
+ pullRequest { id }
+ }
+}`;
+
+/**
+ * The two comment mutations name their comment differently. The variable is spelled the same in
+ * both, so a rewrite sends one set of variables whichever kind of remark it is.
+ */
+export const UPDATE_ISSUE_COMMENT_GRAPHQL_MUTATION = `mutation($commentId: ID!, $body: String!) {
+ updateIssueComment(input: { id: $commentId, body: $body }) { issueComment { id } }
+}`;
+
+export const UPDATE_REVIEW_COMMENT_GRAPHQL_MUTATION = `mutation($commentId: ID!, $body: String!) {
+ updatePullRequestReviewComment(input: { pullRequestReviewCommentId: $commentId, body: $body }) {
+ pullRequestReviewComment { id }
+ }
+}`;
+
/**
* A GraphQL request as `gh api graphql --input -` takes it. Variables travel in the document
* rather than as `-f name=value` flags, so a reader's own words never reach argv.
@@ -588,6 +918,21 @@ const REVIEW_EVENTS: Record<PullRequestReviewVerdict, "COMMENT" | "APPROVE" | "R
"request-changes": "REQUEST_CHANGES",
};
+/**
+ * The dismissal events past the page the thread read carries. A pull request rarely has any:
+ * this is followed only while the embedded page reports more.
+ */
+export const REVIEW_DISMISSALS_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!, $cursor: String) {
+ repository(owner: $owner, name: $name) {
+ pullRequest(number: $number) {
+ timelineItems(itemTypes: [REVIEW_DISMISSED_EVENT], first: ${GRAPHQL_PAGE_SIZE}, after: $cursor) {
+ pageInfo { hasNextPage endCursor }
+ nodes { ... on ReviewDismissedEvent { dismissalMessage review { id } } }
+ }
+ }
+ }
+}`;
+
/** The whole review as one request body, which is how GitHub keeps it invisible until sent. */
export function buildReviewSubmissionJson(input: {
readonly verdict: PullRequestReviewVerdict;
@@ -626,6 +971,8 @@ export interface GitHubPullRequestListItem {
readonly state: PullRequestState;
readonly isDraft: boolean;
readonly mergeability: PullRequestMergeability;
+ /** Null where GitHub has no verdict to summarise, which includes a draft nobody has reviewed. */
+ readonly reviewDecision: PullRequestReviewDecision | null;
readonly additions: number;
readonly deletions: number;
readonly createdAt: string;
@@ -634,14 +981,20 @@ export interface GitHubPullRequestListItem {
/** At least one outstanding request targets a team rather than an individual login. */
readonly hasTeamReviewRequest: boolean;
readonly labels: ReadonlyArray<PullRequestLabel>;
+ /** Null where the head commit reported no checks, which is not the same as passing none. */
+ readonly checksState: PullRequestChecksState | null;
}
export interface GitHubPullRequestDetail extends GitHubPullRequestListItem {
+ /** The owner of the head branch's repository; null where `gh` did not say. */
+ readonly headRepositoryOwner: string | null;
readonly body: string;
readonly changedFiles: number;
readonly mergedAt: string | null;
readonly closedAt: string | null;
readonly checks: ReadonlyArray<PullRequestCheck>;
+ /** Absent where `gh` did not answer for auto-merge at all, which is not the same as off. */
+ readonly autoMergeEnabled?: boolean;
}
export interface GitHubPullRequestActivity {
@@ -731,6 +1084,19 @@ function toMergeability(value: string | null | undefined): PullRequestMergeabili
}
}
+function toReviewDecision(value: string | null | undefined): PullRequestReviewDecision | null {
+ switch (value?.trim().toUpperCase()) {
+ case "APPROVED":
+ return "approved";
+ case "CHANGES_REQUESTED":
+ return "changes-requested";
+ case "REVIEW_REQUIRED":
+ return "review-required";
+ default:
+ return null;
+ }
+}
+
function toLabels(
raw: ReadonlyArray<Schema.Schema.Type<typeof RawLabelSchema>> | undefined,
): ReadonlyArray<PullRequestLabel> {
@@ -792,23 +1158,81 @@ function toCheckStatus(raw: Schema.Schema.Type<typeof RawCheckSchema>): PullRequ
}
}
-function toChecks(
+/** What GitHub writes where a run has not reached that moment yet, which is not a time. */
+const UNSET_TIMESTAMP = "0001-01-01T00:00:00Z";
+
+function realTimestamp(value: string | null | undefined): string | null {
+ const at = trimmed(value);
+ return at === null || at === UNSET_TIMESTAMP ? null : at;
+}
+
+/** Only a row the rollup gives no name of any kind, which is not a check anyone can show. */
+function isNamelessCheck(raw: Schema.Schema.Type<typeof RawCheckSchema>): boolean {
+ return trimmed(raw.name) === null && trimmed(raw.context) === null;
+}
+
+/**
+ * The rollup as the deduper reads it: a check, the workflow that owns it, and when the run last
+ * had something to say. A queued run reports a completion time it has not reached, so the start
+ * stands in for it rather than sorting the newest run to the bottom.
+ */
+function toCheckEntries(
raw: ReadonlyArray<Schema.Schema.Type<typeof RawCheckSchema>> | null | undefined,
-): ReadonlyArray<PullRequestCheck> {
+): ReadonlyArray<{
+ readonly check: PullRequestCheck;
+ readonly workflowName: string | null;
+ readonly at: string | null;
+}> {
return (raw ?? []).flatMap((check) => {
const name = trimmed(check.name) ?? trimmed(check.context);
if (name === null) return [];
return [
{
- name,
- status: toCheckStatus(check),
- description: trimmed(check.description),
- url: trimmed(check.detailsUrl) ?? trimmed(check.targetUrl),
+ check: {
+ name,
+ status: toCheckStatus(check),
+ description: trimmed(check.description),
+ url: trimmed(check.detailsUrl) ?? trimmed(check.targetUrl),
+ },
+ workflowName: trimmed(check.workflowName),
+ at: realTimestamp(check.completedAt) ?? realTimestamp(check.startedAt),
},
];
});
}
+/**
+ * The one word a listing row has space for. A failure outranks anything still running, the way
+ * GitHub's own indicator reads: a run that has already gone red will not go green by finishing.
+ *
+ * Null rather than "passing" for a head commit with no checks at all, so a repository that runs
+ * none shows nothing instead of a green tick it never earned. Checks whose verdict is neither a
+ * pass, a failure nor a wait — skipped, cancelled, neutral — count towards neither.
+ *
+ * Counted off the deduped checks rather than the raw rollup, so the word and the list under it
+ * cannot disagree: the run a re-run replaced is not a verdict twice. A row with no name at all is
+ * counted as it comes, since the cross-repository search dresses GitHub's own rollup enum as one
+ * nameless row, and nothing nameless can collide with anything.
+ */
+function rollupChecksState(
+ raw: ReadonlyArray<Schema.Schema.Type<typeof RawCheckSchema>> | null | undefined,
+): PullRequestChecksState | null {
+ const statuses = [
+ ...toChecks(raw).map((check) => check.status),
+ ...(raw ?? []).filter(isNamelessCheck).map((check) => toCheckStatus(check)),
+ ];
+ if (statuses.length === 0) return null;
+ if (statuses.includes("failure")) return "failing";
+ if (statuses.includes("pending")) return "pending";
+ return statuses.includes("success") ? "passing" : null;
+}
+
+function toChecks(
+ raw: ReadonlyArray<Schema.Schema.Type<typeof RawCheckSchema>> | null | undefined,
+): ReadonlyArray<PullRequestCheck> {
+ return dedupeChecks(toCheckEntries(raw));
+}
+
/** The states that are a verdict in themselves, rather than a wrapper around line comments. */
function isReviewVerdict(reviewState: string | null): boolean {
switch (reviewState?.toUpperCase()) {
@@ -894,6 +1318,7 @@ function toListItem(raw: Schema.Schema.Type<typeof RawListItemSchema>): GitHubPu
state: toState(raw),
isDraft: raw.isDraft ?? false,
mergeability: toMergeability(raw.mergeable),
+ reviewDecision: toReviewDecision(raw.reviewDecision),
additions: raw.additions ?? 0,
deletions: raw.deletions ?? 0,
createdAt: raw.createdAt,
@@ -901,17 +1326,24 @@ function toListItem(raw: Schema.Schema.Type<typeof RawListItemSchema>): GitHubPu
reviewRequestLogins: toReviewRequestLogins(raw.reviewRequests),
hasTeamReviewRequest: hasTeamReviewRequest(raw.reviewRequests),
labels: toLabels(raw.labels),
+ checksState: rollupChecksState(raw.statusCheckRollup),
};
}
function toDetail(raw: Schema.Schema.Type<typeof RawDetailSchema>): GitHubPullRequestDetail {
return {
...toListItem(raw),
+ headRepositoryOwner: trimmed(raw.headRepositoryOwner?.login),
body: raw.body ?? "",
changedFiles: raw.changedFiles ?? 0,
mergedAt: trimmed(raw.mergedAt),
closedAt: trimmed(raw.closedAt),
checks: toChecks(raw.statusCheckRollup),
+ // A JSON null is GitHub saying "nobody armed this"; a missing key is GitHub not saying, and
+ // the difference survives here rather than being flattened into false.
+ ...(raw.autoMergeRequest === undefined
+ ? {}
+ : { autoMergeEnabled: raw.autoMergeRequest !== null }),
};
}
@@ -1006,6 +1438,12 @@ export function decodePullRequestSearchJson(
return login === null ? [] : [{ login }];
}),
labels: (node.labels?.nodes ?? []).flatMap((label) => (label === null ? [] : [label])),
+ // The search asks for the verdict rather than the checks behind it, so it arrives as one
+ // enum. Dressed as a single check here so the rollup is read the same way on both paths.
+ statusCheckRollup: (node.commits?.nodes ?? []).flatMap((commitNode) => {
+ const state = trimmed(commitNode?.commit?.statusCheckRollup?.state);
+ return state === null ? [] : [{ state }];
+ }),
}),
repository,
});
@@ -1094,11 +1532,17 @@ export function decodePullRequestActivityJson(
export interface GitHubReviewThreadComments {
readonly comments: ReadonlyArray<PullRequestComment>;
+ /** Dismissal reasons by the dismissed review's node id, read off the timeline. */
+ readonly dismissalsByReviewId: ReadonlyMap<string, string>;
/** Whole conversations, kept anchored so the diff can pin them to their line. */
readonly reviewThreads: ReadonlyArray<PullRequestReviewThread>;
/** The host's own count of the conversation, which a bounded read can fall short of. */
readonly commentCount: number;
readonly truncated: boolean;
+ /** The pull request's own reactions, which sit on its description. */
+ readonly reactions: ReadonlyArray<PullRequestReaction>;
+ /** Reactions by node id, for the comments and reviews the `gh` JSON read carries no reaction on. */
+ readonly reactionsById: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
/**
* Everyone on the review: those still asked and those who have already answered. Whoever has
* reviewed is no longer an outstanding request, so asking only for requests reports nobody on
@@ -1140,6 +1584,13 @@ export interface GitHubReviewThreadPage {
readonly threads: ReadonlyArray<GitHubReviewThreadEntry>;
/** Where the next page of threads starts, or null once the host has handed them all over. */
readonly nextCursor: string | null;
+ /** The pull request's own reactions, which sit on its description. */
+ readonly reactions: ReadonlyArray<PullRequestReaction>;
+ /**
+ * Reactions by node id, for the conversation comments and reviews `gh pr view --json` answers
+ * for without any. Only ids with a reaction are here; the rest carry none.
+ */
+ readonly reactionsById: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
readonly reviewers: ReadonlyArray<PullRequestActor>;
readonly avatarsByLogin: ReadonlyMap<string, string>;
readonly commitStats: ReadonlyMap<
@@ -1148,6 +1599,10 @@ export interface GitHubReviewThreadPage {
>;
readonly commits: ReadonlyArray<PullRequestCommit>;
readonly viewer: { readonly canUpdate: boolean; readonly didAuthor: boolean };
+ /** Dismissal reasons by the dismissed review's node id, which the review itself never carries. */
+ readonly dismissalsByReviewId: ReadonlyMap<string, string>;
+ /** Where the rest of the dismissal events start, or null once this page carried them all. */
+ readonly nextDismissalCursor: string | null;
}
/**
@@ -1169,12 +1624,71 @@ export function reviewThreadConversation(
url: comment.url,
path: thread.path,
reviewState: null,
+ reactions: comment.reactions ?? [],
}),
),
);
}
/** One page of review threads. Following the cursors it hands back is the caller's job. */
+function toDismissalEntries(
+ nodes:
+ | ReadonlyArray<{
+ readonly dismissalMessage?: string | null | undefined;
+ readonly review?: { readonly id?: string | null | undefined } | null | undefined;
+ }>
+ | undefined,
+): Map<string, string> {
+ const entries = new Map<string, string>();
+ for (const node of nodes ?? []) {
+ const reviewId = trimmed(node.review?.id);
+ const message = trimmed(node.dismissalMessage);
+ if (reviewId !== null && message !== null) entries.set(reviewId, message);
+ }
+ return entries;
+}
+
+const RawReviewDismissalsSchema = Schema.Struct({
+ data: Schema.Struct({
+ repository: Schema.Struct({
+ pullRequest: Schema.Struct({
+ timelineItems: Schema.Struct({
+ pageInfo: Schema.optional(RawPageInfoSchema),
+ nodes: Schema.Array(
+ Schema.Struct({
+ dismissalMessage: Schema.optional(Schema.NullOr(Schema.String)),
+ review: Schema.optional(
+ Schema.NullOr(Schema.Struct({ id: Schema.optional(Schema.NullOr(Schema.String)) })),
+ ),
+ }),
+ ),
+ }),
+ }),
+ }),
+ }),
+});
+
+const decodeReviewDismissals = decodeJsonResult(RawReviewDismissalsSchema);
+
+/** One further page of dismissal events, in the shape the thread read's own page carries. */
+export function decodeReviewDismissalsJson(raw: string): Result.Result<
+ {
+ readonly dismissalsByReviewId: ReadonlyMap<string, string>;
+ readonly nextCursor: string | null;
+ },
+ DecodeFailure
+> {
+ const decoded = decodeReviewDismissals(raw);
+ if (!Result.isSuccess(decoded)) {
+ return Result.fail(decoded.failure);
+ }
+ const items = decoded.success.data.repository.pullRequest.timelineItems;
+ return Result.succeed({
+ dismissalsByReviewId: toDismissalEntries(items.nodes),
+ nextCursor: nextCursorOf(items.pageInfo),
+ });
+}
+
export function decodeReviewThreadsJson(
raw: string,
): Result.Result<GitHubReviewThreadPage, DecodeFailure> {
@@ -1182,6 +1696,7 @@ export function decodeReviewThreadsJson(
if (!Result.isSuccess(decoded)) {
return Result.fail(decoded.failure);
}
+ const viewer = trimmed(decoded.success.data.viewer?.login);
const threads = decoded.success.data.repository.pullRequest.reviewThreads;
const entries = threads.nodes.flatMap((thread): ReadonlyArray<GitHubReviewThreadEntry> => {
const path = trimmed(thread.path);
@@ -1207,6 +1722,7 @@ export function decodeReviewThreadsJson(
body: comment.body ?? "",
createdAt: comment.createdAt,
url: trimmed(comment.url),
+ reactions: toReactions(comment.reactionGroups, viewer),
})),
},
commentCount: thread.comments.totalCount ?? thread.comments.nodes.length,
@@ -1260,14 +1776,28 @@ export function decodeReviewThreadsJson(
}),
});
}
+ const reactionsById = new Map<string, ReadonlyArray<PullRequestReaction>>();
+ for (const node of [
+ ...(pullRequest.comments?.nodes ?? []),
+ ...(pullRequest.reviews?.nodes ?? []),
+ ]) {
+ const id = trimmed(node.id);
+ if (id === null) continue;
+ const reactions = toReactions(node.reactionGroups, viewer);
+ if (reactions.length > 0) reactionsById.set(id, reactions);
+ }
return Result.succeed({
threads: entries,
nextCursor: nextCursorOf(threads.pageInfo),
+ reactions: toReactions(pullRequest.reactionGroups, viewer),
+ reactionsById,
reviewers: [...reviewers.values()],
avatarsByLogin,
commitStats,
commits,
viewer: toPullRequestViewerFields(pullRequest),
+ dismissalsByReviewId: toDismissalEntries(pullRequest.reviewDismissals?.nodes),
+ nextDismissalCursor: nextCursorOf(pullRequest.reviewDismissals?.pageInfo),
});
}
@@ -1283,6 +1813,7 @@ export function decodeReviewThreadCommentsJson(raw: string): Result.Result<
if (!Result.isSuccess(decoded)) {
return Result.fail(decoded.failure);
}
+ const viewer = trimmed(decoded.success.data.viewer?.login);
const comments = decoded.success.data.node?.comments;
return Result.succeed({
comments: (comments?.nodes ?? []).map((comment) => ({
@@ -1291,6 +1822,7 @@ export function decodeReviewThreadCommentsJson(raw: string): Result.Result<
body: comment.body ?? "",
createdAt: comment.createdAt,
url: trimmed(comment.url),
+ reactions: toReactions(comment.reactionGroups, viewer),
})),
nextCursor: nextCursorOf(comments?.pageInfo),
});
@@ -1351,6 +1883,75 @@ export function decodeRepositoryAccessJson(
* need `read:org`, which a repository-scoped token need not carry — and a query GitHub refuses
* fails whole, taking the people down with the teams.
*/
+/**
+ * Where the branch stands against its base, and whether this viewer may move it.
+ *
+ * `mergeStateStatus` is not the answer: GitHub only reports BEHIND where the repository requires
+ * branches to be up to date before merging, so on every other repository a stale branch reads as
+ * CLEAN or BLOCKED like any other. The comparison counts the commits instead, which is the same
+ * number GitHub's own "out-of-date" banner shows.
+ *
+ * `headRef` is qualified `owner:branch` because a pull request from a fork has no branch of that
+ * name in the base repository, and an unqualified name is simply not found there.
+ */
+export const BASE_COMPARISON_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!, $headRef: String!) {
+ repository(owner: $owner, name: $name) {
+ pullRequest(number: $number) {
+ viewerCanUpdateBranch
+ baseRef {
+ compare(headRef: $headRef) {
+ behindBy
+ }
+ }
+ }
+ }
+}`;
+
+const RawBaseComparisonSchema = Schema.Struct({
+ data: Schema.Struct({
+ repository: Schema.NullOr(
+ Schema.Struct({
+ pullRequest: Schema.NullOr(
+ Schema.Struct({
+ viewerCanUpdateBranch: Schema.optional(Schema.NullOr(Schema.Boolean)),
+ /** Null where the head repository is gone, which is a comparison nobody can make. */
+ baseRef: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({
+ compare: Schema.optional(
+ Schema.NullOr(Schema.Struct({ behindBy: Schema.Number })),
+ ),
+ }),
+ ),
+ ),
+ }),
+ ),
+ }),
+ ),
+ }),
+});
+
+const decodeBaseComparison = decodeJsonResult(RawBaseComparisonSchema);
+
+export interface GitHubBaseComparison {
+ /** Null where the host could not compare, which the page reads as "unknown". */
+ readonly behindBy: number | null;
+ readonly viewerCanUpdate: boolean;
+}
+
+export function decodeBaseComparisonJson(
+ raw: string,
+): Result.Result<GitHubBaseComparison, DecodeFailure> {
+ const decoded = decodeBaseComparison(raw);
+ if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
+ const pullRequest = decoded.success.data.repository?.pullRequest;
+ const behindBy = pullRequest?.baseRef?.compare?.behindBy;
+ return Result.succeed({
+ behindBy: typeof behindBy === "number" && behindBy >= 0 ? behindBy : null,
+ viewerCanUpdate: pullRequest?.viewerCanUpdateBranch === true,
+ });
+}
+
export const REVIEWER_CANDIDATES_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
repository(owner: $owner, name: $name) {
assignableUsers(first: ${GRAPHQL_PAGE_SIZE}) {
@@ -1492,6 +2093,12 @@ export interface GitHubViewerAccess {
/** GitHub's own `viewerCanUpdate`, true for the author as well as for anyone with write. */
readonly canUpdate: boolean;
readonly didAuthor: boolean;
+ /**
+ * GitHub's own `viewerCanUpdateBranch`, read with the base comparison rather than here: it is
+ * false for a branch that is already current, so it answers "may update, and there is
+ * something to update" at once. Absent where the comparison was not read.
+ */
+ readonly canUpdateBranch?: boolean;
}
/**
@@ -1539,6 +2146,8 @@ export interface GitHubPullRequestFilesPatch {
readonly truncated: boolean;
/** Files GitHub returned, counted before decoding, so the caller can page. */
readonly rawCount: number;
+ /** GitHub's own counts for the files whose hunks it withheld. */
+ readonly omittedFileStats: ReadonlyArray<PullRequestOmittedFileStat>;
}
/**
@@ -1554,6 +2163,7 @@ export function decodePullRequestFilesJson(
return Result.fail(decoded.failure);
}
const sections: string[] = [];
+ const omittedFileStats: PullRequestOmittedFileStat[] = [];
let truncated = false;
for (const entry of decoded.success) {
const file = decodeFileEntry(entry);
@@ -1565,7 +2175,12 @@ export function decodePullRequestFilesJson(
// A file with no hunks is still a file that changed: a pure rename has none to give, and
// a binary one has none that can be shown. Both are listed, and only the second is a hole
// in the patch — leaving them out entirely would drop them from the change altogether.
- if ((value.additions ?? 0) + (value.deletions ?? 0) > 0) truncated = true;
+ const additions = value.additions ?? 0;
+ const deletions = value.deletions ?? 0;
+ if (additions + deletions > 0) {
+ truncated = true;
+ omittedFileStats.push({ path: value.filename, additions, deletions });
+ }
}
// A rename counts its hunks against the old path, which is the only place it is named.
const oldPath =
@@ -1586,5 +2201,6 @@ export function decodePullRequestFilesJson(
patch: sections.join(""),
truncated,
rawCount: decoded.success.length,
+ omittedFileStats,
});
}
diff --git a/apps/server/src/pullRequest/gitLabMergeRequestJson.test.ts b/apps/server/src/pullRequest/gitLabMergeRequestJson.test.ts
index 553bd7fb6..9221c1ab8 100644
--- a/apps/server/src/pullRequest/gitLabMergeRequestJson.test.ts
+++ b/apps/server/src/pullRequest/gitLabMergeRequestJson.test.ts
@@ -2,12 +2,15 @@ import * as Result from "effect/Result";
import { describe, expect, it } from "vite-plus/test";
import {
+ decodeAwardEmojiJson,
decodeCommitsJson,
decodeMergeRequestDetailJson,
decodeMergeRequestDiffsJson,
decodeMergeRequestListJson,
decodeNotesJson,
+ decodeOwnAwardIdJson,
decodeViewerJson,
+ gitLabAwardName,
} from "./gitLabMergeRequestJson.ts";
function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
@@ -177,6 +180,31 @@ describe("decodeMergeRequestDetailJson", () => {
expect(detail.changedFiles).toBe(0);
});
+ it("reads either auto-merge field, and says nothing where GitLab named neither", () => {
+ const armed = (entry: Record<string, unknown>) =>
+ expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).autoMergeEnabled;
+
+ expect(armed({ merge_when_pipeline_succeeds: true })).toBe(true);
+ // The newer name for the same fact, which older GitLab installs do not send.
+ expect(armed({ auto_merge_enabled: true })).toBe(true);
+ expect(armed({ merge_when_pipeline_succeeds: false })).toBe(false);
+ // Absent is GitLab not saying, which the page must not read as "not armed".
+ expect(armed({})).toBeUndefined();
+ });
+
+ it("keeps a divergence GitLab did not count apart from a divergence of none", () => {
+ const behind = (entry: Record<string, unknown>) =>
+ expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).divergedCommits;
+
+ expect(behind({ diverged_commits_count: 3 })).toBe(3);
+ // Counted and found level, which is the one answer that entitles the page to say so.
+ expect(behind({ diverged_commits_count: 0 })).toBe(0);
+ // An install that does not answer, and a null where the answer would have gone, are both
+ // silence: reading either as zero would tell a stale branch it is current.
+ expect(behind({})).toBeUndefined();
+ expect(behind({ diverged_commits_count: null })).toBeUndefined();
+ });
+
it("maps a pipeline waiting on a person to neutral, not failure", () => {
const detail = expectSuccess(
decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status: "manual" } })),
@@ -453,3 +481,130 @@ describe("merge request viewer fields", () => {
).toBe(true);
});
});
+
+describe("decodeAwardEmojiJson", () => {
+ it("reads MR-level awards, keys per-note awards by the REST id inside their gid, and ignores an award outside the eight", () => {
+ const result = expectSuccess(
+ decodeAwardEmojiJson(
+ JSON.stringify({
+ data: {
+ currentUser: { username: "bilal" },
+ project: {
+ mergeRequest: {
+ awardEmoji: {
+ nodes: [
+ { name: "thumbsup", user: { username: "bilal" } },
+ { name: "thumbsup", user: { username: "julius" } },
+ ],
+ },
+ notes: {
+ pageInfo: { hasNextPage: false, endCursor: null },
+ nodes: [
+ {
+ id: "gid://gitlab/DiffNote/42",
+ awardEmoji: { nodes: [{ name: "heart", user: { username: "julius" } }] },
+ },
+ {
+ id: "gid://gitlab/Note/7",
+ // Not one of the eight the contract carries.
+ awardEmoji: {
+ nodes: [{ name: "partyparrot", user: { username: "bilal" } }],
+ },
+ },
+ ],
+ },
+ },
+ },
+ },
+ }),
+ ),
+ );
+
+ // `bilal` is `currentUser`, so the group they are in reads back as reacted, but their own
+ // username is left out of `actors` — the page names them "You" instead — while `count` still
+ // counts them; `julius` alone does not turn a group's own `viewerHasReacted` on.
+ expect(result.reactions).toEqual([
+ { content: "thumbs-up", count: 2, actors: ["julius"], viewerHasReacted: true },
+ ]);
+ // Note 7's only award named nobody the eight recognise, so it carries no reactions and is
+ // left out of the map rather than kept empty.
+ expect([...result.reactionsByNoteId]).toEqual([
+ ["42", [{ content: "heart", count: 1, actors: ["julius"], viewerHasReacted: false }]],
+ ]);
+ expect(result.nextCursor).toBeNull();
+ });
+
+ it("hands back a cursor when GitLab has more notes to page", () => {
+ const result = expectSuccess(
+ decodeAwardEmojiJson(
+ JSON.stringify({
+ data: {
+ currentUser: null,
+ project: {
+ mergeRequest: {
+ awardEmoji: { nodes: [] },
+ notes: { pageInfo: { hasNextPage: true, endCursor: "Y3Vyc29yOjE" }, nodes: [] },
+ },
+ },
+ },
+ }),
+ ),
+ );
+
+ expect(result.nextCursor).toBe("Y3Vyc29yOjE");
+ });
+
+ it("matches the viewer's username case-insensitively, since GitLab is not consistent about case", () => {
+ const result = expectSuccess(
+ decodeAwardEmojiJson(
+ JSON.stringify({
+ data: {
+ currentUser: { username: "Bilal" },
+ project: {
+ mergeRequest: {
+ awardEmoji: {
+ nodes: [
+ { name: "heart", user: { username: "bilal" } },
+ { name: "heart", user: { username: "julius" } },
+ ],
+ },
+ notes: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] },
+ },
+ },
+ },
+ }),
+ ),
+ );
+
+ expect(result.reactions).toEqual([
+ { content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
+ ]);
+ });
+});
+
+describe("decodeOwnAwardIdJson", () => {
+ const awards = JSON.stringify([
+ { id: 101, name: "thumbsup", user: { username: "julius" } },
+ { id: 102, name: "thumbsup", user: { username: "bilal" } },
+ ]);
+
+ it("finds the reader's own award of that name, which is the one a removal deletes", () => {
+ expect(
+ expectSuccess(decodeOwnAwardIdJson(awards, { content: "thumbs-up", viewer: "bilal" })),
+ ).toBe(102);
+ });
+
+ it("returns nothing where the reader has no award of that name", () => {
+ expect(
+ expectSuccess(decodeOwnAwardIdJson(awards, { content: "heart", viewer: "bilal" })),
+ ).toBeNull();
+ });
+});
+
+describe("gitLabAwardName", () => {
+ it("spells the contents whose GitLab award name is not their own kebab-case", () => {
+ expect(gitLabAwardName("thumbs-up")).toBe("thumbsup");
+ expect(gitLabAwardName("laugh")).toBe("laughing");
+ expect(gitLabAwardName("hooray")).toBe("tada");
+ });
+});
diff --git a/apps/server/src/pullRequest/gitLabMergeRequestJson.ts b/apps/server/src/pullRequest/gitLabMergeRequestJson.ts
index 5c0fd0ac7..9f4bd96ba 100644
--- a/apps/server/src/pullRequest/gitLabMergeRequestJson.ts
+++ b/apps/server/src/pullRequest/gitLabMergeRequestJson.ts
@@ -11,6 +11,8 @@ import type {
PullRequestLabel,
PullRequestMergeability,
PullRequestMergeCapabilities,
+ PullRequestReaction,
+ PullRequestReactionContent,
PullRequestReviewThread,
PullRequestReviewerCandidate,
PullRequestState,
@@ -70,6 +72,21 @@ const RawMergeRequestSchema = Schema.Struct({
user: Schema.optional(
Schema.NullOr(Schema.Struct({ can_merge: Schema.optional(Schema.Boolean) })),
),
+ /**
+ * Whether GitLab is holding this merge request to merge it once its pipeline goes green.
+ * `merge_when_pipeline_succeeds` is the field every version answers with; newer ones also
+ * carry `auto_merge_enabled`, which is the same fact under the name GitLab settled on, so
+ * either one saying yes is a yes.
+ */
+ merge_when_pipeline_succeeds: Schema.optional(Schema.NullOr(Schema.Boolean)),
+ auto_merge_enabled: Schema.optional(Schema.NullOr(Schema.Boolean)),
+ /**
+ * How far the target branch has moved on since this one left it, which is the same number
+ * GitLab's own "out of date" wording counts. It costs a walk of the two branches, so GitLab
+ * withholds it unless `include_diverged_commits_count` asks for it, and answers it only for a
+ * single merge request — a list never carries it, however it is asked for.
+ */
+ diverged_commits_count: Schema.optional(Schema.NullOr(Schema.Int)),
});
const RawNoteSchema = Schema.Struct({
@@ -209,6 +226,13 @@ export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {
readonly viewerCanMerge: boolean;
/** The reviewers as GitLab addresses them, which is what writing the set back takes. */
readonly reviewerIds: ReadonlyArray<number>;
+ /** Absent where GitLab named neither auto-merge field, which is not the same as off. */
+ readonly autoMergeEnabled?: boolean;
+ /**
+ * Absent where GitLab did not count, which is not the same as a branch that has nothing behind
+ * it: an install too old to answer must not be read as saying the branch is current.
+ */
+ readonly divergedCommits?: number;
}
function trimmed(value: string | null | undefined): string | null {
@@ -334,6 +358,10 @@ function toListItem(
function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLabMergeRequestDetail {
const listItem = toListItem(raw);
+ const autoMerge =
+ raw.merge_when_pipeline_succeeds == null && raw.auto_merge_enabled == null
+ ? undefined
+ : raw.merge_when_pipeline_succeeds === true || raw.auto_merge_enabled === true;
return {
...listItem,
body: raw.description ?? "",
@@ -350,6 +378,8 @@ function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLab
reviewerIds: (raw.reviewers ?? []).flatMap((reviewer) =>
reviewer.id === undefined ? [] : [reviewer.id],
),
+ ...(autoMerge === undefined ? {} : { autoMergeEnabled: autoMerge }),
+ ...(raw.diverged_commits_count == null ? {} : { divergedCommits: raw.diverged_commits_count }),
};
}
@@ -696,3 +726,215 @@ export function decodeMergeRequestDiffsJson(
rawCount: decoded.success.length,
});
}
+
+/** GitLab's award names for the eight reactions the contract carries. */
+const GITLAB_AWARD_BY_CONTENT: Readonly<Record<PullRequestReactionContent, string>> = {
+ "thumbs-up": "thumbsup",
+ "thumbs-down": "thumbsdown",
+ laugh: "laughing",
+ hooray: "tada",
+ confused: "confused",
+ heart: "heart",
+ rocket: "rocket",
+ eyes: "eyes",
+};
+
+const CONTENT_BY_GITLAB_AWARD: Readonly<Record<string, PullRequestReactionContent>> =
+ Object.fromEntries(
+ Object.entries(GITLAB_AWARD_BY_CONTENT).map(([content, name]) => [name, content]),
+ ) as Readonly<Record<string, PullRequestReactionContent>>;
+
+export function gitLabAwardName(content: PullRequestReactionContent): string {
+ return GITLAB_AWARD_BY_CONTENT[content];
+}
+
+/**
+ * Awards on the merge request and on every note of it, in one read. The REST notes endpoint the
+ * conversation comes from carries no award at all, and asking per note would be a request each.
+ *
+ * `currentUser` rides along because GitLab names who awarded but never says whether that is the
+ * reader — so the comparison is made here rather than paid for with a request of its own.
+ */
+export const AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) {
+ currentUser { username }
+ project(fullPath: $fullPath) {
+ mergeRequest(iid: $iid) {
+ awardEmoji { nodes { name user { username } } }
+ notes(first: 100, after: $cursor) {
+ pageInfo { hasNextPage endCursor }
+ nodes { id awardEmoji { nodes { name user { username } } } }
+ }
+ }
+ }
+}`;
+
+const RawAwardEmojiNodesSchema = Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({
+ nodes: Schema.optional(
+ Schema.NullOr(
+ Schema.Array(
+ Schema.NullOr(
+ Schema.Struct({
+ name: Schema.optional(Schema.NullOr(Schema.String)),
+ user: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) }),
+ ),
+ ),
+ }),
+ ),
+ ),
+ ),
+ ),
+ }),
+ ),
+);
+
+const RawAwardEmojiPageSchema = Schema.Struct({
+ data: Schema.Struct({
+ currentUser: Schema.optional(
+ Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
+ ),
+ project: Schema.NullOr(
+ Schema.Struct({
+ mergeRequest: Schema.NullOr(
+ Schema.Struct({
+ awardEmoji: RawAwardEmojiNodesSchema,
+ notes: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({
+ pageInfo: Schema.optional(
+ Schema.Struct({
+ hasNextPage: Schema.optional(Schema.Boolean),
+ endCursor: Schema.optional(Schema.NullOr(Schema.String)),
+ }),
+ ),
+ nodes: Schema.Array(
+ Schema.NullOr(
+ Schema.Struct({
+ id: Schema.optional(Schema.NullOr(Schema.String)),
+ awardEmoji: RawAwardEmojiNodesSchema,
+ }),
+ ),
+ ),
+ }),
+ ),
+ ),
+ }),
+ ),
+ }),
+ ),
+ }),
+});
+
+const decodeAwardEmojiPage = decodeJsonResult(RawAwardEmojiPageSchema);
+
+/**
+ * The awards on one subject, grouped the way a reaction pill is drawn. The viewer's own username
+ * is left out of `actors` — the page names them "You" instead, and leaving it in would name them
+ * twice — but `count` still counts them along with everyone else.
+ */
+function toReactions(
+ nodes: Schema.Schema.Type<typeof RawAwardEmojiNodesSchema>,
+ viewer: string | null,
+): ReadonlyArray<PullRequestReaction> {
+ const normalizedViewer = viewer?.toLowerCase() ?? null;
+ const groups = new Map<
+ PullRequestReactionContent,
+ { count: number; actors: string[]; viewer: boolean }
+ >();
+ for (const node of nodes?.nodes ?? []) {
+ // An award outside the eight is left out rather than shown under a name the picker has no
+ // way to take back: GitLab accepts any emoji, and the other hosts accept none of them.
+ const content = CONTENT_BY_GITLAB_AWARD[trimmed(node?.name)?.toLowerCase() ?? ""];
+ if (content === undefined) continue;
+ const username = trimmed(node?.user?.username);
+ if (username === null) continue;
+ const group = groups.get(content) ?? { count: 0, actors: [], viewer: false };
+ group.count++;
+ if (normalizedViewer !== null && username.toLowerCase() === normalizedViewer) {
+ group.viewer = true;
+ } else {
+ group.actors.push(username);
+ }
+ groups.set(content, group);
+ }
+ return [...groups].flatMap(([content, group]) =>
+ group.count === 0
+ ? []
+ : [{ content, count: group.count, actors: group.actors, viewerHasReacted: group.viewer }],
+ );
+}
+
+/** `gid://gitlab/DiffNote/42` is note 42, which is the id the REST conversation carries. */
+function noteIdOf(gid: string | null | undefined): string | null {
+ const id = trimmed(gid)?.split("/").at(-1);
+ return id !== undefined && /^\d+$/.test(id) ? id : null;
+}
+
+export interface GitLabAwardEmojiPage {
+ /** The merge request's own awards, which are the ones on its description. */
+ readonly reactions: ReadonlyArray<PullRequestReaction>;
+ readonly reactionsByNoteId: ReadonlyMap<string, ReadonlyArray<PullRequestReaction>>;
+ readonly nextCursor: string | null;
+}
+
+export function decodeAwardEmojiJson(
+ raw: string,
+): Result.Result<GitLabAwardEmojiPage, DecodeFailure> {
+ const decoded = decodeAwardEmojiPage(raw);
+ if (!Result.isSuccess(decoded)) {
+ return Result.fail(decoded.failure);
+ }
+ const data = decoded.success.data;
+ const viewer = trimmed(data.currentUser?.username);
+ const mergeRequest = data.project?.mergeRequest;
+ const reactionsByNoteId = new Map<string, ReadonlyArray<PullRequestReaction>>();
+ for (const node of mergeRequest?.notes?.nodes ?? []) {
+ const id = noteIdOf(node?.id);
+ if (id === null) continue;
+ const reactions = toReactions(node?.awardEmoji, viewer);
+ if (reactions.length > 0) reactionsByNoteId.set(id, reactions);
+ }
+ const pageInfo = mergeRequest?.notes?.pageInfo;
+ return Result.succeed({
+ reactions: toReactions(mergeRequest?.awardEmoji, viewer),
+ reactionsByNoteId,
+ nextCursor: pageInfo?.hasNextPage === true ? (trimmed(pageInfo.endCursor) ?? null) : null,
+ });
+}
+
+const RawAwardSchema = Schema.Struct({
+ id: Schema.Int,
+ name: Schema.optional(Schema.NullOr(Schema.String)),
+ user: Schema.optional(
+ Schema.NullOr(Schema.Struct({ username: Schema.optional(Schema.NullOr(Schema.String)) })),
+ ),
+});
+
+const decodeAward = Schema.decodeUnknownExit(RawAwardSchema);
+
+/**
+ * The reader's own award of one name on a subject, which is what taking a reaction back is
+ * addressed by: GitLab deletes an award by its id and has no way to name one by its emoji.
+ */
+export function decodeOwnAwardIdJson(
+ raw: string,
+ input: { readonly content: PullRequestReactionContent; readonly viewer: string },
+): Result.Result<number | null, DecodeFailure> {
+ const decoded = decodeUnknownList(raw);
+ if (!Result.isSuccess(decoded)) {
+ return Result.fail(decoded.failure);
+ }
+ const name = gitLabAwardName(input.content);
+ for (const entry of decoded.success) {
+ const award = decodeAward(entry);
+ if (Exit.isFailure(award)) continue;
+ const value = award.value;
+ if (trimmed(value.name)?.toLowerCase() !== name) continue;
+ if (trimmed(value.user?.username) !== input.viewer) continue;
+ return Result.succeed(value.id);
+ }
+ return Result.succeed(null);
+}
diff --git a/apps/server/src/pullRequest/pullRequestChecks.test.ts b/apps/server/src/pullRequest/pullRequestChecks.test.ts
new file mode 100644
index 000000000..ba6850832
--- /dev/null
+++ b/apps/server/src/pullRequest/pullRequestChecks.test.ts
@@ -0,0 +1,93 @@
+import type { PullRequestCheck, PullRequestCheckStatus } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import { dedupeChecks } from "./pullRequestChecks.ts";
+
+function entry(
+ name: string,
+ status: PullRequestCheckStatus,
+ extra: { readonly workflowName?: string | null; readonly at?: string | null } = {},
+): {
+ readonly check: PullRequestCheck;
+ readonly workflowName: string | null;
+ readonly at: string | null;
+} {
+ return {
+ check: { name, status, description: null, url: null },
+ workflowName: extra.workflowName ?? null,
+ at: extra.at ?? null,
+ };
+}
+
+describe("dedupeChecks", () => {
+ it("keeps the newest run of a check the host listed twice", () => {
+ const checks = dedupeChecks([
+ entry("Prepare PR size config", "success", {
+ workflowName: "PR Size",
+ at: "2026-08-11T16:06:25Z",
+ }),
+ entry("Prepare PR size config", "pending", {
+ workflowName: "PR Size",
+ at: "2026-08-11T17:01:04Z",
+ }),
+ ]);
+
+ expect(checks.map((check) => [check.name, check.status])).toEqual([
+ ["Prepare PR size config", "pending"],
+ ]);
+ });
+
+ it("holds a check at the place it first appeared, so a re-run does not reshuffle the list", () => {
+ const checks = dedupeChecks([
+ entry("lint", "success", { workflowName: "CI", at: "2026-08-11T16:00:00Z" }),
+ entry("test", "success", { workflowName: "CI", at: "2026-08-11T16:00:00Z" }),
+ entry("lint", "failure", { workflowName: "CI", at: "2026-08-11T18:00:00Z" }),
+ ]);
+
+ expect(checks.map((check) => [check.name, check.status])).toEqual([
+ ["lint", "failure"],
+ ["test", "success"],
+ ]);
+ });
+
+ it("loses a run that never said when it happened to one that did, whichever came first", () => {
+ const undated = dedupeChecks([
+ entry("build", "success", { at: "2026-08-11T16:00:00Z" }),
+ entry("build", "pending"),
+ ]);
+ const dated = dedupeChecks([
+ entry("build", "pending"),
+ entry("build", "success", { at: "2026-08-11T16:00:00Z" }),
+ ]);
+
+ expect([undated[0]?.status, dated[0]?.status]).toEqual(["success", "success"]);
+ });
+
+ it("takes the last copy when neither run is dated, which is how an update is listed", () => {
+ const checks = dedupeChecks([entry("build", "pending"), entry("build", "failure")]);
+
+ expect(checks.map((check) => check.status)).toEqual(["failure"]);
+ });
+
+ it("keeps two workflows that name a job the same thing, and says which is which", () => {
+ const checks = dedupeChecks([
+ entry("build", "success", { workflowName: "CI", at: "2026-08-11T16:00:00Z" }),
+ entry("build", "failure", { workflowName: "Release", at: "2026-08-11T16:00:00Z" }),
+ ]);
+
+ expect(checks.map((check) => [check.name, check.status])).toEqual([
+ ["CI / build", "success"],
+ ["Release / build", "failure"],
+ ]);
+ });
+
+ it("leaves a colliding check with no workflow of its own unqualified", () => {
+ // An app-provided check run belongs to no workflow, which GitHub reports as an empty name.
+ const checks = dedupeChecks([
+ entry("build", "success", { workflowName: "", at: "2026-08-11T16:00:00Z" }),
+ entry("build", "failure", { workflowName: "CI", at: "2026-08-11T16:00:00Z" }),
+ ]);
+
+ expect(checks.map((check) => check.name)).toEqual(["build", "CI / build"]);
+ });
+});
diff --git a/apps/server/src/pullRequest/pullRequestChecks.ts b/apps/server/src/pullRequest/pullRequestChecks.ts
new file mode 100644
index 000000000..819cf47b0
--- /dev/null
+++ b/apps/server/src/pullRequest/pullRequestChecks.ts
@@ -0,0 +1,55 @@
+import type { PullRequestCheck } from "@t3tools/contracts";
+
+/** ISO-8601 timestamps in UTC compare correctly as plain text, which is all the ordering needs. */
+function isAtLeastAsNew(candidate: string | null, kept: string | null): boolean {
+ if (candidate === null) return kept === null;
+ return kept === null || candidate >= kept;
+}
+
+/**
+ * One row per check rather than one per run of it.
+ *
+ * A host's rollup is a list of runs, not a list of checks: while a workflow is being re-run — or
+ * while a second run of it is already live — the same check arrives twice, and both copies reach
+ * the reader as what looks like a duplicate. Nothing in a check carries an id, so the name is what
+ * identifies it, qualified by the workflow it belongs to since two workflows are free to name a
+ * job the same thing.
+ *
+ * Within a group the newest run is the one worth showing: a re-run is the answer that replaces the
+ * one before it, and a run that never said when it happened loses to one that did. A tie goes to
+ * whichever came last, because a host lists a re-run after the run it repeats.
+ *
+ * The order is the host's own, held at the place each check first appeared, so a re-run landing
+ * mid-read replaces a row where it stands instead of reshuffling the list under the reader.
+ *
+ * Two checks that survive under the same name are then genuinely different ones, since they came
+ * from different workflows — each is shown as `workflow / name`, the way GitHub writes it itself.
+ * A survivor whose workflow the host did not name keeps its bare name rather than being qualified
+ * with nothing.
+ */
+export function dedupeChecks(
+ entries: ReadonlyArray<{
+ readonly check: PullRequestCheck;
+ readonly workflowName: string | null;
+ readonly at: string | null;
+ }>,
+): ReadonlyArray<PullRequestCheck> {
+ const newestByCheck = new Map<string, (typeof entries)[number]>();
+ for (const entry of entries) {
+ const key = `${entry.workflowName ?? ""} ${entry.check.name}`;
+ const kept = newestByCheck.get(key);
+ // Re-setting a key a Map already holds keeps its first position, which is the order wanted.
+ if (kept === undefined || isAtLeastAsNew(entry.at, kept.at)) newestByCheck.set(key, entry);
+ }
+ const survivors = [...newestByCheck.values()];
+ const countsByName = new Map<string, number>();
+ for (const entry of survivors) {
+ countsByName.set(entry.check.name, (countsByName.get(entry.check.name) ?? 0) + 1);
+ }
+ return survivors.map((entry) => {
+ const workflowName = entry.workflowName ?? "";
+ return workflowName.length > 0 && (countsByName.get(entry.check.name) ?? 0) > 1
+ ? { ...entry.check, name: `${workflowName} / ${entry.check.name}` }
+ : entry.check;
+ });
+}
diff --git a/apps/server/src/sourceControl/GitHubCli.test.ts b/apps/server/src/sourceControl/GitHubCli.test.ts
index 5daf7676d..964ed3d02 100644
--- a/apps/server/src/sourceControl/GitHubCli.test.ts
+++ b/apps/server/src/sourceControl/GitHubCli.test.ts
@@ -373,4 +373,34 @@ describe("GitHubCli.layer", () => {
assert.equal(error.message.includes(cause.detail), false);
}).pipe(Effect.provide(layer)),
);
+
+ it.effect("surfaces an actionable rate-limit error without exposing provider stderr", () =>
+ Effect.gen(function* () {
+ const cause = new VcsProcessExitError({
+ operation: "GitHubCli.execute",
+ command: "gh",
+ cwd: "/repo",
+ exitCode: 1,
+ failureKind: "rate-limited",
+ detail: "API rate limit exceeded.",
+ stderrLength: 82,
+ stderrTruncated: false,
+ });
+ mockRun.mockReturnValueOnce(Effect.fail(cause));
+
+ const gh = yield* GitHubCli.GitHubCli;
+ const error = yield* gh
+ .listOpenPullRequests({
+ cwd: "/repo",
+ headSelector: "feature/rate-limited",
+ })
+ .pipe(Effect.flip);
+
+ assert.strictEqual(error._tag, "GitHubCliRateLimitError");
+ assert.include(error.detail, "GitHub API rate limit exceeded");
+ assert.include(error.detail, "gh api rate_limit");
+ assert.strictEqual(error.cause, cause);
+ assert.notInclude(error.message, "user ID");
+ }).pipe(Effect.provide(layer)),
+ );
});
diff --git a/apps/server/src/sourceControl/GitHubCli.ts b/apps/server/src/sourceControl/GitHubCli.ts
index a705b0fb0..974574cbd 100644
--- a/apps/server/src/sourceControl/GitHubCli.ts
+++ b/apps/server/src/sourceControl/GitHubCli.ts
@@ -51,6 +51,19 @@ export class GitHubCliAuthenticationError extends Schema.TaggedErrorClass<GitHub
}
}
+export class GitHubCliRateLimitError extends Schema.TaggedErrorClass<GitHubCliRateLimitError>()(
+ "GitHubCliRateLimitError",
+ gitHubCliFailureFields,
+) {
+ get detail(): string {
+ return "GitHub API rate limit exceeded. Run `gh api rate_limit` to inspect the quota and reset time.";
+ }
+
+ override get message(): string {
+ return `GitHub CLI failed in execute: ${this.detail}`;
+ }
+}
+
export class GitHubPullRequestNotFoundError extends Schema.TaggedErrorClass<GitHubPullRequestNotFoundError>()(
"GitHubPullRequestNotFoundError",
gitHubCliFailureFields,
@@ -138,6 +151,7 @@ export class GitHubRepositoryDecodeError extends Schema.TaggedErrorClass<GitHubR
export const GitHubCliError = Schema.Union([
GitHubCliUnavailableError,
GitHubCliAuthenticationError,
+ GitHubCliRateLimitError,
GitHubPullRequestNotFoundError,
GitHubCliCommandError,
GitHubPullRequestListDecodeError,
@@ -170,6 +184,9 @@ export function fromVcsError(
if (error.failureKind === "authentication") {
return new GitHubCliAuthenticationError({ ...context, cause: error });
}
+ if (error.failureKind === "rate-limited") {
+ return new GitHubCliRateLimitError({ ...context, cause: error });
+ }
if (error.failureKind === "not-found") {
return new GitHubPullRequestNotFoundError({ ...context, cause: error });
}
diff --git a/apps/server/src/sourceControl/GitLabCli.ts b/apps/server/src/sourceControl/GitLabCli.ts
index 05475400d..ce17b2f5b 100644
--- a/apps/server/src/sourceControl/GitLabCli.ts
+++ b/apps/server/src/sourceControl/GitLabCli.ts
@@ -127,6 +127,7 @@ export class GitLabCliCommandError extends Schema.TaggedErrorClass<GitLabCliComm
case "authentication":
return new GitLabCliAuthenticationError({ ...context, cause });
case "not-found":
+ case "rate-limited":
case "command-failed":
case undefined:
return new GitLabCliCommandError({ ...context, cause });
diff --git a/apps/server/src/vcs/VcsProcess.test.ts b/apps/server/src/vcs/VcsProcess.test.ts
index d202fa48c..58596d194 100644
--- a/apps/server/src/vcs/VcsProcess.test.ts
+++ b/apps/server/src/vcs/VcsProcess.test.ts
@@ -140,6 +140,31 @@ describe("VcsProcess.run", () => {
}).pipe(provideLive),
);
+ it.effect("classifies API rate limits without retaining provider stderr", () =>
+ Effect.gen(function* () {
+ const providerStderr =
+ "GraphQL: API rate limit already exceeded for user ID 51714798 and token secret-value.";
+ const error = yield* run({
+ operation: "test.rate-limit",
+ command: "node",
+ args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr],
+ cwd: process.cwd(),
+ }).pipe(Effect.flip);
+
+ expect(error).toBeInstanceOf(VcsProcessExitError);
+ expect(error).toMatchObject({
+ command: "node",
+ exitCode: 1,
+ detail: "API rate limit exceeded.",
+ failureKind: "rate-limited",
+ stderrLength: providerStderr.length,
+ stderrTruncated: false,
+ });
+ expect(error.message).not.toContain(providerStderr);
+ expect(error.message).not.toContain("secret-value");
+ }).pipe(provideLive),
+ );
+
it.effect("retains spawn causes without exposing process arguments in the error message", () =>
Effect.gen(function* () {
const secretArgument = "--token=super-secret-token";
diff --git a/apps/server/src/vcs/VcsProcess.ts b/apps/server/src/vcs/VcsProcess.ts
index 299990e56..ee4ed9712 100644
--- a/apps/server/src/vcs/VcsProcess.ts
+++ b/apps/server/src/vcs/VcsProcess.ts
@@ -69,6 +69,14 @@ const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFai
return "authentication";
}
+ if (
+ normalized.includes("api rate limit") ||
+ normalized.includes("rate limit exceeded") ||
+ normalized.includes("secondary rate limit")
+ ) {
+ return "rate-limited";
+ }
+
if (
(command === "gh" &&
(normalized.includes("could not resolve to a pullrequest") ||
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 126222d21..173c89eca 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -1662,10 +1662,22 @@ const makeWsRpcLayer = (
observeRpcEffect(WS_METHODS.pullRequestsRunAction, pullRequests.runAction(input), {
"rpc.aggregate": "pull-requests",
}),
+ [WS_METHODS.pullRequestsUpdate]: (input) =>
+ observeRpcEffect(WS_METHODS.pullRequestsUpdate, pullRequests.update(input), {
+ "rpc.aggregate": "pull-requests",
+ }),
[WS_METHODS.pullRequestsComment]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsComment, pullRequests.comment(input), {
"rpc.aggregate": "pull-requests",
}),
+ [WS_METHODS.pullRequestsUpdateComment]: (input) =>
+ observeRpcEffect(
+ WS_METHODS.pullRequestsUpdateComment,
+ pullRequests.updateComment(input),
+ {
+ "rpc.aggregate": "pull-requests",
+ },
+ ),
[WS_METHODS.pullRequestsSubmitReview]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsSubmitReview, pullRequests.submitReview(input), {
"rpc.aggregate": "pull-requests",
@@ -1682,6 +1694,10 @@ const makeWsRpcLayer = (
pullRequests.setThreadResolution(input),
{ "rpc.aggregate": "pull-requests" },
),
+ [WS_METHODS.pullRequestsSetReaction]: (input) =>
+ observeRpcEffect(WS_METHODS.pullRequestsSetReaction, pullRequests.setReaction(input), {
+ "rpc.aggregate": "pull-requests",
+ }),
[WS_METHODS.pullRequestsInvalidate]: (input) =>
observeRpcEffect(WS_METHODS.pullRequestsInvalidate, pullRequests.invalidate(input), {
"rpc.aggregate": "pull-requests",
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index 8dc545d31..e9390ed0a 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -1569,13 +1569,14 @@ function ChatMarkdown({
if (href) openChangeRequestLink(event, href);
}}
onContextMenu={(event) => {
- if (!canOpenInPreview || !href || !faviconHost) return;
+ if (!href || !faviconHost) return;
event.preventDefault();
event.stopPropagation();
const api = readLocalApi();
if (!api) return;
void showExternalLinkContextMenu({
href,
+ canOpenInPreview,
position: { x: event.clientX, y: event.clientY },
showContextMenu: (items, position) => api.contextMenu.show(items, position),
openInPreview: async (target) => {
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 5c2fb3d6d..1f00c177c 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -123,11 +123,11 @@ import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
import {
- pullRequestSurfaceId,
selectActiveRightPanel,
selectActiveRightPanelSurface,
selectThreadRightPanelState,
type RightPanelSurface,
+ updatePullRequestTabStatus,
useRightPanelStore,
} from "../rightPanelStore";
import {
@@ -144,6 +144,7 @@ import {
selectThreadPreviewMiniPlayer,
usePreviewMiniPlayerStore,
} from "../previewMiniPlayerStore";
+import { isThreadOwnPullRequest } from "./pullRequest/pullRequestDetail.logic";
import { PullRequestDetailPanel } from "./pullRequest/PullRequestDetailPanel";
import { PullRequestDetailGhost } from "./pullRequest/PullRequestGhosts";
import { PullRequestsUnavailableState } from "./pullRequest/PullRequestsUnavailableState";
@@ -1600,14 +1601,18 @@ function ChatViewContent(props: ChatViewProps) {
const [pullRequestTabStatuses, setPullRequestTabStatuses] = useState<
Record<string, PullRequestTabStatus>
>({});
- const handlePullRequestTabStatusChange = useCallback((status: PullRequestTabStatus) => {
- const id = pullRequestSurfaceId(status);
- setPullRequestTabStatuses((current) =>
- current[id]?.state === status.state && current[id]?.isDraft === status.isDraft
- ? current
- : { ...current, [id]: status },
- );
- }, []);
+ // Keyed by the surface the panel is showing rather than by a key rebuilt from the status, so
+ // the tab is found again whether or not that surface was opened with an environment on it.
+ const activePullRequestSurfaceId =
+ activeRightPanelSurface?.kind === "pull-request" ? activeRightPanelSurface.id : undefined;
+ const handlePullRequestTabStatusChange = useCallback(
+ (status: PullRequestTabStatus) => {
+ const id = activePullRequestSurfaceId;
+ if (id === undefined) return;
+ setPullRequestTabStatuses((current) => updatePullRequestTabStatus(current, id, status));
+ },
+ [activePullRequestSurfaceId],
+ );
const activeFileSurface =
activeRightPanelSurface?.kind === "file" ? activeRightPanelSurface : null;
const activePreviewState = useThreadPreviewState(activeThreadRef);
@@ -6082,11 +6087,23 @@ function ChatViewContent(props: ChatViewProps) {
number: activeRightPanelSurface.number,
}}
context={
- activeThreadPr?.number === activeRightPanelSurface.number &&
- threadRepository === activeRightPanelSurface.repository
+ isThreadOwnPullRequest(
+ {
+ projectId: activeProject?.id ?? null,
+ repository: threadRepository,
+ number: activeThreadPr?.number ?? null,
+ },
+ {
+ projectId: activeRightPanelSurface.projectId,
+ repository: activeRightPanelSurface.repository,
+ number: activeRightPanelSurface.number,
+ },
+ )
? "thread"
: "page"
}
+ chromeVariant="collapse"
+ composerDraftTarget={composerDraftTarget}
onStateChange={handlePullRequestTabStatusChange}
/>
) : activeRightPanelSurface?.kind === "agents" ? (
diff --git a/apps/web/src/components/chat/externalLinkContextMenu.test.ts b/apps/web/src/components/chat/externalLinkContextMenu.test.ts
index 64935d53e..4f3dd1a15 100644
--- a/apps/web/src/components/chat/externalLinkContextMenu.test.ts
+++ b/apps/web/src/components/chat/externalLinkContextMenu.test.ts
@@ -41,6 +41,25 @@ describe("external chat link context menu", () => {
expect(harness.copyLink).not.toHaveBeenCalled();
});
+ it("still offers the link's own actions where the integrated browser cannot be opened", async () => {
+ const harness = createHarness(null);
+
+ await showExternalLinkContextMenu({
+ href: "https://github.com/pingdotgg/t3code/pull/6169",
+ canOpenInPreview: false,
+ position: { x: 4, y: 8 },
+ ...harness,
+ });
+
+ expect(harness.showContextMenu).toHaveBeenCalledWith(
+ [
+ { id: "open-external", label: "Open in system browser" },
+ { id: "copy-link", label: "Copy Link" },
+ ],
+ { x: 4, y: 8 },
+ );
+ });
+
it("copies the exact destination without opening it", async () => {
const harness = createHarness("copy-link");
const href = "https://example.com/docs?topic=menus#copy";
diff --git a/apps/web/src/components/chat/externalLinkContextMenu.ts b/apps/web/src/components/chat/externalLinkContextMenu.ts
index 398ca40da..e93061c9f 100644
--- a/apps/web/src/components/chat/externalLinkContextMenu.ts
+++ b/apps/web/src/components/chat/externalLinkContextMenu.ts
@@ -20,9 +20,25 @@ const EXTERNAL_LINK_CONTEXT_MENU_ITEMS = [
{ id: "copy-link", label: "Copy Link" },
] as const satisfies readonly ContextMenuItem<ExternalLinkContextMenuAction>[];
+/**
+ * The integrated browser is not always there to offer — it needs a thread to open beside and a
+ * runtime that can show it — but the other two answers hold wherever a link does. Dropping the
+ * whole menu with the one item that cannot be honoured is what left a right-click on a link
+ * showing the platform's cut-and-paste menu instead of a way to copy the link.
+ */
+export function externalLinkContextMenuItems(options: {
+ readonly canOpenInPreview: boolean;
+}): readonly ContextMenuItem<ExternalLinkContextMenuAction>[] {
+ return options.canOpenInPreview
+ ? EXTERNAL_LINK_CONTEXT_MENU_ITEMS
+ : EXTERNAL_LINK_CONTEXT_MENU_ITEMS.filter((item) => item.id !== "open-in-preview");
+}
+
interface ShowExternalLinkContextMenuOptions {
readonly href: string;
readonly position: { readonly x: number; readonly y: number };
+ /** Absent means yes, which is what every caller before the browser could be missing meant. */
+ readonly canOpenInPreview?: boolean;
readonly showContextMenu: (
items: readonly ContextMenuItem<ExternalLinkContextMenuAction>[],
position: { readonly x: number; readonly y: number },
@@ -50,6 +66,7 @@ export function resolveExternalWebLinkHost(href: string | undefined): string | n
export async function showExternalLinkContextMenu({
href,
position,
+ canOpenInPreview = true,
showContextMenu,
openInPreview,
openExternal,
@@ -58,7 +75,7 @@ export async function showExternalLinkContextMenu({
}: ShowExternalLinkContextMenuOptions): Promise<void> {
let action: ExternalLinkContextMenuAction | null;
try {
- action = await showContextMenu(EXTERNAL_LINK_CONTEXT_MENU_ITEMS, position);
+ action = await showContextMenu(externalLinkContextMenuItems({ canOpenInPreview }), position);
} catch (cause) {
reportFailure("show-link-context-menu", cause);
return;
diff --git a/apps/web/src/components/diffs/StyledDiffCodeView.tsx b/apps/web/src/components/diffs/StyledDiffCodeView.tsx
index f422c7aeb..37ce2085b 100644
--- a/apps/web/src/components/diffs/StyledDiffCodeView.tsx
+++ b/apps/web/src/components/diffs/StyledDiffCodeView.tsx
@@ -269,6 +269,11 @@ type StyledDiffCodeViewProps<LAnnotation> = (
) & {
readonly options?: StyledDiffCodeViewOptions<LAnnotation>;
readonly viewerRef?: Ref<CodeViewHandle<LAnnotation>>;
+ /**
+ * Appended to the shared stylesheet inside the viewer's shadow root, for a surface that has
+ * to restyle chrome the viewer owns — such as replacing its per-file line counts.
+ */
+ readonly unsafeCSSExtra?: string;
};
/** The shared web CodeView surface: app styling and virtualized geometry stay paired here. */
@@ -276,6 +281,7 @@ export function StyledDiffCodeView<LAnnotation = undefined>({
options,
viewerRef,
className,
+ unsafeCSSExtra,
...props
}: StyledDiffCodeViewProps<LAnnotation>) {
return (
@@ -291,7 +297,9 @@ export function StyledDiffCodeView<LAnnotation = undefined>({
}
options={{
...options,
- unsafeCSS: DIFF_VIEW_UNSAFE_CSS,
+ unsafeCSS: unsafeCSSExtra
+ ? `${DIFF_VIEW_UNSAFE_CSS}\n${unsafeCSSExtra}`
+ : DIFF_VIEW_UNSAFE_CSS,
itemMetrics: {
diffHeaderHeight: 32,
hunkSeparatorHeight: 24,
diff --git a/apps/web/src/components/pullRequest/PullRequestChecksPopover.tsx b/apps/web/src/components/pullRequest/PullRequestChecksPopover.tsx
new file mode 100644
index 000000000..3b8ffd2b2
--- /dev/null
+++ b/apps/web/src/components/pullRequest/PullRequestChecksPopover.tsx
@@ -0,0 +1,134 @@
+import type {
+ EnvironmentId,
+ PullRequestCheck,
+ PullRequestChecksState,
+ PullRequestRef,
+} from "@t3tools/contracts";
+
+import { readLocalApi } from "~/localApi";
+import { cn } from "~/lib/utils";
+import { pullRequestEnvironment } from "~/state/pullRequests";
+import { useEnvironmentQuery } from "~/state/query";
+
+import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
+import {
+ PullRequestCheckStatusIcon,
+ pullRequestCheckStatusLabel,
+ pullRequestChecksStatePresentation,
+ summarizePullRequestChecks,
+} from "./pullRequestPresentation";
+
+/**
+ * The checks behind the rollup, for a row that only carries the rollup. Mounted by the popup, so
+ * the read starts when somebody opens it rather than once per row of a listing — the detail read
+ * is a request per pull request, and a page of them at rest would be a hundred.
+ */
+function LazyChecksBody({
+ environmentId,
+ reference,
+}: {
+ environmentId: EnvironmentId;
+ reference: PullRequestRef;
+}) {
+ const detailQuery = useEnvironmentQuery(
+ pullRequestEnvironment.detail({ environmentId, input: reference }),
+ );
+ if (detailQuery.error !== null) {
+ return <p className="text-muted-foreground text-xs">{detailQuery.error}</p>;
+ }
+ if (detailQuery.data === null) {
+ return (
+ <p className="text-muted-foreground text-xs">
+ {detailQuery.isPending ? "Loading checks…" : "No checks reported"}
+ </p>
+ );
+ }
+ return <ChecksBody checks={detailQuery.data.checks} />;
+}
+
+function ChecksBody({ checks }: { checks: ReadonlyArray<PullRequestCheck> }) {
+ if (checks.length === 0) {
+ return <p className="text-muted-foreground text-xs">No checks reported</p>;
+ }
+ return (
+ <ul className="flex flex-col gap-1">
+ {/* Keyed by position as well as by name: the host is the one that decides how many runs
+ share a name, and a repeated key is a rendering fault rather than a wrong list. */}
+ {checks.map((check, index) => (
+ <li key={`${index}:${check.name}`} className="flex items-center gap-2 text-xs">
+ <PullRequestCheckStatusIcon status={check.status} />
+ <span className="min-w-0 flex-1 truncate" title={check.description ?? check.name}>
+ {check.name}
+ </span>
+ <span className="shrink-0 text-muted-foreground">
+ {pullRequestCheckStatusLabel(check.status)}
+ </span>
+ {check.url === null ? null : (
+ <button
+ type="button"
+ className="shrink-0 text-primary hover:underline"
+ onClick={() => void readLocalApi()?.shell.openExternal(check.url ?? "")}
+ >
+ Details
+ </button>
+ )}
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+/**
+ * The checks indicator and what it opens, in both places a change request is shown: a listing
+ * row, which knows only the rollup, and the detail header, which is already holding every check.
+ *
+ * `checks` decides between the two. Given them, nothing is read; without them, the popup reads
+ * the detail itself, which is why the row must also say which environment it came from.
+ */
+export function PullRequestChecksPopover({
+ checksState,
+ checks,
+ environmentId,
+ reference,
+ className,
+}: {
+ checksState: PullRequestChecksState;
+ /** The checks already in hand, for the detail header. Absent on a listing row. */
+ checks?: ReadonlyArray<PullRequestCheck>;
+ environmentId?: EnvironmentId;
+ reference?: PullRequestRef;
+ className?: string;
+}) {
+ const presentation = pullRequestChecksStatePresentation(checksState);
+ // Counts beat the rollup's own wording where they are known, the way GitHub's own header reads.
+ const summary = checks === undefined ? null : summarizePullRequestChecks(checks);
+ return (
+ <Popover>
+ {/* A listing row is itself a button, so the trigger renders as a span: a nested button is
+ not valid inside one. The click is stopped here so opening the checks does not also
+ select the row it sits on. */}
+ <PopoverTrigger
+ render={
+ <span
+ role="button"
+ tabIndex={0}
+ aria-label={`Checks: ${presentation.label}`}
+ className={cn("inline-flex shrink-0 cursor-pointer items-center", className)}
+ />
+ }
+ onClick={(event) => event.stopPropagation()}
+ >
+ <presentation.Icon aria-hidden className={cn("size-3.5", presentation.toneClassName)} />
+ </PopoverTrigger>
+ <PopoverPopup align="start" className="w-80 max-w-full" side="bottom">
+ <p className="mb-2 font-medium text-sm">{presentation.label}</p>
+ {summary === null ? null : <p className="mb-2 text-muted-foreground text-xs">{summary}</p>}
+ {checks !== undefined ? (
+ <ChecksBody checks={checks} />
+ ) : environmentId !== undefined && reference !== undefined ? (
+ <LazyChecksBody environmentId={environmentId} reference={reference} />
+ ) : null}
+ </PopoverPopup>
+ </Popover>
+ );
+}
diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
index 93418e7c3..a5b3c9739 100644
--- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
@@ -4,6 +4,7 @@ import type {
EnvironmentId,
PullRequestDetailView,
PullRequestDiffSide,
+ PullRequestOmittedFileStat,
PullRequestRef,
PullRequestReviewThread,
} from "@t3tools/contracts";
@@ -28,6 +29,8 @@ import { useClientSettings } from "~/hooks/useSettings";
import { useTheme } from "~/hooks/useTheme";
import { areAllDiffFilesCollapsed } from "~/lib/diffCollapse";
import { pullRequestFindingKey, type PullRequestFinding } from "./pullRequestDetail.logic";
+import { canEditPullRequestComment } from "./pullRequestEditing.logic";
+import { orderDiffFiles } from "./pullRequestFileOrder.logic";
import {
buildFileDiffRenderKey,
fnv1a32,
@@ -95,8 +98,20 @@ interface DiffSlice {
readonly patch: string;
readonly truncated: boolean;
readonly nextCursor: string | null;
+ readonly omittedFileStats: ReadonlyArray<PullRequestOmittedFileStat>;
}
+/**
+ * The viewer's own per-file counts are hidden and drawn from this side of its shadow root
+ * instead: its counts are hunk sums, and a file whose hunks the host withheld would read as
+ * an empty change rather than as the counts the host did report.
+ */
+const REPLACE_FILE_COUNTS_CSS = `
+[data-diffs-header] [data-additions-count],
+[data-diffs-header] [data-deletions-count] {
+ display: none !important;
+}`;
+
/** Nothing loaded yet, as one identity, so the memos below do not see a new array every render. */
const NO_SLICES: ReadonlyArray<DiffSlice> = [];
@@ -155,6 +170,7 @@ export function PullRequestCodeTab({
selectedCommitOid,
onSelectedCommitChange,
pendingFinding,
+ fixFindingLabel = "Fix in a thread",
onFixFinding,
onAskAboutSelection,
onRefresh,
@@ -168,6 +184,7 @@ export function PullRequestCodeTab({
onSelectedCommitChange: (oid: string | null) => void;
/** The hand-off currently preparing, if any, so only the finding it belongs to says so. */
pendingFinding?: string | null;
+ fixFindingLabel?: string;
onFixFinding?: (finding: PullRequestFinding) => void;
/** Absent where a selection has no agent to go to, which takes the Ask button off the box. */
onAskAboutSelection?: (input: PullRequestAskSelectionInput) => void;
@@ -246,6 +263,7 @@ export function PullRequestCodeTab({
patch: data.patch,
truncated: data.truncated,
nextCursor: data.nextCursor,
+ omittedFileStats: data.omittedFileStats ?? [],
};
const index = slices.findIndex((slice) => slice.cursor === cursor);
if (index === -1) {
@@ -256,7 +274,17 @@ export function PullRequestCodeTab({
existing !== undefined &&
existing.patch === next.patch &&
existing.truncated === next.truncated &&
- existing.nextCursor === next.nextCursor
+ existing.nextCursor === next.nextCursor &&
+ existing.omittedFileStats.length === next.omittedFileStats.length &&
+ existing.omittedFileStats.every((file, index) => {
+ const refreshed = next.omittedFileStats[index];
+ return (
+ refreshed !== undefined &&
+ refreshed.path === file.path &&
+ refreshed.additions === file.additions &&
+ refreshed.deletions === file.deletions
+ );
+ })
) {
return previous;
}
@@ -290,6 +318,9 @@ export function PullRequestCodeTab({
const setThreadResolution = useAtomCommand(pullRequestEnvironment.setThreadResolution, {
reportFailure: false,
});
+ const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
+ reportFailure: false,
+ });
const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents);
const loadDiffFiles = useMemo(
() =>
@@ -337,16 +368,12 @@ export function PullRequestCodeTab({
}),
[loadedSlices, resolvedTheme, scopeKey],
);
- // Sorted within a slice rather than across them: sorting the accumulated set would let a late
+ // Ordered within a slice rather than across them: ordering the accumulated set would let a late
// slice push a file the reader is part way through further down the page.
const files = useMemo(
() =>
parsedSlices.flatMap((parsed) =>
- parsed?.kind === "files"
- ? parsed.files.toSorted((left, right) =>
- resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right)),
- )
- : [],
+ parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [],
),
[parsedSlices],
);
@@ -449,7 +476,13 @@ export function PullRequestCodeTab({
}:${thread.comments
.map(
(comment) =>
- `${comment.id}:${comment.author?.login ?? ""}:${comment.createdAt}:${comment.body}`,
+ `${comment.id}:${comment.author?.login ?? ""}:${comment.createdAt}:${comment.body}:${(
+ comment.reactions ?? []
+ )
+ .map(
+ (r) => `${r.content}:${r.count}:${r.viewerHasReacted ? "v" : ""}`,
+ )
+ .join(",")}`,
)
.join(";")}`,
)
@@ -471,6 +504,15 @@ export function PullRequestCodeTab({
],
);
const lineStat = useMemo(() => getDiffLineStat(files), [files]);
+ const omittedFileStats = useMemo(
+ () =>
+ new Map(
+ loadedSlices.flatMap((slice) =>
+ slice.omittedFileStats.map((file) => [file.path, file] as const),
+ ),
+ ),
+ [loadedSlices],
+ );
const fileKeys = useMemo(() => items.map((item) => item.id), [items]);
const collapsedFileKeys = useMemo(
() => new Set(items.filter((item) => item.collapsed === true).map((item) => item.id)),
@@ -649,6 +691,30 @@ export function PullRequestCodeTab({
[toggleFile],
);
+ const renderHeaderMetadata = useCallback(
+ (item: CodeViewItem<ReviewAnnotationGroup>) => {
+ if (item.type !== "diff") return null;
+ let additions = 0;
+ let deletions = 0;
+ for (const hunk of item.fileDiff.hunks) {
+ additions += hunk.additionLines;
+ deletions += hunk.deletionLines;
+ }
+ if (additions === 0 && deletions === 0) {
+ const withheld = omittedFileStats.get(resolveFileDiffPath(item.fileDiff));
+ if (withheld) ({ additions, deletions } = withheld);
+ }
+ return (
+ <PullRequestDiffStat
+ additions={additions}
+ deletions={deletions}
+ className="font-mono text-[11px]"
+ />
+ );
+ },
+ [omittedFileStats],
+ );
+
const diffViewOptions = useMemo(
() => ({
diffStyle: diffRenderMode === "split" ? ("split" as const) : ("unified" as const),
@@ -699,13 +765,20 @@ export function PullRequestCodeTab({
const renderThreadCard = useCallback(
(thread: PullRequestReviewThread) => (
<ReviewThreadCard
- key={thread.id}
+ // Named with the pull request too: a thread's id is the host's own, and two pull requests
+ // can hand out the same one — which would leave one card's open editor standing over the
+ // other's conversation.
+ key={`${reference.projectId}#${reference.number}:${thread.id}`}
thread={thread}
workspaceRoot={detail.workspaceRoot}
canReply={review.reply}
canResolve={review.resolve}
+ canReact={detail.capabilities.reactions === true}
+ environmentId={environmentId}
+ reference={reference}
pending={threadPending}
fixPending={pendingFinding === pullRequestFindingKey({ kind: "thread", thread })}
+ fixLabel={fixFindingLabel}
{...(onFixFinding ? { onFix: () => onFixFinding({ kind: "thread", thread }) } : {})}
onReply={(body) =>
runThreadCommand("Reply could not be posted", () =>
@@ -715,6 +788,18 @@ export function PullRequestCodeTab({
}),
)
}
+ // A conversation on a line is made of review comments, whatever the host filed them as.
+ canEditComment={(comment) =>
+ canEditPullRequestComment(detail, { author: comment.author, kind: "review-comment" })
+ }
+ onEditComment={(commentId, body) =>
+ runThreadCommand("The comment could not be saved", () =>
+ updateComment({
+ environmentId,
+ input: { ...reference, commentId, kind: "review-comment", body },
+ }),
+ )
+ }
onToggleResolved={() =>
void runThreadCommand("The conversation could not be updated", () =>
setThreadResolution({
@@ -723,11 +808,14 @@ export function PullRequestCodeTab({
}),
)
}
+ onReacted={onRefresh}
/>
),
[
- detail.workspaceRoot,
+ detail,
environmentId,
+ fixFindingLabel,
+ onRefresh,
onFixFinding,
pendingFinding,
reference,
@@ -737,12 +825,13 @@ export function PullRequestCodeTab({
runThreadCommand,
setThreadResolution,
threadPending,
+ updateComment,
],
);
const renderAnnotation = useCallback(
(annotation: ReviewAnnotation) => (
- <div className="py-1">
+ <div className="py-1 font-sans text-foreground">
{annotation.metadata.threads.map(renderThreadCard)}
{annotation.metadata.pending.map((comment) => (
<PendingReviewCommentCard
@@ -1222,7 +1311,9 @@ export function PullRequestCodeTab({
// is running out of diff.
renderCodeViewFooter={renderCodeViewFooter}
renderHeaderPrefix={renderHeaderPrefix}
+ renderHeaderMetadata={renderHeaderMetadata}
renderAnnotation={renderAnnotation}
+ unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS}
/>
{reviewOverlay}
</div>
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
index 4ac181280..7237b4357 100644
--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
@@ -1,11 +1,13 @@
-import { scopeProjectRef } from "@t3tools/client-runtime/environment";
+import { scopedThreadKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type {
EnvironmentId,
PullRequestAction,
PullRequestMergeMethod,
+ PullRequestUpdateMethod,
PullRequestRef,
PullRequestState,
+ ScopedThreadRef,
} from "@t3tools/contracts";
import {
ArrowDownUpIcon,
@@ -28,12 +30,15 @@ import {
LinkIcon,
MoreHorizontalIcon,
PanelRightIcon,
+ PencilIcon,
RefreshCwIcon,
+ ServerIcon,
TriangleAlertIcon,
} from "lucide-react";
import {
lazy,
Suspense,
+ type MouseEvent as ReactMouseEvent,
useCallback,
useEffect,
useLayoutEffect,
@@ -49,6 +54,8 @@ import { usePreparePullRequestThreadAction } from "~/lib/sourceControlActions";
import { cn } from "~/lib/utils";
import { readLocalApi } from "~/localApi";
import type { ReviewCommentContext } from "~/reviewCommentContext";
+import { useProjects } from "~/state/entities";
+import { useEnvironments } from "~/state/environments";
import { useEnvironmentQuery } from "~/state/query";
import { useLiveRefresh } from "~/hooks/useLiveRefresh";
import { pullRequestEnvironment } from "~/state/pullRequests";
@@ -66,6 +73,7 @@ import {
} from "../ui/alert-dialog";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
+import { Input } from "../ui/input";
import {
Menu,
MenuItem,
@@ -75,12 +83,14 @@ import {
MenuSeparator,
MenuTrigger,
} from "../ui/menu";
+import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { toastManager } from "../ui/toast";
import { PullRequestDetailGhost, PullRequestTimelineGhost } from "./PullRequestGhosts";
import { PullRequestActivityUnavailableState } from "./PullRequestActivityUnavailableState";
import { DiffPanelLoadingState } from "../DiffPanelShell";
import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";
import type { PullRequestAskSelectionInput } from "./PullRequestCodeTab";
+import { openOnHostLabel, showPullRequestLinkContextMenu } from "./pullRequestLinkContextMenu";
import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
import { PullRequestTimelineTab } from "./PullRequestTimelineTab";
import {
@@ -92,14 +102,24 @@ import {
buildResolveConflictsPrompt,
handoffPrompt,
handoffReviewComments,
+ pullRequestActionNeedsHostRefresh,
pullRequestFindingKey,
+ pullRequestHandoffLabels,
readableFailure,
+ resolveBaseFreshness,
type PullRequestFinding,
} from "./pullRequestDetail.logic";
+import { canEditPullRequestChangeRequest } from "./pullRequestEditing.logic";
+import {
+ resolvePickableEnvironments,
+ type PickableEnvironment,
+} from "./pullRequestProjectAssignment.logic";
+import { PullRequestChecksPopover } from "./PullRequestChecksPopover";
import {
PullRequestActorLabel,
PullRequestDiffStat,
PullRequestMetaLine,
+ pullRequestChecksState,
resolvePullRequestState,
summarizePullRequestChecks,
} from "./pullRequestPresentation";
@@ -112,6 +132,12 @@ const ACTION_SUCCESS_LABELS: Record<PullRequestAction, string> = {
draft: "Converted to draft",
close: "Pull request closed",
reopen: "Pull request reopened",
+ "update-branch": "Branch updated with the base branch",
+ // True whichever it did: a pull request that was already mergeable merges the moment this is
+ // armed, and the client has no way to tell that apart from one still waiting on something.
+ "enable-auto-merge":
+ "Auto-merge turned on — merges as soon as this is ready, sooner if it already is",
+ "disable-auto-merge": "Auto-merge turned off",
};
/** Said as the thing that did not happen, rather than as the operation that returned an error. */
@@ -121,6 +147,9 @@ const ACTION_FAILURE_LABELS: Record<PullRequestAction, string> = {
draft: "Could not convert this to a draft",
close: "Could not close this pull request",
reopen: "Could not reopen this pull request",
+ "update-branch": "Could not update this branch",
+ "enable-auto-merge": "Could not turn on auto-merge",
+ "disable-auto-merge": "Could not turn off auto-merge",
};
/** What to try, for the times the host says only that it refused. */
@@ -132,15 +161,25 @@ const ACTION_FAILURE_HINTS: Record<PullRequestAction, string> = {
close: "The host refused it. Check that you have write access, or that you opened it.",
reopen:
"The host refused it. Check that you have write access, and that the branch still exists.",
+ // Said for the merge commit, which is what an update is unless a rebase was asked for. The
+ // rebase has its own reasons to fail and its own sentence below.
+ "update-branch":
+ "The host refused it. Check that you have write access to the branch — one from a fork also needs its author to allow edits from maintainers — and that it does not conflict with the base.",
+ // The one refusal that is usually a repository setting rather than anything about this branch:
+ // GitHub will not arm an auto-merge at all unless the repository has the feature switched on.
+ "enable-auto-merge":
+ "The host refused it. Check that this repository allows auto-merge, that you have write access, and that there is something left for it to wait on.",
+ "disable-auto-merge":
+ "The host refused it. Check that you have write access, and that the merge has not already happened.",
};
-/** Named for the host rather than "externally": the point is where you will land. */
-const OPEN_ON_HOST_LABELS: Partial<Record<string, string>> = {
- github: "Open on GitHub",
- gitlab: "Open on GitLab",
- bitbucket: "Open on Bitbucket",
- "azure-devops": "Open on Azure DevOps",
-};
+/**
+ * Said instead of the update hint when the reader asked for a rebase: it is the one that fails on
+ * its own merits, because GitHub replays the commits and stops at the first that does not apply.
+ * Offering the merge commit only makes sense to somebody who did not already choose it.
+ */
+const UPDATE_BRANCH_REBASE_FAILURE_HINT =
+ "The host refused it. A rebase stops at the first commit that does not apply cleanly; updating with a merge commit may still work.";
const TABS: ReadonlyArray<{ value: DetailTab; label: string }> = [
{ value: "summary", label: "Summary" },
@@ -159,7 +198,148 @@ const PullRequestCodeTab = lazy(loadCodeTab);
* is closed by the time the next one opens. It is how a prompt the reader has since edited is told
* apart from the one they were handed: only the sentence still exactly as written may be replaced.
*/
-const lastHandoffPromptByDraft = new Map<DraftId, string>();
+const lastHandoffPromptByDraft = new Map<string, string>();
+
+const composerTargetKey = (target: ScopedThreadRef | DraftId): string =>
+ typeof target === "string" ? target : scopedThreadKey(target);
+
+/**
+ * Which server the checkout and the hand-offs land on, where more than one of them holds this
+ * repository. The list picked one of them to show the pull request under, so that everything on
+ * it is read from somewhere; where the reader wants to work is a separate answer, and this is
+ * where they give it.
+ */
+function ActOnEnvironmentPicker({
+ environments,
+ value,
+ onChange,
+ disabled,
+}: {
+ environments: ReadonlyArray<PickableEnvironment>;
+ value: EnvironmentId;
+ onChange: (environmentId: EnvironmentId) => void;
+ disabled: boolean;
+}) {
+ return (
+ <>
+ <MenuSeparator />
+ <MenuRadioGroup
+ value={value}
+ onValueChange={(environmentId) => onChange(environmentId as EnvironmentId)}
+ >
+ {environments.map((environment) => (
+ <MenuRadioItem
+ key={environment.environmentId}
+ value={environment.environmentId}
+ disabled={disabled}
+ >
+ {/* The radio item lays its children out as one block, so the icon and the label
+ need their own row to share a line. */}
+ <span className="flex min-w-0 items-center gap-2">
+ <ServerIcon className="size-3.5 shrink-0" />
+ <span className="truncate">{environment.label}</span>
+ </span>
+ </MenuRadioItem>
+ ))}
+ </MenuRadioGroup>
+ </>
+ );
+}
+
+/** The number is a link in every place the host writes it, so the right-click that copies one
+ has to answer here too — otherwise the platform's own cut/paste menu opens over it. */
+const openNumberContextMenu = (
+ event: ReactMouseEvent,
+ detail: { readonly url: string; readonly provider: string },
+): void => {
+ event.preventDefault();
+ event.stopPropagation();
+ void showPullRequestLinkContextMenu({
+ url: detail.url,
+ openLabel: openOnHostLabel(detail.provider),
+ position: { x: event.clientX, y: event.clientY },
+ });
+};
+
+/**
+ * The stale-branch warning, said beside the branch it is about rather than as a bar of its own.
+ * The banner this replaces held a row of chrome open across the top of every pull request that
+ * had fallen behind, pushing the reading down to say something that is true of the base branch
+ * and nothing else; as a mark on the base branch it is where a reader would look for it, and the
+ * sentence and the way out of it arrive together the moment the mark is pointed at.
+ *
+ * A popover rather than a tooltip because what it holds can be pressed: a tooltip's layer takes
+ * no pointer, and a control nobody can reach is worse than no control.
+ */
+function PullRequestBaseFreshnessWarning({
+ baseBranch,
+ freshness,
+ pending,
+ onUpdate,
+ iconClassName,
+}: {
+ readonly baseBranch: string;
+ readonly freshness: {
+ readonly behindBy: number | null;
+ readonly methods: ReadonlyArray<PullRequestUpdateMethod>;
+ };
+ readonly pending: boolean;
+ readonly onUpdate: (method: PullRequestUpdateMethod) => void;
+ readonly iconClassName?: string;
+}) {
+ const behind =
+ freshness.behindBy === null
+ ? ""
+ : ` by ${freshness.behindBy.toLocaleString()} ${
+ freshness.behindBy === 1 ? "commit" : "commits"
+ }`;
+ const summary = `This branch is out-of-date with ${baseBranch}${behind}.`;
+ return (
+ <Popover>
+ <PopoverTrigger
+ openOnHover
+ delay={0}
+ closeDelay={120}
+ render={
+ <button
+ type="button"
+ aria-label={summary}
+ className="inline-flex shrink-0 cursor-help items-center rounded-sm text-amber-600 outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ }
+ >
+ <TriangleAlertIcon aria-hidden className={cn("size-3.5", iconClassName)} />
+ </PopoverTrigger>
+ <PopoverPopup
+ align="start"
+ side="bottom"
+ className="max-w-80"
+ viewportClassName="py-2.5 [--viewport-inline-padding:--spacing(3)]"
+ >
+ <p className="text-xs text-foreground">{summary}</p>
+ <p className="mt-0.5 text-xs text-muted-foreground">Changes can be cleanly merged.</p>
+ {/* Each way the host offers and this reader may take, as its own button: a split button
+ would need a menu inside a popover, and two buttons say the same thing in one layer. */}
+ {freshness.methods.length > 0 ? (
+ <span className="mt-2 flex flex-wrap items-center gap-1.5">
+ {freshness.methods.map((method) => (
+ <Button
+ key={method}
+ size="xs"
+ variant="outline"
+ disabled={pending}
+ onClick={() => onUpdate(method)}
+ >
+ <GitMergeIcon aria-hidden className="size-3" />
+ {method === "rebase" ? "Update with rebase" : "Update branch"}
+ </Button>
+ ))}
+ </span>
+ ) : null}
+ </PopoverPopup>
+ </Popover>
+ );
+}
export function PullRequestDetailPanel({
environmentId,
@@ -170,6 +350,7 @@ export function PullRequestDetailPanel({
onStateChange,
context = "page",
chromeVariant = "full",
+ composerDraftTarget,
}: {
environmentId: EnvironmentId;
reference: PullRequestRef;
@@ -206,6 +387,11 @@ export function PullRequestDetailPanel({
* top — the chrome spends its height on what is being read.
*/
chromeVariant?: "full" | "collapse";
+ /**
+ * The open thread's composer. Beside the thread whose own pull request this is, hand-offs
+ * land here instead of opening a new thread — the branch is already under the reader's feet.
+ */
+ composerDraftTarget?: ScopedThreadRef | DraftId;
}) {
const pullRequestKey = `${reference.projectId}:${reference.repository}#${reference.number}`;
const [tab, setTab] = useState<DetailTab>("summary");
@@ -267,7 +453,9 @@ export function PullRequestDetailPanel({
if (scroller) scroller.scrollTop = Math.max(0, scroller.scrollTop + delta);
}, [condensed]);
const [mergeMethod, setMergeMethod] = useState<PullRequestMergeMethod>("merge");
- const [confirmAction, setConfirmAction] = useState<"merge" | "close" | null>(null);
+ const [confirmAction, setConfirmAction] = useState<
+ "merge" | "close" | "enable-auto-merge" | null
+ >(null);
// Which handoff is preparing, keyed so a per-finding button can say "Preparing..." on itself
// alone. One at a time whatever the key: they all check the same pull request out.
const [handoff, setHandoff] = useState<string | null>(null);
@@ -310,6 +498,7 @@ export function PullRequestDetailPanel({
commentsTruncated: activity?.commentsTruncated ?? false,
reviewThreads: activity?.reviewThreads ?? [],
commits: activity?.commits ?? [],
+ reactions: activity?.reactions ?? [],
},
[activity, coreDetail],
);
@@ -355,44 +544,157 @@ export function PullRequestDetailPanel({
void refreshFromHost();
}, [forcedRefreshToken, refreshFromHost]);
const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
- const [actionPending, setActionPending] = useState(false);
+ // Which action is in flight, not merely that one is: every control here is disabled while any
+ // of them runs, but only the button that was pressed may say what it is doing.
+ const [pendingAction, setPendingAction] = useState<PullRequestAction | null>(null);
+ const actionPending = pendingAction !== null;
+ const update = useAtomCommand(pullRequestEnvironment.update, { reportFailure: false });
+ // Scoped to the pull request it was typed against, since this one panel shows a different one
+ // every time it is opened and a half-written title must not follow it there.
+ const [titleScope, setTitleScope] = useState<{
+ readonly pullRequestKey: string;
+ readonly text: string;
+ } | null>(null);
+ const titleDraft = titleScope?.pullRequestKey === pullRequestKey ? titleScope.text : null;
+ const [titleSaving, setTitleSaving] = useState(false);
const newThread = useNewThreadHandler();
+ const { environments } = useEnvironments();
+ const projects = useProjects();
+ // Beside a thread there is nothing to pick: the hand-offs land in that thread's composer, and
+ // the thread is already on one server's copy of the branch.
+ const pickableEnvironments = useMemo(
+ () =>
+ context === "page"
+ ? resolvePickableEnvironments(
+ { environmentId, projectId: reference.projectId },
+ projects,
+ environments,
+ )
+ : [],
+ [context, environmentId, environments, projects, reference.projectId],
+ );
+ // Which server the reader chose, and only for the pull request they chose it on: this one panel
+ // shows a different pull request every time it is opened, and the choice does not follow.
+ const [actingScope, setActingScope] = useState<{
+ readonly pullRequestKey: string;
+ readonly environmentId: EnvironmentId;
+ } | null>(null);
+ const chosenEnvironmentId =
+ actingScope?.pullRequestKey === pullRequestKey ? actingScope.environmentId : environmentId;
+ // Null wherever there is no choice on offer — one server, or a chosen one that has since gone —
+ // and then the panel's own server and its own checkout are the answer, as they always were.
+ const acting =
+ pickableEnvironments.find((entry) => entry.environmentId === chosenEnvironmentId) ?? null;
+ const actingEnvironmentId = acting?.environmentId ?? environmentId;
const prepareThread = usePreparePullRequestThreadAction({
- environmentId,
- cwd: detail?.workspaceRoot ?? null,
+ environmentId: actingEnvironmentId,
+ cwd: acting?.workspaceRoot ?? detail?.workspaceRoot ?? null,
});
- const perform = async (action: PullRequestAction, method?: PullRequestMergeMethod) => {
- if (actionPending) return;
- setActionPending(true);
+ const perform = async (
+ action: PullRequestAction,
+ method?: PullRequestMergeMethod,
+ updateMethod?: PullRequestUpdateMethod,
+ ) => {
+ if (pendingAction !== null) return;
+ setPendingAction(action);
const result = await runAction({
environmentId,
- input: { ...reference, action, ...(method ? { mergeMethod: method } : {}) },
+ input: {
+ ...reference,
+ action,
+ ...(method ? { mergeMethod: method } : {}),
+ ...(updateMethod ? { updateMethod } : {}),
+ },
});
- setActionPending(false);
+ setPendingAction(null);
if (result._tag === "Failure") {
// The host's own sentence, because it is the only thing that says why. A merge strategy a
// branch policy forbids is refused at completion and nowhere earlier — Azure DevOps
// publishes no per-strategy availability to hide the control with — so "action failed"
// would leave the reader pressing the same button again.
const failure = squashAtomCommandFailure(result);
+ // The hint stands for what was actually asked for: a reader who pressed Update branch is
+ // told to check their access, not offered the merge commit they already chose.
+ const hint =
+ updateMethod === "rebase"
+ ? UPDATE_BRANCH_REBASE_FAILURE_HINT
+ : ACTION_FAILURE_HINTS[action];
toastManager.add({
type: "error",
title: ACTION_FAILURE_LABELS[action],
- description: readableFailure(failure, ACTION_FAILURE_HINTS[action]),
+ description: readableFailure(failure, hint),
});
return;
}
toastManager.add({ type: "success", title: ACTION_SUCCESS_LABELS[action] });
- refreshDetail();
+ // A branch update moves the head commit, which leaves the diff atom pointed at a comparison
+ // that no longer exists — the same staleness the manual refresh button fixes, so it goes
+ // through that path rather than a second one. Every other action here only changes metadata;
+ // a merge does move the branch too, but it also closes the pull request, where the diff is
+ // no longer what anyone is looking at.
+ if (pullRequestActionNeedsHostRefresh(action)) {
+ void refreshFromHost();
+ } else {
+ refreshDetail();
+ }
onActed?.();
};
+ const saveTitle = async (next: string) => {
+ const title = next.trim();
+ if (detail === null || titleSaving) return;
+ if (title.length === 0 || title === detail.title) {
+ setTitleScope(null);
+ return;
+ }
+ setTitleSaving(true);
+ const result = await update({ environmentId, input: { ...reference, title } });
+ setTitleSaving(false);
+ if (result._tag === "Failure") {
+ // The draft stays open with the words still in it: retyping a title somebody has just
+ // rewritten is the one thing a failed save must not cost them.
+ toastManager.add({
+ type: "error",
+ title: "The title could not be saved",
+ description: readableFailure(
+ squashAtomCommandFailure(result),
+ "The host refused the new title.",
+ ),
+ });
+ return;
+ }
+ setTitleScope(null);
+ refreshDetail();
+ };
+
type ThreadTask = {
prompt: string;
reviewComments?: ReadonlyArray<ReviewCommentContext>;
};
+ // Beside the thread whose own pull request this is, a task belongs in that thread's composer:
+ // the branch is already checked out under it, so opening a second thread would only scatter
+ // the work.
+ const attachTarget = context === "thread" ? (composerDraftTarget ?? null) : null;
+ const handoffLabels = pullRequestHandoffLabels(attachTarget !== null);
+
+ const writeTaskToComposer = (target: ScopedThreadRef | DraftId, task: ThreadTask) => {
+ const store = useComposerDraftStore.getState();
+ const draft = store.getComposerDraft(target);
+ const key = composerTargetKey(target);
+ const prompt = handoffPrompt(
+ { prompt: draft?.prompt ?? "", lastHandoffPrompt: lastHandoffPromptByDraft.get(key) },
+ task.prompt,
+ );
+ lastHandoffPromptByDraft.set(key, task.prompt);
+ store.setPrompt(target, prompt);
+ store.setReviewComments(
+ target,
+ handoffReviewComments(draft?.reviewComments ?? [], task.reviewComments ?? []),
+ );
+ };
+
/**
* Opens a thread on this project and leaves the task in its composer for the reader to send.
*
@@ -412,37 +714,32 @@ export function PullRequestDetailPanel({
() => null,
));
if (session === null) return null;
- const store = useComposerDraftStore.getState();
if (task === null) return session;
// The latest press is the ask: it takes over what an earlier hand-off left, prompt and chips
// both, rather than stacking a second one under the first. What the reader typed themselves
// survives — the composer they are handed is not always a fresh one, and a prompt they have
// since edited is theirs rather than the hand-off's.
- const draft = store.getComposerDraft(session.draftId);
- const existingComments = draft?.reviewComments ?? [];
- const prompt = handoffPrompt(
- {
- prompt: draft?.prompt ?? "",
- lastHandoffPrompt: lastHandoffPromptByDraft.get(session.draftId),
- },
- task.prompt,
- );
- // Remember the hand-off's own contribution, not the merged prompt: only that sentence is
- // this session's to take back next time, and the reader's text around it is not.
- lastHandoffPromptByDraft.set(session.draftId, task.prompt);
- store.setPrompt(session.draftId, prompt);
- store.setReviewComments(
- session.draftId,
- handoffReviewComments(existingComments, task.reviewComments ?? []),
- );
+ writeTaskToComposer(session.draftId, task);
return session;
};
/** A question about the change, which needs a thread and nothing else. */
const startAsk = async (kind: string, task: ThreadTask) => {
if (!detail || handoff !== null) return;
+ if (attachTarget !== null) {
+ writeTaskToComposer(attachTarget, task);
+ toastManager.add({
+ type: "success",
+ title: "Added to the composer",
+ description:
+ task.prompt.length > 0
+ ? "The question is in the composer — read it over, then send."
+ : "The pull request is in the composer — type your question, then send.",
+ });
+ return;
+ }
setHandoff(kind);
- const projectRef = scopeProjectRef(environmentId, detail.projectId);
+ const projectRef = scopeProjectRef(actingEnvironmentId, acting?.projectId ?? detail.projectId);
const opened = await openThreadWithTask(projectRef, task);
setHandoff(null);
if (opened === null) {
@@ -477,6 +774,15 @@ export function PullRequestDetailPanel({
mode: "worktree" | "local" = "worktree",
) => {
if (!detail || handoff !== null) return;
+ if (attachTarget !== null && task !== null) {
+ writeTaskToComposer(attachTarget, task);
+ toastManager.add({
+ type: "success",
+ title: "Added to the composer",
+ description: "The task is in the composer — read it over, then send.",
+ });
+ return;
+ }
setHandoff(kind);
// The menu closes on the press and takes its "Preparing..." label with it, so this is the
// only thing answering for the checkout. It carries no timeout of its own: a loading toast
@@ -485,7 +791,9 @@ export function PullRequestDetailPanel({
type: "loading",
title: "Preparing the pull request checkout...",
});
- const projectRef = scopeProjectRef(environmentId, detail.projectId);
+ // Wherever the reader chose to act: the thread, the checkout it is pointed at and the composer
+ // the task lands in are all one server's, and picking another one moves all three.
+ const projectRef = scopeProjectRef(actingEnvironmentId, acting?.projectId ?? detail.projectId);
// The thread is opened before the checkout rather than after it, because the project's setup
// script only runs for a checkout that knows which thread it is for — and a worktree with no
// dependencies installed is not something anyone can test.
@@ -688,6 +996,12 @@ export function PullRequestDetailPanel({
? mergeMethod
: (allowedMergeMethods[0] ?? "merge");
const conflicting = detail?.state === "open" && detail.mergeability === "conflicting";
+ // Only an outright yes arms it. A host that reports nothing has not said the merge is already
+ // spoken for, and an off switch for something that may not be on says the wrong thing twice.
+ const autoMergeArmed = detail?.state === "open" && detail.autoMergeEnabled === true;
+ // Out of date with the base, and still cleanly mergeable — the one pairing an update button
+ // exists for. Null everywhere else, including hosts that cannot compare at all.
+ const freshness = detail === null ? null : resolveBaseFreshness(detail);
// A host that cannot produce a patch has no Code tab to open. The tabs themselves stay hidden
// until the detail arrives, so the loading ghost is the panel's only unfinished UI.
const visibleTabs = TABS.filter(
@@ -725,6 +1039,7 @@ export function PullRequestDetailPanel({
? resolvePullRequestState({ state: detail.state, isDraft: detail.isDraft })
: null;
const checksSummary = detail ? summarizePullRequestChecks(detail.checks) : null;
+ const checksState = detail ? pullRequestChecksState(detail.checks) : null;
return (
<div className="flex h-full min-h-0 w-full flex-col bg-background">
@@ -755,11 +1070,12 @@ export function PullRequestDetailPanel({
<button
type="button"
onClick={() => void readLocalApi()?.shell.openExternal(detail.url)}
+ onContextMenu={(event) => openNumberContextMenu(event, detail)}
className={cn(
"shrink-0 font-medium underline-offset-2 hover:underline",
statePresentation.toneClassName,
)}
- title={OPEN_ON_HOST_LABELS[detail.provider] ?? "Open on host"}
+ title={openOnHostLabel(detail.provider)}
aria-label={`Open pull request #${detail.number} on host`}
>
#{detail.number}
@@ -783,11 +1099,12 @@ export function PullRequestDetailPanel({
type="button"
tabIndex={condensed ? 0 : -1}
onClick={() => void readLocalApi()?.shell.openExternal(detail.url)}
+ onContextMenu={(event) => openNumberContextMenu(event, detail)}
className={cn(
"shrink-0 font-medium underline-offset-2 hover:underline",
statePresentation.toneClassName,
)}
- title={OPEN_ON_HOST_LABELS[detail.provider] ?? "Open on host"}
+ title={openOnHostLabel(detail.provider)}
aria-label={`Open pull request #${detail.number} on host`}
>
#{detail.number}
@@ -804,7 +1121,10 @@ export function PullRequestDetailPanel({
Conflicts
</Badge>
) : checksSummary ? (
- <span className="shrink-0 text-[10px] text-muted-foreground">
+ <span className="flex shrink-0 items-center gap-1 text-[10px] text-muted-foreground">
+ {detail && checksState !== null ? (
+ <PullRequestChecksPopover checks={detail.checks} checksState={checksState} />
+ ) : null}
{checksSummary}
</span>
) : null}
@@ -832,7 +1152,9 @@ export function PullRequestDetailPanel({
<span className="flex min-w-0 flex-col">
<span>{handoff === "ask" ? "Opening..." : "Ask a question"}</span>
<span className="text-xs text-muted-foreground">
- Opens a thread that knows which pull request you mean.
+ {attachTarget !== null
+ ? "Adds the pull request to this thread's composer."
+ : "Opens a thread that knows which pull request you mean."}
</span>
</span>
</MenuItem>
@@ -847,8 +1169,16 @@ export function PullRequestDetailPanel({
</MenuItem>
<MenuItem disabled={handoff !== null} onClick={startFixFindings}>
<HammerIcon className="size-3.5" />
- {handoff === "findings" ? "Preparing..." : "Fix findings in a thread"}
+ {handoff === "findings" ? "Preparing..." : handoffLabels.fixFindings}
</MenuItem>
+ {pickableEnvironments.length > 0 ? (
+ <ActOnEnvironmentPicker
+ environments={pickableEnvironments}
+ value={actingEnvironmentId}
+ onChange={(next) => setActingScope({ pullRequestKey, environmentId: next })}
+ disabled={handoff !== null}
+ />
+ ) : null}
<MenuSeparator />
{detail.state === "open" ? (
<>
@@ -869,6 +1199,32 @@ export function PullRequestDetailPanel({
{detail.isDraft ? "Ready for review" : "Convert to draft"}
</MenuItem>
) : null}
+ {/* The same merge, left with the host to carry out once the things it
+ waits on are done. It is offered beside the merge rather than instead
+ of it, because the reader who can wait and the reader who cannot are
+ the same person on different days — and a conflicting branch is neither,
+ since nothing the host waits for will clear it. */}
+ {autoMergeArmed && can("disable-auto-merge") ? (
+ <MenuItem
+ disabled={actionPending}
+ onClick={() => void perform("disable-auto-merge")}
+ >
+ <GitMergeIcon className="size-3.5" />
+ Disable auto-merge
+ </MenuItem>
+ ) : !autoMergeArmed &&
+ !detail.isDraft &&
+ !conflicting &&
+ can("enable-auto-merge") &&
+ allowedMergeMethods.length > 0 ? (
+ <MenuItem
+ disabled={actionPending}
+ onClick={() => setConfirmAction("enable-auto-merge")}
+ >
+ <GitMergeIcon className="size-3.5" />
+ Enable auto-merge
+ </MenuItem>
+ ) : null}
{/* A preference for the merge action rather than a second action, so it
is a radio group here instead of a chevron welded to the Merge pill.
Hidden while conflicting: every method would fail. */}
@@ -904,7 +1260,7 @@ export function PullRequestDetailPanel({
) : null}
<MenuItem onClick={() => void readLocalApi()?.shell.openExternal(detail.url)}>
<ArrowUpRightIcon className="size-3.5" />
- {OPEN_ON_HOST_LABELS[detail.provider] ?? "Open on host"}
+ {openOnHostLabel(detail.provider)}
</MenuItem>
<MenuItem onClick={() => void writeTextToClipboard(detail.url)}>
<LinkIcon className="size-3.5" />
@@ -914,7 +1270,7 @@ export function PullRequestDetailPanel({
{conflicting && primaryAction !== "resolve" ? (
<MenuItem disabled={handoff !== null} onClick={startResolveConflicts}>
<GitMergeIcon className="size-3.5" />
- {handoff === "conflicts" ? "Preparing..." : "Resolve conflicts in a thread"}
+ {handoff === "conflicts" ? "Preparing..." : handoffLabels.resolveConflicts}
</MenuItem>
) : null}
{detail.state === "open" && can("close") ? (
@@ -982,9 +1338,29 @@ export function PullRequestDetailPanel({
</span>
</span>
</MenuItem>
+ {pickableEnvironments.length > 0 ? (
+ <ActOnEnvironmentPicker
+ environments={pickableEnvironments}
+ value={actingEnvironmentId}
+ onChange={(next) => setActingScope({ pullRequestKey, environmentId: next })}
+ disabled={handoff !== null}
+ />
+ ) : null}
</MenuPopup>
</Menu>
) : null}
+ {/* Said where the Merge button is, because it is the answer to why nobody has
+ pressed it: the merge is already asked for, and the host is holding it. */}
+ {autoMergeArmed ? (
+ <Badge
+ variant="info"
+ className="h-5 shrink-0 gap-1 rounded px-1.5 text-[10px]"
+ title="The host will merge this on its own once its requirements are met"
+ >
+ <GitMergeIcon aria-hidden className="size-3" />
+ Auto-merge
+ </Badge>
+ ) : null}
{primaryAction === "ready" ? (
<Button size="xs" disabled={actionPending} onClick={() => void perform("ready")}>
Ready for review
@@ -995,7 +1371,7 @@ export function PullRequestDetailPanel({
disabled={actionPending}
onClick={() => setConfirmAction("merge")}
>
- {actionPending ? "Merging..." : "Merge"}
+ {pendingAction === "merge" ? "Merging..." : "Merge"}
</Button>
) : null}
</>
@@ -1015,7 +1391,16 @@ export function PullRequestDetailPanel({
{/* The condensed chrome's second row: the tabs that the closing fold takes with it,
and compact copies of the branch pair and diff stat so they stay in sight while
the full rows are folded away. Same zero-track mechanism as the fold, inverted. */}
- <div className={cn("col-span-2 grid", condensed ? "grid-rows-[1fr]" : "grid-rows-[0fr]")}>
+ <div
+ className={cn(
+ "col-span-2 grid",
+ // Inverse of the fold's track: closing eases while the fold above eases open,
+ // so the chrome trades rows in one motion instead of two jumps.
+ condensed
+ ? "grid-rows-[1fr]"
+ : "grid-rows-[0fr] transition-[grid-template-rows] duration-200 ease-out motion-reduce:transition-none",
+ )}
+ >
<div
ref={condensedRowRef}
className={cn(
@@ -1052,6 +1437,15 @@ export function PullRequestDetailPanel({
title={`${detail.baseBranch} ← ${detail.headBranch}`}
>
<span className="truncate">{detail.baseBranch}</span>
+ {freshness ? (
+ <PullRequestBaseFreshnessWarning
+ baseBranch={detail.baseBranch}
+ freshness={freshness}
+ pending={actionPending}
+ onUpdate={(method) => void perform("update-branch", undefined, method)}
+ iconClassName="size-3"
+ />
+ ) : null}
<ArrowLeftIcon aria-label="receives changes from" className="size-3 shrink-0" />
<span className="truncate">{detail.headBranch}</span>
</span>
@@ -1077,10 +1471,13 @@ export function PullRequestDetailPanel({
<div
className={cn(
"col-span-2 grid",
- // Instant in both directions: the scroll compensation keeps the content pinned
- // through either flip, and an animated track would fight it frame by frame. The
- // top row's crossfade is the transition.
- condensed ? "grid-rows-[0fr]" : "grid-rows-[1fr]",
+ // Collapse is instant: it happens mid-scroll, and the compensation that keeps the
+ // content pinned would fight an animated track frame by frame. Reopening happens
+ // at the top with no compensation, so the fold can ease back in instead of
+ // snapping the content down.
+ condensed
+ ? "grid-rows-[0fr]"
+ : "grid-rows-[1fr] transition-[grid-template-rows] duration-200 ease-out motion-reduce:transition-none",
)}
>
<div
@@ -1098,7 +1495,66 @@ export function PullRequestDetailPanel({
>
{detail ? (
<div className="col-span-2 mt-3 min-w-0 px-4 pb-4">
- <h1 className="text-base font-semibold leading-snug">{detail.title}</h1>
+ {titleDraft === null ? (
+ <div className="group flex min-w-0 items-start gap-1">
+ <h1 className="min-w-0 flex-1 text-base font-semibold leading-snug">
+ {detail.title}
+ </h1>
+ {canEditPullRequestChangeRequest(detail) ? (
+ <Button
+ size="icon-xs"
+ variant="ghost"
+ className="shrink-0 text-muted-foreground opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100"
+ aria-label="Edit title"
+ onClick={() => setTitleScope({ pullRequestKey, text: detail.title })}
+ >
+ <PencilIcon className="size-3" />
+ </Button>
+ ) : null}
+ </div>
+ ) : (
+ // A title is one line of text, not markdown, so it takes an input rather than
+ // the editor the description and the remarks share.
+ <div className="space-y-2">
+ <Input
+ autoFocus
+ size="sm"
+ disabled={titleSaving}
+ value={titleDraft}
+ aria-label="Pull request title"
+ onChange={(event) =>
+ setTitleScope({ pullRequestKey, text: event.target.value })
+ }
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ void saveTitle(titleDraft);
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ setTitleScope(null);
+ }
+ }}
+ />
+ <div className="flex justify-end gap-2">
+ <Button
+ size="xs"
+ variant="ghost"
+ disabled={titleSaving}
+ onClick={() => setTitleScope(null)}
+ >
+ Cancel
+ </Button>
+ <Button
+ size="xs"
+ variant="outline"
+ disabled={titleSaving || titleDraft.trim().length === 0}
+ onClick={() => void saveTitle(titleDraft)}
+ >
+ {titleSaving ? "Saving..." : "Save"}
+ </Button>
+ </div>
+ </div>
+ )}
<PullRequestMetaLine className="mt-2 text-xs text-muted-foreground">
<PullRequestActorLabel actor={detail.author} className="font-medium" />
<span>updated {formatRelativeTimeLabel(detail.updatedAt)}</span>
@@ -1111,6 +1567,14 @@ export function PullRequestDetailPanel({
>
{detail.baseBranch}
</code>
+ {freshness ? (
+ <PullRequestBaseFreshnessWarning
+ baseBranch={detail.baseBranch}
+ freshness={freshness}
+ pending={actionPending}
+ onUpdate={(method) => void perform("update-branch", undefined, method)}
+ />
+ ) : null}
<ArrowLeftIcon aria-label="receives changes from" className="size-4 shrink-0" />
<button
type="button"
@@ -1170,7 +1634,7 @@ export function PullRequestDetailPanel({
disabled={handoff !== null}
onClick={startResolveConflicts}
>
- {handoff === "conflicts" ? "Preparing..." : "Resolve in a new thread"}
+ {handoff === "conflicts" ? "Preparing..." : handoffLabels.resolve}
<ArrowUpRightIcon className="size-3.5 text-destructive" />
</Button>
</div>
@@ -1178,7 +1642,7 @@ export function PullRequestDetailPanel({
{detail ? (
<nav
- className="col-span-2 flex min-w-0 items-center gap-1 overflow-x-auto border-t border-border/60 px-4 py-2"
+ className="col-span-2 flex min-w-0 items-center gap-1 overflow-x-auto border-t border-border/60 px-4 py-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
aria-label="Pull request tabs"
>
{visibleTabs.map((item) => (
@@ -1202,7 +1666,13 @@ export function PullRequestDetailPanel({
className="ml-auto inline-flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground"
aria-label={checksSummary ? `Checks: ${checksSummary}` : "Checks"}
>
- <CircleDotIcon aria-hidden className="size-3.5" />
+ {/* The rollup icon opens the checks behind the summary; with none reported
+ there is nothing to open, so the plain glyph stays. */}
+ {detail && checksState !== null ? (
+ <PullRequestChecksPopover checks={detail.checks} checksState={checksState} />
+ ) : (
+ <CircleDotIcon aria-hidden className="size-3.5" />
+ )}
{checksSummary}
</span>
) : tab === "timeline" ? (
@@ -1290,11 +1760,10 @@ export function PullRequestDetailPanel({
// scrollport actually gains is the difference between the two.
const chromeDelta = foldHeight - (condensedRowRef.current?.scrollHeight ?? 0);
if (previous) {
- // The hard top reopens the chrome. The refund puts the reader a fold's height
- // from the top, pinned to the same pixels — the metadata is scrolled up to,
- // not thrown at them.
+ // The hard top reopens the chrome with no refund: the reader asked for the top,
+ // and moving them a fold's height back down would snatch it away — the fold
+ // slides in above while the content stays where they left it.
if (top < 4 && foldHeight > 0) {
- compensationRef.current = chromeDelta;
next = false;
}
} else if (foldHeight > 0 && top > foldHeight + 32) {
@@ -1329,6 +1798,8 @@ export function PullRequestDetailPanel({
activityPending={activityPending}
activityError={activityError}
pendingFinding={handoff}
+ fixFindingLabel={handoffLabels.fixFinding}
+ fixCheckLabel={handoffLabels.fixCheck}
onFixFinding={startFixFinding}
onRefresh={refreshDetail}
/>
@@ -1346,8 +1817,11 @@ export function PullRequestDetailPanel({
) : (
<PullRequestTimelineTab
detail={detail}
+ environmentId={environmentId}
+ reference={reference}
order={timelineOrder}
onOpenCommit={openCommit}
+ onRefresh={refreshDetail}
/>
)}
</div>
@@ -1363,6 +1837,7 @@ export function PullRequestDetailPanel({
selectedCommitOid={selectedCodeCommitOid}
onSelectedCommitChange={selectCodeCommit}
pendingFinding={handoff}
+ fixFindingLabel={handoffLabels.fixFinding}
onFixFinding={startFixFinding}
onRefresh={refreshDetail}
refreshToken={refreshToken}
@@ -1381,12 +1856,21 @@ export function PullRequestDetailPanel({
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>
- {confirmAction === "merge" ? "Merge pull request?" : "Close pull request?"}
+ {confirmAction === "merge"
+ ? "Merge pull request?"
+ : confirmAction === "enable-auto-merge"
+ ? "Enable auto-merge?"
+ : "Close pull request?"}
</AlertDialogTitle>
<AlertDialogDescription>
{confirmAction === "merge"
? `This merges #${reference.number} using ${selectedMergeMethod}.`
- : `This closes #${reference.number} without merging it.`}
+ : confirmAction === "enable-auto-merge"
+ ? // The host merges this as soon as it considers the pull request ready, which
+ // may be immediately — there is no telling from here whether anything is
+ // still outstanding.
+ `This merges #${reference.number} using ${selectedMergeMethod} as soon as the host considers it ready, which may be immediately.`
+ : `This closes #${reference.number} without merging it.`}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
@@ -1401,10 +1885,16 @@ export function PullRequestDetailPanel({
const action = confirmAction;
setConfirmAction(null);
if (action === "merge") void perform("merge", selectedMergeMethod);
+ if (action === "enable-auto-merge")
+ void perform("enable-auto-merge", selectedMergeMethod);
if (action === "close") void perform("close");
}}
>
- {confirmAction === "merge" ? "Merge" : "Close"}
+ {confirmAction === "merge"
+ ? "Merge"
+ : confirmAction === "enable-auto-merge"
+ ? "Enable auto-merge"
+ : "Close"}
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
diff --git a/apps/web/src/components/pullRequest/PullRequestListFilters.test.tsx b/apps/web/src/components/pullRequest/PullRequestListFilters.test.tsx
index 545e3066f..f8224f70a 100644
--- a/apps/web/src/components/pullRequest/PullRequestListFilters.test.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestListFilters.test.tsx
@@ -1,4 +1,4 @@
-import type { ProjectId } from "@t3tools/contracts";
+import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { CircleIcon } from "lucide-react";
import { Children, isValidElement, type ReactElement, type ReactNode } from "react";
import { describe, expect, it, vi } from "vite-plus/test";
@@ -53,12 +53,17 @@ function menu(overrides: Partial<Parameters<typeof PullRequestFiltersMenu>[0]>)
involvement: "all",
involvementOptions: [{ value: "all", label: "All", Icon: CircleIcon }],
onInvolvement: () => undefined,
+ filters: {},
+ onFilters: () => undefined,
host: undefined,
hostOptions: [],
onHost: () => undefined,
- environmentId: null,
+ server: undefined,
+ serverOptions: [],
+ onServer: () => undefined,
projects: [],
projectId: undefined,
+ projectEnvironmentId: undefined,
unavailable: new Map(),
onProject: () => undefined,
...overrides,
@@ -79,21 +84,82 @@ describe("pull request filters menu", () => {
expect(onState).toHaveBeenCalledWith("closed");
});
+ it("names the chosen narrowing and leaves the others alone", () => {
+ const onFilters = vi.fn();
+ const group = findValueChange(
+ findLabeledGroup(menu({ filters: { review: "approved" }, onFilters }), "Draft"),
+ );
+ expect(group).toBeDefined();
+
+ group?.props.onValueChange("hide");
+ expect(onFilters).toHaveBeenCalledWith({ review: "approved", draft: "hide" });
+ });
+
+ it("drops a narrowing chosen back to all rather than sending it as undefined", () => {
+ const onFilters = vi.fn();
+ const group = findValueChange(
+ findLabeledGroup(
+ menu({ filters: { review: "none", checks: "failing" }, onFilters }),
+ "Review",
+ ),
+ );
+ expect(group).toBeDefined();
+
+ group?.props.onValueChange("all");
+ expect(onFilters).toHaveBeenCalledWith({ checks: "failing" });
+ });
+
it("does not emit a change when the selected project is chosen again", () => {
const projectId = "project-1" as ProjectId;
+ const environmentId = "env-1" as EnvironmentId;
const onProject = vi.fn();
const view = menu({
- projects: [{ id: projectId, title: "T3 Code", workspaceRoot: "/work/t3code" }],
+ projects: [
+ {
+ id: projectId,
+ environmentId,
+ title: "T3 Code",
+ workspaceRoot: "/work/t3code",
+ },
+ ],
projectId,
+ projectEnvironmentId: environmentId,
onProject,
});
const radioGroup = findValueChange(view);
expect(radioGroup).toBeDefined();
- radioGroup?.props.onValueChange(projectId);
+ radioGroup?.props.onValueChange(`${environmentId} ${projectId}`);
expect(onProject).not.toHaveBeenCalled();
radioGroup?.props.onValueChange("all");
- expect(onProject).toHaveBeenCalledWith(undefined);
+ expect(onProject).toHaveBeenCalledWith(undefined, undefined);
+ });
+
+ it("passes the environment along so a duplicate project id on another server is told apart", () => {
+ const projectId = "project-1" as ProjectId;
+ const onProject = vi.fn();
+ const view = menu({
+ projects: [
+ {
+ id: projectId,
+ environmentId: "env-1" as EnvironmentId,
+ title: "T3 Code · one",
+ workspaceRoot: "/work/t3code-1",
+ },
+ {
+ id: projectId,
+ environmentId: "env-2" as EnvironmentId,
+ title: "T3 Code · two",
+ workspaceRoot: "/work/t3code-2",
+ },
+ ],
+ onProject,
+ });
+ const radioGroup = findValueChange(view);
+ expect(radioGroup).toBeDefined();
+
+ radioGroup?.props.onValueChange(`env-2 ${projectId}`);
+ expect(onProject).toHaveBeenCalledWith(projectId, "env-2");
});
});
diff --git a/apps/web/src/components/pullRequest/PullRequestListFilters.tsx b/apps/web/src/components/pullRequest/PullRequestListFilters.tsx
index cb95a5be3..71d7c6570 100644
--- a/apps/web/src/components/pullRequest/PullRequestListFilters.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestListFilters.tsx
@@ -2,10 +2,23 @@ import type {
EnvironmentId,
ProjectId,
PullRequestInvolvement,
+ PullRequestListFilters,
PullRequestListState,
SourceControlProviderKind,
} from "@t3tools/contracts";
-import { FolderGit2Icon, LayersIcon, ListFilterIcon, LoaderIcon, SearchIcon } from "lucide-react";
+import {
+ CircleCheckIcon,
+ CircleDashedIcon,
+ CircleSlashIcon,
+ CircleXIcon,
+ EyeOffIcon,
+ FolderGit2Icon,
+ GitPullRequestDraftIcon,
+ LayersIcon,
+ ListFilterIcon,
+ LoaderIcon,
+ SearchIcon,
+} from "lucide-react";
import type { ElementType } from "react";
import { cn } from "~/lib/utils";
@@ -82,7 +95,7 @@ export function PullRequestSearchInput({
type="text"
value={value}
onChange={(event) => onChange(event.currentTarget.value)}
- placeholder="Search pull requests"
+ placeholder="Search pull requests, or label:bug"
aria-label="Search pull requests"
// Tracks the shared input's height at both widths, so it stays level with the icon
// button beside it rather than towering over it on wide screens.
@@ -101,6 +114,38 @@ export function PullRequestSearchInput({
const ALL_PROJECTS_VALUE = "all";
/** MenuRadioGroup wants a string, so "every host" wears the one value no host can be. */
const ALL_HOSTS_VALUE = "";
+/** The same trick for the servers, which are named by an id no empty string can collide with. */
+const ALL_SERVERS_VALUE = "";
+/** The unset value of each narrowing group, which no filter of theirs is named after. */
+const UNFILTERED_VALUE = "all";
+/**
+ * A project's own radio value, carrying the server along with the id: the id alone is only
+ * unique within its own server, so two rows sharing one would otherwise both read as checked.
+ */
+const projectMenuValue = (project: {
+ readonly id: ProjectId;
+ readonly environmentId: EnvironmentId;
+}) => `${project.environmentId} ${project.id}`;
+
+const DRAFT_OPTIONS = [
+ { value: UNFILTERED_VALUE, label: "All", Icon: LayersIcon },
+ { value: "only", label: "Drafts only", Icon: GitPullRequestDraftIcon },
+ { value: "hide", label: "Hide drafts", Icon: EyeOffIcon },
+] as const satisfies ReadonlyArray<PullRequestFilterOption<string>>;
+
+const REVIEW_OPTIONS = [
+ { value: UNFILTERED_VALUE, label: "All", Icon: LayersIcon },
+ { value: "approved", label: "Approved", Icon: CircleCheckIcon },
+ { value: "changes-requested", label: "Changes requested", Icon: CircleXIcon },
+ { value: "review-required", label: "Review required", Icon: CircleDashedIcon },
+ { value: "none", label: "No reviews", Icon: CircleSlashIcon },
+] as const satisfies ReadonlyArray<PullRequestFilterOption<string>>;
+
+const CHECKS_OPTIONS = [
+ { value: UNFILTERED_VALUE, label: "All", Icon: LayersIcon },
+ { value: "passing", label: "Passing", Icon: CircleCheckIcon },
+ { value: "failing", label: "Failing", Icon: CircleXIcon },
+] as const satisfies ReadonlyArray<PullRequestFilterOption<string>>;
function PullRequestFilterRadioGroup<Value extends string>({
label,
@@ -147,12 +192,17 @@ export function PullRequestFiltersMenu({
involvement,
involvementOptions,
onInvolvement,
+ filters,
+ onFilters,
host,
hostOptions,
onHost,
- environmentId,
+ server,
+ serverOptions,
+ onServer,
projects,
projectId,
+ projectEnvironmentId,
unavailable,
onProject,
}: {
@@ -162,6 +212,9 @@ export function PullRequestFiltersMenu({
involvement: PullRequestInvolvement;
involvementOptions: ReadonlyArray<PullRequestFilterOption<PullRequestInvolvement>>;
onInvolvement: (involvement: PullRequestInvolvement) => void;
+ /** The narrowings beyond state and involvement; an absent field is that group unfiltered. */
+ filters: PullRequestListFilters;
+ onFilters: (filters: PullRequestListFilters) => void;
host: string | undefined;
/**
* Includes the "all hosts" entry, whose value is the empty string. With fewer than two real
@@ -169,24 +222,52 @@ export function PullRequestFiltersMenu({
*/
hostOptions: ReadonlyArray<PullRequestFilterOption<string>>;
onHost: (host: string | undefined) => void;
- /** Where the projects' own favicons are read from; null before the environment is known. */
- environmentId: EnvironmentId | null;
+ server: EnvironmentId | undefined;
+ /**
+ * Includes the "all servers" entry, whose value is the empty string. With one server there is
+ * nothing to switch between, so the whole group stays out of the menu.
+ */
+ serverOptions: ReadonlyArray<PullRequestFilterOption<string>>;
+ onServer: (server: EnvironmentId | undefined) => void;
+ /** The projects of every connected environment, each carrying the one its favicon is read from. */
projects: ReadonlyArray<{
readonly id: ProjectId;
+ readonly environmentId: EnvironmentId;
readonly title: string;
readonly workspaceRoot: string;
}>;
projectId: ProjectId | undefined;
+ /**
+ * The server the selected project belongs to. A project id is only unique within its own
+ * server, so without this two rows sharing an id would both read as checked here.
+ */
+ projectEnvironmentId: EnvironmentId | undefined;
/**
* Projects whose repository could not be read this time round. They are named here, where
* the reader is already choosing between projects, rather than as a count above the list
* that says something is missing without saying which.
*/
unavailable: ReadonlyMap<ProjectId, string>;
- onProject: (projectId: ProjectId | undefined) => void;
+ /** The environment comes with the project id, since picking a row picks a specific server's copy of it. */
+ onProject: (projectId: ProjectId | undefined, environmentId: EnvironmentId | undefined) => void;
}) {
const filtered =
- state !== "open" || involvement !== "all" || host !== undefined || projectId !== undefined;
+ state !== "open" ||
+ involvement !== "all" ||
+ host !== undefined ||
+ server !== undefined ||
+ projectId !== undefined ||
+ Object.keys(filters).length > 0;
+ /**
+ * Rebuilt rather than spread so an unfiltered group leaves the record instead of lingering in
+ * it as an explicit `undefined`, which the listing input does not accept.
+ */
+ const withFilter = (key: keyof PullRequestListFilters, value: string): PullRequestListFilters =>
+ Object.fromEntries(
+ Object.entries({ ...filters, [key]: value === UNFILTERED_VALUE ? undefined : value }).filter(
+ ([, held]) => held !== undefined,
+ ),
+ ) as PullRequestListFilters;
return (
<Menu>
<MenuTrigger
@@ -219,6 +300,27 @@ export function PullRequestFiltersMenu({
options={involvementOptions}
onChange={onInvolvement}
/>
+ <MenuSeparator />
+ <PullRequestFilterRadioGroup
+ label="Draft"
+ value={filters.draft ?? UNFILTERED_VALUE}
+ options={DRAFT_OPTIONS}
+ onChange={(next) => onFilters(withFilter("draft", next))}
+ />
+ <MenuSeparator />
+ <PullRequestFilterRadioGroup
+ label="Review"
+ value={filters.review ?? UNFILTERED_VALUE}
+ options={REVIEW_OPTIONS}
+ onChange={(next) => onFilters(withFilter("review", next))}
+ />
+ <MenuSeparator />
+ <PullRequestFilterRadioGroup
+ label="Checks"
+ value={filters.checks ?? UNFILTERED_VALUE}
+ options={CHECKS_OPTIONS}
+ onChange={(next) => onFilters(withFilter("checks", next))}
+ />
{hostOptions.length > 2 ? (
<>
<MenuSeparator />
@@ -230,12 +332,40 @@ export function PullRequestFiltersMenu({
/>
</>
) : null}
+ {serverOptions.length > 2 ? (
+ <>
+ <MenuSeparator />
+ <PullRequestFilterRadioGroup
+ label="Server"
+ value={server ?? ALL_SERVERS_VALUE}
+ options={serverOptions}
+ onChange={(next) =>
+ onServer(next === ALL_SERVERS_VALUE ? undefined : (next as EnvironmentId))
+ }
+ />
+ </>
+ ) : null}
<MenuSeparator />
<MenuRadioGroup
- value={projectId ?? ALL_PROJECTS_VALUE}
+ value={
+ projectId === undefined || projectEnvironmentId === undefined
+ ? ALL_PROJECTS_VALUE
+ : projectMenuValue({ id: projectId, environmentId: projectEnvironmentId })
+ }
onValueChange={(next) => {
- const nextProjectId = next === ALL_PROJECTS_VALUE ? undefined : (next as ProjectId);
- if (nextProjectId !== projectId) onProject(nextProjectId);
+ if (next === ALL_PROJECTS_VALUE) {
+ if (projectId !== undefined) onProject(undefined, undefined);
+ return;
+ }
+ // The value carries both halves, since the id alone cannot tell two servers' rows
+ // apart once they share one.
+ const project = projects.find((candidate) => projectMenuValue(candidate) === next);
+ if (
+ project !== undefined &&
+ (project.id !== projectId || project.environmentId !== projectEnvironmentId)
+ ) {
+ onProject(project.id, project.environmentId);
+ }
}}
>
<MenuGroupLabel>Project</MenuGroupLabel>
@@ -255,22 +385,18 @@ export function PullRequestFiltersMenu({
const reason = unavailable.get(project.id);
return (
<MenuRadioItem
- key={project.id}
- value={project.id}
+ key={projectMenuValue(project)}
+ value={projectMenuValue(project)}
disabled={reason !== undefined}
title={reason}
>
<span className="flex min-w-0 flex-1 items-center gap-2">
- {environmentId === null ? (
- <FolderGit2Icon aria-hidden className="size-3.5 shrink-0" />
- ) : (
- <ProjectFavicon
- environmentId={environmentId}
- cwd={project.workspaceRoot}
- fallbackIcon={FolderGit2Icon}
- className="size-3.5 shrink-0"
- />
- )}
+ <ProjectFavicon
+ environmentId={project.environmentId}
+ cwd={project.workspaceRoot}
+ fallbackIcon={FolderGit2Icon}
+ className="size-3.5 shrink-0"
+ />
<span className="min-w-0 flex-1 truncate">{project.title}</span>
{reason === undefined ? null : (
<span className="shrink-0 rounded-full border border-amber-500/40 bg-amber-500/10 px-1.5 py-px text-[10px] font-medium text-amber-600 dark:text-amber-400/90">
diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx
new file mode 100644
index 000000000..f0145c059
--- /dev/null
+++ b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx
@@ -0,0 +1,113 @@
+import { useState } from "react";
+
+import { cn } from "~/lib/utils";
+
+import { Button } from "../ui/button";
+import { Textarea } from "../ui/textarea";
+import { PullRequestMarkdown } from "./PullRequestMarkdown";
+
+/**
+ * The box a body is rewritten in — a description, or a remark already posted. It owns the draft
+ * and nothing else: the caller sends the request and says whether it is still in flight, so the
+ * same box serves every mutation without knowing which one it is.
+ *
+ * Preview renders through the same component the saved body will be read through, which is the
+ * only way to see what a host's markdown will actually become before it is sent.
+ */
+export function PullRequestMarkdownEditor({
+ value,
+ cwd,
+ placeholder,
+ label,
+ saving,
+ allowEmpty = false,
+ className,
+ onSave,
+ onCancel,
+}: {
+ readonly value: string;
+ readonly cwd: string;
+ readonly placeholder?: string | undefined;
+ readonly label: string;
+ readonly saving: boolean;
+ /** A description may be cleared, which is how one is removed; a remark may not be emptied. */
+ readonly allowEmpty?: boolean;
+ readonly className?: string | undefined;
+ readonly onSave: (next: string) => void;
+ readonly onCancel: () => void;
+}) {
+ const [draft, setDraft] = useState(value);
+ const [preview, setPreview] = useState(false);
+ // The words this draft started from. React keeps a component instance wherever the same
+ // position and key come round again, so an editor opened on one remark can be handed another's
+ // words without being rebuilt — and saving would then write the first remark's text onto the
+ // second. Different words mean a different subject, and the draft starts again from them.
+ const [seed, setSeed] = useState(value);
+ if (seed !== value) {
+ setSeed(value);
+ setDraft(value);
+ }
+ const empty = draft.trim().length === 0;
+
+ return (
+ <div
+ className={cn("space-y-2", className)}
+ onKeyDown={(event) => {
+ if (event.key !== "Escape" || saving) return;
+ event.preventDefault();
+ onCancel();
+ }}
+ >
+ <div className="flex items-center gap-1">
+ <Button
+ size="xs"
+ variant={preview ? "ghost" : "outline"}
+ disabled={saving}
+ onClick={() => setPreview(false)}
+ >
+ Write
+ </Button>
+ <Button
+ size="xs"
+ variant={preview ? "outline" : "ghost"}
+ disabled={saving}
+ onClick={() => setPreview(true)}
+ >
+ Preview
+ </Button>
+ </div>
+ {preview ? (
+ <div className="rounded-lg border border-border/60 px-3 py-2">
+ {empty ? (
+ <p className="text-xs text-muted-foreground">Nothing to preview.</p>
+ ) : (
+ <PullRequestMarkdown text={draft} cwd={cwd} />
+ )}
+ </div>
+ ) : (
+ <Textarea
+ autoFocus
+ disabled={saving}
+ value={draft}
+ rows={6}
+ placeholder={placeholder}
+ aria-label={label}
+ onChange={(event) => setDraft(event.target.value)}
+ />
+ )}
+ <div className="flex justify-end gap-2">
+ <Button size="xs" variant="ghost" disabled={saving} onClick={onCancel}>
+ Cancel
+ </Button>
+ <Button
+ size="xs"
+ variant="outline"
+ disabled={saving || (empty && !allowEmpty)}
+ onClick={() => onSave(draft)}
+ >
+ {saving ? "Saving..." : "Save"}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/pullRequest/PullRequestReactions.tsx b/apps/web/src/components/pullRequest/PullRequestReactions.tsx
new file mode 100644
index 000000000..2ef90b09a
--- /dev/null
+++ b/apps/web/src/components/pullRequest/PullRequestReactions.tsx
@@ -0,0 +1,178 @@
+import type {
+ EnvironmentId,
+ PullRequestReaction,
+ PullRequestReactionContent,
+ PullRequestRef,
+} from "@t3tools/contracts";
+import { SmilePlusIcon } from "lucide-react";
+import { useState } from "react";
+
+import { cn } from "~/lib/utils";
+import { pullRequestEnvironment } from "~/state/pullRequests";
+import { useAtomCommand } from "~/state/use-atom-command";
+
+import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
+import { toastManager } from "../ui/toast";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import {
+ applyPendingPullRequestReactions,
+ PULL_REQUEST_REACTION_ORDER,
+ pullRequestReactionEmoji,
+ pullRequestReactionName,
+ pullRequestReactionTooltip,
+} from "./pullRequestReactions.logic";
+
+const PILL_CLASS =
+ "inline-flex h-6 shrink-0 items-center gap-1 rounded-full border px-2 text-xs outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring";
+
+const EMPTY_PENDING: ReadonlyMap<PullRequestReactionContent, boolean> = new Map();
+
+/** What the host last said, so a press in flight is forgotten the moment the real counts land. */
+function reactionsSignature(reactions: ReadonlyArray<PullRequestReaction>): string {
+ return reactions
+ .map((reaction) => `${reaction.content}:${reaction.count}:${reaction.viewerHasReacted ? 1 : 0}`)
+ .join(" ");
+}
+
+/**
+ * The reaction pills under a remark, and the picker that adds one. The same bar serves the
+ * description, a conversation comment and a review thread's comments: what differs between them
+ * is only which subject the host is told about.
+ *
+ * The add button is revealed by hovering the remark it belongs to, the way GitHub's is, so the
+ * parent must carry `group`. It stays put once there is something to press it beside, while the
+ * picker is open, and whenever it is focused — a control only a mouse can find is no control.
+ */
+export function PullRequestReactionBar({
+ reactions,
+ canReact,
+ subjectId,
+ environmentId,
+ reference,
+ onRefresh,
+ className,
+}: {
+ readonly reactions: ReadonlyArray<PullRequestReaction>;
+ readonly canReact: boolean;
+ /** Absent reacts to the change request itself, which is where its description's reactions live. */
+ readonly subjectId?: string | undefined;
+ readonly environmentId: EnvironmentId;
+ readonly reference: PullRequestRef;
+ readonly onRefresh: () => void;
+ readonly className?: string | undefined;
+}) {
+ const [pickerOpen, setPickerOpen] = useState(false);
+ const [pending, setPending] = useState<{
+ readonly signature: string;
+ readonly values: ReadonlyMap<PullRequestReactionContent, boolean>;
+ }>({ signature: "", values: EMPTY_PENDING });
+ const setReaction = useAtomCommand(pullRequestEnvironment.setReaction, { reportFailure: false });
+
+ const signature = reactionsSignature(reactions);
+ const values = pending.signature === signature ? pending.values : EMPTY_PENDING;
+ const shown = applyPendingPullRequestReactions(reactions, values);
+
+ const toggle = async (content: PullRequestReactionContent, reacted: boolean) => {
+ setPending({ signature, values: new Map([...values, [content, reacted]]) });
+ const result = await setReaction({
+ environmentId,
+ input: {
+ ...reference,
+ ...(subjectId === undefined ? {} : { subjectId }),
+ content,
+ reacted,
+ },
+ });
+ if (result._tag === "Failure") {
+ setPending((current) => {
+ const next = new Map(current.values);
+ next.delete(content);
+ return { signature: current.signature, values: next };
+ });
+ toastManager.add({ type: "error", title: "The reaction could not be saved" });
+ return;
+ }
+ onRefresh();
+ };
+
+ if (shown.length === 0 && !canReact) return null;
+
+ return (
+ <div className={cn("flex flex-wrap items-center gap-1", className)}>
+ {shown.map((reaction) => (
+ <Tooltip key={reaction.content}>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ aria-pressed={reaction.viewerHasReacted}
+ aria-label={`${pullRequestReactionName(reaction.content)}, ${reaction.count}`}
+ disabled={!canReact}
+ className={cn(
+ PILL_CLASS,
+ reaction.viewerHasReacted
+ ? "border-primary/60 bg-primary/10 text-foreground"
+ : "border-border/70 bg-muted/40 text-muted-foreground",
+ canReact ? "hover:border-primary/60" : "cursor-default",
+ )}
+ onClick={() => void toggle(reaction.content, !reaction.viewerHasReacted)}
+ />
+ }
+ >
+ <span aria-hidden>{pullRequestReactionEmoji(reaction.content)}</span>
+ <span className="tabular-nums">{reaction.count}</span>
+ </TooltipTrigger>
+ <TooltipPopup side="top">{pullRequestReactionTooltip(reaction)}</TooltipPopup>
+ </Tooltip>
+ ))}
+
+ {canReact ? (
+ <Popover open={pickerOpen} onOpenChange={setPickerOpen}>
+ <PopoverTrigger
+ render={
+ <button
+ type="button"
+ aria-label="Add a reaction"
+ className={cn(
+ PILL_CLASS,
+ "border-border/70 px-1.5 text-muted-foreground hover:border-primary/60 hover:text-foreground",
+ shown.length === 0 &&
+ !pickerOpen &&
+ "opacity-0 group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100",
+ )}
+ />
+ }
+ >
+ <SmilePlusIcon aria-hidden className="size-3.5" />
+ </PopoverTrigger>
+ <PopoverPopup align="start" className="w-auto" side="top" viewportClassName="py-2">
+ <div className="flex items-center gap-0.5">
+ {PULL_REQUEST_REACTION_ORDER.map((content) => {
+ const reacted =
+ shown.find((reaction) => reaction.content === content)?.viewerHasReacted ?? false;
+ return (
+ <button
+ key={content}
+ type="button"
+ aria-pressed={reacted}
+ aria-label={pullRequestReactionName(content)}
+ className={cn(
+ "flex size-7 items-center justify-center rounded-md text-base outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",
+ reacted && "bg-primary/10",
+ )}
+ onClick={() => {
+ setPickerOpen(false);
+ void toggle(content, !reacted);
+ }}
+ >
+ <span aria-hidden>{pullRequestReactionEmoji(content)}</span>
+ </button>
+ );
+ })}
+ </div>
+ </PopoverPopup>
+ </Popover>
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx
index 03fc512d8..47f59240a 100644
--- a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx
@@ -2,12 +2,18 @@
* Pull-request-specific annotations: conversations already on the host and comments queued for
* the review being written. New comment composition uses the shared diff annotation.
*/
-import type { PullRequestReviewThread } from "@t3tools/contracts";
+import type {
+ EnvironmentId,
+ PullRequestRef,
+ PullRequestReviewThread,
+ PullRequestThreadComment,
+} from "@t3tools/contracts";
import {
CheckCircle2Icon,
CircleIcon,
HammerIcon,
MessageSquareIcon,
+ PencilIcon,
Trash2Icon,
} from "lucide-react";
import { useRef, useState } from "react";
@@ -20,6 +26,8 @@ import { Textarea } from "../ui/textarea";
import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
import { PullRequestActorLabel } from "./pullRequestPresentation";
import { PullRequestMarkdown } from "./PullRequestMarkdown";
+import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
+import { PullRequestReactionBar } from "./PullRequestReactions";
import type { PendingReviewComment } from "./pullRequestReviewStore";
const CARD_CLASS =
@@ -82,31 +90,57 @@ export function ReviewThreadCard({
workspaceRoot,
canReply,
canResolve,
+ canReact,
+ environmentId,
+ reference,
pending,
fixPending,
+ fixLabel = "Fix in a thread",
onFix,
onReply,
+ canEditComment,
+ onEditComment,
onToggleResolved,
+ onReacted,
}: {
thread: PullRequestReviewThread;
workspaceRoot: string;
canReply: boolean;
canResolve: boolean;
+ canReact: boolean;
+ environmentId: EnvironmentId;
+ reference: PullRequestRef;
pending: boolean;
/** True while this thread's own hand-off is preparing, so only its button says so. */
fixPending?: boolean;
+ fixLabel?: string;
/** Absent where a thread is shown outside the pull request page's reach. */
onFix?: () => void;
/** Resolves to whether the host took it, so a reply that failed keeps the words it was given. */
onReply: (body: string) => Promise<boolean>;
+ /** Whether this reader wrote this remark, which is what rewriting one takes. */
+ canEditComment: (comment: PullRequestThreadComment) => boolean;
+ /** Resolves to whether the host took it, like `onReply`. */
+ onEditComment: (commentId: string, body: string) => Promise<boolean>;
onToggleResolved: () => void;
+ onReacted: () => void;
}) {
// A resolved thread is finished work, so it opens collapsed and stays one line until asked for.
const [expanded, setExpanded] = useState(!thread.isResolved);
const [replying, setReplying] = useState(false);
const [reply, setReply] = useState("");
+ const [editingId, setEditingId] = useState<string | null>(null);
+ const [savingEdit, setSavingEdit] = useState(false);
const sendingRef = useRef(false);
+ const saveEdit = async (commentId: string, body: string) => {
+ if (savingEdit) return;
+ setSavingEdit(true);
+ const saved = await onEditComment(commentId, body);
+ setSavingEdit(false);
+ if (saved) setEditingId(null);
+ };
+
const send = async () => {
const trimmed = reply.trim();
if (trimmed.length === 0 || pending || sendingRef.current) return;
@@ -154,7 +188,7 @@ export function ReviewThreadCard({
onClick={onFix}
>
<HammerIcon className="size-3" />
- {fixPending ? "Preparing..." : "Fix in a thread"}
+ {fixPending ? "Preparing..." : fixLabel}
</Button>
) : null}
{canResolve ? (
@@ -174,15 +208,49 @@ export function ReviewThreadCard({
<>
<div className="mt-2 space-y-3">
{thread.comments.map((comment) => (
- <article key={comment.id} className="min-w-0">
+ <article key={comment.id} className="group min-w-0">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<PullRequestActorLabel actor={comment.author} className="text-foreground" />
<span>{formatRelativeTimeLabel(comment.createdAt)}</span>
</div>
- <PullRequestMarkdown
- className="mt-1 text-sm"
- text={comment.body}
- cwd={workspaceRoot}
+ {editingId === comment.id ? (
+ <PullRequestMarkdownEditor
+ className="mt-1"
+ value={comment.body}
+ cwd={workspaceRoot}
+ label="Edit comment"
+ saving={savingEdit}
+ onSave={(body) => void saveEdit(comment.id, body)}
+ onCancel={() => setEditingId(null)}
+ />
+ ) : (
+ <div className="mt-1 flex items-start gap-1">
+ <PullRequestMarkdown
+ className="min-w-0 flex-1 text-sm"
+ text={comment.body}
+ cwd={workspaceRoot}
+ />
+ {canEditComment(comment) ? (
+ <Button
+ size="icon-xs"
+ variant="ghost"
+ className="shrink-0 text-muted-foreground opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100"
+ aria-label="Edit comment"
+ onClick={() => setEditingId(comment.id)}
+ >
+ <PencilIcon className="size-3" />
+ </Button>
+ ) : null}
+ </div>
+ )}
+ <PullRequestReactionBar
+ className="mt-1.5"
+ reactions={comment.reactions ?? []}
+ canReact={canReact}
+ subjectId={comment.id}
+ environmentId={environmentId}
+ reference={reference}
+ onRefresh={onReacted}
/>
</article>
))}
diff --git a/apps/web/src/components/pullRequest/PullRequestRow.tsx b/apps/web/src/components/pullRequest/PullRequestRow.tsx
index e1ada6efc..06e83f2b0 100644
--- a/apps/web/src/components/pullRequest/PullRequestRow.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestRow.tsx
@@ -1,5 +1,3 @@
-import type { PullRequestListEntry } from "@t3tools/contracts";
-
import { memo } from "react";
import { cn } from "~/lib/utils";
@@ -7,6 +5,9 @@ import { getSourceControlPresentationForKind } from "~/sourceControlPresentation
import { formatRelativeTimeLabel } from "~/timestampFormat";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { PullRequestChecksPopover } from "./PullRequestChecksPopover";
+import type { EnvironmentPullRequestEntry } from "./pullRequestList.logic";
+import { openOnHostLabel, showPullRequestLinkContextMenu } from "./pullRequestLinkContextMenu";
import {
PullRequestActorLabel,
PullRequestDiffStat,
@@ -19,20 +20,23 @@ function PullRequestRowImpl({
selected,
showProjectTitle,
showProvider,
+ environmentLabel,
matchedElsewhere,
onSelect,
}: {
- entry: PullRequestListEntry;
+ entry: EnvironmentPullRequestEntry;
selected: boolean;
showProjectTitle: boolean;
/** Only when the list spans more than one host, where the repository alone is ambiguous. */
showProvider: boolean;
+ /** Names the server this row was read from, where the list spans more than one. */
+ environmentLabel?: string;
/**
* A search found this, but in something the row does not show — a description, a comment, a
* commit message. Saying so is the difference between a result and an apparently random row.
*/
matchedElsewhere?: boolean;
- onSelect: (entry: PullRequestListEntry) => void;
+ onSelect: (entry: EnvironmentPullRequestEntry) => void;
}) {
const { Icon, providerName } = getSourceControlPresentationForKind(entry.provider);
return (
@@ -67,13 +71,52 @@ function PullRequestRowImpl({
<TooltipPopup>{providerName}</TooltipPopup>
</Tooltip>
) : null}
- #{entry.number}
+ {/* The number carries the link, here as much as on the detail: a right-click on it
+ copies the pull request's own address rather than opening the editing menu. */}
+ <span
+ onContextMenu={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ void showPullRequestLinkContextMenu({
+ url: entry.url,
+ openLabel: openOnHostLabel(entry.provider),
+ position: { x: event.clientX, y: event.clientY },
+ });
+ }}
+ >
+ #{entry.number}
+ </span>
</span>
{showProjectTitle ? <span className="truncate">{entry.repository}</span> : null}
+ {environmentLabel ? (
+ <span className="max-w-32 shrink-0 truncate">{environmentLabel}</span>
+ ) : null}
<PullRequestActorLabel actor={entry.author} className="max-w-40 shrink-0" />
- <span className="truncate" title={`${entry.headBranch} to ${entry.baseBranch}`}>
- {entry.headBranch}
- </span>
+ {/* Only a verdict somebody has actually given: "review required" is the absence of
+ one, and saying so on every unreviewed row would say nothing. */}
+ {entry.reviewDecision === "approved" || entry.reviewDecision === "changes-requested" ? (
+ <span
+ className={cn(
+ "shrink-0",
+ entry.reviewDecision === "approved"
+ ? "text-emerald-600/90 dark:text-emerald-400/80"
+ : "text-amber-600/90 dark:text-amber-400/80",
+ )}
+ >
+ {entry.reviewDecision === "approved" ? "Approved" : "Changes requested"}
+ </span>
+ ) : null}
+ {entry.checksState === undefined ? null : (
+ <PullRequestChecksPopover
+ checksState={entry.checksState}
+ environmentId={entry.environmentId}
+ reference={{
+ projectId: entry.projectId,
+ repository: entry.repository,
+ number: entry.number,
+ }}
+ />
+ )}
{matchedElsewhere ? (
<span className="shrink-0 rounded-full border border-border/60 px-1.5 text-[10px]">
matched in the description
diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
index 345753fe8..a57f2a4d1 100644
--- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
@@ -1,13 +1,22 @@
-import type { EnvironmentId, PullRequestDetailView, PullRequestRef } from "@t3tools/contracts";
+import type {
+ EnvironmentId,
+ PullRequestActor,
+ PullRequestComment,
+ PullRequestDetailView,
+ PullRequestRef,
+} from "@t3tools/contracts";
import {
ArrowDownUpIcon,
+ ChevronDownIcon,
ChevronRightIcon,
HammerIcon,
MessageSquareIcon,
+ PencilIcon,
SendIcon,
+ TagIcon,
UsersIcon,
} from "lucide-react";
-import { useState, type ReactNode } from "react";
+import { useRef, useState, type ReactNode } from "react";
import { useAtomCommand } from "~/state/use-atom-command";
import { pullRequestEnvironment } from "~/state/pullRequests";
@@ -21,9 +30,9 @@ import { Textarea } from "../ui/textarea";
import { toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
+ PullRequestActorAvatar,
PullRequestActorLabel,
PullRequestCheckStatusIcon,
- PullRequestMetaLine,
pullRequestCheckStatusLabel,
} from "./pullRequestPresentation";
import { PullRequestReviewerPicker } from "./PullRequestReviewerPicker";
@@ -33,8 +42,149 @@ import {
pullRequestFindingKey,
type PullRequestFinding,
} from "./pullRequestDetail.logic";
+import {
+ canEditPullRequestChangeRequest,
+ canEditPullRequestComment,
+} from "./pullRequestEditing.logic";
import { PullRequestMarkdown } from "./PullRequestMarkdown";
+import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
+import { PullRequestReactionBar } from "./PullRequestReactions";
import { PullRequestConversationGhost } from "./PullRequestGhosts";
+import { sectionCollapseAnchorScrollTop } from "./pullRequestSummaryScroll.logic";
+
+/** A host colour only when it is one, so a malformed value falls back to the neutral dot. */
+function labelDotColor(color: string | null): string | null {
+ const hex = color?.trim().replace(/^#/, "") ?? "";
+ return /^[0-9a-fA-F]{6}$/.test(hex) ? `#${hex}` : null;
+}
+
+/** The avatar carries the attribution alone; who it is arrives on hover, like the reviewer row. */
+function CommentAuthor({ actor }: { actor: PullRequestActor | null }) {
+ const login = actor?.login ?? "ghost";
+ return (
+ <Tooltip>
+ <TooltipTrigger render={<span className="shrink-0 rounded-full" aria-label={login} />}>
+ <PullRequestActorAvatar actor={actor} />
+ </TooltipTrigger>
+ <TooltipPopup side="bottom">
+ {actor?.name && actor.name !== login ? `${actor.name} (@${login})` : login}
+ </TooltipPopup>
+ </Tooltip>
+ );
+}
+
+/** "CHANGES_REQUESTED" reads as "Changes requested": one capital, the host's underscores gone. */
+function reviewStateLabel(state: string): string {
+ const words = state.toLowerCase().replace(/_/g, " ");
+ return words.charAt(0).toUpperCase() + words.slice(1);
+}
+
+/** What every remark in the conversation needs to be rewritten where it sits. */
+interface CommentEditing {
+ readonly cwd: string;
+ readonly canEdit: (comment: PullRequestComment) => boolean;
+ readonly editingId: string | null;
+ readonly saving: boolean;
+ readonly onEdit: (comment: PullRequestComment | null) => void;
+ readonly onSave: (comment: PullRequestComment, body: string) => void;
+}
+
+/**
+ * A remark's words, and the pencil that swaps them for the editor. The pencil is revealed by
+ * hovering the remark, like the reaction bar's own, so the parent must carry `group`.
+ */
+function CommentBody({
+ comment,
+ editing,
+ className,
+}: {
+ comment: PullRequestComment;
+ editing: CommentEditing;
+ className?: string | undefined;
+}) {
+ if (editing.editingId === comment.id) {
+ return (
+ <PullRequestMarkdownEditor
+ className={className}
+ value={comment.body}
+ cwd={editing.cwd}
+ label="Edit comment"
+ saving={editing.saving}
+ onSave={(body) => editing.onSave(comment, body)}
+ onCancel={() => editing.onEdit(null)}
+ />
+ );
+ }
+ return (
+ <div className={cn("flex items-start gap-1", className)}>
+ <PullRequestMarkdown className="min-w-0 flex-1" text={comment.body} cwd={editing.cwd} />
+ {editing.canEdit(comment) ? (
+ <Button
+ size="icon-xs"
+ variant="ghost"
+ className="shrink-0 text-muted-foreground opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100"
+ aria-label="Edit comment"
+ onClick={() => editing.onEdit(comment)}
+ >
+ <PencilIcon className="size-3" />
+ </Button>
+ ) : null}
+ </div>
+ );
+}
+
+/** Finished work — a resolved conversation or a dismissed approval — opens collapsed. */
+function CollapsedComment({
+ comment,
+ editing,
+ label,
+ reactionBar,
+}: {
+ comment: PullRequestComment;
+ editing: CommentEditing;
+ label: string;
+ reactionBar: ReactNode;
+}) {
+ const [open, setOpen] = useState(false);
+ return (
+ <Collapsible open={open} onOpenChange={setOpen}>
+ <article className="group rounded-lg border border-border/60 [contain-intrinsic-block-size:44px] [content-visibility:auto]">
+ <CollapsibleTrigger
+ className={cn(
+ "flex w-full items-center gap-2 p-3 text-left transition-opacity hover:opacity-100",
+ open ? "opacity-100" : "opacity-65",
+ )}
+ >
+ <span className="flex min-w-0 flex-1 items-center gap-2 text-xs text-muted-foreground">
+ <CommentAuthor actor={comment.author} />
+ <span>{formatRelativeTimeLabel(comment.createdAt)}</span>
+ <span>{label}</span>
+ </span>
+ <ChevronDownIcon
+ aria-hidden
+ className={cn(
+ "size-3.5 shrink-0 text-muted-foreground transition-transform",
+ open && "rotate-180",
+ )}
+ />
+ </CollapsibleTrigger>
+ <CollapsiblePanel>
+ {open ? (
+ <div className="px-3 pb-3">
+ {comment.path ? (
+ <p className="truncate text-xs text-muted-foreground" title={comment.path}>
+ {comment.path}
+ </p>
+ ) : null}
+ <CommentBody className="mt-2" comment={comment} editing={editing} />
+ {reactionBar}
+ </div>
+ ) : null}
+ </CollapsiblePanel>
+ </article>
+ </Collapsible>
+ );
+}
function MetaRow({
icon,
@@ -72,9 +222,39 @@ function Section({
children: ReactNode;
}) {
const [open, setOpen] = useState(defaultOpen);
+ const headingRef = useRef<HTMLDivElement>(null);
+ const setOpenWithScrollAnchor = (nextOpen: boolean) => {
+ if (!nextOpen) {
+ const heading = headingRef.current;
+ const section = heading?.closest<HTMLElement>("[data-pull-request-summary-section]");
+ const scroller = heading?.closest<HTMLElement>("[data-pull-request-summary-scroll]");
+ if (heading && section && scroller) {
+ const target = sectionCollapseAnchorScrollTop({
+ scrollTop: scroller.scrollTop,
+ viewportTop: scroller.getBoundingClientRect().top,
+ sectionTop: section.getBoundingClientRect().top,
+ headingTop: heading.getBoundingClientRect().top,
+ });
+ // Synchronous with the press: React commits the collapsed height before the browser
+ // paints, so the reader sees the heading they pressed stay put rather than a jump first.
+ if (target !== null) scroller.scrollTop = target;
+ }
+ }
+ setOpen(nextOpen);
+ };
return (
- <Collapsible open={open} onOpenChange={setOpen}>
- <div className="flex w-full items-center border-t border-border/60 pr-4">
+ <Collapsible
+ open={open}
+ onOpenChange={setOpenWithScrollAnchor}
+ data-pull-request-summary-section
+ >
+ {/* The heading rides the top of the scroll box the way a diff's file header does, so a
+ section can be collapsed from wherever its body has been read to rather than only from
+ where it started. Opaque, because the rows it covers scroll beneath it. */}
+ <div
+ ref={headingRef}
+ className="sticky top-0 z-10 flex w-full items-center border-t border-border/60 bg-background pr-4"
+ >
{/* Title first, chevron riding to its right, count last: the row reads as a heading
with an affordance rather than a tree node. */}
<CollapsibleTrigger className="flex min-w-0 flex-1 items-center gap-1.5 px-4 py-3 text-left text-sm font-medium">
@@ -174,6 +354,8 @@ export function PullRequestSummaryTab({
activityPending,
activityError,
pendingFinding,
+ fixFindingLabel = "Fix in a thread",
+ fixCheckLabel = "Fix",
onFixFinding,
onRefresh,
}: {
@@ -184,6 +366,8 @@ export function PullRequestSummaryTab({
activityError: string | null;
/** The hand-off currently preparing, if any, so only the finding it belongs to says so. */
pendingFinding?: string | null;
+ fixFindingLabel?: string;
+ fixCheckLabel?: string;
onFixFinding?: (finding: PullRequestFinding) => void;
onRefresh: () => void;
}) {
@@ -211,8 +395,66 @@ export function PullRequestSummaryTab({
void readLocalApi()?.shell.openExternal(url);
};
+ const update = useAtomCommand(pullRequestEnvironment.update, { reportFailure: false });
+ const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
+ reportFailure: false,
+ });
+ // Keyed by the pull request, like the comment window above it, so an editor left open never
+ // reappears over the next pull request's description.
+ const [bodyScope, setBodyScope] = useState<string | null>(null);
+ const [bodySaving, setBodySaving] = useState(false);
+ // The remark being rewritten, named with the pull request it belongs to: a comment id is the
+ // host's own, and two hosts — or two pull requests on Azure DevOps, which numbers a remark
+ // inside its thread — hand out the same one. Without the pull request beside it, opening a
+ // different one would leave its like-numbered remark sitting open in an editor.
+ const [commentScope, setCommentScope] = useState<{
+ readonly pullRequest: string;
+ readonly commentId: string;
+ } | null>(null);
+ const [commentSaving, setCommentSaving] = useState(false);
+ const editingCommentId = commentScope?.pullRequest === detail.url ? commentScope.commentId : null;
+
+ const saveBody = async (body: string) => {
+ if (bodySaving) return;
+ setBodySaving(true);
+ const result = await update({ environmentId, input: { ...reference, body } });
+ setBodySaving(false);
+ if (result._tag === "Failure") {
+ toastManager.add({ type: "error", title: "Could not save the description" });
+ return;
+ }
+ setBodyScope(null);
+ onRefresh();
+ };
+
+ const commentEditing: CommentEditing = {
+ cwd: detail.workspaceRoot,
+ canEdit: (comment) => canEditPullRequestComment(detail, comment),
+ editingId: editingCommentId,
+ saving: commentSaving,
+ onEdit: (comment) =>
+ setCommentScope(comment === null ? null : { pullRequest: detail.url, commentId: comment.id }),
+ onSave: async (comment, body) => {
+ // A review's own summary is not a kind any host rewrites, which is why no pencil is ever
+ // offered on one; the check is here because the comment's own type still allows it.
+ if (commentSaving || comment.kind === "review") return;
+ setCommentSaving(true);
+ const result = await updateComment({
+ environmentId,
+ input: { ...reference, commentId: comment.id, kind: comment.kind, body },
+ });
+ setCommentSaving(false);
+ if (result._tag === "Failure") {
+ toastManager.add({ type: "error", title: "Could not save the comment" });
+ return;
+ }
+ setCommentScope(null);
+ onRefresh();
+ },
+ };
+
return (
- <div className="h-full overflow-y-auto">
+ <div className="h-full overflow-y-auto" data-pull-request-summary-scroll>
<section className="px-4 py-3">
<div>
<MetaRow icon={<UsersIcon className="size-3.5" />} label="Reviewers">
@@ -261,6 +503,28 @@ export function PullRequestSummaryTab({
) : null}
</span>
</MetaRow>
+ {detail.labels.length > 0 ? (
+ <MetaRow icon={<TagIcon className="size-3.5" />} label="Labels">
+ <span className="flex min-w-0 flex-wrap items-center gap-1">
+ {detail.labels.map((label) => {
+ const dot = labelDotColor(label.color);
+ return (
+ <span
+ key={label.name}
+ className="inline-flex max-w-48 items-center gap-1.5 rounded-full border border-border/70 bg-muted/40 py-0.5 pl-1.5 pr-2 text-xs"
+ >
+ <span
+ aria-hidden
+ className="size-2 shrink-0 rounded-full bg-muted-foreground"
+ {...(dot ? { style: { backgroundColor: dot } } : {})}
+ />
+ <span className="truncate">{label.name}</span>
+ </span>
+ );
+ })}
+ </span>
+ </MetaRow>
+ ) : null}
<MetaRow icon={<MessageSquareIcon className="size-3.5" />} label="Comments">
{activityPending
? "Loading conversation…"
@@ -274,10 +538,48 @@ export function PullRequestSummaryTab({
</section>
<Section title="Description">
- <PullRequestMarkdown
- text={detail.body.trim().length > 0 ? detail.body : "_No description provided._"}
- cwd={detail.workspaceRoot}
- />
+ <div className="group">
+ {bodyScope === detail.url ? (
+ <PullRequestMarkdownEditor
+ // Empty is a real answer here: saving nothing is how a description is cleared.
+ allowEmpty
+ value={detail.body}
+ cwd={detail.workspaceRoot}
+ label="Pull request description"
+ placeholder="Describe this pull request"
+ saving={bodySaving}
+ onSave={(body) => void saveBody(body)}
+ onCancel={() => setBodyScope(null)}
+ />
+ ) : (
+ <div className="flex items-start gap-1">
+ <PullRequestMarkdown
+ className="min-w-0 flex-1"
+ text={detail.body.trim().length > 0 ? detail.body : "_No description provided._"}
+ cwd={detail.workspaceRoot}
+ />
+ {canEditPullRequestChangeRequest(detail) ? (
+ <Button
+ size="icon-xs"
+ variant="ghost"
+ className="shrink-0 text-muted-foreground opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100"
+ aria-label="Edit description"
+ onClick={() => setBodyScope(detail.url)}
+ >
+ <PencilIcon className="size-3" />
+ </Button>
+ ) : null}
+ </div>
+ )}
+ <PullRequestReactionBar
+ className="mt-2"
+ reactions={detail.reactions ?? []}
+ canReact={detail.capabilities.reactions === true}
+ environmentId={environmentId}
+ reference={reference}
+ onRefresh={onRefresh}
+ />
+ </div>
</Section>
<Section title="Checks" count={detail.checks.length}>
@@ -285,12 +587,14 @@ export function PullRequestSummaryTab({
<p className="text-xs text-muted-foreground">No checks reported.</p>
) : (
<div className="space-y-0.5">
- {detail.checks.map((check) => {
+ {detail.checks.map((check, index) => {
const finding = { kind: "check", check } as const;
const failing = check.status === "failure" || check.status === "cancelled";
return (
<div
- key={`${check.name}:${check.url ?? ""}`}
+ // Position too: the host decides how many runs share a name, and a repeated
+ // key would be a rendering fault on top of whatever the list already says.
+ key={`${index}:${check.name}:${check.url ?? ""}`}
className="group flex items-center gap-1 rounded-md pr-1 hover:bg-accent/60"
>
<button
@@ -319,7 +623,9 @@ export function PullRequestSummaryTab({
onClick={() => onFixFinding(finding)}
>
<HammerIcon className="size-3" />
- {pendingFinding === pullRequestFindingKey(finding) ? "Preparing..." : "Fix"}
+ {pendingFinding === pullRequestFindingKey(finding)
+ ? "Preparing..."
+ : fixCheckLabel}
</Button>
) : null}
</div>
@@ -385,32 +691,51 @@ export function PullRequestSummaryTab({
) : null}
{visibleComments.map((comment) => {
const thread = threadByCommentId.get(comment.id);
+ const reviewState = comment.reviewState?.toLowerCase();
+ if (thread?.isResolved || reviewState === "dismissed") {
+ return (
+ <CollapsedComment
+ key={comment.id}
+ comment={comment}
+ editing={commentEditing}
+ label={thread?.isResolved ? "Resolved" : "Approval dismissed"}
+ reactionBar={
+ <PullRequestReactionBar
+ className="mt-2"
+ reactions={comment.reactions ?? []}
+ canReact={detail.capabilities.reactions === true}
+ subjectId={comment.id}
+ environmentId={environmentId}
+ reference={reference}
+ onRefresh={onRefresh}
+ />
+ }
+ />
+ );
+ }
+ // An approval is a verdict, not a finding: there is nothing in it to fix.
const finding: PullRequestFinding | null =
- comment.kind !== "review" && comment.kind !== "review-comment"
+ (comment.kind !== "review" && comment.kind !== "review-comment") ||
+ reviewState === "approved"
? null
: thread === undefined
? { kind: "comment", comment }
- : thread.isResolved
- ? null
- : { kind: "thread", thread };
+ : { kind: "thread", thread };
return (
<article
key={comment.id}
// Offscreen comments skip style, layout and paint. Bot comments carry pages of
// highlighted code, and the conversation is below the description either way.
- className="rounded-lg border border-border/60 p-3 [contain-intrinsic-block-size:120px] [content-visibility:auto]"
+ className="group rounded-lg border border-border/60 p-3 [contain-intrinsic-block-size:120px] [content-visibility:auto]"
>
<div className="flex items-start gap-2">
- <PullRequestMetaLine className="min-w-0 flex-1 text-xs text-muted-foreground">
- <PullRequestActorLabel
- actor={comment.author}
- className="font-medium text-foreground"
- />
+ <span className="flex min-w-0 flex-1 items-center gap-2 text-xs text-muted-foreground">
+ <CommentAuthor actor={comment.author} />
<span>{formatRelativeTimeLabel(comment.createdAt)}</span>
{comment.reviewState ? (
- <span>{comment.reviewState.toLowerCase()}</span>
+ <span>{reviewStateLabel(comment.reviewState)}</span>
) : null}
- </PullRequestMetaLine>
+ </span>
{/* Review remarks only. A plain conversation comment is talk, not a finding,
and offering to fix one would promise more than it says. */}
{onFixFinding && finding ? (
@@ -424,7 +749,7 @@ export function PullRequestSummaryTab({
<HammerIcon className="size-3" />
{pendingFinding === pullRequestFindingKey(finding)
? "Preparing..."
- : "Fix in a thread"}
+ : fixFindingLabel}
</Button>
) : null}
</div>
@@ -436,10 +761,15 @@ export function PullRequestSummaryTab({
{comment.path}
</p>
) : null}
- <PullRequestMarkdown
+ <CommentBody className="mt-2" comment={comment} editing={commentEditing} />
+ <PullRequestReactionBar
className="mt-2"
- text={comment.body}
- cwd={detail.workspaceRoot}
+ reactions={comment.reactions ?? []}
+ canReact={detail.capabilities.reactions === true}
+ subjectId={comment.id}
+ environmentId={environmentId}
+ reference={reference}
+ onRefresh={onRefresh}
/>
</article>
);
diff --git a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
index 43d4f1a9c..3bcaa8177 100644
--- a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
@@ -1,4 +1,10 @@
-import type { PullRequestActor, PullRequestDetailView } from "@t3tools/contracts";
+import type {
+ EnvironmentId,
+ PullRequestActor,
+ PullRequestComment,
+ PullRequestDetailView,
+ PullRequestRef,
+} from "@t3tools/contracts";
import {
ChevronDownIcon,
ExternalLinkIcon,
@@ -8,27 +14,42 @@ import {
GitPullRequestClosedIcon,
GitPullRequestIcon,
MessageSquareIcon,
+ PencilIcon,
} from "lucide-react";
import { useState, type ReactNode } from "react";
import { cn } from "~/lib/utils";
import { readLocalApi } from "~/localApi";
+import { pullRequestEnvironment } from "~/state/pullRequests";
+import { useAtomCommand } from "~/state/use-atom-command";
import { formatRelativeTimeLabel } from "~/timestampFormat";
import { Button } from "../ui/button";
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
+import { toastManager } from "../ui/toast";
import {
buildPullRequestTimeline,
groupPullRequestTimelineConversations,
type PullRequestTimelineEvent,
} from "./pullRequestDetail.logic";
+import { canEditPullRequestComment } from "./pullRequestEditing.logic";
import { PullRequestMarkdown } from "./PullRequestMarkdown";
+import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
+import { PullRequestReactionBar } from "./PullRequestReactions";
import {
PullRequestActorAvatar,
PullRequestDiffStat,
PullRequestMetaLine,
} from "./pullRequestPresentation";
+/** What every comment on the timeline needs to react; only the subject differs between them. */
+interface ReactionSurface {
+ readonly canReact: boolean;
+ readonly environmentId: EnvironmentId;
+ readonly reference: PullRequestRef;
+ readonly onRefresh: () => void;
+}
+
function TimelineBody({ body, markdown, cwd }: { body: string; markdown: boolean; cwd: string }) {
return (
<div className="mt-3">
@@ -130,15 +151,44 @@ function OpenOnHostButton({ url, onOpen }: { url: string | null; onOpen: (url: s
function ConversationCard({
event,
+ editable,
cwd,
onOpen,
+ reactions,
}: {
event: PullRequestTimelineEvent;
+ /** The remark behind this entry, only where this reader may rewrite it. */
+ editable: PullRequestComment | null;
cwd: string;
onOpen: (url: string) => void;
+ reactions: ReactionSurface;
}) {
+ const [editing, setEditing] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
+ reportFailure: false,
+ });
+
+ const save = async (body: string) => {
+ // A review's own summary is not a kind any host rewrites, which is why `editable` is never
+ // one; the check is here because the comment's own type still allows it.
+ if (editable === null || saving || editable.kind === "review") return;
+ setSaving(true);
+ const result = await updateComment({
+ environmentId: reactions.environmentId,
+ input: { ...reactions.reference, commentId: editable.id, kind: editable.kind, body },
+ });
+ setSaving(false);
+ if (result._tag === "Failure") {
+ toastManager.add({ type: "error", title: "Could not save the comment" });
+ return;
+ }
+ setEditing(false);
+ reactions.onRefresh();
+ };
+
return (
- <article className="py-2">
+ <article className="group py-2">
<div className="px-2">
<div className="flex min-w-0 items-start gap-2">
<div className="min-w-0 flex-1">
@@ -157,14 +207,48 @@ function ConversationCard({
) : null}
</PullRequestMetaLine>
</div>
+ {editable !== null && !editing ? (
+ <Button
+ size="icon-xs"
+ variant="ghost"
+ className="-mt-1 shrink-0 text-muted-foreground opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100"
+ aria-label="Edit comment"
+ onClick={() => setEditing(true)}
+ >
+ <PencilIcon className="size-3" />
+ </Button>
+ ) : null}
<OpenOnHostButton url={event.url} onOpen={onOpen} />
</div>
</div>
- {event.body ? (
+ {editing && editable !== null ? (
+ <div className="px-2 pb-2 pt-3">
+ <PullRequestMarkdownEditor
+ value={editable.body}
+ cwd={cwd}
+ label="Edit comment"
+ saving={saving}
+ onSave={(body) => void save(body)}
+ onCancel={() => setEditing(false)}
+ />
+ </div>
+ ) : event.body ? (
<div className="px-2 pb-2">
<TimelineBody body={event.body} markdown={event.markdown} cwd={cwd} />
</div>
) : null}
+ {reactions.canReact || event.reactions.length > 0 ? (
+ <div className="px-2 pb-2">
+ <PullRequestReactionBar
+ reactions={event.reactions}
+ canReact={reactions.canReact}
+ subjectId={event.id}
+ environmentId={reactions.environmentId}
+ reference={reactions.reference}
+ onRefresh={reactions.onRefresh}
+ />
+ </div>
+ ) : null}
</article>
);
}
@@ -180,12 +264,16 @@ function uniqueConversationActors(events: ReadonlyArray<PullRequestTimelineEvent
function ConversationGroup({
events,
+ editable,
cwd,
onOpen,
+ reactions,
}: {
events: ReadonlyArray<PullRequestTimelineEvent>;
+ editable: ReadonlyMap<string, PullRequestComment>;
cwd: string;
onOpen: (url: string) => void;
+ reactions: ReactionSurface;
}) {
const [open, setOpen] = useState(false);
const actors = uniqueConversationActors(events);
@@ -229,7 +317,17 @@ function ConversationGroup({
{open ? (
<div className="mt-1 space-y-1">
{events.map((event) => (
- <ConversationCard key={event.id} event={event} cwd={cwd} onOpen={onOpen} />
+ <ConversationCard
+ // Named with the pull request too: a remark's id is the host's own, and two
+ // pull requests can hand out the same one — which would leave one card's open
+ // editor standing over the other's remark.
+ key={`${reactions.reference.projectId}#${reactions.reference.number}:${event.id}`}
+ event={event}
+ editable={editable.get(event.id) ?? null}
+ cwd={cwd}
+ onOpen={onOpen}
+ reactions={reactions}
+ />
))}
</div>
) : null}
@@ -315,14 +413,33 @@ function LifecycleEvent({ event }: { event: PullRequestTimelineEvent }) {
export function PullRequestTimelineTab({
detail,
+ environmentId,
+ reference,
order,
onOpenCommit,
+ onRefresh,
}: {
detail: PullRequestDetailView;
+ environmentId: EnvironmentId;
+ reference: PullRequestRef;
order: "newest" | "oldest";
onOpenCommit: (oid: string) => void;
+ onRefresh: () => void;
}) {
const events = buildPullRequestTimeline(detail);
+ const reactions: ReactionSurface = {
+ canReact: detail.capabilities.reactions === true,
+ environmentId,
+ reference,
+ onRefresh,
+ };
+ // A timeline entry keeps only what it draws, so the remarks this reader may rewrite are looked
+ // up here by the id the entry carries.
+ const editable = new Map(
+ detail.comments
+ .filter((comment) => canEditPullRequestComment(detail, comment))
+ .map((comment) => [comment.id, comment] as const),
+ );
const orderedEvents = order === "newest" ? events : events.toReversed();
const rows = groupPullRequestTimelineConversations(orderedEvents);
const openOnHost = (url: string) => {
@@ -340,8 +457,10 @@ export function PullRequestTimelineTab({
<ConversationGroup
key={`comments:${row.events[0]?.id ?? "empty"}`}
events={row.events}
+ editable={editable}
cwd={detail.workspaceRoot}
onOpen={openOnHost}
+ reactions={reactions}
/>
);
}
diff --git a/apps/web/src/components/pullRequest/pullRequestChecks.test.tsx b/apps/web/src/components/pullRequest/pullRequestChecks.test.tsx
new file mode 100644
index 000000000..23d70ae7b
--- /dev/null
+++ b/apps/web/src/components/pullRequest/pullRequestChecks.test.tsx
@@ -0,0 +1,85 @@
+import type { EnvironmentId, ProjectId, PullRequestCheck } from "@t3tools/contracts";
+import { Children, isValidElement, type ReactNode } from "react";
+import { describe, expect, it } from "vite-plus/test";
+
+import { PullRequestChecksPopover } from "./PullRequestChecksPopover";
+import type { EnvironmentPullRequestEntry } from "./pullRequestList.logic";
+import { PullRequestRow } from "./PullRequestRow";
+import { pullRequestChecksState } from "./pullRequestPresentation";
+
+function check(status: PullRequestCheck["status"]): PullRequestCheck {
+ return { name: `check-${status}`, status, description: null, url: null };
+}
+
+describe("pullRequestChecksState", () => {
+ it("lets a failure outrank a run still going, and reports nothing without checks", () => {
+ expect(pullRequestChecksState([check("success"), check("pending"), check("failure")])).toBe(
+ "failing",
+ );
+ expect(pullRequestChecksState([check("success"), check("cancelled")])).toBe("failing");
+ expect(pullRequestChecksState([check("success"), check("pending")])).toBe("pending");
+ expect(pullRequestChecksState([check("success")])).toBe("passing");
+ // Skipped and neutral are neither a pass nor a failure, so they are no verdict at all.
+ expect(pullRequestChecksState([check("skipped"), check("neutral")])).toBe(null);
+ expect(pullRequestChecksState([])).toBe(null);
+ });
+});
+
+/** Every element of the tree the row returned, so a nested indicator can be looked for. */
+function flatten(node: ReactNode): ReadonlyArray<ReturnType<typeof Object>> {
+ const found: unknown[] = [];
+ for (const child of Children.toArray(node)) {
+ if (!isValidElement(child)) continue;
+ found.push(child);
+ found.push(...flatten((child.props as { readonly children?: ReactNode }).children));
+ }
+ return found as ReadonlyArray<ReturnType<typeof Object>>;
+}
+
+function entry(overrides: Partial<EnvironmentPullRequestEntry>): EnvironmentPullRequestEntry {
+ return {
+ environmentId: "env-1" as EnvironmentId,
+ projectId: "project-1" as ProjectId,
+ provider: "github",
+ repository: "pingdotgg/t3code",
+ number: 1,
+ title: "Add the pull requests page",
+ url: "https://github.com/pingdotgg/t3code/pull/1",
+ author: null,
+ headBranch: "feat/page",
+ baseBranch: "main",
+ state: "open",
+ isDraft: false,
+ mergeability: "mergeable",
+ additions: 1,
+ deletions: 0,
+ createdAt: "2026-07-01T00:00:00Z",
+ updatedAt: "2026-07-02T00:00:00Z",
+ viewerReviewRequested: false,
+ labels: [],
+ ...overrides,
+ } as EnvironmentPullRequestEntry;
+}
+
+function row(overrides: Partial<EnvironmentPullRequestEntry>): ReactNode {
+ return PullRequestRow.type({
+ entry: entry(overrides),
+ selected: false,
+ showProjectTitle: false,
+ showProvider: false,
+ onSelect: () => {},
+ });
+}
+
+describe("PullRequestRow checks indicator", () => {
+ function indicators(node: ReactNode): number {
+ return flatten(node).filter(
+ (element) => (element as { type?: unknown }).type === PullRequestChecksPopover,
+ ).length;
+ }
+
+ it("shows the indicator only for a row the host reported a rollup for", () => {
+ expect(indicators(row({ checksState: "failing" }))).toBe(1);
+ expect(indicators(row({}))).toBe(0);
+ });
+});
diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
index d9de190e7..9b247002f 100644
--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
@@ -1,8 +1,9 @@
-import type {
- PullRequestCheck,
- PullRequestComment,
- PullRequestDetailView,
- PullRequestReviewThread,
+import {
+ PullRequestAction,
+ type PullRequestCheck,
+ type PullRequestComment,
+ type PullRequestDetailView,
+ type PullRequestReviewThread,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
@@ -15,9 +16,13 @@ import {
groupPullRequestTimelineConversations,
handoffPrompt,
handoffReviewComments,
+ isThreadOwnPullRequest,
orderPullRequestComments,
+ pullRequestActionNeedsHostRefresh,
pullRequestFindingKey,
+ pullRequestHandoffLabels,
readableFailure,
+ resolveBaseFreshness,
buildPullRequestTimeline,
describePullRequestState,
} from "./pullRequestDetail.logic";
@@ -57,6 +62,28 @@ describe("pull request state description", () => {
});
});
+describe("pull request handoff labels", () => {
+ it("names the open thread when actions write to its composer", () => {
+ expect(pullRequestHandoffLabels(true)).toEqual({
+ fixFinding: "Fix in this thread",
+ fixCheck: "Fix in this thread",
+ fixFindings: "Fix findings in this thread",
+ resolve: "Resolve in this thread",
+ resolveConflicts: "Resolve conflicts in this thread",
+ });
+ });
+
+ it("keeps the standalone pull request page labels", () => {
+ expect(pullRequestHandoffLabels(false)).toEqual({
+ fixFinding: "Fix in a thread",
+ fixCheck: "Fix",
+ fixFindings: "Fix findings in a thread",
+ resolve: "Resolve in a new thread",
+ resolveConflicts: "Resolve conflicts in a thread",
+ });
+ });
+});
+
describe("ordering comments", () => {
it("reverses the chronological list for newest first, and leaves oldest first alone", () => {
const comments = [{ createdAt: "a" }, { createdAt: "b" }, { createdAt: "c" }];
@@ -787,3 +814,126 @@ describe("a second ask into the same composer", () => {
]);
});
});
+
+describe("how the branch stands against its base", () => {
+ const detail = (overrides: Record<string, unknown> = {}) =>
+ ({
+ state: "open",
+ mergeability: "mergeable",
+ baseComparison: "behind",
+ behindBy: 12,
+ capabilities: { updateMethods: ["merge", "rebase"] },
+ viewerPermissions: { updateMethods: ["merge", "rebase"] },
+ ...overrides,
+ }) as Parameters<typeof resolveBaseFreshness>[0];
+
+ it("offers both ways where the host and the reader both allow them", () => {
+ expect(resolveBaseFreshness(detail())).toEqual({ behindBy: 12, methods: ["merge", "rebase"] });
+ });
+
+ it("says nothing about a branch that is already current", () => {
+ expect(resolveBaseFreshness(detail({ baseComparison: "up-to-date" }))).toBeNull();
+ });
+
+ it("says nothing where the host could not compare, rather than claiming it is current", () => {
+ expect(resolveBaseFreshness(detail({ baseComparison: "unknown" }))).toBeNull();
+ expect(resolveBaseFreshness(detail({ baseComparison: undefined }))).toBeNull();
+ });
+
+ it("leaves a conflicting branch to the conflicts row", () => {
+ expect(resolveBaseFreshness(detail({ mergeability: "conflicting" }))).toBeNull();
+ });
+
+ it("says nothing where the host has no merge verdict yet", () => {
+ expect(resolveBaseFreshness(detail({ mergeability: "unknown" }))).toBeNull();
+ });
+
+ it("says nothing about a merged or closed pull request", () => {
+ expect(resolveBaseFreshness(detail({ state: "merged" }))).toBeNull();
+ expect(resolveBaseFreshness(detail({ state: "closed" }))).toBeNull();
+ });
+
+ it("narrows to what this reader may actually take", () => {
+ expect(
+ resolveBaseFreshness(detail({ viewerPermissions: { updateMethods: ["merge"] } }))?.methods,
+ ).toEqual(["merge"]);
+ });
+
+ it("still reports the news where the reader may take none of it", () => {
+ // Somebody reading another account's pull request is told why it is blocked without being
+ // offered a button the host would refuse.
+ expect(resolveBaseFreshness(detail({ viewerPermissions: {} }))).toEqual({
+ behindBy: 12,
+ methods: [],
+ });
+ });
+
+ it("reports a count only where the host counted", () => {
+ expect(resolveBaseFreshness(detail({ behindBy: undefined }))?.behindBy).toBeNull();
+ });
+});
+
+describe("whether the panel is showing the thread's own pull request", () => {
+ const surface = { projectId: "proj-a", repository: "acme/app", number: 7 };
+
+ it("matches on project, repository and number together", () => {
+ expect(
+ isThreadOwnPullRequest({ projectId: "proj-a", repository: "acme/app", number: 7 }, surface),
+ ).toBe(true);
+ });
+
+ it("rejects a second checkout of the same repository under another project", () => {
+ expect(
+ isThreadOwnPullRequest({ projectId: "proj-b", repository: "acme/app", number: 7 }, surface),
+ ).toBe(false);
+ });
+
+ it("rejects another repository or another number", () => {
+ expect(
+ isThreadOwnPullRequest({ projectId: "proj-a", repository: "acme/web", number: 7 }, surface),
+ ).toBe(false);
+ expect(
+ isThreadOwnPullRequest({ projectId: "proj-a", repository: "acme/app", number: 8 }, surface),
+ ).toBe(false);
+ });
+
+ it("rejects a thread with no project or no pull request of its own", () => {
+ expect(
+ isThreadOwnPullRequest({ projectId: null, repository: "acme/app", number: 7 }, surface),
+ ).toBe(false);
+ expect(
+ isThreadOwnPullRequest(
+ { projectId: "proj-a", repository: "acme/app", number: null },
+ surface,
+ ),
+ ).toBe(false);
+ });
+});
+
+describe("which actions need the host read again after they run", () => {
+ it("classifies every action the contract knows about", () => {
+ // Imported from the contract rather than hand-listed, so a new PullRequestAction fails this
+ // test until somebody decides which side of the diff it belongs on.
+ expect(PullRequestAction.literals.map(pullRequestActionNeedsHostRefresh)).toEqual(
+ PullRequestAction.literals.map((action) => action === "update-branch"),
+ );
+ });
+
+ it("sends update-branch back to the host, having moved the head commit", () => {
+ expect(pullRequestActionNeedsHostRefresh("update-branch")).toBe(true);
+ });
+
+ it("leaves every action that only changes metadata to the cheaper detail refresh", () => {
+ for (const action of [
+ "ready",
+ "draft",
+ "close",
+ "reopen",
+ "enable-auto-merge",
+ "disable-auto-merge",
+ "merge",
+ ] as const) {
+ expect(pullRequestActionNeedsHostRefresh(action)).toBe(false);
+ }
+ });
+});
diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
index e7d16fd31..ddb4e813b 100644
--- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
+++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
@@ -1,14 +1,62 @@
import type {
+ PullRequestAction,
PullRequestActor,
+ PullRequestBaseComparison,
PullRequestCheck,
PullRequestComment,
PullRequestDetailView,
+ PullRequestMergeability,
+ PullRequestReaction,
PullRequestReviewThread,
PullRequestState,
+ PullRequestUpdateMethod,
} from "@t3tools/contracts";
import { inferReviewCommentFenceLanguage, type ReviewCommentContext } from "~/reviewCommentContext";
+/**
+ * Whether the pull request on a right-panel surface is the thread's own one. Repository and
+ * number are not enough: one environment can hold two checkouts of the same repository under
+ * different projects, and the other project's checkout is somebody else's branch.
+ */
+export function isThreadOwnPullRequest(
+ thread: {
+ readonly projectId: string | null;
+ readonly repository: string | null;
+ readonly number: number | null;
+ },
+ surface: {
+ readonly projectId: string;
+ readonly repository: string;
+ readonly number: number;
+ },
+): boolean {
+ return (
+ thread.projectId === surface.projectId &&
+ thread.repository === surface.repository &&
+ thread.number === surface.number
+ );
+}
+
+/** Names where a pull-request task will land, without letting each surface guess independently. */
+export function pullRequestHandoffLabels(inThisThread: boolean) {
+ return inThisThread
+ ? {
+ fixFinding: "Fix in this thread",
+ fixCheck: "Fix in this thread",
+ fixFindings: "Fix findings in this thread",
+ resolve: "Resolve in this thread",
+ resolveConflicts: "Resolve conflicts in this thread",
+ }
+ : {
+ fixFinding: "Fix in a thread",
+ fixCheck: "Fix",
+ fixFindings: "Fix findings in a thread",
+ resolve: "Resolve in a new thread",
+ resolveConflicts: "Resolve conflicts in a thread",
+ };
+}
+
/** Plain-language state, shown beside the author. Conflicts are a merge signal, not a state. */
export function describePullRequestState(state: PullRequestState, isDraft: boolean): string {
if (state === "merged") return "Merged";
@@ -41,6 +89,8 @@ export interface PullRequestTimelineEvent {
readonly deletions: number | null;
readonly path: string | null;
readonly reviewState: string | null;
+ /** Empty for everything but a comment, which is the only entry a host lets anyone react to. */
+ readonly reactions: ReadonlyArray<PullRequestReaction>;
}
export type PullRequestTimelineRow =
@@ -111,6 +161,7 @@ export function buildPullRequestTimeline(
deletions: null,
path: null,
reviewState: null,
+ reactions: [],
},
...detail.commits.map((commit) => ({
id: commit.oid,
@@ -126,6 +177,7 @@ export function buildPullRequestTimeline(
deletions: commit.deletions ?? null,
path: null,
reviewState: null,
+ reactions: [],
})),
...detail.comments.map((comment) => ({
id: comment.id,
@@ -141,6 +193,7 @@ export function buildPullRequestTimeline(
deletions: null,
path: comment.path,
reviewState: comment.reviewState,
+ reactions: comment.reactions ?? [],
})),
...(detail.mergedAt
? [
@@ -158,6 +211,7 @@ export function buildPullRequestTimeline(
deletions: null,
path: null,
reviewState: null,
+ reactions: [],
},
]
: []),
@@ -177,6 +231,7 @@ export function buildPullRequestTimeline(
deletions: null,
path: null,
reviewState: null,
+ reactions: [],
},
]
: []),
@@ -648,3 +703,62 @@ export function readableFailure(failure: unknown, hint: string): string {
// that contradicts it is worse than no guess at all.
return bounded;
}
+
+/**
+ * Where the branch stands against its base, said the way GitHub says it: current, out of date but
+ * still cleanly mergeable, or conflicting. Only the middle one is an offer — the conflicts row
+ * already speaks for a branch that collides, and a current branch has nothing to report.
+ *
+ * Null where there is nothing to show, which is also every host that cannot compare or has not
+ * said yet: silence is not the same claim as "up to date", and a banner nobody can act on is
+ * noise. Only a host verdict of "mergeable" earns the clean-merge wording.
+ */
+export function resolveBaseFreshness(detail: {
+ readonly state: PullRequestState;
+ readonly mergeability: PullRequestMergeability;
+ readonly baseComparison?: PullRequestBaseComparison | undefined;
+ readonly behindBy?: number | undefined;
+ readonly capabilities: {
+ readonly updateMethods?: ReadonlyArray<PullRequestUpdateMethod> | undefined;
+ };
+ readonly viewerPermissions: {
+ readonly updateMethods?: ReadonlyArray<PullRequestUpdateMethod> | undefined;
+ };
+}): {
+ readonly behindBy: number | null;
+ /** Empty where the branch is stale but this reader may not move it: news, not an offer. */
+ readonly methods: ReadonlyArray<PullRequestUpdateMethod>;
+} | null {
+ if (detail.state !== "open" || detail.baseComparison !== "behind") return null;
+ // A conflicting branch cannot be updated cleanly either, and the conflicts row is already
+ // saying the more useful half of that. An unknown verdict is not a clean merge in waiting.
+ if (detail.mergeability !== "mergeable") return null;
+ const offered = detail.capabilities.updateMethods ?? [];
+ const allowed = detail.viewerPermissions.updateMethods ?? [];
+ return {
+ behindBy: detail.behindBy ?? null,
+ methods: offered.filter((method) => allowed.includes(method)),
+ };
+}
+
+/**
+ * Whether a completed action leaves the diff atom pointed at a comparison that no longer exists,
+ * the same staleness the manual refresh button fixes. Only `update-branch` moves the head commit;
+ * a merge moves the branch too, but it also closes the pull request, where the diff is no longer
+ * what anyone is looking at. Written as a `Record` so a new `PullRequestAction` fails to compile
+ * here until somebody decides which side of the diff it belongs on.
+ */
+const ACTION_NEEDS_HOST_REFRESH: Record<PullRequestAction, boolean> = {
+ "update-branch": true,
+ merge: false,
+ ready: false,
+ draft: false,
+ close: false,
+ reopen: false,
+ "enable-auto-merge": false,
+ "disable-auto-merge": false,
+};
+
+export function pullRequestActionNeedsHostRefresh(action: PullRequestAction): boolean {
+ return ACTION_NEEDS_HOST_REFRESH[action];
+}
diff --git a/apps/web/src/components/pullRequest/pullRequestEditing.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestEditing.logic.test.ts
new file mode 100644
index 000000000..1b43ff209
--- /dev/null
+++ b/apps/web/src/components/pullRequest/pullRequestEditing.logic.test.ts
@@ -0,0 +1,172 @@
+import type {
+ PullRequestActor,
+ PullRequestCapabilities,
+ PullRequestComment,
+ PullRequestDetail,
+ PullRequestViewerPermissions,
+} from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ canEditPullRequestChangeRequest,
+ canEditPullRequestComment,
+} from "./pullRequestEditing.logic";
+
+type Subject = Pick<PullRequestDetail, "author" | "capabilities" | "viewer" | "viewerPermissions">;
+
+function actor(login: string): PullRequestActor {
+ return { login, name: null, avatarUrl: null };
+}
+
+function capabilities(edit?: PullRequestCapabilities["edit"]): PullRequestCapabilities {
+ return {
+ diff: true,
+ comment: true,
+ actions: [],
+ mergeMethods: [],
+ search: true,
+ reactions: true,
+ review: { inlineComment: true, reply: true, resolve: true, verdicts: [] },
+ reviewers: { request: true, listCandidates: true },
+ ...(edit === undefined ? {} : { edit }),
+ };
+}
+
+function permissions(
+ overrides: Partial<PullRequestViewerPermissions> = {},
+): PullRequestViewerPermissions {
+ return {
+ actions: [],
+ comment: true,
+ resolve: true,
+ verdicts: [],
+ requestReviewers: true,
+ ...overrides,
+ };
+}
+
+function subject(overrides: Partial<Subject> = {}): Subject {
+ return {
+ author: actor("octocat"),
+ capabilities: capabilities({ changeRequest: true, comment: true }),
+ viewer: "octocat",
+ viewerPermissions: permissions(),
+ ...overrides,
+ };
+}
+
+function comment(overrides: Partial<PullRequestComment> = {}): PullRequestComment {
+ return {
+ id: "c1",
+ kind: "issue-comment",
+ author: actor("octocat"),
+ body: "words",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ url: null,
+ path: null,
+ reviewState: null,
+ ...overrides,
+ };
+}
+
+describe("canEditPullRequestChangeRequest", () => {
+ it("lets the author rewrite their own change request", () => {
+ expect(canEditPullRequestChangeRequest(subject())).toBe(true);
+ });
+
+ it("matches the author regardless of case", () => {
+ expect(canEditPullRequestChangeRequest(subject({ viewer: "OctoCat" }))).toBe(true);
+ });
+
+ it("lets somebody who may merge rewrite a change request they did not write", () => {
+ expect(
+ canEditPullRequestChangeRequest(
+ subject({
+ author: actor("someone-else"),
+ viewerPermissions: permissions({ actions: ["merge"] }),
+ }),
+ ),
+ ).toBe(true);
+ });
+
+ it("refuses a reader who neither wrote it nor may merge it", () => {
+ expect(
+ canEditPullRequestChangeRequest(
+ subject({
+ author: actor("someone-else"),
+ viewerPermissions: permissions({ actions: ["close"] }),
+ }),
+ ),
+ ).toBe(false);
+ });
+
+ it("refuses where the host cannot rewrite a change request at all", () => {
+ expect(
+ canEditPullRequestChangeRequest(
+ subject({ capabilities: capabilities({ changeRequest: false, comment: true }) }),
+ ),
+ ).toBe(false);
+ expect(canEditPullRequestChangeRequest(subject({ capabilities: capabilities() }))).toBe(false);
+ });
+
+ it("refuses where the host did not say who the reader is", () => {
+ expect(canEditPullRequestChangeRequest(subject({ viewer: undefined }))).toBe(false);
+ });
+
+ it("still allows a merger the host could not name", () => {
+ expect(
+ canEditPullRequestChangeRequest(
+ subject({ viewer: undefined, viewerPermissions: permissions({ actions: ["merge"] }) }),
+ ),
+ ).toBe(true);
+ });
+});
+
+describe("canEditPullRequestComment", () => {
+ it("lets the reader rewrite their own conversation comment", () => {
+ expect(canEditPullRequestComment(subject(), comment())).toBe(true);
+ });
+
+ it("lets the reader rewrite their own remark on a line", () => {
+ expect(canEditPullRequestComment(subject(), comment({ kind: "review-comment" }))).toBe(true);
+ });
+
+ it("matches the author regardless of case", () => {
+ expect(
+ canEditPullRequestComment(
+ subject({ viewer: "OCTOCAT" }),
+ comment({ author: actor("octocat") }),
+ ),
+ ).toBe(true);
+ });
+
+ it("refuses somebody else's remark", () => {
+ expect(canEditPullRequestComment(subject(), comment({ author: actor("someone-else") }))).toBe(
+ false,
+ );
+ });
+
+ it("refuses a remark the host attributes to nobody", () => {
+ expect(canEditPullRequestComment(subject(), comment({ author: null }))).toBe(false);
+ });
+
+ it("refuses a review's own summary", () => {
+ expect(canEditPullRequestComment(subject(), comment({ kind: "review" }))).toBe(false);
+ });
+
+ it("refuses where the host cannot rewrite a remark at all", () => {
+ expect(
+ canEditPullRequestComment(
+ subject({ capabilities: capabilities({ changeRequest: true, comment: false }) }),
+ comment(),
+ ),
+ ).toBe(false);
+ expect(canEditPullRequestComment(subject({ capabilities: capabilities() }), comment())).toBe(
+ false,
+ );
+ });
+
+ it("refuses where the host did not say who the reader is", () => {
+ expect(canEditPullRequestComment(subject({ viewer: undefined }), comment())).toBe(false);
+ });
+});
diff --git a/apps/web/src/components/pullRequest/pullRequestEditing.logic.ts b/apps/web/src/components/pullRequest/pullRequestEditing.logic.ts
new file mode 100644
index 000000000..a7e49f3f6
--- /dev/null
+++ b/apps/web/src/components/pullRequest/pullRequestEditing.logic.ts
@@ -0,0 +1,41 @@
+import type { PullRequestComment, PullRequestDetail } from "@t3tools/contracts";
+
+/** Only the parts of a detail either answer reads, so a caller can pass a whole detail view. */
+type EditingSubject = Pick<
+ PullRequestDetail,
+ "author" | "capabilities" | "viewer" | "viewerPermissions"
+>;
+
+/** Hosts disagree about the case of a login and none of them treats two casings as two people. */
+function sameLogin(one: string | null | undefined, other: string | null | undefined): boolean {
+ if (one == null || other == null) return false;
+ return one.trim().toLowerCase() === other.trim().toLowerCase();
+}
+
+/**
+ * Whether the title and description can be rewritten from here. Beyond the host being able to at
+ * all, either the reader wrote the change request or they may merge it — merging is the one action
+ * every host here grants with write access and withholds without it, so it stands in for the
+ * permission none of them publishes by name.
+ */
+export function canEditPullRequestChangeRequest(detail: EditingSubject): boolean {
+ if (detail.capabilities.edit?.changeRequest !== true) return false;
+ return (
+ sameLogin(detail.viewer, detail.author?.login) ||
+ detail.viewerPermissions.actions.includes("merge")
+ );
+}
+
+/**
+ * Whether this remark can be rewritten from here. A review's own summary is left out: the hosts
+ * disagree about what one even is, and none of them takes a rewrite of it through the mutation
+ * a comment goes through.
+ */
+export function canEditPullRequestComment(
+ detail: EditingSubject,
+ comment: Pick<PullRequestComment, "author" | "kind">,
+): boolean {
+ if (detail.capabilities.edit?.comment !== true) return false;
+ if (comment.kind !== "issue-comment" && comment.kind !== "review-comment") return false;
+ return sameLogin(detail.viewer, comment.author?.login);
+}
diff --git a/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.test.ts
new file mode 100644
index 000000000..720a56691
--- /dev/null
+++ b/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.test.ts
@@ -0,0 +1,167 @@
+import type { FileDiffMetadata } from "@pierre/diffs";
+import { describe, expect, it } from "vite-plus/test";
+
+import { diffFileTier, orderDiffFiles } from "./pullRequestFileOrder.logic";
+
+/** Only the path and the patch's own lines matter here; the viewer fills the rest in. */
+function file(name: string, additionLines: ReadonlyArray<string> = []): FileDiffMetadata {
+ return { name, hunks: [], additionLines, deletionLines: [] } as unknown as FileDiffMetadata;
+}
+
+function order(files: ReadonlyArray<FileDiffMetadata>): Array<string> {
+ return orderDiffFiles(files).map((entry) => entry.name);
+}
+
+describe("diffFileTier", () => {
+ it("puts lockfiles, snapshots and build output last", () => {
+ expect(diffFileTier("pnpm-lock.yaml")).toBe("generated");
+ expect(diffFileTier("apps/web/package-lock.json")).toBe("generated");
+ expect(diffFileTier("src/__snapshots__/app.ts")).toBe("generated");
+ expect(diffFileTier("src/app.test.ts.snap")).toBe("generated");
+ expect(diffFileTier("src/api.generated.ts")).toBe("generated");
+ expect(diffFileTier("public/app.min.js")).toBe("generated");
+ expect(diffFileTier("dist/app.js")).toBe("generated");
+ expect(diffFileTier("packages/core/vendor/lib.js")).toBe("generated");
+ });
+
+ it("recognises a test by its name or by the directory holding it", () => {
+ expect(diffFileTier("src/app.test.ts")).toBe("test");
+ expect(diffFileTier("src/app.spec.tsx")).toBe("test");
+ expect(diffFileTier("src/__tests__/app.ts")).toBe("test");
+ expect(diffFileTier("test/app.ts")).toBe("test");
+ expect(diffFileTier("tests/helpers/app.ts")).toBe("test");
+ });
+
+ it("treats everything else as source, including files merely named like a directory", () => {
+ expect(diffFileTier("src/app.ts")).toBe("source");
+ expect(diffFileTier("src/testing.ts")).toBe("source");
+ expect(diffFileTier("src/dist.ts")).toBe("source");
+ });
+});
+
+describe("orderDiffFiles", () => {
+ it("answers an empty diff with an empty order", () => {
+ expect(order([])).toEqual([]);
+ });
+
+ it("puts a dependency before what imports it", () => {
+ expect(order([file("src/a.ts", ['import { b } from "./b";']), file("src/b.ts")])).toEqual([
+ "src/b.ts",
+ "src/a.ts",
+ ]);
+ });
+
+ it("follows a chain the whole way down", () => {
+ expect(
+ order([
+ file("src/a.ts", ['import { b } from "./b";']),
+ file("src/b.ts", ['import { c } from "./c";']),
+ file("src/c.ts"),
+ ]),
+ ).toEqual(["src/c.ts", "src/b.ts", "src/a.ts"]);
+ });
+
+ it("resolves a specifier that climbs out of the importer's directory", () => {
+ expect(
+ order([file("src/ui/a.ts", ['import { b } from "../lib/b";']), file("src/lib/b.ts")]),
+ ).toEqual(["src/lib/b.ts", "src/ui/a.ts"]);
+ });
+
+ it("resolves a directory specifier to that directory's index file", () => {
+ expect(
+ order([file("src/a.ts", ['import { b } from "./lib";']), file("src/lib/index.ts")]),
+ ).toEqual(["src/lib/index.ts", "src/a.ts"]);
+ });
+
+ it("falls back to the specifier's last segment when the path does not line up", () => {
+ // An aliased import (`~/lib/b`) resolves to nothing on disk here, but the diff has only one
+ // file that could be meant.
+ expect(order([file("src/a.ts", ['import { b } from "~/lib/b";']), file("lib/b.ts")])).toEqual([
+ "lib/b.ts",
+ "src/a.ts",
+ ]);
+ });
+
+ it("ignores an ambiguous last segment rather than guessing", () => {
+ expect(
+ order([
+ file("src/a.ts", ['import { b } from "~/somewhere/b";']),
+ file("one/b.ts"),
+ file("two/b.ts"),
+ ]),
+ ).toEqual(["one/b.ts", "src/a.ts", "two/b.ts"]);
+ });
+
+ it("resolves a specifier naming an extension, including the .js beside a .ts", () => {
+ expect(order([file("src/a.ts", ['import { b } from "./b.js";']), file("src/b.ts")])).toEqual([
+ "src/b.ts",
+ "src/a.ts",
+ ]);
+ });
+
+ it("reads require and bare imports too", () => {
+ expect(
+ order([
+ file("src/a.ts", ['const b = require("./b");', 'import "./c";']),
+ file("src/b.ts"),
+ file("src/c.ts"),
+ ]),
+ ).toEqual(["src/b.ts", "src/c.ts", "src/a.ts"]);
+ });
+
+ it("falls back to path order inside a cycle", () => {
+ expect(
+ order([
+ file("src/b.ts", ['import { a } from "./a";']),
+ file("src/a.ts", ['import { b } from "./b";']),
+ ]),
+ ).toEqual(["src/a.ts", "src/b.ts"]);
+ });
+
+ it("clusters unrelated files by path", () => {
+ expect(order([file("src/ui/b.ts"), file("src/lib/z.ts"), file("src/lib/a.ts")])).toEqual([
+ "src/lib/a.ts",
+ "src/lib/z.ts",
+ "src/ui/b.ts",
+ ]);
+ });
+
+ it("keeps the tiers apart and orders tests by the source they cover", () => {
+ expect(
+ order([
+ file("pnpm-lock.yaml"),
+ file("src/a.test.ts"),
+ file("src/__tests__/b.ts"),
+ file("src/a.ts", ['import { b } from "./b";']),
+ file("src/b.ts"),
+ file("dist/a.js"),
+ ]),
+ ).toEqual([
+ "src/b.ts",
+ "src/a.ts",
+ "src/__tests__/b.ts",
+ "src/a.test.ts",
+ "dist/a.js",
+ "pnpm-lock.yaml",
+ ]);
+ });
+
+ it("puts a test with no source in the diff after the ones that have theirs", () => {
+ expect(order([file("src/orphan.spec.ts"), file("src/a.test.ts"), file("src/a.ts")])).toEqual([
+ "src/a.ts",
+ "src/a.test.ts",
+ "src/orphan.spec.ts",
+ ]);
+ });
+
+ it("orders the same diff the same way whatever order it arrives in", () => {
+ const files = [
+ file("src/a.ts", ['import { b } from "./b";']),
+ file("src/b.ts"),
+ file("src/c.ts"),
+ file("src/a.test.ts"),
+ file("yarn.lock"),
+ ];
+ expect(order(files)).toEqual(order(files.toReversed()));
+ });
+});
diff --git a/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.ts b/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.ts
new file mode 100644
index 000000000..b46ed8853
--- /dev/null
+++ b/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.ts
@@ -0,0 +1,197 @@
+import type { FileDiffMetadata } from "@pierre/diffs";
+
+import { resolveFileDiffPath } from "~/lib/diffRendering";
+
+/**
+ * Which of the three reading passes a file belongs to.
+ *
+ * A reviewer reads the change itself first, then what proves it, and a lockfile or a build output
+ * only ever confirms what the source already said. Ordering by path alone buries the one file the
+ * change is really about under whichever directory happens to sort first.
+ */
+export type DiffFileTier = "source" | "test" | "generated";
+
+const GENERATED_FILE_NAMES = new Set([
+ "pnpm-lock.yaml",
+ "yarn.lock",
+ "package-lock.json",
+ "bun.lockb",
+ "Cargo.lock",
+ "go.sum",
+ "composer.lock",
+ "Gemfile.lock",
+]);
+const GENERATED_DIRECTORIES = new Set([
+ "__snapshots__",
+ "__generated__",
+ "dist",
+ "build",
+ "vendor",
+]);
+const TEST_DIRECTORIES = new Set(["__tests__", "tests", "test"]);
+const MODULE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
+
+export function diffFileTier(path: string): DiffFileTier {
+ const segments = path.split("/");
+ const name = segments.at(-1) ?? "";
+ if (
+ GENERATED_FILE_NAMES.has(name) ||
+ name.endsWith(".snap") ||
+ name.endsWith(".min.js") ||
+ name.endsWith(".min.css") ||
+ /\.generated\./.test(name) ||
+ segments.slice(0, -1).some((segment) => GENERATED_DIRECTORIES.has(segment))
+ ) {
+ return "generated";
+ }
+ if (
+ /\.(?:test|spec)\./.test(name) ||
+ segments.slice(0, -1).some((segment) => TEST_DIRECTORIES.has(segment))
+ ) {
+ return "test";
+ }
+ return "source";
+}
+
+function stripExtension(path: string): string {
+ const dot = path.lastIndexOf(".");
+ const slash = path.lastIndexOf("/");
+ return dot > slash ? path.slice(0, dot) : path;
+}
+
+function baseName(path: string): string {
+ return stripExtension(path.split("/").at(-1) ?? "");
+}
+
+/** Resolves `../x` against the importer's directory; no package resolution, only what git shows. */
+function resolveRelative(fromPath: string, specifier: string): string {
+ const segments = fromPath.split("/").slice(0, -1);
+ for (const part of specifier.split("/")) {
+ if (part === "." || part === "") continue;
+ if (part === "..") segments.pop();
+ else segments.push(part);
+ }
+ return segments.join("/");
+}
+
+// `import x from "y"`, `import "y"`, `export … from "y"` and `require("y")` all reduce to a quoted
+// specifier preceded by one of three words.
+const IMPORT_SPECIFIER = /(?:\bfrom|\bimport|\brequire\s*\()\s*\(?\s*["']([^"']+)["']/g;
+
+/** Which changed files a file's patch lines import, by path. */
+function importedPaths(
+ path: string,
+ lines: ReadonlyArray<string>,
+ byModulePath: ReadonlyMap<string, string>,
+ byBaseName: ReadonlyMap<string, string>,
+): ReadonlySet<string> {
+ const imported = new Set<string>();
+ for (const line of lines) {
+ IMPORT_SPECIFIER.lastIndex = 0;
+ let match = IMPORT_SPECIFIER.exec(line);
+ while (match !== null) {
+ const specifier = match[1] ?? "";
+ const withExtension = specifier.startsWith(".")
+ ? resolveRelative(path, specifier)
+ : specifier;
+ // A specifier may name the extension the module map dropped, and it need not be the one on
+ // disk: TypeScript's own imports point at the `.js` beside a `.ts`.
+ const extension = MODULE_EXTENSIONS.find((candidate) => withExtension.endsWith(candidate));
+ const resolved =
+ extension === undefined ? withExtension : withExtension.slice(0, -extension.length);
+ const target =
+ byModulePath.get(resolved) ??
+ byModulePath.get(`${resolved}/index`) ??
+ byBaseName.get(baseName(resolved));
+ if (target !== undefined && target !== path) imported.add(target);
+ match = IMPORT_SPECIFIER.exec(line);
+ }
+ }
+ return imported;
+}
+
+/**
+ * Source files with what they import ahead of what imports them.
+ *
+ * Kahn's, but every step takes the lowest remaining path rather than any ready node, so the same
+ * change always reads the same way and files of one directory stay together. A cycle leaves nothing
+ * ready: the lowest path still standing is taken anyway, which is the alphabetical order the tier
+ * would have had without a graph.
+ */
+function orderByImports(
+ paths: ReadonlyArray<string>,
+ imports: ReadonlyMap<string, ReadonlySet<string>>,
+): Array<string> {
+ const remaining = new Set(paths);
+ const ordered: Array<string> = [];
+ const sorted = [...paths].sort((left, right) => left.localeCompare(right));
+ while (remaining.size > 0) {
+ const candidates = sorted.filter((path) => remaining.has(path));
+ const next =
+ candidates.find((path) =>
+ [...(imports.get(path) ?? [])].every((dependency) => !remaining.has(dependency)),
+ ) ?? candidates[0]!;
+ remaining.delete(next);
+ ordered.push(next);
+ }
+ return ordered;
+}
+
+/** The implementation a test names: `foo.test.ts` and `__tests__/foo.ts` both point at `foo`. */
+function testedBaseName(path: string): string {
+ return (path.split("/").at(-1) ?? "").replace(/\.(?:test|spec)\..*$/, "").replace(/\.[^.]+$/, "");
+}
+
+/**
+ * Diff files in reading order: source in dependency order, then the tests that cover it, then
+ * whatever a tool wrote.
+ */
+export function orderDiffFiles(
+ files: ReadonlyArray<FileDiffMetadata>,
+): ReadonlyArray<FileDiffMetadata> {
+ const byPath = new Map<string, FileDiffMetadata>();
+ for (const file of files) byPath.set(resolveFileDiffPath(file), file);
+ const tiers = new Map<string, DiffFileTier>();
+ for (const path of byPath.keys()) tiers.set(path, diffFileTier(path));
+
+ const sourcePaths = [...byPath.keys()].filter((path) => tiers.get(path) === "source");
+ const byModulePath = new Map<string, string>();
+ const ambiguousBaseNames = new Set<string>();
+ const byBaseName = new Map<string, string>();
+ for (const path of sourcePaths) {
+ byModulePath.set(stripExtension(path), path);
+ const base = baseName(path);
+ if (byBaseName.has(base)) ambiguousBaseNames.add(base);
+ byBaseName.set(base, path);
+ }
+ for (const base of ambiguousBaseNames) byBaseName.delete(base);
+
+ const imports = new Map<string, ReadonlySet<string>>();
+ for (const path of sourcePaths) {
+ const file = byPath.get(path)!;
+ imports.set(
+ path,
+ importedPaths(path, [...file.additionLines, ...file.deletionLines], byModulePath, byBaseName),
+ );
+ }
+ const orderedSource = orderByImports(sourcePaths, imports);
+
+ const sourcePositions = new Map<string, number>();
+ orderedSource.forEach((path, index) => {
+ const base = baseName(path);
+ if (!sourcePositions.has(base)) sourcePositions.set(base, index);
+ });
+ const orderedTests = [...byPath.keys()]
+ .filter((path) => tiers.get(path) === "test")
+ .sort((left, right) => {
+ const leftPosition = sourcePositions.get(testedBaseName(left)) ?? Number.MAX_SAFE_INTEGER;
+ const rightPosition = sourcePositions.get(testedBaseName(right)) ?? Number.MAX_SAFE_INTEGER;
+ return leftPosition - rightPosition || left.localeCompare(right);
+ });
+
+ const orderedGenerated = [...byPath.keys()]
+ .filter((path) => tiers.get(path) === "generated")
+ .sort((left, right) => left.localeCompare(right));
+
+ return [...orderedSource, ...orderedTests, ...orderedGenerated].map((path) => byPath.get(path)!);
+}
diff --git a/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.test.ts b/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.test.ts
new file mode 100644
index 000000000..db105f97f
--- /dev/null
+++ b/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { openOnHostLabel, pullRequestLinkContextMenuItems } from "./pullRequestLinkContextMenu";
+
+describe("pull request link context menu", () => {
+ it("offers the copy first and the host's own page after it", () => {
+ expect(pullRequestLinkContextMenuItems("Open on GitHub")).toEqual([
+ { id: "copy-link", label: "Copy link", icon: "copy" },
+ { id: "open-external", label: "Open on GitHub" },
+ ]);
+ });
+
+ it("names every host it knows, and says nothing false about one it does not", () => {
+ expect(openOnHostLabel("github")).toBe("Open on GitHub");
+ expect(openOnHostLabel("gitlab")).toBe("Open on GitLab");
+ expect(openOnHostLabel("bitbucket")).toBe("Open on Bitbucket");
+ expect(openOnHostLabel("azure-devops")).toBe("Open on Azure DevOps");
+ expect(openOnHostLabel("something-else")).toBe("Open on host");
+ });
+});
diff --git a/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.ts b/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.ts
new file mode 100644
index 000000000..16b749445
--- /dev/null
+++ b/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.ts
@@ -0,0 +1,68 @@
+import type { ContextMenuItem } from "@t3tools/contracts";
+
+import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
+import { readLocalApi } from "~/localApi";
+
+import { toastManager } from "../ui/toast";
+
+export type PullRequestLinkContextMenuAction = "copy-link" | "open-external";
+
+/** Named for the host rather than "externally": the point is where you will land. */
+export const OPEN_ON_HOST_LABELS: Partial<Record<string, string>> = {
+ github: "Open on GitHub",
+ gitlab: "Open on GitLab",
+ bitbucket: "Open on Bitbucket",
+ "azure-devops": "Open on Azure DevOps",
+};
+
+export const openOnHostLabel = (provider: string): string =>
+ OPEN_ON_HOST_LABELS[provider] ?? "Open on host";
+
+/** Copy first: it is the reason to right-click a number rather than click it. */
+export function pullRequestLinkContextMenuItems(
+ openLabel: string,
+): readonly ContextMenuItem<PullRequestLinkContextMenuAction>[] {
+ return [
+ { id: "copy-link", label: "Copy link", icon: "copy" },
+ { id: "open-external", label: openLabel },
+ ];
+}
+
+/**
+ * The right-click on a change request's number. Everywhere else that number is written it is a
+ * link, and the gesture that copies a link is the one hand reaches for — so without this the
+ * platform's own edit menu opens over a control that has nothing to cut, paste or select.
+ *
+ * The host is named by the caller rather than guessed here: the same number belongs to GitHub,
+ * GitLab, Bitbucket or Azure DevOps depending on where it was read, and the `url` the contract
+ * carries is already whichever of them it came from.
+ */
+export async function showPullRequestLinkContextMenu({
+ url,
+ openLabel,
+ position,
+}: {
+ readonly url: string;
+ readonly openLabel: string;
+ readonly position: { readonly x: number; readonly y: number };
+}): Promise<void> {
+ const api = readLocalApi();
+ if (!api) return;
+ let action: PullRequestLinkContextMenuAction | null = null;
+ try {
+ action = await api.contextMenu.show(pullRequestLinkContextMenuItems(openLabel), position);
+ } catch {
+ // A menu that could not be shown has already cost the reader their right-click; there is
+ // nothing to say about it that a second popup would not make worse.
+ return;
+ }
+ try {
+ if (action === "copy-link") await writeTextToClipboard(url, "link");
+ else if (action === "open-external") await api.shell.openExternal(url);
+ } catch {
+ toastManager.add({
+ type: "error",
+ title: action === "copy-link" ? "Could not copy the link" : "Could not open the link",
+ });
+ }
+}
diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
index 11f5f86d4..b0580a72a 100644
--- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
@@ -1,10 +1,16 @@
-import type { PullRequestListEntry } from "@t3tools/contracts";
+import type { EnvironmentId, PullRequestListEntry } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
filterPullRequestsByInvolvement,
+ findScopedProject,
+ mergePullRequestLists,
+ pullRequestEntryKey,
+ pullRequestEnvironmentSetKey,
groupPullRequestsByInvolvement,
+ matchesPullRequestFilters,
matchesPullRequestQuery,
+ parsePullRequestQuery,
mergePullRequestDiffStats,
narrowPullRequestsToFilters,
partitionPullRequestsWithPriority,
@@ -14,13 +20,19 @@ import {
scorePullRequestMatch,
withDiffStat,
resolveProjectScope,
+ resolveQueryEnvironmentIds,
+ resolveSelectedEnvironmentId,
+ type EnvironmentPullRequestEntry,
} from "./pullRequestList.logic";
const VIEWERS = { "github.com": "Bilal" } as const;
const NO_VIEWERS = {} as const;
-function entry(overrides: Partial<PullRequestListEntry> & Pick<PullRequestListEntry, "number">) {
+function entry(
+ overrides: Partial<EnvironmentPullRequestEntry> & Pick<PullRequestListEntry, "number">,
+) {
return {
+ environmentId: "env-1",
provider: "github",
host: "github.com",
projectId: "project-1",
@@ -41,7 +53,7 @@ function entry(overrides: Partial<PullRequestListEntry> & Pick<PullRequestListEn
viewerReviewRequested: false,
labels: [],
...overrides,
- } as PullRequestListEntry;
+ } as EnvironmentPullRequestEntry;
}
describe("pull request involvement filtering", () => {
@@ -208,6 +220,172 @@ describe("carrying rows already read into filters nothing has answered yet", ()
});
});
+describe("narrowing rows by the filters a host may not have applied", () => {
+ const rows = [
+ entry({ number: 1 }),
+ entry({ number: 2, isDraft: true }),
+ entry({ number: 3, reviewDecision: "approved" }),
+ entry({
+ number: 4,
+ labels: [{ name: "Needs design", color: null }],
+ author: { login: "Hubot", name: null, avatarUrl: null },
+ reviewDecision: "changes-requested",
+ }),
+ ];
+ const narrow = (filters: Parameters<typeof matchesPullRequestFilters>[1]) =>
+ rows.filter((row) => matchesPullRequestFilters(row, filters)).map((row) => row.number);
+
+ it("keeps or drops drafts as asked", () => {
+ expect(narrow({ draft: "only" })).toEqual([2]);
+ expect(narrow({ draft: "hide" })).toEqual([1, 3, 4]);
+ });
+
+ it("keeps the review state that was asked for, and no reviews means none at all", () => {
+ expect(narrow({ review: "approved" })).toEqual([3]);
+ expect(narrow({ review: "changes-requested" })).toEqual([4]);
+ expect(narrow({ review: "none" })).toEqual([1, 2]);
+ });
+
+ it("matches labels and authors however either was capitalized", () => {
+ expect(narrow({ labels: [["needs DESIGN"]] })).toEqual([4]);
+ expect(narrow({ excludedLabels: ["needs design"] })).toEqual([1, 2, 3]);
+ expect(narrow({ author: "hubot" })).toEqual([4]);
+ });
+
+ it("resolves author:me to the given viewer, case-insensitively", () => {
+ const mine = entry({ number: 30, author: { login: "Bilal", name: null, avatarUrl: null } });
+ const theirs = entry({ number: 31, author: { login: "Hubot", name: null, avatarUrl: null } });
+ expect(matchesPullRequestFilters(mine, { author: "me" }, "bilal")).toBe(true);
+ expect(matchesPullRequestFilters(theirs, { author: "me" }, "bilal")).toBe(false);
+ });
+
+ it("resolves author:@me the same way as author:me", () => {
+ const mine = entry({ number: 32, author: { login: "Bilal", name: null, avatarUrl: null } });
+ const theirs = entry({ number: 33, author: { login: "Hubot", name: null, avatarUrl: null } });
+ expect(matchesPullRequestFilters(mine, { author: "@me" }, "Bilal")).toBe(true);
+ expect(matchesPullRequestFilters(theirs, { author: "@me" }, "Bilal")).toBe(false);
+ });
+
+ it("compares author:me against the literal name when there is no viewer", () => {
+ const literalMe = entry({ number: 34, author: { login: "me", name: null, avatarUrl: null } });
+ const someoneElse = entry({
+ number: 35,
+ author: { login: "Bilal", name: null, avatarUrl: null },
+ });
+ expect(matchesPullRequestFilters(literalMe, { author: "me" })).toBe(true);
+ expect(matchesPullRequestFilters(someoneElse, { author: "me" })).toBe(false);
+ });
+
+ it("takes a group of labels as an either-or", () => {
+ const sized = [
+ entry({ number: 10, labels: [{ name: "size:S", color: null }] }),
+ entry({ number: 11, labels: [{ name: "size:XS", color: null }] }),
+ entry({ number: 12, labels: [{ name: "size:L", color: null }] }),
+ ];
+ const kept = (labels: ReadonlyArray<ReadonlyArray<string>>) =>
+ sized.filter((row) => matchesPullRequestFilters(row, { labels })).map((row) => row.number);
+
+ expect(kept([["size:S", "size:XS"]])).toEqual([10, 11]);
+ expect(kept([["size:XXL"]])).toEqual([]);
+ });
+
+ it("takes two groups as an and, each satisfied on its own", () => {
+ const row = entry({
+ number: 20,
+ labels: [
+ { name: "size:S", color: null },
+ { name: "bug", color: null },
+ ],
+ });
+ expect(matchesPullRequestFilters(row, { labels: [["size:S", "size:XS"], ["bug"]] })).toBe(true);
+ // The second group holds nothing this row carries, so the first one satisfied is not enough.
+ expect(matchesPullRequestFilters(row, { labels: [["size:S"], ["wip"]] })).toBe(false);
+ });
+
+ it("holds on to every row for a filter no row carries the answer to", () => {
+ expect(narrow({ checks: "passing" })).toEqual([1, 2, 3, 4]);
+ });
+});
+
+describe("reading qualifiers out of a typed query", () => {
+ it("keeps quoted values whole and separates negation", () => {
+ expect(parsePullRequestQuery('label:"needs design" -label:wip Fix the parser')).toEqual({
+ text: "Fix the parser",
+ filters: { labels: [["needs design"]], excludedLabels: ["wip"] },
+ });
+ });
+
+ it("reads a comma-separated list as one group either name satisfies", () => {
+ expect(parsePullRequestQuery("label:size:S,size:XS").filters.labels).toEqual([
+ ["size:S", "size:XS"],
+ ]);
+ });
+
+ it("keeps the spaces in a quoted name of a list, and drops an empty part", () => {
+ expect(parsePullRequestQuery('label:"needs design","wip"').filters.labels).toEqual([
+ ["needs design", "wip"],
+ ]);
+ expect(parsePullRequestQuery("label:a,,b").filters.labels).toEqual([["a", "b"]]);
+ });
+
+ it("excludes every name of a negated list", () => {
+ expect(parsePullRequestQuery("-label:a,b").filters).toEqual({ excludedLabels: ["a", "b"] });
+ });
+
+ it("makes each label qualifier its own group, so the groups are an AND", () => {
+ expect(parsePullRequestQuery("label:bug label:a,b").filters.labels).toEqual([
+ ["bug"],
+ ["a", "b"],
+ ]);
+ });
+
+ it("reads the scalar qualifiers in GitHub's own spelling", () => {
+ expect(
+ parsePullRequestQuery("author:octocat DRAFT:false review:changes_requested status:failure")
+ .filters,
+ ).toEqual({
+ author: "octocat",
+ draft: "hide",
+ review: "changes-requested",
+ checks: "failing",
+ });
+ });
+
+ it("leaves an unknown value and a stray colon as text, and reads an unknown key as a label", () => {
+ const parsed = parsePullRequestQuery("milestone:v2 draft:maybe status: parser");
+ expect(parsed.filters).toEqual({ labels: [["milestone:v2"]] });
+ // A known key whose value it does not take is text, so "status:" itself stays findable.
+ expect(parsed.text).toBe("draft:maybe status: parser");
+ });
+
+ it("reads a quoted name holding a comma as the one label it is", () => {
+ expect(parsePullRequestQuery('label:"needs,triage"').filters.labels).toEqual([
+ ["needs,triage"],
+ ]);
+ expect(parsePullRequestQuery('-label:"needs,triage"').filters.excludedLabels).toEqual([
+ "needs,triage",
+ ]);
+ });
+
+ it("cuts a typed query back to what the contract carries", () => {
+ const many = Array.from({ length: 14 }, (_, index) => `l${index}`).join(",");
+ const long = "x".repeat(240);
+ const parsed = parsePullRequestQuery(`label:${many} label:${long} author:${long}`);
+ expect(parsed.filters.labels?.[0]).toHaveLength(10);
+ expect(parsed.filters.labels?.[1]).toEqual(["x".repeat(200)]);
+ expect(parsed.filters.author).toBe("x".repeat(200));
+ });
+
+ it("cuts a namespaced label after its key is prefixed on", () => {
+ const parsed = parsePullRequestQuery(`size:${"x".repeat(240)}`);
+ expect(parsed.filters.labels).toEqual([[`size:${"x".repeat(240)}`.slice(0, 200)]]);
+ });
+
+ it("answers an empty query with an empty everything", () => {
+ expect(parsePullRequestQuery(" ")).toEqual({ text: "", filters: {} });
+ });
+});
+
describe("resolveProjectScope", () => {
const projects = [{ id: "p1" }, { id: "p2" }];
@@ -283,7 +461,7 @@ describe("ranking what a search found", () => {
});
describe("line counts that arrive after the rows", () => {
- const stats = new Map([["project-1 7", { additions: 42, deletions: 3 }]]);
+ const stats = new Map([["env-1 project-1 7", { additions: 42, deletions: 3 }]]);
it("fills in a row whose host left the counts for later", () => {
const row = entry({ number: 7, additions: 0, deletions: 0 });
@@ -304,33 +482,33 @@ describe("line counts that arrive after the rows", () => {
describe("merging line counts across keyed stats queries", () => {
it("keeps counts already held while a fresh batch says nothing about them", () => {
const held = mergePullRequestDiffStats(new Map(), [
- { projectId: "project-1", number: 1, additions: 10, deletions: 2 },
- { projectId: "project-1", number: 2, additions: 5, deletions: 1 },
+ { environmentId: "env-1", projectId: "project-1", number: 1, additions: 10, deletions: 2 },
+ { environmentId: "env-1", projectId: "project-1", number: 2, additions: 5, deletions: 1 },
]);
// A third row appeared; its batch is still pending and contributes nothing yet.
const merged = mergePullRequestDiffStats(held, []);
- expect(merged.get("project-1 1")).toEqual({ additions: 10, deletions: 2 });
- expect(merged.get("project-1 2")).toEqual({ additions: 5, deletions: 1 });
+ expect(merged.get("env-1 project-1 1")).toEqual({ additions: 10, deletions: 2 });
+ expect(merged.get("env-1 project-1 2")).toEqual({ additions: 5, deletions: 1 });
});
it("replaces a count once its replacement arrives, keeping its neighbours", () => {
const held = mergePullRequestDiffStats(new Map(), [
- { projectId: "project-1", number: 1, additions: 10, deletions: 2 },
+ { environmentId: "env-1", projectId: "project-1", number: 1, additions: 10, deletions: 2 },
]);
const merged = mergePullRequestDiffStats(held, [
- { projectId: "project-1", number: 1, additions: 11, deletions: 2 },
- { projectId: "project-1", number: 3, additions: 7, deletions: 0 },
+ { environmentId: "env-1", projectId: "project-1", number: 1, additions: 11, deletions: 2 },
+ { environmentId: "env-1", projectId: "project-1", number: 3, additions: 7, deletions: 0 },
]);
- expect(merged.get("project-1 1")).toEqual({ additions: 11, deletions: 2 });
- expect(merged.get("project-1 3")).toEqual({ additions: 7, deletions: 0 });
+ expect(merged.get("env-1 project-1 1")).toEqual({ additions: 11, deletions: 2 });
+ expect(merged.get("env-1 project-1 3")).toEqual({ additions: 7, deletions: 0 });
});
it("does not mutate the map it was handed", () => {
- const held = new Map([["project-1 1", { additions: 1, deletions: 1 }]]);
+ const held = new Map([["env-1 project-1 1", { additions: 1, deletions: 1 }]]);
mergePullRequestDiffStats(held, [
- { projectId: "project-1", number: 1, additions: 2, deletions: 2 },
+ { environmentId: "env-1", projectId: "project-1", number: 1, additions: 2, deletions: 2 },
]);
- expect(held.get("project-1 1")).toEqual({ additions: 1, deletions: 1 });
+ expect(held.get("env-1 project-1 1")).toEqual({ additions: 1, deletions: 1 });
});
});
@@ -442,4 +620,384 @@ describe("the list snapshot across a reload", () => {
expect(readPullRequestListSnapshot(storage, "env-1")).toBeNull();
expect(readPullRequestListSnapshot(undefined, "env-1")).toBeNull();
});
+
+ it("caps the accumulated rows but keeps the whole host set", () => {
+ // The page keeps growing as the reader scrolls, so what gets written is the accumulated
+ // list rather than one round's answer — capped at the one page a cold start needs, while
+ // the hosts it was read from (which do not grow with the page) are kept in full.
+ const storage = makeStorage();
+ const manyEntries = Array.from({ length: 120 }, (_, index) => entry({ number: index + 1 }));
+ const viewers = { "github.com": "Bilal", "gitlab.com": "Bilal" };
+ const providers = [
+ {
+ host: "github.com",
+ kind: "github",
+ searchesOnHost: true,
+ projectCount: 1,
+ configured: true,
+ detail: null,
+ },
+ {
+ host: "gitlab.com",
+ kind: "gitlab",
+ searchesOnHost: true,
+ projectCount: 1,
+ configured: true,
+ detail: null,
+ },
+ ];
+ const accumulated = {
+ entries: manyEntries,
+ viewers,
+ providers,
+ errors: [],
+ truncated: true,
+ nextCursors: {},
+ } as never;
+ writePullRequestListSnapshot(storage, "env-1", { scope: "s", data: accumulated });
+ const snapshot = readPullRequestListSnapshot(storage, "env-1");
+ expect(snapshot?.data.entries).toHaveLength(99);
+ expect(snapshot?.data.viewers).toEqual(viewers);
+ expect(snapshot?.data.providers).toEqual(providers);
+ });
+});
+
+const ENV_1 = "env-1" as EnvironmentId;
+const ENV_2 = "env-2" as EnvironmentId;
+
+describe("merging the environments' own listings", () => {
+ const answer = (
+ overrides: Partial<Parameters<typeof mergePullRequestLists>[0][number][1]> = {},
+ ) =>
+ ({
+ viewers: { "github.com": "Bilal" },
+ providers: [
+ {
+ host: "github.com",
+ kind: "github",
+ searchesOnHost: true,
+ projectCount: 1,
+ configured: true,
+ detail: null,
+ },
+ ],
+ entries: [],
+ errors: [],
+ truncated: false,
+ nextCursors: {},
+ ...overrides,
+ }) as Parameters<typeof mergePullRequestLists>[0][number][1];
+
+ it("answers nothing until an environment has", () => {
+ expect(mergePullRequestLists([])).toBeNull();
+ });
+
+ it("tags every row with the environment that read it, newest first", () => {
+ const merged = mergePullRequestLists([
+ [ENV_1, answer({ entries: [entry({ number: 1, updatedAt: "2026-07-01T00:00:00Z" })] })],
+ [ENV_2, answer({ entries: [entry({ number: 2, updatedAt: "2026-08-01T00:00:00Z" })] })],
+ ]);
+ expect(merged?.entries.map((row) => [row.environmentId, row.number])).toEqual([
+ [ENV_2, 2],
+ [ENV_1, 1],
+ ]);
+ });
+
+ it("tells two environments' copies of one pull request apart", () => {
+ const row = entry({ number: 4 });
+ expect(pullRequestEntryKey({ ...row, environmentId: ENV_1 })).not.toBe(
+ pullRequestEntryKey({ ...row, environmentId: ENV_2 }),
+ );
+ });
+
+ it("folds a host reached from two environments into one switcher row", () => {
+ const merged = mergePullRequestLists([
+ [ENV_1, answer()],
+ [
+ ENV_2,
+ answer({
+ providers: [
+ {
+ host: "github.com",
+ kind: "github",
+ searchesOnHost: false,
+ projectCount: 2,
+ configured: false,
+ detail: "Not signed in.",
+ },
+ ],
+ }),
+ ],
+ ]);
+ // Readable because one environment could read it, but narrowed locally because the other
+ // answers unsearched.
+ expect(merged?.providers).toEqual([
+ {
+ host: "github.com",
+ kind: "github",
+ searchesOnHost: false,
+ projectCount: 3,
+ configured: true,
+ detail: null,
+ },
+ ]);
+ });
+
+ it("keeps each environment's continuation to itself", () => {
+ const merged = mergePullRequestLists([
+ [ENV_1, answer({ nextCursors: { "github.com pingdotgg/t3code": "cursor-1" } })],
+ [ENV_2, answer()],
+ ]);
+ expect(merged?.nextCursors).toEqual({
+ [ENV_1]: { "github.com pingdotgg/t3code": "cursor-1" },
+ });
+ });
+
+ it("reads the same key whichever order the environments connected in", () => {
+ expect(pullRequestEnvironmentSetKey(["env-2", "env-1"])).toBe(
+ pullRequestEnvironmentSetKey(["env-1", "env-2"]),
+ );
+ });
+});
+
+describe('who "I" am, per server', () => {
+ const answer = (viewers: Record<string, string>, entries: ReadonlyArray<PullRequestListEntry>) =>
+ ({
+ viewers,
+ providers: [],
+ entries,
+ errors: [],
+ truncated: false,
+ nextCursors: {},
+ }) as Parameters<typeof mergePullRequestLists>[0][number][1];
+ const byBilal = { login: "Bilal", name: null, avatarUrl: null };
+
+ it("does not let one server's account decide who authored another server's rows", () => {
+ // Both servers reach github.com, signed in as different people. Folded into one host-keyed
+ // record, whichever answered last spoke for both — and every row of the reader's own work
+ // was filed under Others.
+ const merged = mergePullRequestLists([
+ [ENV_1, answer({ "github.com": "Bilal" }, [entry({ number: 1, author: byBilal })])],
+ [ENV_2, answer({ "github.com": "Octocat" }, [entry({ number: 2, author: byBilal })])],
+ ])!;
+
+ const groups = groupPullRequestsByInvolvement(merged.entries, merged.viewers);
+ expect(
+ groups.find((group) => group.key === "authored")?.entries.map((row) => row.number),
+ ).toEqual([1]);
+ expect(
+ filterPullRequestsByInvolvement(merged.entries, merged.viewers, "authored").map(
+ (row) => row.number,
+ ),
+ ).toEqual([1]);
+ });
+
+ it("still reads a single server's host-keyed viewers, which is what a snapshot carries", () => {
+ expect(
+ filterPullRequestsByInvolvement(
+ [entry({ number: 1, author: byBilal })],
+ { "github.com": "Bilal" },
+ "authored",
+ ).map((row) => row.number),
+ ).toEqual([1]);
+ });
+
+ it("names the servers with more rows and no cursor to reach them by", () => {
+ const merged = mergePullRequestLists([
+ [
+ ENV_1,
+ { ...answer({}, []), truncated: true, nextCursors: { "github.com acme/web": "cursor-1" } },
+ ],
+ [ENV_2, { ...answer({}, []), truncated: true }],
+ ])!;
+
+ expect(merged.truncatedEnvironments).toEqual([ENV_1, ENV_2]);
+ expect(Object.keys(merged.nextCursors)).toEqual([ENV_1]);
+ });
+});
+
+describe("the project an id names", () => {
+ const projects = [
+ { id: "project-1", environmentId: ENV_1 },
+ { id: "project-1", environmentId: ENV_2 },
+ { id: "project-2", environmentId: ENV_2 },
+ ];
+
+ it("takes the server it was given", () => {
+ expect(findScopedProject(projects, ENV_2, "project-1")?.environmentId).toBe(ENV_2);
+ });
+
+ it("answers a bare id only where one server has it", () => {
+ expect(findScopedProject(projects, null, "project-2")?.environmentId).toBe(ENV_2);
+ // Two servers hold this id: narrowing to either would be a coin toss the reader cannot see.
+ expect(findScopedProject(projects, null, "project-1")).toBeUndefined();
+ });
+
+ it("answers nothing for a server that does not have it", () => {
+ expect(findScopedProject(projects, ENV_1, "project-2")).toBeUndefined();
+ });
+});
+
+describe("which environments a listing should ask", () => {
+ const ENV_3 = "env-3" as EnvironmentId;
+ const environmentIds = [ENV_1, ENV_2, ENV_3];
+
+ it("asks only the owning server once the project is unambiguous", () => {
+ const projects = [{ id: "project-1", environmentId: ENV_2 }];
+ expect(
+ resolveQueryEnvironmentIds(
+ environmentIds,
+ projects,
+ { environmentId: ENV_2 },
+ "project-1",
+ true,
+ ),
+ ).toEqual([ENV_2]);
+ });
+
+ it("asks every environment when there is no project narrowing at all", () => {
+ expect(resolveQueryEnvironmentIds(environmentIds, [], undefined, undefined, true)).toEqual(
+ environmentIds,
+ );
+ });
+
+ it("asks only the environments that actually hold an ambiguous bare id, never a third that doesn't", () => {
+ const projects = [
+ { id: "project-1", environmentId: ENV_1 },
+ { id: "project-1", environmentId: ENV_2 },
+ ];
+ // Two servers can genuinely hold the same project id string; the third holds no such project
+ // and asking it would return an unrelated project's rows rather than an honest empty answer.
+ expect(
+ resolveQueryEnvironmentIds(environmentIds, projects, undefined, "project-1", true),
+ ).toEqual([ENV_1, ENV_2]);
+ });
+
+ it("asks nothing for a bare id no environment holds", () => {
+ const projects = [{ id: "project-1", environmentId: ENV_1 }];
+ expect(
+ resolveQueryEnvironmentIds(environmentIds, projects, undefined, "project-9", true),
+ ).toEqual([]);
+ });
+
+ it("asks every environment while the servers have not said what they hold yet", () => {
+ // Nothing matches the id because nothing has been read yet, which is not the same answer as
+ // no server holding it: reading none of them would show an empty page for a project that is
+ // there.
+ expect(resolveQueryEnvironmentIds(environmentIds, [], undefined, "project-1", false)).toEqual(
+ environmentIds,
+ );
+ });
+
+ it("keeps the single-environment case unchanged", () => {
+ const projects = [{ id: "project-1", environmentId: ENV_1 }];
+ expect(resolveQueryEnvironmentIds([ENV_1], projects, undefined, "project-1", true)).toEqual([
+ ENV_1,
+ ]);
+ });
+});
+
+describe("the server a saved selection names", () => {
+ const known = new Set([ENV_1, ENV_2]);
+
+ it("resolves to nothing yet for a server that is known but not ready, rather than falling back", () => {
+ // ENV_2 is in the catalog (still connecting, say) but not the fallback; a caller that then
+ // looks a project up under ENV_2 finds none rather than one belonging to the fallback server.
+ expect(resolveSelectedEnvironmentId(ENV_2, known, ENV_1)).toBe(ENV_2);
+ });
+
+ it("falls back for a server the workspace genuinely no longer has", () => {
+ const goneServer = "env-gone" as EnvironmentId;
+ expect(resolveSelectedEnvironmentId(goneServer, known, ENV_1)).toBe(ENV_1);
+ });
+
+ it("falls back to nothing when no server names a fallback either", () => {
+ const goneServer = "env-gone" as EnvironmentId;
+ expect(resolveSelectedEnvironmentId(goneServer, known, null)).toBeNull();
+ });
+
+ it("uses the fallback outright when nothing was named", () => {
+ expect(resolveSelectedEnvironmentId(undefined, known, ENV_1)).toBe(ENV_1);
+ expect(resolveSelectedEnvironmentId(undefined, known, null)).toBeNull();
+ });
+});
+
+describe("colon-namespaced labels typed as a search", () => {
+ it("reads an unknown key as the label it almost always is", () => {
+ expect(parsePullRequestQuery("size:XXL").filters.labels).toEqual([["size:XXL"]]);
+ expect(parsePullRequestQuery("vouch:trusted").filters.labels).toEqual([["vouch:trusted"]]);
+ expect(parsePullRequestQuery("size:XXL").text).toBe("");
+ });
+
+ it("reads the key as the namespace of every bare name in its list", () => {
+ expect(parsePullRequestQuery("size:S,XS").filters.labels).toEqual([["size:S", "size:XS"]]);
+ });
+
+ it("leaves a name that already carries its own namespace alone", () => {
+ // `size:S,size:XS` is the same pair written out; prefixing again would ask for `size:size:XS`.
+ expect(parsePullRequestQuery("size:S,size:XS").filters.labels).toEqual([["size:S", "size:XS"]]);
+ });
+
+ it("excludes one the same way", () => {
+ expect(parsePullRequestQuery("-size:XXL").filters.excludedLabels).toEqual(["size:XXL"]);
+ expect(parsePullRequestQuery("-size:S,XS").filters.excludedLabels).toEqual([
+ "size:S",
+ "size:XS",
+ ]);
+ });
+
+ it("keeps a quoted token as text, which is the way back to a literal search", () => {
+ const parsed = parsePullRequestQuery('"size:XXL"');
+ expect(parsed.filters.labels).toBeUndefined();
+ expect(parsed.text).toBe('"size:XXL"');
+ });
+
+ it("reads a hyphenated namespace as a label too", () => {
+ expect(parsePullRequestQuery("priority-1:high").filters.labels).toEqual([["priority-1:high"]]);
+ expect(parsePullRequestQuery("priority-1:high").text).toBe("");
+ });
+
+ it("leaves a pasted link alone rather than naming a label after its scheme", () => {
+ const parsed = parsePullRequestQuery("https://github.com/pingdotgg/t3code/pull/1");
+ expect(parsed.filters.labels).toBeUndefined();
+ expect(parsed.text).toBe("https://github.com/pingdotgg/t3code/pull/1");
+ });
+
+ it("mixes with the keys it does know, and with plain words", () => {
+ const parsed = parsePullRequestQuery("area:web draft:true wizard label:bug");
+ expect(parsed.filters).toEqual({ labels: [["area:web"], ["bug"]], draft: "only" });
+ expect(parsed.text).toBe("wizard");
+ });
+
+ it("shares the ceiling with the labels typed as labels", () => {
+ const many = Array.from({ length: 12 }, (_, index) => `area:${index}`).join(" ");
+ expect(parsePullRequestQuery(many).filters.labels).toHaveLength(10);
+ });
+});
+
+describe("the priority groups against a paginated feed", () => {
+ const authoredRow = (number: number, updatedAt: string) =>
+ entry({ number, updatedAt, author: { login: "Bilal", name: null, avatarUrl: null } });
+
+ it("shows every authored row the host reported, not only the ones the feed page holds", () => {
+ // The feed is one page ordered by recency, so on a busy repository it can hold exactly one of
+ // somebody's own pull requests while the rest sit further down the host's list. The Authored
+ // group comes from its own server-filtered read for that reason: grouping the page instead
+ // leaves the older ones under Others, or off the page altogether.
+ const newest = authoredRow(6039, "2026-08-11T08:00:00Z");
+ const older = [
+ authoredRow(5499, "2026-08-10T17:00:00Z"),
+ authoredRow(5544, "2026-08-10T16:00:00Z"),
+ ];
+ const feed = [newest, entry({ number: 6123, updatedAt: "2026-08-11T09:00:00Z" })];
+
+ const groups = partitionPullRequestsWithPriority(feed, [newest, ...older], []);
+
+ expect(
+ groups.find((group) => group.key === "authored")?.entries.map((row) => row.number),
+ ).toEqual([6039, 5499, 5544]);
+ expect(
+ groups.find((group) => group.key === "others")?.entries.map((row) => row.number),
+ ).toEqual([6123]);
+ });
});
diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.ts
index 059004447..c27797f51 100644
--- a/apps/web/src/components/pullRequest/pullRequestList.logic.ts
+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.ts
@@ -1,19 +1,54 @@
import * as Schema from "effect/Schema";
-import { PullRequestListEntry, PullRequestListResult } from "@t3tools/contracts";
-import type { PullRequestInvolvement, PullRequestListState } from "@t3tools/contracts";
+import {
+ EnvironmentId,
+ PullRequestListEntry,
+ PullRequestListResult,
+ resolvePullRequestAuthorFilter,
+} from "@t3tools/contracts";
+import type {
+ PullRequestDiffStat,
+ PullRequestInvolvement,
+ PullRequestListCursors,
+ PullRequestListFilters,
+ PullRequestListState,
+} from "@t3tools/contracts";
+
+/**
+ * A listed change request with the environment that read it. Nothing on a row says which machine
+ * it came from, and the page unions every connected one — so acting on a row, refreshing it, or
+ * opening its detail all need the tag the listing itself does not carry.
+ */
+export interface EnvironmentPullRequestEntry extends PullRequestListEntry {
+ readonly environmentId: EnvironmentId;
+}
+
+export interface EnvironmentPullRequestStat extends PullRequestDiffStat {
+ readonly environmentId: EnvironmentId;
+}
export type PullRequestGroupKey = "reviewRequested" | "authored" | "others";
-export interface PullRequestGroup {
+export interface PullRequestGroup<Entry extends PullRequestListEntry = PullRequestListEntry> {
readonly key: PullRequestGroupKey;
readonly label: string;
- readonly entries: ReadonlyArray<PullRequestListEntry>;
+ readonly entries: ReadonlyArray<Entry>;
}
-/** The signed-in account per host, as the listing reports it. */
+/**
+ * The signed-in account per host. Keyed `"<environmentId> <host>"` once a listing spans more than
+ * one environment: two machines can both reach github.com signed in as different people, and a
+ * single host-keyed record would let whichever answered last decide who "I" am — which is how
+ * every row of somebody's own work came to be filed under Others.
+ */
export type PullRequestViewers = PullRequestListResult["viewers"];
+/** A row plus the environment that read it, where the caller has one to give. */
+type ScopedEntry = PullRequestListEntry & { readonly environmentId?: string };
+
+export const pullRequestViewerKey = (entry: ScopedEntry): string =>
+ `${entry.environmentId ?? ""} ${entry.host}`;
+
const GROUP_LABELS: Record<PullRequestGroupKey, string> = {
reviewRequested: "Review requested",
authored: "Authored",
@@ -25,16 +60,181 @@ function normalize(value: string | null | undefined): string | null {
return trimmed.length > 0 ? trimmed : null;
}
+/**
+ * The signed-in login for the host a row came from, or null where none was given. Shared by
+ * authorship matching here and by `author:me` resolution wherever a row's own viewer is needed.
+ */
+export function pullRequestEntryViewer(
+ entry: ScopedEntry,
+ viewers: PullRequestViewers,
+): string | null {
+ // The environment's own answer first; a plain host key is what a single-environment listing
+ // still writes, and what the snapshot from one carries.
+ return normalize(viewers[pullRequestViewerKey(entry)] ?? viewers[entry.host]);
+}
+
/**
* Authorship is per host, not per provider kind: the same list can hold change requests from
* GitHub, GitLab and a GitHub Enterprise install, and the account that owns one says nothing
* about the others.
*/
-function isAuthoredByViewer(entry: PullRequestListEntry, viewers: PullRequestViewers): boolean {
- const viewer = normalize(viewers[entry.host]);
+function isAuthoredByViewer(entry: ScopedEntry, viewers: PullRequestViewers): boolean {
+ const viewer = pullRequestEntryViewer(entry, viewers);
return viewer !== null && normalize(entry.author?.login) === viewer;
}
+/** What `review:` and `status:` take, in GitHub's spelling and in the contract's. */
+const REVIEW_VALUES: Record<string, PullRequestListFilters["review"]> = {
+ approved: "approved",
+ changes_requested: "changes-requested",
+ "changes-requested": "changes-requested",
+ required: "review-required",
+ "review-required": "review-required",
+ none: "none",
+};
+const CHECKS_VALUES: Record<string, PullRequestListFilters["checks"]> = {
+ success: "passing",
+ passing: "passing",
+ failure: "failing",
+ failing: "failing",
+};
+
+/**
+ * One token of a typed query: a run of non-space characters in which a quoted stretch counts as
+ * part of the token, so `label:"needs design"` stays whole. An unbalanced quote is dropped rather
+ * than swallowing the rest of the line.
+ */
+const QUERY_TOKEN = /(?:[^\s"]|"[^"]*")+/g;
+/** The contract's own ceilings on a qualifier: this many names, each this long. */
+const MAX_QUALIFIER_VALUES = 10;
+const MAX_QUALIFIER_LENGTH = 200;
+
+function qualifierValue(raw: string): string {
+ return raw.replaceAll('"', "").trim();
+}
+
+/** A qualifier's value as the list it may be: split on commas, each name unquoted on its own. */
+function splitQualifierList(raw: string): string[] {
+ // Quoting names one whole label however many commas it holds: `label:"needs,triage"` asks for
+ // the label written that way, not for either half of it.
+ if (/^\s*"[^"]*"\s*$/.test(raw)) {
+ const whole = qualifierValue(raw);
+ return whole.length === 0 ? [] : [whole];
+ }
+ return raw
+ .split(",")
+ .map((part) => qualifierValue(part))
+ .filter((part) => part.length > 0);
+}
+
+/**
+ * A typed query is written by hand, and the contract bounds what a qualifier may carry — so what
+ * is typed past those bounds is cut here rather than refused by the request that carries it.
+ */
+function boundedNames(names: ReadonlyArray<string>): string[] {
+ return names
+ .slice(0, MAX_QUALIFIER_VALUES)
+ .map((name) => name.slice(0, MAX_QUALIFIER_LENGTH).trim())
+ .filter((name) => name.length > 0);
+}
+
+/**
+ * A typed query split into the qualifiers the hosts can act on and the text that is left. Written
+ * GitHub's way — `label:foo`, `-label:"needs design"`, `author:octocat`, `draft:true`,
+ * `review:approved`, `status:success` — because a project's labels are its own and a menu cannot
+ * list them.
+ *
+ * A key this does not know is read as a label of that whole name: repositories namespace their
+ * labels with a colon — `size:XXL`, `area:web`, `vouch:trusted` — and someone typing one means
+ * the label, not a description that happens to contain it. `-size:XXL` excludes the same way.
+ *
+ * Quoting is the way back to plain text: `"size:XXL"` is searched for as written, which is what
+ * makes a literal search for a colon still possible. A known key whose value it does not take is
+ * text too, so a search for "status:" itself is still findable.
+ */
+export function parsePullRequestQuery(raw: string): {
+ readonly text: string;
+ readonly filters: PullRequestListFilters;
+} {
+ const text: string[] = [];
+ const labels: string[][] = [];
+ const excludedLabels: string[] = [];
+ let author: string | undefined;
+ let draft: PullRequestListFilters["draft"];
+ let review: PullRequestListFilters["review"];
+ let checks: PullRequestListFilters["checks"];
+ for (const [token] of raw.matchAll(QUERY_TOKEN)) {
+ const qualifier = /^(-?)([A-Za-z][A-Za-z0-9_-]*):(.*)$/.exec(token);
+ const value = qualifier === null ? "" : qualifierValue(qualifier[3] ?? "");
+ const negated = qualifier?.[1] === "-";
+ switch (value.length === 0 ? "" : (qualifier?.[2]?.toLowerCase() ?? "")) {
+ case "label": {
+ // GitHub's own OR: `label:a,b` is one qualifier satisfied by either name. Negated, the
+ // comma excludes each — a row carrying any of them goes.
+ const names = boundedNames(splitQualifierList(qualifier?.[3] ?? ""));
+ if (names.length === 0) break;
+ if (negated) excludedLabels.push(...names);
+ else labels.push(names);
+ continue;
+ }
+ case "author":
+ if (negated) break;
+ author = value.slice(0, MAX_QUALIFIER_LENGTH).trim();
+ continue;
+ case "draft":
+ if (negated || (value.toLowerCase() !== "true" && value.toLowerCase() !== "false")) break;
+ draft = value.toLowerCase() === "true" ? "only" : "hide";
+ continue;
+ case "review": {
+ const decision = negated ? undefined : REVIEW_VALUES[value.toLowerCase()];
+ if (decision === undefined) break;
+ review = decision;
+ continue;
+ }
+ case "status":
+ case "checks": {
+ const state = negated ? undefined : CHECKS_VALUES[value.toLowerCase()];
+ if (state === undefined) break;
+ checks = state;
+ continue;
+ }
+ case "":
+ break;
+ default:
+ // An unknown key, read as the namespaced label it almost always is. A pasted link is
+ // not one — `https://…` would otherwise become a label named after its own scheme.
+ if (!value.startsWith("/")) {
+ // The key names the namespace, so the bare parts of `size:S,XS` are both sizes. A part
+ // that already carries a colon names its whole label — `size:S,size:XS` is the same
+ // pair written out, and prefixing it again would ask for `size:size:XS`.
+ const names = boundedNames(
+ splitQualifierList(qualifier?.[3] ?? "").map((name) =>
+ name.includes(":") ? name : `${qualifier?.[2] ?? ""}:${name}`,
+ ),
+ );
+ if (names.length === 0) break;
+ if (negated) excludedLabels.push(...names);
+ else labels.push(names);
+ continue;
+ }
+ }
+ text.push(token);
+ }
+ return {
+ text: text.join(" "),
+ filters: {
+ ...(labels.length === 0 ? {} : { labels: labels.slice(0, MAX_QUALIFIER_VALUES) }),
+ ...(excludedLabels.length === 0
+ ? {}
+ : { excludedLabels: excludedLabels.slice(0, MAX_QUALIFIER_VALUES) }),
+ ...(author === undefined ? {} : { author }),
+ ...(draft === undefined ? {} : { draft }),
+ ...(review === undefined ? {} : { review }),
+ ...(checks === undefined ? {} : { checks }),
+ },
+ };
+}
+
/** Free-text filter over the fields a row actually shows, plus `#123` / `123`. */
export function matchesPullRequestQuery(entry: PullRequestListEntry, query: string): boolean {
const normalizedQuery = query.trim().toLowerCase();
@@ -48,11 +248,11 @@ export function matchesPullRequestQuery(entry: PullRequestListEntry, query: stri
* The server returns the involvement superset for a state, so switching between the Reviewing
* and Authored tabs never waits on the network.
*/
-export function filterPullRequestsByInvolvement(
- entries: ReadonlyArray<PullRequestListEntry>,
+export function filterPullRequestsByInvolvement<Entry extends ScopedEntry>(
+ entries: ReadonlyArray<Entry>,
viewers: PullRequestViewers,
involvement: PullRequestInvolvement,
-): ReadonlyArray<PullRequestListEntry> {
+): ReadonlyArray<Entry> {
if (involvement === "reviewing") {
return entries.filter((entry) => entry.viewerReviewRequested);
}
@@ -75,14 +275,14 @@ export function filterPullRequestsByInvolvement(
* it needs to know who is signed in on each host, and the search text because searching is the
* hosts' own answer; both are narrowed where that knowledge already lives.
*/
-export function narrowPullRequestsToFilters(
- entries: ReadonlyArray<PullRequestListEntry>,
+export function narrowPullRequestsToFilters<Entry extends PullRequestListEntry>(
+ entries: ReadonlyArray<Entry>,
filters: {
readonly state: PullRequestListState;
readonly projectId: string | undefined;
readonly host: string | undefined;
},
-): ReadonlyArray<PullRequestListEntry> {
+): ReadonlyArray<Entry> {
return entries.filter(
(entry) =>
(filters.state === "all" || entry.state === filters.state) &&
@@ -91,15 +291,46 @@ export function narrowPullRequestsToFilters(
);
}
+/**
+ * The further narrowings over rows that have already arrived, for the hosts that could not apply
+ * them themselves and for the moment before an answer that did lands.
+ *
+ * `checks` is absent because no listed row carries its check state: that one filter is the
+ * host's alone, and a row a host did not narrow stays rather than being guessed at.
+ *
+ * `viewer` is the row's own host's signed-in login, so `author:me` resolves against it rather
+ * than being compared as the literal name "me". Optional, and left unresolved without one.
+ */
+export function matchesPullRequestFilters(
+ entry: PullRequestListEntry,
+ filters: PullRequestListFilters,
+ viewer?: string | null,
+): boolean {
+ const labels = entry.labels.map((label) => label.name.trim().toLowerCase());
+ const holds = (label: string) => labels.includes(label.trim().toLowerCase());
+ return (
+ (filters.draft === undefined || entry.isDraft === (filters.draft === "only")) &&
+ (filters.review === undefined ||
+ (filters.review === "none"
+ ? entry.reviewDecision === undefined
+ : entry.reviewDecision === filters.review)) &&
+ (filters.labels === undefined || filters.labels.every((group) => group.some(holds))) &&
+ (filters.excludedLabels === undefined || !filters.excludedLabels.some(holds)) &&
+ (filters.author === undefined ||
+ entry.author?.login.toLowerCase() ===
+ resolvePullRequestAuthorFilter(filters.author, viewer).toLowerCase())
+ );
+}
+
/**
* Only relationships the list data actually carries: no "previously reviewed" bucket is
* inferred, because the listing has no review history.
*/
-export function groupPullRequestsByInvolvement(
- entries: ReadonlyArray<PullRequestListEntry>,
+export function groupPullRequestsByInvolvement<Entry extends ScopedEntry>(
+ entries: ReadonlyArray<Entry>,
viewers: PullRequestViewers,
-): ReadonlyArray<PullRequestGroup> {
- const buckets: Record<PullRequestGroupKey, PullRequestListEntry[]> = {
+): ReadonlyArray<PullRequestGroup<Entry>> {
+ const buckets: Record<PullRequestGroupKey, Entry[]> = {
reviewRequested: [],
authored: [],
others: [],
@@ -118,9 +349,14 @@ export function groupPullRequestsByInvolvement(
.map((key) => ({ key, label: GROUP_LABELS[key], entries: buckets[key] }));
}
-/** Repository plus number is unique on one host, so the host makes the key unique overall. */
-export function pullRequestEntryKey(entry: PullRequestListEntry): string {
- return `${entry.host}:${entry.repository}#${entry.number}`;
+/**
+ * Repository plus number is unique on one host, so the host makes the key unique overall — and
+ * the environment on top of that, because two connected machines can hold the same repository and
+ * would otherwise contribute two rows under one key.
+ */
+export function pullRequestEntryKey(entry: ScopedEntry): string {
+ const scope = entry.environmentId === undefined ? "" : `${entry.environmentId}:`;
+ return `${scope}${entry.host}:${entry.repository}#${entry.number}`;
}
/**
@@ -131,11 +367,11 @@ export function pullRequestEntryKey(entry: PullRequestListEntry): string {
* server-filtered reads, the feed fills "Others" in its own order, and a continuation can only
* append — a row it carries that a partition already holds is dropped rather than moved.
*/
-export function partitionPullRequestsWithPriority(
- entries: ReadonlyArray<PullRequestListEntry>,
- authored: ReadonlyArray<PullRequestListEntry>,
- reviewRequested: ReadonlyArray<PullRequestListEntry>,
-): ReadonlyArray<PullRequestGroup> {
+export function partitionPullRequestsWithPriority<Entry extends PullRequestListEntry>(
+ entries: ReadonlyArray<Entry>,
+ authored: ReadonlyArray<Entry>,
+ reviewRequested: ReadonlyArray<Entry>,
+): ReadonlyArray<PullRequestGroup<Entry>> {
const authoredByKey = new Map(authored.map((entry) => [pullRequestEntryKey(entry), entry]));
// A row can be both authored and review-requested; authored wins, as the local grouping has it.
const reviewByKey = new Map(
@@ -144,7 +380,7 @@ export function partitionPullRequestsWithPriority(
return authoredByKey.has(key) ? [] : [[key, entry] as const];
}),
);
- const others: PullRequestListEntry[] = [];
+ const others: Entry[] = [];
for (const entry of entries) {
const key = pullRequestEntryKey(entry);
// The feed's copy of a partitioned row is at least as fresh — it replaces in place.
@@ -156,8 +392,7 @@ export function partitionPullRequestsWithPriority(
others.push(entry);
}
}
- const byRecency = (left: PullRequestListEntry, right: PullRequestListEntry) =>
- right.updatedAt.localeCompare(left.updatedAt);
+ const byRecency = (left: Entry, right: Entry) => right.updatedAt.localeCompare(left.updatedAt);
return (
[
{ key: "reviewRequested", entries: [...reviewByKey.values()].toSorted(byRecency) },
@@ -183,6 +418,7 @@ export type PullRequestDiffStats = ReadonlyMap<
export function mergePullRequestDiffStats(
previous: PullRequestDiffStats,
stats: ReadonlyArray<{
+ readonly environmentId: string;
readonly projectId: string;
readonly number: number;
readonly additions: number;
@@ -192,20 +428,109 @@ export function mergePullRequestDiffStats(
if (stats.length === 0) return previous;
const next = new Map(previous);
for (const stat of stats) {
- next.set(`${stat.projectId} ${stat.number}`, {
- additions: stat.additions,
- deletions: stat.deletions,
- });
+ next.set(diffStatKey(stat), { additions: stat.additions, deletions: stat.deletions });
}
return next;
}
+/** A project id only names a project within its own environment, so the key carries both. */
+const diffStatKey = (row: {
+ readonly environmentId: string;
+ readonly projectId: string;
+ readonly number: number;
+}) => `${row.environmentId} ${row.projectId} ${row.number}`;
+
+/**
+ * Every connected environment's listing, read as one list.
+ *
+ * `nextCursors` is keyed by environment rather than by repository: a cursor only means anything
+ * to the host that issued it, and two machines can hold the same repository. `viewers` is not —
+ * a host names one account, and the same host reached from two machines is the same account.
+ */
+export interface MergedPullRequestList {
+ /** Keyed `"<environmentId> <host>"`, so one host's two accounts stay two accounts. */
+ readonly viewers: PullRequestViewers;
+ readonly providers: PullRequestListResult["providers"];
+ readonly entries: ReadonlyArray<EnvironmentPullRequestEntry>;
+ readonly errors: PullRequestListResult["errors"];
+ readonly truncated: boolean;
+ readonly nextCursors: Readonly<Record<string, PullRequestListCursors>>;
+ /**
+ * The environments with rows still on their hosts. Those with a cursor are continued from it;
+ * the rest can only be reached by asking them for a longer page, and are named here so that
+ * asking still happens once every other environment has run out of cursors.
+ */
+ readonly truncatedEnvironments: ReadonlyArray<string>;
+}
+
+/**
+ * The environments' answers folded into one. A host reached from more than one environment is one
+ * row in the switcher, readable if any environment could read it and searched on the host only if
+ * every one of them did — a host answering unnarrowed anywhere still needs the local pass.
+ */
+export function mergePullRequestLists(
+ answers: ReadonlyArray<readonly [EnvironmentId, PullRequestListResult]>,
+): MergedPullRequestList | null {
+ if (answers.length === 0) return null;
+ const viewers: Record<string, string> = {};
+ const truncatedEnvironments: string[] = [];
+ const providers = new Map<string, PullRequestListResult["providers"][number]>();
+ const entries: EnvironmentPullRequestEntry[] = [];
+ const errors: Array<PullRequestListResult["errors"][number]> = [];
+ const nextCursors: Record<string, PullRequestListCursors> = {};
+ let truncated = false;
+ for (const [environmentId, answer] of answers) {
+ for (const [host, login] of Object.entries(answer.viewers)) {
+ viewers[`${environmentId} ${host}`] = login;
+ }
+ for (const provider of answer.providers) {
+ const held = providers.get(provider.host);
+ providers.set(
+ provider.host,
+ held === undefined
+ ? provider
+ : {
+ ...(held.configured ? held : provider),
+ projectCount: held.projectCount + provider.projectCount,
+ searchesOnHost: held.searchesOnHost && provider.searchesOnHost,
+ configured: held.configured || provider.configured,
+ },
+ );
+ }
+ entries.push(...answer.entries.map((entry) => ({ ...entry, environmentId })));
+ errors.push(...answer.errors);
+ truncated ||= answer.truncated;
+ if (answer.truncated) truncatedEnvironments.push(environmentId);
+ if (Object.keys(answer.nextCursors).length > 0) {
+ nextCursors[environmentId] = answer.nextCursors;
+ }
+ }
+ return {
+ viewers,
+ providers: [...providers.values()],
+ entries: entries.toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
+ errors,
+ truncated,
+ nextCursors,
+ truncatedEnvironments,
+ };
+}
+
/** One page is what the list itself starts with, and all a cold start needs to look warm. */
const SNAPSHOT_MAX_ENTRIES = 99;
type SnapshotStorage = Pick<Storage, "getItem" | "setItem">;
-const snapshotStorageKey = (environmentId: string) => `t3.pullRequests.list:${environmentId}`;
+/**
+ * Keyed by the whole set of environments the list was read from: connecting or dropping one
+ * changes which rows belong on the page, and a snapshot taken from a different set would
+ * hydrate rows no longer being read.
+ */
+export const pullRequestEnvironmentSetKey = (environmentIds: ReadonlyArray<string>): string =>
+ [...environmentIds].sort((left, right) => left.localeCompare(right)).join(",");
+
+const snapshotStorageKey = (environmentSetKey: string) =>
+ `t3.pullRequests.list:${environmentSetKey}`;
/**
* The priority groups' own server-filtered answers, carried with the feed. An authored pull
@@ -213,13 +538,13 @@ const snapshotStorageKey = (environmentId: string) => `t3.pullRequests.list:${en
* cold-starts into an Authored group missing exactly the rows that made it worth having.
*/
export interface PullRequestPartitionsSnapshot {
- readonly authored: ReadonlyArray<PullRequestListEntry>;
- readonly reviewing: ReadonlyArray<PullRequestListEntry>;
+ readonly authored: ReadonlyArray<EnvironmentPullRequestEntry>;
+ readonly reviewing: ReadonlyArray<EnvironmentPullRequestEntry>;
}
export interface PullRequestListSnapshot {
readonly scope: string;
- readonly data: PullRequestListResult;
+ readonly data: MergedPullRequestList;
readonly partitions?: PullRequestPartitionsSnapshot | undefined;
}
@@ -229,15 +554,26 @@ export interface PullRequestListSnapshot {
* otherwise crash the list on every reload until the key is cleared. A snapshot from before a
* schema change is rejected the same way, which is exactly the cold start it would have broken.
*/
+const EnvironmentPullRequestEntrySchema = Schema.Struct({
+ ...PullRequestListEntry.fields,
+ environmentId: EnvironmentId,
+});
+
const decodeSnapshot = Schema.decodeUnknownOption(
Schema.Struct({
scope: Schema.String,
- data: PullRequestListResult,
+ data: Schema.Struct({
+ ...PullRequestListResult.fields,
+ entries: Schema.Array(EnvironmentPullRequestEntrySchema),
+ // Per environment here, unlike the wire shape, which is per repository within one.
+ nextCursors: Schema.Record(Schema.String, PullRequestListResult.fields.nextCursors),
+ truncatedEnvironments: Schema.Array(Schema.String),
+ }),
// Optional so a snapshot written before the partitions existed still hydrates the feed.
partitions: Schema.optional(
Schema.Struct({
- authored: Schema.Array(PullRequestListEntry),
- reviewing: Schema.Array(PullRequestListEntry),
+ authored: Schema.Array(EnvironmentPullRequestEntrySchema),
+ reviewing: Schema.Array(EnvironmentPullRequestEntrySchema),
}),
),
}),
@@ -252,10 +588,10 @@ const decodeSnapshot = Schema.decodeUnknownOption(
*/
export function readPullRequestListSnapshot(
storage: SnapshotStorage | undefined,
- environmentId: string,
+ environmentSetKey: string,
): PullRequestListSnapshot | null {
try {
- const raw = storage?.getItem(snapshotStorageKey(environmentId));
+ const raw = storage?.getItem(snapshotStorageKey(environmentSetKey));
if (!raw) return null;
const decoded = decodeSnapshot(JSON.parse(raw));
return decoded._tag === "Some" ? decoded.value : null;
@@ -266,12 +602,12 @@ export function readPullRequestListSnapshot(
export function writePullRequestListSnapshot(
storage: SnapshotStorage | undefined,
- environmentId: string,
+ environmentSetKey: string,
snapshot: PullRequestListSnapshot,
): void {
try {
storage?.setItem(
- snapshotStorageKey(environmentId),
+ snapshotStorageKey(environmentSetKey),
JSON.stringify({
scope: snapshot.scope,
data: {
@@ -281,6 +617,8 @@ export function writePullRequestListSnapshot(
// position in a listing the host has long since forgotten.
errors: [],
nextCursors: {},
+ // Where a listing stopped is as stale as the cursor that named it.
+ truncatedEnvironments: [],
},
...(snapshot.partitions === undefined
? {}
@@ -316,6 +654,73 @@ export function resolveProjectScope<Id extends string>(
return projects.some((project) => project.id === projectId) ? projectId : undefined;
}
+/**
+ * The project an id names, on the server that owns it. A project id is only unique within its own
+ * environment, so an id alone can name two projects on two connected machines: with a server in
+ * hand the answer is exact, and without one it is only given where a single environment has that
+ * id — narrowing to the wrong machine reads an empty list nobody asked for.
+ */
+export function findScopedProject<
+ Project extends { readonly id: string; readonly environmentId: string },
+>(
+ projects: ReadonlyArray<Project>,
+ environmentId: string | null | undefined,
+ projectId: string | undefined,
+): Project | undefined {
+ if (projectId === undefined) return undefined;
+ const matches = projects.filter((project) => project.id === projectId);
+ if (environmentId === null || environmentId === undefined) {
+ return matches.length === 1 ? matches[0] : undefined;
+ }
+ return matches.find((project) => project.environmentId === environmentId);
+}
+
+/**
+ * Which environments a listing should ask, once the project scope is known. Scoping to a project
+ * scopes to the server that owns it, saving every other server a read that could only answer with
+ * nothing. Where an id is ambiguous — two servers holding the same project id, with no server
+ * named — only the servers that actually hold that id are asked: a server without it may still
+ * hold an unrelated project of its own under the same string, and asking it would return that
+ * project's rows rather than an honest empty answer.
+ */
+export function resolveQueryEnvironmentIds<Id extends string>(
+ environmentIds: ReadonlyArray<Id>,
+ projects: ReadonlyArray<{ readonly id: string; readonly environmentId: Id }>,
+ scopedProject: { readonly environmentId: Id } | undefined,
+ scopedProjectId: string | undefined,
+ projectsKnown: boolean,
+): ReadonlyArray<Id> {
+ if (scopedProject !== undefined) {
+ return environmentIds.filter((environmentId) => environmentId === scopedProject.environmentId);
+ }
+ // Before the servers have said what they hold, an id nothing matches is an id nothing has been
+ // asked about yet — reading none of them would show an empty page for a project that is there.
+ if (scopedProjectId === undefined || !projectsKnown) return environmentIds;
+ const holders = new Set(
+ projects
+ .filter((project) => project.id === scopedProjectId)
+ .map((project) => project.environmentId),
+ );
+ return environmentIds.filter((environmentId) => holders.has(environmentId));
+}
+
+/**
+ * The server a saved selection names, before its project is looked up against it. Still
+ * connecting is not the same as gone: a server the workspace already knows about is kept named
+ * here even while it has nothing to answer with yet, so the lookup that follows finds nothing
+ * under it rather than falling through to a different server's project of the same id. Only a
+ * name outside the workspace's whole catalog falls back to the page's own scope, which is what
+ * lets a link to a server since removed still resolve by project id alone.
+ */
+export function resolveSelectedEnvironmentId<Id extends string>(
+ namedEnvironmentId: Id | undefined,
+ knownEnvironmentIds: ReadonlySet<Id>,
+ fallbackEnvironmentId: Id | null,
+): Id | null {
+ if (namedEnvironmentId === undefined) return fallbackEnvironmentId;
+ return knownEnvironmentIds.has(namedEnvironmentId) ? namedEnvironmentId : fallbackEnvironmentId;
+}
+
/**
* How well a row answers the text that was searched for, as a number to order by.
*
@@ -353,10 +758,10 @@ export function scorePullRequestMatch(entry: PullRequestListEntry, query: string
* Search results in the order they answer the question, most convincing first, and by recency
* among equals. Only for a search: without one, a listing is a timeline and recency is the order.
*/
-export function rankPullRequestMatches(
- entries: ReadonlyArray<PullRequestListEntry>,
+export function rankPullRequestMatches<Entry extends PullRequestListEntry>(
+ entries: ReadonlyArray<Entry>,
query: string,
-): ReadonlyArray<PullRequestListEntry> {
+): ReadonlyArray<Entry> {
if (query.trim().length === 0) return entries;
return entries.toSorted((left, right) => {
const byScore = scorePullRequestMatch(right, query) - scorePullRequestMatch(left, query);
@@ -369,11 +774,13 @@ export function rankPullRequestMatches(
* listing that carried them is not second-guessed — and only where they have arrived, since a row
* draws perfectly well without them in the meantime.
*/
-export function withDiffStat(
- entry: PullRequestListEntry,
+export function withDiffStat<
+ Entry extends PullRequestListEntry & { readonly environmentId: string },
+>(
+ entry: Entry,
statsByRow: ReadonlyMap<string, { readonly additions: number; readonly deletions: number }>,
-): PullRequestListEntry {
+): Entry {
if (entry.additions !== 0 || entry.deletions !== 0) return entry;
- const stat = statsByRow.get(`${entry.projectId} ${entry.number}`);
+ const stat = statsByRow.get(diffStatKey(entry));
return stat === undefined ? entry : { ...entry, ...stat };
}
diff --git a/apps/web/src/components/pullRequest/pullRequestPresentation.tsx b/apps/web/src/components/pullRequest/pullRequestPresentation.tsx
index 28e952015..370400292 100644
--- a/apps/web/src/components/pullRequest/pullRequestPresentation.tsx
+++ b/apps/web/src/components/pullRequest/pullRequestPresentation.tsx
@@ -2,12 +2,14 @@ import type {
PullRequestActor,
PullRequestCheck,
PullRequestCheckStatus,
+ PullRequestChecksState,
PullRequestMergeability,
PullRequestState,
} from "@t3tools/contracts";
import {
CircleCheckIcon,
CircleDashedIcon,
+ CircleDotIcon,
CircleXIcon,
GitMergeIcon,
GitPullRequestClosedIcon,
@@ -144,6 +146,51 @@ export function PullRequestCheckStatusIcon({ status }: { status: PullRequestChec
);
}
+/**
+ * The rollup a listing row carries, which is one word rather than the checks behind it. The
+ * headline is GitHub's own wording, so a reader who knows that page reads this one the same way.
+ */
+const CHECKS_STATE_PRESENTATION = {
+ passing: {
+ label: "All checks have passed",
+ Icon: CircleCheckIcon,
+ toneClassName: "text-emerald-600 dark:text-emerald-300/90",
+ },
+ failing: {
+ label: "Some checks were not successful",
+ Icon: CircleXIcon,
+ toneClassName: "text-destructive",
+ },
+ pending: {
+ label: "Some checks haven't completed yet",
+ Icon: CircleDotIcon,
+ toneClassName: "text-amber-600 dark:text-amber-400/90",
+ },
+} as const satisfies Record<
+ PullRequestChecksState,
+ { label: string; Icon: typeof CircleCheckIcon; toneClassName: string }
+>;
+
+export function pullRequestChecksStatePresentation(state: PullRequestChecksState) {
+ return CHECKS_STATE_PRESENTATION[state];
+}
+
+/**
+ * The same rollup the server sends with a listing row, worked out here from the checks a detail
+ * already holds — so the header shows the icon without a second field travelling with it.
+ *
+ * Null for a change request with no checks: nothing to show beats a tick nobody earned.
+ */
+export function pullRequestChecksState(
+ checks: ReadonlyArray<PullRequestCheck>,
+): PullRequestChecksState | null {
+ if (checks.length === 0) return null;
+ const statuses = checks.map((check) => check.status);
+ if (statuses.includes("failure") || statuses.includes("cancelled")) return "failing";
+ if (statuses.includes("pending")) return "pending";
+ return statuses.includes("success") ? "passing" : null;
+}
+
export function PullRequestActorAvatar({
actor,
className,
diff --git a/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts
new file mode 100644
index 000000000..71ddcbf66
--- /dev/null
+++ b/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts
@@ -0,0 +1,259 @@
+import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ assignProjectsToEnvironments,
+ resolvePickableEnvironments,
+ type AssignableProject,
+} from "./pullRequestProjectAssignment.logic";
+
+const project = (
+ id: string,
+ environmentId: string,
+ canonicalKey?: string,
+): AssignableProject & { workspaceRoot: string } => ({
+ id: id as ProjectId,
+ environmentId: environmentId as EnvironmentId,
+ repositoryIdentity: canonicalKey === undefined ? null : { canonicalKey },
+ workspaceRoot: `/srv/${environmentId}/${id}`,
+});
+
+const envs = (...ids: ReadonlyArray<string>) => ids as ReadonlyArray<EnvironmentId>;
+
+const plain = (assignment: Map<EnvironmentId, ProjectId[]>) =>
+ Object.fromEntries([...assignment].map(([id, projectIds]) => [id, projectIds]));
+
+describe("one server per repository", () => {
+ it("lets the first server list a repository both hold", () => {
+ const assignment = assignProjectsToEnvironments(
+ [
+ project("a1", "env-1", "github.com/acme/app"),
+ project("b1", "env-1", "github.com/acme/tools"),
+ project("a2", "env-2", "github.com/acme/app"),
+ project("c2", "env-2", "github.com/acme/site"),
+ ],
+ envs("env-1", "env-2"),
+ "env-1" as EnvironmentId,
+ );
+ expect(plain(assignment)).toEqual({ "env-1": ["a1", "b1"], "env-2": ["c2"] });
+ });
+
+ it("prefers the named server over the first one", () => {
+ const assignment = assignProjectsToEnvironments(
+ [
+ project("a1", "env-1", "github.com/acme/app"),
+ project("a2", "env-2", "github.com/acme/app"),
+ ],
+ envs("env-1", "env-2"),
+ "env-2" as EnvironmentId,
+ );
+ expect(plain(assignment)).toEqual({ "env-2": ["a2"] });
+ });
+
+ it("drops a server with nothing of its own", () => {
+ const assignment = assignProjectsToEnvironments(
+ [
+ project("a1", "env-1", "github.com/acme/app"),
+ project("a2", "env-2", "github.com/acme/app"),
+ ],
+ envs("env-1", "env-2"),
+ "env-1" as EnvironmentId,
+ );
+ expect(assignment.has("env-2" as EnvironmentId)).toBe(false);
+ });
+
+ it("keeps every copy of a project that has no identity to compare", () => {
+ const assignment = assignProjectsToEnvironments(
+ [project("p1", "env-1"), project("p2", "env-2")],
+ envs("env-1", "env-2"),
+ "env-1" as EnvironmentId,
+ );
+ expect(plain(assignment)).toEqual({ "env-1": ["p1"], "env-2": ["p2"] });
+ });
+
+ it("keeps a repository listed by the one server that holds it", () => {
+ const assignment = assignProjectsToEnvironments(
+ [
+ project("a1", "env-1", "github.com/acme/app"),
+ project("b2", "env-2", "gitlab.com/acme/app"),
+ ],
+ envs("env-1", "env-2"),
+ "env-1" as EnvironmentId,
+ );
+ expect(plain(assignment)).toEqual({ "env-1": ["a1"], "env-2": ["b2"] });
+ });
+
+ it("keeps a server's own worktrees of the repository it lists", () => {
+ const assignment = assignProjectsToEnvironments(
+ [
+ project("a1", "env-1", "github.com/acme/app"),
+ project("a1-wt", "env-1", "GitHub.com/acme/app"),
+ project("a2", "env-2", "github.com/acme/app"),
+ ],
+ envs("env-1", "env-2"),
+ "env-1" as EnvironmentId,
+ );
+ expect(plain(assignment)).toEqual({ "env-1": ["a1", "a1-wt"] });
+ });
+
+ it("reads two servers' copies of one repository as one however the remote is cased", () => {
+ const assignment = assignProjectsToEnvironments(
+ [
+ project("a1", "env-1", "git.example.com/Team/App"),
+ project("a2", "env-2", "GIT.example.com/team/app"),
+ ],
+ envs("env-1", "env-2"),
+ "env-1" as EnvironmentId,
+ );
+ expect(plain(assignment)).toEqual({ "env-1": ["a1"] });
+ });
+
+ it("ignores a project on a server that is not being read", () => {
+ const assignment = assignProjectsToEnvironments(
+ [
+ project("a1", "env-1", "github.com/acme/app"),
+ project("a2", "env-2", "github.com/acme/app"),
+ ],
+ envs("env-2"),
+ "env-2" as EnvironmentId,
+ );
+ expect(plain(assignment)).toEqual({ "env-2": ["a2"] });
+ });
+
+ it("answers the same whatever order the projects arrive in", () => {
+ const projects = [
+ project("a2", "env-2", "github.com/acme/app"),
+ project("a1", "env-1", "github.com/acme/app"),
+ ];
+ const forward = assignProjectsToEnvironments(projects, envs("env-1", "env-2"), null);
+ const backward = assignProjectsToEnvironments(
+ projects.toReversed(),
+ envs("env-1", "env-2"),
+ null,
+ );
+ expect(plain(forward)).toEqual({ "env-1": ["a1"] });
+ expect(plain(backward)).toEqual(plain(forward));
+ });
+});
+
+const connected = (...ids: ReadonlyArray<string>) =>
+ ids.map((id) => ({ environmentId: id as EnvironmentId, label: `Server ${id}` }));
+
+const on = (environmentId: string, projectId: string) => ({
+ environmentId: environmentId as EnvironmentId,
+ projectId: projectId as ProjectId,
+});
+
+describe("where a pull request can be acted on", () => {
+ it("offers every server holding the repository, the panel's own first", () => {
+ const pickable = resolvePickableEnvironments(
+ on("env-2", "a2"),
+ [
+ project("a1", "env-1", "github.com/acme/app"),
+ project("a2", "env-2", "github.com/acme/app"),
+ project("c3", "env-3", "github.com/acme/site"),
+ ],
+ connected("env-1", "env-2", "env-3"),
+ );
+ expect(pickable).toEqual([
+ {
+ environmentId: "env-2",
+ projectId: "a2",
+ workspaceRoot: "/srv/env-2/a2",
+ label: "Server env-2",
+ },
+ {
+ environmentId: "env-1",
+ projectId: "a1",
+ workspaceRoot: "/srv/env-1/a1",
+ label: "Server env-1",
+ },
+ ]);
+ });
+
+ it("matches copies however the remote is cased", () => {
+ const pickable = resolvePickableEnvironments(
+ on("env-1", "a1"),
+ [
+ project("a1", "env-1", "github.com/acme/app"),
+ project("a2", "env-2", "GitHub.com/ACME/app"),
+ ],
+ connected("env-1", "env-2"),
+ );
+ expect(pickable.map((entry) => entry.environmentId)).toEqual(["env-1", "env-2"]);
+ });
+
+ it("offers nothing where one server holds the repository", () => {
+ expect(
+ resolvePickableEnvironments(
+ on("env-1", "a1"),
+ [
+ project("a1", "env-1", "github.com/acme/app"),
+ project("c2", "env-2", "github.com/acme/site"),
+ ],
+ connected("env-1", "env-2"),
+ ),
+ ).toEqual([]);
+ });
+
+ it("offers nothing for a project with no identity to compare", () => {
+ expect(
+ resolvePickableEnvironments(
+ on("env-1", "p1"),
+ [project("p1", "env-1"), project("p2", "env-2")],
+ connected("env-1", "env-2"),
+ ),
+ ).toEqual([]);
+ });
+
+ it("offers nothing while the projects are still arriving", () => {
+ expect(resolvePickableEnvironments(on("env-1", "a1"), [], connected("env-1", "env-2"))).toEqual(
+ [],
+ );
+ });
+
+ it("leaves out a server that is not connected", () => {
+ expect(
+ resolvePickableEnvironments(
+ on("env-1", "a1"),
+ [
+ project("a1", "env-1", "github.com/acme/app"),
+ project("a2", "env-2", "github.com/acme/app"),
+ ],
+ connected("env-1"),
+ ),
+ ).toEqual([]);
+ });
+
+ it("names one copy per server, so two worktrees are one choice", () => {
+ const pickable = resolvePickableEnvironments(
+ on("env-1", "a1"),
+ [
+ project("a1", "env-1", "github.com/acme/app"),
+ project("a1-wt", "env-1", "github.com/acme/app"),
+ project("a2", "env-2", "github.com/acme/app"),
+ project("a2-wt", "env-2", "github.com/acme/app"),
+ ],
+ connected("env-1", "env-2"),
+ );
+ expect(pickable.map((entry) => entry.projectId)).toEqual(["a1", "a2"]);
+ });
+
+ it("keeps the panel's own worktree rather than the server's first copy", () => {
+ const pickable = resolvePickableEnvironments(
+ on("env-1", "a1-wt"),
+ [
+ project("a1", "env-1", "github.com/acme/app"),
+ project("a1-wt", "env-1", "github.com/acme/app"),
+ project("a2", "env-2", "github.com/acme/app"),
+ ],
+ connected("env-1", "env-2"),
+ );
+ expect(pickable[0]).toEqual({
+ environmentId: "env-1",
+ projectId: "a1-wt",
+ workspaceRoot: "/srv/env-1/a1-wt",
+ label: "Server env-1",
+ });
+ });
+});
diff --git a/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.ts b/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.ts
new file mode 100644
index 000000000..aea26286f
--- /dev/null
+++ b/apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.ts
@@ -0,0 +1,130 @@
+import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
+
+/** The little of a project this needs: who holds it, and which repository it is a copy of. */
+export interface AssignableProject {
+ readonly id: ProjectId;
+ readonly environmentId: EnvironmentId;
+ readonly repositoryIdentity?: { readonly canonicalKey?: string | undefined } | null | undefined;
+}
+
+/**
+ * The remote's normalized URL is what says "same repository" across machines — it comes from the
+ * remote, not from a local path. Empty where the project has no identity to compare with.
+ *
+ * `normalizeGitRemoteUrl` already lower-cases the whole remote, so the key arrives cased one way
+ * whatever the remote said; the fold here only guards a key assembled some other way.
+ */
+function repositoryKey(project: AssignableProject): string | undefined {
+ return project.repositoryIdentity?.canonicalKey?.toLowerCase();
+}
+
+/**
+ * Two servers can hold the same repository, and both would list the same pull requests, so one
+ * copy is picked by its repository key.
+ *
+ * A project with no identity is never de-duplicated: nothing proves it is a copy of anything, and
+ * dropping it would lose its rows outright.
+ */
+export function assignProjectsToEnvironments(
+ projects: ReadonlyArray<AssignableProject>,
+ environmentIds: ReadonlyArray<EnvironmentId>,
+ preferredEnvironmentId?: EnvironmentId | null,
+): Map<EnvironmentId, ProjectId[]> {
+ const rank = new Map(environmentIds.map((id, index) => [id, index] as const));
+ // Which server lists each repository: the preferred one where it has it, else the first.
+ const owner = new Map<string, EnvironmentId>();
+ for (const project of projects) {
+ const key = repositoryKey(project);
+ if (!key) continue;
+ const environmentRank = rank.get(project.environmentId);
+ if (environmentRank === undefined) continue;
+ const current = owner.get(key);
+ if (current === undefined) {
+ owner.set(key, project.environmentId);
+ continue;
+ }
+ if (current === preferredEnvironmentId) continue;
+ if (
+ project.environmentId === preferredEnvironmentId ||
+ environmentRank < (rank.get(current) ?? Number.MAX_SAFE_INTEGER)
+ ) {
+ owner.set(key, project.environmentId);
+ }
+ }
+ const assignment = new Map<EnvironmentId, ProjectId[]>();
+ for (const project of projects) {
+ if (!rank.has(project.environmentId)) continue;
+ const key = repositoryKey(project);
+ if (key && owner.get(key) !== project.environmentId) continue;
+ const listed = assignment.get(project.environmentId);
+ if (listed === undefined) assignment.set(project.environmentId, [project.id]);
+ else listed.push(project.id);
+ }
+ return assignment;
+}
+
+/** A copy of the repository the reader could act on, named by the server holding it. */
+export interface PickableEnvironment {
+ readonly environmentId: EnvironmentId;
+ readonly projectId: ProjectId;
+ readonly workspaceRoot: string;
+ readonly label: string;
+}
+
+/**
+ * Which servers a pull request could be acted on, given the one it is listed under.
+ *
+ * Listing picks a single server per repository so each pull request appears once; acting is a
+ * different question. Checking the branch out, or handing it to a thread, happens wherever the
+ * reader means to work — and the copy the listing happened not to pick is just as real.
+ *
+ * Empty where there is no choice to offer: one server, no repository identity to match copies by,
+ * or projects not read yet. The caller renders nothing then, so a lone server keeps the surface it
+ * has always had.
+ */
+export function resolvePickableEnvironments(
+ current: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId },
+ projects: ReadonlyArray<AssignableProject & { readonly workspaceRoot: string }>,
+ environments: ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly label: string }>,
+): ReadonlyArray<PickableEnvironment> {
+ const own = projects.find(
+ (project) =>
+ project.environmentId === current.environmentId && project.id === current.projectId,
+ );
+ const key = own === undefined ? undefined : repositoryKey(own);
+ const ownLabel = environments.find(
+ (environment) => environment.environmentId === current.environmentId,
+ )?.label;
+ if (own === undefined || !key || ownLabel === undefined) return [];
+ const others = environments.flatMap((environment) => {
+ if (environment.environmentId === current.environmentId) return [];
+ // One entry per server, whichever copy comes first: a server holding two worktrees of the
+ // repository is still one place to act, and what is being picked here is the server.
+ const copy = projects.find(
+ (project) =>
+ project.environmentId === environment.environmentId && repositoryKey(project) === key,
+ );
+ return copy === undefined
+ ? []
+ : [
+ {
+ environmentId: environment.environmentId,
+ projectId: copy.id,
+ workspaceRoot: copy.workspaceRoot,
+ label: environment.label,
+ },
+ ];
+ });
+ if (others.length === 0) return [];
+ // The panel's own server first: it is what everything else on the panel is showing, so it is
+ // also what acting means until the reader says otherwise.
+ return [
+ {
+ environmentId: current.environmentId,
+ projectId: own.id,
+ workspaceRoot: own.workspaceRoot,
+ label: ownLabel,
+ },
+ ...others,
+ ];
+}
diff --git a/apps/web/src/components/pullRequest/pullRequestReactions.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestReactions.logic.test.ts
new file mode 100644
index 000000000..d474a2071
--- /dev/null
+++ b/apps/web/src/components/pullRequest/pullRequestReactions.logic.test.ts
@@ -0,0 +1,210 @@
+import type { PullRequestReaction, PullRequestReactionContent } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ applyPendingPullRequestReactions,
+ PULL_REQUEST_REACTION_ORDER,
+ pullRequestReactionEmoji,
+ pullRequestReactionName,
+ pullRequestReactionTooltip,
+} from "./pullRequestReactions.logic";
+
+function reaction(overrides: Partial<PullRequestReaction> = {}): PullRequestReaction {
+ return {
+ content: "heart",
+ count: 1,
+ actors: ["octocat"],
+ viewerHasReacted: false,
+ ...overrides,
+ };
+}
+
+describe("reaction presentation", () => {
+ it("names and draws all eight, in GitHub's picker order", () => {
+ expect(PULL_REQUEST_REACTION_ORDER).toEqual([
+ "thumbs-up",
+ "thumbs-down",
+ "laugh",
+ "hooray",
+ "confused",
+ "heart",
+ "rocket",
+ "eyes",
+ ]);
+ expect(PULL_REQUEST_REACTION_ORDER.map(pullRequestReactionEmoji)).toEqual([
+ "👍",
+ "👎",
+ "😄",
+ "🎉",
+ "😕",
+ "❤️",
+ "🚀",
+ "👀",
+ ]);
+ expect(pullRequestReactionName("thumbs-up")).toBe("thumbs up");
+ expect(pullRequestReactionName("eyes")).toBe("eyes");
+ });
+});
+
+describe("reaction tooltip", () => {
+ it("reads as GitHub's sentence for one, two and three names", () => {
+ expect(
+ pullRequestReactionTooltip(reaction({ content: "thumbs-up", count: 1, actors: ["Bil0000"] })),
+ ).toBe("Bil0000 reacted with thumbs up emoji");
+ expect(pullRequestReactionTooltip(reaction({ count: 2, actors: ["Bil0000", "octocat"] }))).toBe(
+ "Bil0000 and octocat reacted with heart emoji",
+ );
+ expect(
+ pullRequestReactionTooltip(
+ reaction({
+ content: "eyes",
+ count: 3,
+ actors: ["Bil0000", "octocat"],
+ viewerHasReacted: true,
+ }),
+ ),
+ ).toBe("You, Bil0000, and octocat reacted with eyes emoji");
+ });
+
+ it("counts everyone past the third name, including the ones the host never named", () => {
+ expect(
+ pullRequestReactionTooltip(
+ reaction({
+ content: "rocket",
+ count: 15,
+ actors: ["a", "b", "c", "d"],
+ viewerHasReacted: true,
+ }),
+ ),
+ ).toBe("You, a, b, and 12 others reacted with rocket emoji");
+ // A host that counted more than it named still says who is missing.
+ expect(pullRequestReactionTooltip(reaction({ count: 2, actors: ["octocat"] }))).toBe(
+ "octocat and 1 other reacted with heart emoji",
+ );
+ // Nothing named at all leaves the count to speak for itself, and nobody to be "other" than.
+ expect(pullRequestReactionTooltip(reaction({ count: 4, actors: [] }))).toBe(
+ "4 people reacted with heart emoji",
+ );
+ expect(pullRequestReactionTooltip(reaction({ count: 1, actors: [] }))).toBe(
+ "1 person reacted with heart emoji",
+ );
+ });
+
+ it("names the viewer as You, ahead of the other people who reacted", () => {
+ // The host already leaves the viewer's own login out of `actors`.
+ expect(
+ pullRequestReactionTooltip(
+ reaction({ count: 3, actors: ["Bil0000", "octocat"], viewerHasReacted: true }),
+ ),
+ ).toBe("You, Bil0000, and octocat reacted with heart emoji");
+ });
+
+ it("names nobody as You when the viewer has not reacted", () => {
+ expect(
+ pullRequestReactionTooltip(
+ reaction({ count: 2, actors: ["Bil0000", "octocat"], viewerHasReacted: false }),
+ ),
+ ).toBe("Bil0000 and octocat reacted with heart emoji");
+ });
+
+ it("names actors as given, and leaves off You, for a host with no room for the viewer", () => {
+ // `count` says two and `actors` already lists two logins, one of them the viewer's own —
+ // there is no slot left for "You" that wouldn't invent or hide a real reactor.
+ expect(
+ pullRequestReactionTooltip(
+ reaction({ count: 2, actors: ["Bil0000", "octocat"], viewerHasReacted: true }),
+ ),
+ ).toBe("Bil0000 and octocat reacted with heart emoji");
+ // Same shape past the naming cap: the display limit still leaves an honest remainder.
+ expect(
+ pullRequestReactionTooltip(
+ reaction({
+ count: 4,
+ actors: ["Bil0000", "octocat", "hubot", "zzz"],
+ viewerHasReacted: true,
+ }),
+ ),
+ ).toBe("Bil0000, octocat, hubot, and 1 other reacted with heart emoji");
+ });
+
+ it("keeps naming the viewer You when the host does leave them room", () => {
+ // `actors` has fewer logins than `count`, so the viewer fits without being counted twice.
+ expect(
+ pullRequestReactionTooltip(
+ reaction({ count: 2, actors: ["octocat"], viewerHasReacted: true }),
+ ),
+ ).toBe("You and octocat reacted with heart emoji");
+ });
+});
+
+describe("reaction tooltip, with a reaction in flight", () => {
+ it("still says You after an optimistic react, even at full capacity", () => {
+ // The host's last snapshot had every reactor named and nobody left over; the optimistic
+ // bump grows `count` without touching `actors`, so there is now room for "You" and the
+ // sentence should use it rather than reading as a non-compliant host.
+ const applied = applyPendingPullRequestReactions(
+ [reaction({ count: 2, actors: ["a", "b"], viewerHasReacted: false })],
+ new Map([["heart", true] as const]),
+ );
+ expect(pullRequestReactionTooltip(applied[0]!)).toBe("You, a, and b reacted with heart emoji");
+ });
+
+ it("drops You after an optimistic un-react, without treating the host as non-compliant", () => {
+ const applied = applyPendingPullRequestReactions(
+ [reaction({ count: 2, actors: ["octocat"], viewerHasReacted: true })],
+ new Map([["heart", false] as const]),
+ );
+ expect(pullRequestReactionTooltip(applied[0]!)).toBe("octocat reacted with heart emoji");
+ });
+});
+
+describe("pending reactions", () => {
+ const pending = (
+ entries: ReadonlyArray<readonly [PullRequestReactionContent, boolean]>,
+ ): ReadonlyMap<PullRequestReactionContent, boolean> => new Map(entries);
+
+ it("returns the host's list untouched while nothing is in flight", () => {
+ const reactions = [reaction()];
+ expect(applyPendingPullRequestReactions(reactions, pending([]))).toBe(reactions);
+ });
+
+ it("adds a reaction nobody had yet, in picker order", () => {
+ const applied = applyPendingPullRequestReactions(
+ [reaction({ content: "rocket", count: 2, actors: ["a", "b"] })],
+ pending([["thumbs-up", true]]),
+ );
+ expect(applied).toEqual([
+ { content: "thumbs-up", count: 1, actors: [], viewerHasReacted: true },
+ { content: "rocket", count: 2, actors: ["a", "b"], viewerHasReacted: false },
+ ]);
+ });
+
+ it("joins and leaves an existing reaction, and drops the pill nobody is left on", () => {
+ expect(
+ applyPendingPullRequestReactions(
+ [reaction({ count: 2, actors: ["a", "b"] })],
+ pending([["heart", true]]),
+ ),
+ ).toEqual([{ content: "heart", count: 3, actors: ["a", "b"], viewerHasReacted: true }]);
+ expect(
+ applyPendingPullRequestReactions(
+ [reaction({ count: 2, actors: ["a", "b"], viewerHasReacted: true })],
+ pending([["heart", false]]),
+ ),
+ ).toEqual([{ content: "heart", count: 1, actors: ["a", "b"], viewerHasReacted: false }]);
+ expect(
+ applyPendingPullRequestReactions(
+ [reaction({ count: 1, viewerHasReacted: true })],
+ pending([["heart", false]]),
+ ),
+ ).toEqual([]);
+ });
+
+ it("ignores a pending state the host has already caught up with", () => {
+ const reactions = [reaction({ count: 3, viewerHasReacted: true })];
+ expect(applyPendingPullRequestReactions(reactions, pending([["heart", true]]))).toEqual(
+ reactions,
+ );
+ expect(applyPendingPullRequestReactions([], pending([["heart", false]]))).toEqual([]);
+ });
+});
diff --git a/apps/web/src/components/pullRequest/pullRequestReactions.logic.ts b/apps/web/src/components/pullRequest/pullRequestReactions.logic.ts
new file mode 100644
index 000000000..e54511b08
--- /dev/null
+++ b/apps/web/src/components/pullRequest/pullRequestReactions.logic.ts
@@ -0,0 +1,108 @@
+import type { PullRequestReaction, PullRequestReactionContent } from "@t3tools/contracts";
+
+/** The picker's order, which is GitHub's: the two verdicts first, then the rest as it lists them. */
+export const PULL_REQUEST_REACTION_ORDER: ReadonlyArray<PullRequestReactionContent> = [
+ "thumbs-up",
+ "thumbs-down",
+ "laugh",
+ "hooray",
+ "confused",
+ "heart",
+ "rocket",
+ "eyes",
+];
+
+const REACTION_EMOJI: Record<PullRequestReactionContent, string> = {
+ "thumbs-up": "👍",
+ "thumbs-down": "👎",
+ laugh: "😄",
+ hooray: "🎉",
+ confused: "😕",
+ heart: "❤️",
+ rocket: "🚀",
+ eyes: "👀",
+};
+
+/** The spoken names GitHub uses in its own hover text, which is what a screen reader reads out. */
+const REACTION_NAME: Record<PullRequestReactionContent, string> = {
+ "thumbs-up": "thumbs up",
+ "thumbs-down": "thumbs down",
+ laugh: "laugh",
+ hooray: "hooray",
+ confused: "confused",
+ heart: "heart",
+ rocket: "rocket",
+ eyes: "eyes",
+};
+
+export function pullRequestReactionEmoji(content: PullRequestReactionContent): string {
+ return REACTION_EMOJI[content];
+}
+
+export function pullRequestReactionName(content: PullRequestReactionContent): string {
+ return REACTION_NAME[content];
+}
+
+/** Past three names the sentence stops being readable and starts being a list. */
+const NAMED_ACTOR_LIMIT = 3;
+
+function joinNames(parts: ReadonlyArray<string>): string {
+ if (parts.length <= 1) return parts[0] ?? "";
+ if (parts.length === 2) return `${parts[0]} and ${parts[1]}`;
+ return `${parts.slice(0, -1).join(", ")}, and ${parts.at(-1)}`;
+}
+
+/** "others" only alongside somebody named; on its own a count is people, not other people. */
+function countRemainder(count: number, named: boolean): string {
+ if (named) return `${count} ${count === 1 ? "other" : "others"}`;
+ return `${count} ${count === 1 ? "person" : "people"}`;
+}
+
+/**
+ * Who reacted, in GitHub's sentence. The viewer reads as "You" and comes first, because that is
+ * the name they are looking for; a compliant host already leaves the viewer's own login out of
+ * `actors` when they have reacted, leaving room for "You" without ever exceeding `count`. This
+ * function has no viewer login to match against `actors`, so it cannot tell a non-compliant host
+ * apart by name — but such a host gives itself away by leaving no room: `actors` alone already
+ * accounts for everyone `count` claims. Then the viewer is already in `actors` under their own
+ * login, and naming them "You" too would either invent a person or hide a real one, so `actors`
+ * is named as given instead. The cap still guards further: the sentence never names more people
+ * than `count` claims, and the remainder is counted rather than named — a host reports fewer
+ * logins than it counts, so `count` is the only trustworthy total.
+ */
+export function pullRequestReactionTooltip(reaction: PullRequestReaction): string {
+ const viewerHasRoom = reaction.actors.length < reaction.count;
+ const names =
+ reaction.viewerHasReacted && viewerHasRoom ? ["You", ...reaction.actors] : [...reaction.actors];
+ const shown = names.slice(0, Math.min(NAMED_ACTOR_LIMIT, reaction.count));
+ const others = Math.max(0, reaction.count - shown.length);
+ const parts = [...shown, ...(others > 0 ? [countRemainder(others, shown.length > 0)] : [])];
+ return `${joinNames(parts)} reacted with ${pullRequestReactionName(reaction.content)} emoji`;
+}
+
+/**
+ * The list as it should be drawn while a reaction is still in flight. Reading a change request
+ * back from the host takes seconds, and a pill that does not move until then reads as a press
+ * that did nothing.
+ */
+export function applyPendingPullRequestReactions(
+ reactions: ReadonlyArray<PullRequestReaction>,
+ pending: ReadonlyMap<PullRequestReactionContent, boolean>,
+): ReadonlyArray<PullRequestReaction> {
+ if (pending.size === 0) return reactions;
+ const byContent = new Map(reactions.map((reaction) => [reaction.content, reaction] as const));
+ for (const [content, reacted] of pending) {
+ const current = byContent.get(content);
+ if (current === undefined) {
+ if (reacted) {
+ byContent.set(content, { content, count: 1, actors: [], viewerHasReacted: true });
+ }
+ continue;
+ }
+ if (current.viewerHasReacted === reacted) continue;
+ const count = current.count + (reacted ? 1 : -1);
+ if (count <= 0) byContent.delete(content);
+ else byContent.set(content, { ...current, count, viewerHasReacted: reacted });
+ }
+ return PULL_REQUEST_REACTION_ORDER.flatMap((content) => byContent.get(content) ?? []);
+}
diff --git a/apps/web/src/components/pullRequest/pullRequestSummaryScroll.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestSummaryScroll.logic.test.ts
new file mode 100644
index 000000000..8733eed90
--- /dev/null
+++ b/apps/web/src/components/pullRequest/pullRequestSummaryScroll.logic.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { sectionCollapseAnchorScrollTop } from "./pullRequestSummaryScroll.logic";
+
+describe("section collapse scroll anchoring", () => {
+ it("returns the section's natural offset when its heading is pinned", () => {
+ expect(
+ sectionCollapseAnchorScrollTop({
+ scrollTop: 600,
+ viewportTop: 264,
+ sectionTop: -200,
+ headingTop: 264,
+ }),
+ ).toBe(136);
+ });
+
+ it("allows a fractional sticky-edge difference", () => {
+ expect(
+ sectionCollapseAnchorScrollTop({
+ scrollTop: 500,
+ viewportTop: 264,
+ sectionTop: 100,
+ headingTop: 264.5,
+ }),
+ ).toBe(336);
+ });
+
+ it("leaves the scroll position alone before the heading becomes sticky", () => {
+ expect(
+ sectionCollapseAnchorScrollTop({
+ scrollTop: 120,
+ viewportTop: 264,
+ sectionTop: 320,
+ headingTop: 320,
+ }),
+ ).toBeNull();
+ });
+
+ it("does not produce a negative scroll offset", () => {
+ expect(
+ sectionCollapseAnchorScrollTop({
+ scrollTop: 20,
+ viewportTop: 264,
+ sectionTop: 200,
+ headingTop: 264,
+ }),
+ ).toBe(0);
+ });
+});
diff --git a/apps/web/src/components/pullRequest/pullRequestSummaryScroll.logic.ts b/apps/web/src/components/pullRequest/pullRequestSummaryScroll.logic.ts
new file mode 100644
index 000000000..432fae65e
--- /dev/null
+++ b/apps/web/src/components/pullRequest/pullRequestSummaryScroll.logic.ts
@@ -0,0 +1,20 @@
+const STICKY_EDGE_TOLERANCE_PX = 1;
+
+/**
+ * Returns the scroll offset that puts a section's natural top where its sticky heading is now.
+ * Collapsing removes the body below that heading; without this adjustment, the unchanged numeric
+ * offset points into the next section and makes its sticky heading appear to replace the one the
+ * reader pressed.
+ */
+export function sectionCollapseAnchorScrollTop(input: {
+ readonly scrollTop: number;
+ readonly viewportTop: number;
+ readonly sectionTop: number;
+ readonly headingTop: number;
+}): number | null {
+ const sectionHasScrolledPastViewport = input.sectionTop < input.viewportTop;
+ const headingIsPinned = input.headingTop <= input.viewportTop + STICKY_EDGE_TOLERANCE_PX;
+ if (!sectionHasScrolledPastViewport || !headingIsPinned) return null;
+
+ return Math.max(0, input.scrollTop + input.sectionTop - input.viewportTop);
+}
diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsx
index 667a58d83..232be0a45 100644
--- a/apps/web/src/components/sidebar/SidebarChrome.tsx
+++ b/apps/web/src/components/sidebar/SidebarChrome.tsx
@@ -9,7 +9,7 @@ import { Link, useLocation, useNavigate } from "@tanstack/react-router";
import { useEnvironmentIdentificationMode } from "../../hooks/useSettings";
import { cn } from "../../lib/utils";
-import { usePrimaryEnvironment } from "../../state/environments";
+import { useEnvironments } from "../../state/environments";
import {
resolveEnvironmentIdentificationPillLabel,
resolveSidebarStageBackdropVariant,
@@ -128,9 +128,12 @@ export const SidebarChromeFooter = memo(function SidebarChromeFooter() {
? "pull-requests"
: null,
});
- const primaryEnvironment = usePrimaryEnvironment();
- const pullRequestsSupported =
- primaryEnvironment?.serverConfig?.environment.capabilities.pullRequests === true;
+ const { environments } = useEnvironments();
+ // The page reads every connected server, so one of them offering pull requests is enough for
+ // the link to lead somewhere.
+ const pullRequestsSupported = environments.some(
+ (environment) => environment.serverConfig?.environment.capabilities.pullRequests === true,
+ );
const closeMobileSidebar = useCallback(() => {
if (isMobile) {
setOpenMobile(false);
diff --git a/apps/web/src/lib/openPullRequestLink.ts b/apps/web/src/lib/openPullRequestLink.ts
index 8943f907b..d2263d961 100644
--- a/apps/web/src/lib/openPullRequestLink.ts
+++ b/apps/web/src/lib/openPullRequestLink.ts
@@ -1,4 +1,4 @@
-import type { LocalApi, ScopedThreadRef } from "@t3tools/contracts";
+import type { EnvironmentId, LocalApi, ScopedThreadRef } from "@t3tools/contracts";
import { useNavigate } from "@tanstack/react-router";
import * as Schema from "effect/Schema";
import { type MouseEvent, useCallback } from "react";
@@ -197,20 +197,28 @@ export function useOpenChangeRequestLink(
(event, targetUrl, targetThreadRef) => {
if (shouldOpenPullRequestExternally(event)) return false;
const resolvedThreadRef = targetThreadRef ?? threadRef;
- const environmentId = resolvedThreadRef?.environmentId ?? primaryEnvironmentId;
- if (
- environmentId === null ||
- serverConfigs.get(environmentId)?.environment.capabilities.pullRequests !== true
- ) {
- return false;
- }
+ const parsed = parseChangeRequestUrl(targetUrl);
+ if (parsed === null) return false;
+ const reads = (environmentId: string) =>
+ serverConfigs.get(environmentId as EnvironmentId)?.environment.capabilities.pullRequests ===
+ true;
// Beside a thread the panel reads on that thread's environment, so a project from another
// one could not be read there whatever its remote says: two environments can hold the same
// repository, and handing the panel the wrong one's id opens a surface that never loads.
- const projects = allProjects.filter((project) => project.environmentId === environmentId);
- const parsed = parseChangeRequestUrl(targetUrl);
- const project = parsed === null ? undefined : findProjectForChangeRequest(projects, parsed);
- if (parsed === null || project === undefined) return false;
+ //
+ // The page has no such tie — it lists every server at once — so the link is resolved
+ // against all of them, the primary first where two hold the same repository.
+ const projects = resolvedThreadRef
+ ? allProjects.filter((project) => project.environmentId === resolvedThreadRef.environmentId)
+ : allProjects
+ .filter((project) => reads(project.environmentId))
+ .toSorted(
+ (left, right) =>
+ Number(right.environmentId === primaryEnvironmentId) -
+ Number(left.environmentId === primaryEnvironmentId),
+ );
+ const project = findProjectForChangeRequest(projects, parsed);
+ if (project === undefined || !reads(project.environmentId)) return false;
event.preventDefault();
event.stopPropagation();
if (resolvedThreadRef) {
@@ -233,6 +241,8 @@ export function useOpenChangeRequestLink(
repository: parsed.repository,
number: parsed.number,
selectedProjectId: project.id,
+ // Named so the page opens the right one of two servers holding this project.
+ selectedEnvironmentId: project.environmentId,
},
});
return true;
diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.ts
index 039f8ef72..b6997554e 100644
--- a/apps/web/src/rightPanelStore.test.ts
+++ b/apps/web/src/rightPanelStore.test.ts
@@ -9,6 +9,7 @@ import {
selectActiveRightPanelSurface,
selectSelectedRightPanelSurface,
selectThreadRightPanelState,
+ updatePullRequestTabStatus,
useRightPanelStore,
} from "./rightPanelStore";
@@ -419,6 +420,127 @@ describe("rightPanelStore", () => {
expect(state.activeSurfaceId).toBe(pullRequestSurfaceId(first));
});
+ it("keeps one pull request read from two servers as two tabs", () => {
+ const local = {
+ environmentId: "local",
+ projectId: "project-a",
+ repository: "pingdotgg/t3code",
+ number: 4909,
+ };
+ const remote = { ...local, environmentId: "remote" };
+
+ useRightPanelStore.getState().openPullRequest(refA, local);
+ useRightPanelStore.getState().openPullRequest(refA, remote);
+
+ const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);
+ expect(state.surfaces.map((surface) => surface.id)).toEqual([
+ pullRequestSurfaceId(local),
+ pullRequestSurfaceId(remote),
+ ]);
+ });
+
+ it("keeps the page's panel tabs reachable when the set of connected servers changes", () => {
+ // The pull-requests page keys its one shared panel by a fixed sentinel environment, not by
+ // whichever capable server happens to sort first (see PULL_REQUESTS_PANEL_ENVIRONMENT_ID in
+ // _chat.pull-requests.tsx) — a server disconnecting must not move every open tab to a store
+ // key nobody wrote them under.
+ const panelId = ThreadId.make("pull-requests-panel");
+ const stableRef = scopeThreadRef("pull-requests-panel" as EnvironmentId, panelId);
+ const fromServerA = {
+ environmentId: "server-a",
+ projectId: "project-a",
+ repository: "pingdotgg/t3code",
+ number: 1,
+ };
+ const fromServerB = {
+ environmentId: "server-b",
+ projectId: "project-b",
+ repository: "pingdotgg/t3code",
+ number: 2,
+ };
+
+ // Both servers connected: tabs from each open under the one stable ref.
+ useRightPanelStore.getState().openPullRequest(stableRef, fromServerA);
+ useRightPanelStore.getState().openPullRequest(stableRef, fromServerB);
+
+ // Server A disconnects. The stable ref does not depend on which servers remain connected, so
+ // the same lookup still finds both tabs.
+ const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, stableRef);
+ expect(state.surfaces.map((surface) => surface.id)).toEqual([
+ pullRequestSurfaceId(fromServerA),
+ pullRequestSurfaceId(fromServerB),
+ ]);
+
+ // The bug this guards against: a ref keyed by the first capable environment instead of a
+ // fixed sentinel changes identity when that environment drops out, and a lookup under the new
+ // key finds nothing even though the tabs are still sitting under the old one.
+ const refWhileBothConnected = scopeThreadRef("server-a" as EnvironmentId, panelId);
+ const refAfterServerADisconnects = scopeThreadRef("server-b" as EnvironmentId, panelId);
+ expect(refWhileBothConnected).not.toEqual(refAfterServerADisconnects);
+ expect(
+ selectThreadRightPanelState(
+ useRightPanelStore.getState().byThreadKey,
+ refAfterServerADisconnects,
+ ).surfaces,
+ ).toEqual([]);
+ });
+
+ describe("updatePullRequestTabStatus", () => {
+ const status = (isDraft: boolean) => ({
+ projectId: "project-a",
+ repository: "pingdotgg/t3code",
+ number: 4909,
+ state: "open" as const,
+ isDraft,
+ });
+
+ // Regression for the tab wearing no state: this failed when the status was written under a
+ // key rebuilt from the pull request while the tab strip reads it under the surface's own id.
+ it("keys a status under the same id a surface opened from an environment carries", () => {
+ const target = {
+ environmentId: "remote",
+ projectId: "project-a",
+ repository: "pingdotgg/t3code",
+ number: 4909,
+ };
+ useRightPanelStore.getState().openPullRequest(refA, target);
+ const surface = selectSelectedRightPanelSurface(
+ useRightPanelStore.getState().byThreadKey,
+ refA,
+ );
+ expect(surface).not.toBeNull();
+
+ const statuses = updatePullRequestTabStatus({}, surface!.id, status(false));
+ expect(statuses[surface!.id]).toEqual(status(false));
+ });
+
+ it("keys a status under the same id a thread surface with no environment carries", () => {
+ const target = { projectId: "project-a", repository: "pingdotgg/t3code", number: 4909 };
+ useRightPanelStore.getState().openPullRequest(refA, target);
+ const surface = selectSelectedRightPanelSurface(
+ useRightPanelStore.getState().byThreadKey,
+ refA,
+ );
+ expect(surface).not.toBeNull();
+
+ const statuses = updatePullRequestTabStatus({}, surface!.id, status(false));
+ expect(statuses[surface!.id]).toEqual(status(false));
+ });
+
+ it("returns the identical map when the tab's state and draft flag are unchanged", () => {
+ const first = updatePullRequestTabStatus({}, "pull-request:1", status(false));
+ const second = updatePullRequestTabStatus(first, "pull-request:1", status(false));
+ expect(second).toBe(first);
+ });
+
+ it("replaces the entry when the draft flag changes", () => {
+ const first = updatePullRequestTabStatus({}, "pull-request:1", status(false));
+ const second = updatePullRequestTabStatus(first, "pull-request:1", status(true));
+ expect(second).not.toBe(first);
+ expect(second["pull-request:1"]).toEqual(status(true));
+ });
+ });
+
it("tracks one surface per terminal session", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().openTerminal(refA, "term-2");
diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts
index 5adee07a1..27d5ded5d 100644
--- a/apps/web/src/rightPanelStore.ts
+++ b/apps/web/src/rightPanelStore.ts
@@ -52,6 +52,12 @@ export type RightPanelSurface =
*/
id: `pull-request:${string}`;
kind: "pull-request";
+ /**
+ * Which server the change request was read from. The list spans every connected one, so
+ * two of them can hold the same project id; a panel beside a thread leaves this out and
+ * takes the environment from its own ref.
+ */
+ environmentId?: string;
projectId: string;
repository: string;
number: number;
@@ -86,7 +92,7 @@ interface RightPanelStoreState {
openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void;
openPullRequest: (
ref: ScopedThreadRef,
- target: { projectId: string; repository: string; number: number },
+ target: { environmentId?: string; projectId: string; repository: string; number: number },
) => void;
openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;
splitTerminal: (
@@ -161,14 +167,20 @@ const terminalSurface = (terminalId: string): RightPanelSurface => ({
export type PullRequestSurface = Extract<RightPanelSurface, { kind: "pull-request" }>;
export function pullRequestSurfaceId(target: {
+ environmentId?: string;
projectId: string;
repository: string;
number: number;
}): PullRequestSurface["id"] {
- return `pull-request:${encodeURIComponent(target.projectId)}:${encodeURIComponent(target.repository)}:${target.number}`;
+ // The environment leads the id where there is one, so the same change request read from two
+ // servers is two tabs rather than one tab that changes its mind about which server it is on.
+ const scope =
+ target.environmentId === undefined ? "" : `${encodeURIComponent(target.environmentId)}:`;
+ return `pull-request:${scope}${encodeURIComponent(target.projectId)}:${encodeURIComponent(target.repository)}:${target.number}`;
}
export function pullRequestSurface(target: {
+ environmentId?: string;
projectId: string;
repository: string;
number: number;
@@ -176,12 +188,30 @@ export function pullRequestSurface(target: {
return {
id: pullRequestSurfaceId(target),
kind: "pull-request",
+ ...(target.environmentId === undefined ? {} : { environmentId: target.environmentId }),
projectId: target.projectId,
repository: target.repository,
number: target.number,
};
}
+/**
+ * A pull-request tab's status map with one entry set. Keyed by the surface the panel is showing
+ * rather than by a key rebuilt from the status, so the tab is found again whether or not that
+ * surface was opened with an environment on it. Returns the same map when the tab's own fields
+ * have not changed, so a caller can skip a re-render.
+ */
+export function updatePullRequestTabStatus<Status extends { state: unknown; isDraft: boolean }>(
+ statuses: Readonly<Record<string, Status>>,
+ surfaceId: string,
+ status: Status,
+): Readonly<Record<string, Status>> {
+ return statuses[surfaceId]?.state === status.state &&
+ statuses[surfaceId]?.isDraft === status.isDraft
+ ? statuses
+ : { ...statuses, [surfaceId]: status };
+}
+
const upsertSurface = (
current: ThreadRightPanelState,
surface: RightPanelSurface,
@@ -260,7 +290,14 @@ export function migratePersistedRightPanelState(persistedState: unknown): {
) {
return [];
}
- return [pullRequestSurface(surface)];
+ const { environmentId, ...rest } = surface;
+ // Anything else stored under that name is not an environment.
+ return [
+ pullRequestSurface({
+ ...rest,
+ ...(typeof environmentId === "string" ? { environmentId } : {}),
+ }),
+ ];
}
if (surface.kind !== "terminal") return [surface];
if (
diff --git a/apps/web/src/routes/_chat.pull-requests.tsx b/apps/web/src/routes/_chat.pull-requests.tsx
index ecdc183b8..b6ad2e1f9 100644
--- a/apps/web/src/routes/_chat.pull-requests.tsx
+++ b/apps/web/src/routes/_chat.pull-requests.tsx
@@ -4,7 +4,9 @@ import type {
EnvironmentId,
ProjectId,
PullRequestInvolvement,
- PullRequestListEntry,
+ PullRequestListCursors,
+ PullRequestListFilters,
+ PullRequestListInput,
PullRequestListResult,
PullRequestListState,
SourceControlProviderKind,
@@ -13,6 +15,8 @@ import { createFileRoute, useNavigate } from "@tanstack/react-router";
import {
ChevronDownIcon,
EyeIcon,
+ MonitorIcon,
+ ServerIcon,
GitMergeIcon,
GitPullRequestClosedIcon,
GitPullRequestIcon,
@@ -26,21 +30,31 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } fro
import {
filterPullRequestsByInvolvement,
+ findScopedProject,
groupPullRequestsByInvolvement,
+ matchesPullRequestFilters,
matchesPullRequestQuery,
+ parsePullRequestQuery,
narrowPullRequestsToFilters,
mergePullRequestDiffStats,
partitionPullRequestsWithPriority,
pullRequestEntryKey,
+ pullRequestEntryViewer,
rankPullRequestMatches,
+ pullRequestEnvironmentSetKey,
readPullRequestListSnapshot,
resolveProjectScope,
+ resolveQueryEnvironmentIds,
+ resolveSelectedEnvironmentId,
withDiffStat,
writePullRequestListSnapshot,
scorePullRequestMatch,
+ type EnvironmentPullRequestEntry,
+ type MergedPullRequestList,
type PullRequestDiffStats,
type PullRequestPartitionsSnapshot,
} from "../components/pullRequest/pullRequestList.logic";
+import { assignProjectsToEnvironments } from "../components/pullRequest/pullRequestProjectAssignment.logic";
import { PullRequestDetailPanel } from "../components/pullRequest/PullRequestDetailPanel";
import {
PullRequestFiltersMenu,
@@ -65,18 +79,22 @@ import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "../
import { SidebarInset } from "../components/ui/sidebar";
import { useLiveRefresh } from "../hooks/useLiveRefresh";
import {
- pullRequestSurfaceId,
selectActiveRightPanelSurface,
selectSelectedRightPanelSurface,
selectThreadRightPanelState,
+ updatePullRequestTabStatus,
useRightPanelStore,
type PullRequestSurface,
} from "../rightPanelStore";
import { useDebouncedValue } from "../state/queries";
import { useAllEnvironmentShellsBootstrapped, useProjects } from "../state/entities";
-import { usePrimaryEnvironment } from "../state/environments";
-import { pullRequestEnvironment } from "../state/pullRequests";
-import { useEnvironmentQuery } from "../state/query";
+import { useEnvironments } from "../state/environments";
+import {
+ pullRequestEnvironment,
+ usePullRequestList,
+ usePullRequestListStats,
+ type EnvironmentQueryTarget,
+} from "../state/pullRequests";
import { useAtomCommand } from "../state/use-atom-command";
import { cn } from "~/lib/utils";
import { getSourceControlPresentationForKind } from "~/sourceControlPresentation";
@@ -85,6 +103,11 @@ import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
export interface PullRequestsSearch {
readonly involvement: PullRequestInvolvement;
readonly state: PullRequestListState;
+ /**
+ * Narrows the list to one server. Absent means every connected one, which is the default the
+ * page has now — so a link written before servers could be chosen still opens the whole list.
+ */
+ readonly environmentId?: EnvironmentId;
/** Scopes the list. Separate from the selection so one cannot silently change the other. */
readonly projectId?: ProjectId;
/**
@@ -95,7 +118,20 @@ export interface PullRequestsSearch {
readonly repository?: string;
readonly number?: number;
readonly selectedProjectId?: ProjectId;
+ /**
+ * Which server the selected pull request was read from. A project id only names a project on
+ * its own server, so this is what tells two servers holding one project apart. Optional: a
+ * link without it still opens, resolved by project id alone where that is unambiguous.
+ */
+ readonly selectedEnvironmentId?: EnvironmentId;
readonly q?: string;
+ /**
+ * The narrowings beyond state and involvement, each absent when that group is unfiltered. Flat
+ * in the URL because a link is read and edited by hand; folded into one record for the listing.
+ */
+ readonly draft?: "only" | "hide";
+ readonly review?: NonNullable<PullRequestListFilters["review"]>;
+ readonly checks?: NonNullable<PullRequestListFilters["checks"]>;
}
// The state filters wear the same glyphs the rows do, so the two read as one vocabulary.
@@ -128,6 +164,15 @@ const MAX_PAGE_SIZE = 500;
const EMPTY_VIEWERS: PullRequestListResult["viewers"] = {};
/** The list owns one environment-scoped right panel rather than borrowing a real thread's. */
const PULL_REQUESTS_PANEL_ID = ThreadId.make("pull-requests-panel");
+/**
+ * A fixed sentinel, not a real server: the panel is one workspace-level surface list (each
+ * surface already carries the server it was read from), so its store key must not move when a
+ * capable server disconnects or reconnects. Real environment ids are server-generated UUIDs, so
+ * this string can never collide with one.
+ */
+const PULL_REQUESTS_PANEL_ENVIRONMENT_ID = "pull-requests-panel" as EnvironmentId;
+/** Stable so a read that is not wanted right now does not re-key on every render. */
+const NO_LIST_TARGETS: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>> = [];
const EMPTY_PREVIEW_SESSIONS = {};
const EMPTY_TERMINAL_LABELS = new Map<string, string>();
const EMPTY_PENDING_SURFACES = new Set<string>();
@@ -147,11 +192,25 @@ export const Route = createFileRoute("/_chat/pull-requests")({
...(typeof raw.projectId === "string" && raw.projectId
? { projectId: raw.projectId as ProjectId }
: {}),
+ ...(typeof raw.environmentId === "string" && raw.environmentId
+ ? { environmentId: raw.environmentId as EnvironmentId }
+ : {}),
...(typeof raw.host === "string" && raw.host ? { host: raw.host.slice(0, 200) } : {}),
...(typeof raw.selectedProjectId === "string" && raw.selectedProjectId
? { selectedProjectId: raw.selectedProjectId as ProjectId }
: {}),
+ ...(typeof raw.selectedEnvironmentId === "string" && raw.selectedEnvironmentId
+ ? { selectedEnvironmentId: raw.selectedEnvironmentId as EnvironmentId }
+ : {}),
...(typeof raw.q === "string" && raw.q ? { q: raw.q.slice(0, 200) } : {}),
+ ...(raw.draft === "only" || raw.draft === "hide" ? { draft: raw.draft } : {}),
+ ...(raw.review === "approved" ||
+ raw.review === "changes-requested" ||
+ raw.review === "review-required" ||
+ raw.review === "none"
+ ? { review: raw.review }
+ : {}),
+ ...(raw.checks === "passing" || raw.checks === "failing" ? { checks: raw.checks } : {}),
}),
component: PullRequestsRouteView,
});
@@ -159,44 +218,155 @@ export const Route = createFileRoute("/_chat/pull-requests")({
function PullRequestsRouteView() {
const search = Route.useSearch();
const navigate = useNavigate({ from: Route.fullPath });
- const primaryEnvironment = usePrimaryEnvironment();
- const environmentId = primaryEnvironment?.environmentId ?? null;
- const capabilityKnown = primaryEnvironment !== null && primaryEnvironment.serverConfig !== null;
- const pullRequestsSupported =
- primaryEnvironment?.serverConfig?.environment.capabilities.pullRequests === true;
- // The primary environment may still be connecting, or may predate this feature. In either
- // case every query remains idle until the server has explicitly advertised these APIs.
- const pullRequestEnvironmentId = pullRequestsSupported ? environmentId : null;
+ const { environments } = useEnvironments();
+ // Every connected environment that has said it can list pull requests. Sorted, so the query
+ // keys, the scope key and the stored snapshot all read the same whichever order the
+ // connections happened to come up in.
+ const capableEnvironments = useMemo(
+ () =>
+ environments
+ .filter(
+ (environment) => environment.serverConfig?.environment.capabilities.pullRequests === true,
+ )
+ .toSorted((left, right) => left.environmentId.localeCompare(right.environmentId)),
+ [environments],
+ );
+ // The server the URL asks for, kept only while it is one the page could read: a link naming a
+ // server this workspace no longer has falls back to all of them rather than to nothing.
+ const scopedEnvironmentId =
+ capableEnvironments.find((environment) => environment.environmentId === search.environmentId)
+ ?.environmentId ?? null;
+ // Every server this workspace has ever heard of, connecting or not — wider than
+ // `capableEnvironments`, which only holds the ones ready to answer.
+ const knownEnvironmentIds = useMemo(
+ () => new Set(environments.map((environment) => environment.environmentId)),
+ [environments],
+ );
+ const environmentIds = useMemo(
+ () =>
+ capableEnvironments
+ .filter(
+ (environment) =>
+ scopedEnvironmentId === null || environment.environmentId === scopedEnvironmentId,
+ )
+ .map((environment) => environment.environmentId),
+ [capableEnvironments, scopedEnvironmentId],
+ );
+ const environmentKey = useMemo(
+ () => pullRequestEnvironmentSetKey(environmentIds),
+ [environmentIds],
+ );
+ // An environment may still be connecting, or may predate this feature. Until at least one has
+ // reported, an empty set means "not known yet" rather than "no environment can", and the page
+ // waits rather than telling a reader to upgrade a server that has not spoken.
+ const capabilityKnown = environments.some((environment) => environment.serverConfig !== null);
+ const pullRequestsSupported = environmentIds.length > 0;
const allProjects = useProjects();
// Whether the workspace has said what it holds yet. Until it has, an empty project list is
// "not loaded" rather than "none", and telling a reader to add a project they already have is
// the one wrong answer the empty state can give.
const projectsKnown = useAllEnvironmentShellsBootstrapped();
- // The page reads one environment, so a project from another one could neither be listed
- // nor acted on: scoping here keeps the filter and the selection honest.
+ // Only the projects the page can actually read: one on an environment that cannot list pull
+ // requests could neither be listed nor acted on.
const projects = useMemo(
- () => allProjects.filter((project) => project.environmentId === environmentId),
- [allProjects, environmentId],
+ () => allProjects.filter((project) => environmentIds.includes(project.environmentId)),
+ [allProjects, environmentIds],
);
- const scopedProjects = useMemo(
+ const environmentLabels = useMemo(
() =>
- projects
- .map((project) => ({
- id: project.id,
- title: project.title,
- workspaceRoot: project.workspaceRoot,
- }))
- .toSorted((left, right) => left.title.localeCompare(right.title)),
- [projects],
+ new Map(
+ environments.map((environment) => [environment.environmentId, environment.label] as const),
+ ),
+ [environments],
);
- // The scope the URL asks for, once the environment has had its say about whether it exists.
+ const scopedProjects = useMemo(() => {
+ // Two machines can hold the same repository, so a title the workspace carries twice is told
+ // apart by the environment it lives on rather than left as two identical rows.
+ const titleCounts = new Map<string, number>();
+ for (const project of projects) {
+ titleCounts.set(project.title, (titleCounts.get(project.title) ?? 0) + 1);
+ }
+ return projects
+ .map((project) => ({
+ id: project.id,
+ environmentId: project.environmentId,
+ title:
+ (titleCounts.get(project.title) ?? 0) > 1
+ ? `${project.title} · ${environmentLabels.get(project.environmentId) ?? project.environmentId}`
+ : project.title,
+ workspaceRoot: project.workspaceRoot,
+ }))
+ .toSorted((left, right) => left.title.localeCompare(right.title));
+ }, [environmentLabels, projects]);
+ // The scope the URL asks for, once the environments have had their say about whether it exists.
const scopedProjectId = useMemo(
() => resolveProjectScope(search.projectId, projects, projectsKnown),
[projects, projectsKnown, search.projectId],
);
+ const scopedProject = useMemo(
+ () => findScopedProject(projects, scopedEnvironmentId, scopedProjectId),
+ [projects, scopedEnvironmentId, scopedProjectId],
+ );
+
+ // A link from a thread or the sidebar only knows the repository, so the owning project is
+ // resolved here; an explicit `projectId` in the URL still wins.
+ const projectIdForRepository = useMemo(() => {
+ const repository = search.repository?.toLowerCase();
+ if (repository === undefined) return undefined;
+ const identity = projects.find(
+ (project) =>
+ project.repositoryIdentity?.owner &&
+ project.repositoryIdentity.name &&
+ `${project.repositoryIdentity.owner}/${project.repositoryIdentity.name}`.toLowerCase() ===
+ repository &&
+ // The same `owner/name` can exist on two hosts. Without this the first match wins, and
+ // a link that named its host opens the pull request from the other one.
+ (search.host === undefined ||
+ pullRequestHostOf(
+ project.repositoryIdentity,
+ project.repositoryIdentity.provider as SourceControlProviderKind,
+ ) === search.host.toLowerCase()),
+ );
+ return identity?.id;
+ }, [projects, search.host, search.repository]);
+
+ // The selection is resolved the same way the scope is: an id no connected environment has can
+ // never be read here, and one that arrived before the projects did is not yet wrong.
+ const linkedProjectId = useMemo(
+ () => resolveProjectScope(search.selectedProjectId, projects, projectsKnown),
+ [projects, projectsKnown, search.selectedProjectId],
+ );
+ // The scope filter stands in as a last resort: a link can carry `projectId` with a repository
+ // whose identity the inference above cannot match, and refusing to open it because of the
+ // weaker signal would ignore the stronger one the URL spelled out.
+ const selectedProjectId = linkedProjectId ?? projectIdForRepository ?? scopedProjectId;
+ // Which server the selection belongs to. Named by the URL where a link had one to give;
+ // otherwise the project id decides, and only where exactly one server has that project.
+ // A named server still connecting is kept named rather than falling back: falling back while
+ // it is merely not ready yet would resolve the project against whatever other server has
+ // answered, which can be the wrong one where two servers share a project id. Only a name this
+ // workspace has never heard of falls back to the scope above, the same way that scope treats a
+ // stale name — a saved link naming a server that has since gone would otherwise open nothing,
+ // even where the project id it also carries names exactly one remaining server.
+ const selectedEnvironmentId = resolveSelectedEnvironmentId(
+ search.selectedEnvironmentId,
+ knownEnvironmentIds,
+ scopedEnvironmentId,
+ );
+ const selectedProject = useMemo(
+ () => findScopedProject(projects, selectedEnvironmentId, selectedProjectId),
+ [projects, selectedEnvironmentId, selectedProjectId],
+ );
+ // One panel for the page rather than one per server: the surfaces carry the server they were
+ // read from, so tabs from two of them sit side by side instead of replacing each other. Its ref
+ // uses a fixed sentinel environment, not whichever server happens to sort first, so the tab
+ // strip survives a capable server disconnecting or losing the pull-requests capability.
const rightPanelRef = useMemo(
- () => (environmentId === null ? null : scopeThreadRef(environmentId, PULL_REQUESTS_PANEL_ID)),
- [environmentId],
+ () =>
+ capableEnvironments.length === 0
+ ? null
+ : scopeThreadRef(PULL_REQUESTS_PANEL_ENVIRONMENT_ID, PULL_REQUESTS_PANEL_ID),
+ [capableEnvironments.length],
);
const rightPanelState = useRightPanelStore((state) =>
selectThreadRightPanelState(state.byThreadKey, rightPanelRef),
@@ -207,17 +377,27 @@ function PullRequestsRouteView() {
const selectedPullRequestSurface =
selectedRightPanelSurface?.kind === "pull-request" ? selectedRightPanelSurface : null;
const activePullRequestSurface = rightPanelState.isOpen ? selectedPullRequestSurface : null;
+ // The open tab names its own server; a link that arrived before any tab was opened names it
+ // through the project it selected.
+ const panelEnvironmentId =
+ (activePullRequestSurface?.environmentId as EnvironmentId | undefined) ??
+ selectedProject?.environmentId ??
+ null;
const [pullRequestTabStatuses, setPullRequestTabStatuses] = useState<
Record<string, PullRequestTabStatus>
>({});
- const handlePullRequestTabStatusChange = useCallback((status: PullRequestTabStatus) => {
- const id = pullRequestSurfaceId(status);
- setPullRequestTabStatuses((current) =>
- current[id]?.state === status.state && current[id]?.isDraft === status.isDraft
- ? current
- : { ...current, [id]: status },
- );
- }, []);
+ // Keyed by the surface the panel is showing rather than by a key rebuilt from the status: a
+ // surface opened from this page carries the environment its row was listed under, and a key
+ // assembled from the pull request alone would never name that surface back.
+ const activePullRequestSurfaceId = activePullRequestSurface?.id;
+ const handlePullRequestTabStatusChange = useCallback(
+ (status: PullRequestTabStatus) => {
+ const id = activePullRequestSurfaceId;
+ if (id === undefined) return;
+ setPullRequestTabStatuses((current) => updatePullRequestTabStatus(current, id, status));
+ },
+ [activePullRequestSurfaceId],
+ );
const updateSearch = useCallback(
(patch: {
@@ -234,9 +414,16 @@ function PullRequestsRouteView() {
...(next.repository ? { repository: next.repository } : {}),
...(next.number ? { number: next.number } : {}),
...(next.projectId ? { projectId: next.projectId } : {}),
+ ...(next.environmentId ? { environmentId: next.environmentId } : {}),
...(next.host ? { host: next.host } : {}),
...(next.selectedProjectId ? { selectedProjectId: next.selectedProjectId } : {}),
+ ...(next.selectedEnvironmentId
+ ? { selectedEnvironmentId: next.selectedEnvironmentId }
+ : {}),
...(next.q ? { q: next.q } : {}),
+ ...(next.draft ? { draft: next.draft } : {}),
+ ...(next.review ? { review: next.review } : {}),
+ ...(next.checks ? { checks: next.checks } : {}),
};
},
replace: true,
@@ -250,6 +437,7 @@ function PullRequestsRouteView() {
repository: undefined,
number: undefined,
selectedProjectId: undefined,
+ selectedEnvironmentId: undefined,
};
const updateListScope = (patch: {
[Key in keyof PullRequestsSearch]?: PullRequestsSearch[Key] | undefined;
@@ -267,47 +455,170 @@ function PullRequestsRouteView() {
const typedQuery = (search.q ?? "").trim();
const sentQuery = useDebouncedValue(typedQuery, SEARCH_DEBOUNCE_MS);
const querySettled = typedQuery === sentQuery;
+ // What was typed, split into the qualifiers the hosts can act on and the words that are left.
+ // The URL keeps the line as it was written; only the request sees the two halves.
+ const typedParsed = useMemo(() => parsePullRequestQuery(typedQuery), [typedQuery]);
+ const sentParsed = useMemo(() => parsePullRequestQuery(sentQuery), [sentQuery]);
+ // One record for the hosts, rebuilt only when the URL's own fields change so the listing
+ // inputs stay identical between renders.
+ const menuFilters = useMemo(
+ (): PullRequestListFilters => ({
+ ...(search.draft ? { draft: search.draft } : {}),
+ ...(search.review ? { review: search.review } : {}),
+ ...(search.checks ? { checks: search.checks } : {}),
+ }),
+ [search.checks, search.draft, search.review],
+ );
+ const menuFiltered = Object.keys(menuFilters).length > 0;
+ // A typed qualifier wins over the menu's own answer for the same thing, since it is the more
+ // recent word on it; labels only ever come from the query, so there is nothing to overrule.
+ const filters = useMemo(
+ (): PullRequestListFilters => ({ ...menuFilters, ...sentParsed.filters }),
+ [menuFilters, sentParsed.filters],
+ );
+ const hasFilters = Object.keys(filters).length > 0;
+ /** The same narrowings the moment they are typed, for the rows already on screen. */
+ const localFilters = useMemo(
+ (): PullRequestListFilters => ({ ...menuFilters, ...typedParsed.filters }),
+ [menuFilters, typedParsed.filters],
+ );
+ const hasLocalFilters = Object.keys(localFilters).length > 0;
+ // Scoping to a project scopes to the server that owns it, saving every other server a read
+ // that could only answer with nothing. Where an id is ambiguous — two servers holding the
+ // same project id, with no server named — only the servers that actually hold that id are
+ // asked: a server without it may still hold an unrelated project of its own under the same
+ // string, and asking it would return that project's rows rather than an honest empty answer.
+ const queryEnvironmentIds = useMemo(
+ () =>
+ resolveQueryEnvironmentIds(
+ environmentIds,
+ projects,
+ scopedProject,
+ scopedProjectId,
+ projectsKnown,
+ ),
+ [environmentIds, projects, projectsKnown, scopedProject, scopedProjectId],
+ );
+ /**
+ * Which projects each server is asked about. Two servers holding the same repository would both
+ * list the same pull requests, so each repository is listed by one of them — the first, which is
+ * where the page's actions land — and the others are asked only for what is theirs alone. A
+ * server left with nothing of its own is not read at all.
+ *
+ * Left alone while the projects are still arriving, and while the scope is a single project:
+ * that path deliberately asks both servers holding an ambiguous id.
+ */
+ const environmentQueries = useMemo((): ReadonlyArray<{
+ readonly environmentId: EnvironmentId;
+ readonly projectIds?: ReadonlyArray<ProjectId>;
+ }> => {
+ const plain = queryEnvironmentIds.map((environmentId) => ({ environmentId }));
+ if (!projectsKnown || scopedProjectId !== undefined) return plain;
+ const assignment = assignProjectsToEnvironments(
+ projects,
+ queryEnvironmentIds,
+ queryEnvironmentIds[0],
+ );
+ const totals = new Map<EnvironmentId, number>();
+ for (const project of projects) {
+ totals.set(project.environmentId, (totals.get(project.environmentId) ?? 0) + 1);
+ }
+ return queryEnvironmentIds.flatMap((environmentId) => {
+ const projectIds = assignment.get(environmentId);
+ if (projectIds === undefined) return [];
+ // It lists everything it holds anyway, so the filter is left off and a one-server workspace
+ // asks exactly the question it asked before.
+ if (projectIds.length === (totals.get(environmentId) ?? 0)) return [{ environmentId }];
+ return [{ environmentId, projectIds }];
+ });
+ }, [projects, projectsKnown, queryEnvironmentIds, scopedProjectId]);
+ // Part of the scope, since a different split is a different question and its answers must not
+ // be filed under the same page state.
+ const assignmentKey = useMemo(
+ () =>
+ environmentQueries
+ .map(({ environmentId, projectIds }) => `${environmentId}#${projectIds?.join("+") ?? "*"}`)
+ .join("|"),
+ [environmentQueries],
+ );
// Page size is view state, not a URL concern: a shared link should open the first page.
- const scopeKey = `${environmentId ?? ""}:${search.state}:${search.involvement}:${scopedProjectId ?? ""}:${search.host ?? ""}`;
+ const scopeKey = `${environmentKey}:${assignmentKey}:${search.state}:${search.involvement}:${scopedProjectId ?? ""}:${search.host ?? ""}:${search.draft ?? ""}:${search.review ?? ""}:${search.checks ?? ""}`;
const filterKey = `${scopeKey}:${sentQuery}`;
- // Where the next slice carries on from, per repository, as the server handed it back. Sending
- // it is what makes a second page cost a second page rather than the whole list again — and a
- // repository it does not name has run out and is not read a second time.
+ // Where the next slice carries on from, per repository within each environment, as that
+ // environment handed it back. Sending it is what makes a second page cost a second page rather
+ // than the whole list again — and a repository it does not name has run out and is not read a
+ // second time. An environment absent from it has nothing more to give at all.
const [page, setPage] = useState<{
key: string;
size: number;
- cursors: Record<string, string> | null;
- }>({ key: filterKey, size: PAGE_SIZE, cursors: null });
+ cursors: Readonly<Record<string, PullRequestListCursors>> | null;
+ /**
+ * The environments read again from the top at the larger page rather than continued. An
+ * environment can say it has more without saying where to carry on from — its provider has
+ * no cursor to give — and a continuation naming only the others would strand its rows on
+ * the host forever.
+ */
+ regrown: ReadonlyArray<string>;
+ }>({ key: filterKey, size: PAGE_SIZE, cursors: null, regrown: [] });
const pageSize = page.key === filterKey ? page.size : PAGE_SIZE;
const sentCursors = page.key === filterKey ? page.cursors : null;
+ const sentRegrown = page.key === filterKey ? page.regrown : [];
// Typing a search, or clearing one, starts the list again at its first page. Without this the
// paging state from before the search is still filed under these filters and comes back with
// it, so clearing would return to the slice that had been scrolled to rather than to the list.
useEffect(() => {
- setPage({ key: filterKey, size: PAGE_SIZE, cursors: null });
+ setPage({ key: filterKey, size: PAGE_SIZE, cursors: null, regrown: [] });
}, [filterKey]);
- const listQuery = useEnvironmentQuery(
- pullRequestEnvironmentId === null
- ? null
- : pullRequestEnvironment.list({
- environmentId: pullRequestEnvironmentId,
- input: {
- state: search.state,
- // The hosts narrow by involvement themselves — GitHub by author and review request,
- // and so on — so asking them is the difference between a page of results and a page
- // of everything with the answer somewhere further down it.
- involvement: search.involvement,
- limit: pageSize,
- ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
- ...(search.host ? { host: search.host } : {}),
- ...(sentQuery ? { query: sentQuery } : {}),
- ...(sentCursors ? { cursors: sentCursors } : {}),
+ /** The listing input each environment is asked for, which differs only in its continuation. */
+ const listTargets = useMemo(
+ () =>
+ environmentQueries.flatMap(({ environmentId, projectIds }) => {
+ const cursors = sentCursors?.[environmentId];
+ // A continuation asks the environments that said where to carry on from, plus the ones
+ // that have more to give but no cursor to give it from — those are read again at the
+ // larger page. The rest have run out, and re-reading them would answer with the page
+ // that is already on screen.
+ if (sentCursors !== null && cursors === undefined && !sentRegrown.includes(environmentId)) {
+ return [];
+ }
+ return [
+ {
+ environmentId,
+ input: {
+ state: search.state,
+ // The hosts narrow by involvement themselves — GitHub by author and review
+ // request, and so on — so asking them is the difference between a page of results
+ // and a page of everything with the answer somewhere further down it.
+ involvement: search.involvement,
+ limit: pageSize,
+ ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
+ ...(projectIds ? { projectIds } : {}),
+ ...(search.host ? { host: search.host } : {}),
+ ...(hasFilters ? { filters } : {}),
+ ...(sentParsed.text ? { query: sentParsed.text } : {}),
+ ...(cursors === undefined ? {} : { cursors }),
+ } satisfies PullRequestListInput,
},
- }),
+ ];
+ }),
+ [
+ filters,
+ hasFilters,
+ pageSize,
+ environmentQueries,
+ scopedProjectId,
+ search.host,
+ search.involvement,
+ search.state,
+ sentCursors,
+ sentRegrown,
+ sentParsed.text,
+ ],
);
+ const listQuery = usePullRequestList(listTargets);
/**
* The same filters with nothing typed, read whether or not anything is. It is the same atom the
@@ -319,20 +630,31 @@ function PullRequestsRouteView() {
* say which question it belongs to: mid-switch the text has already changed and the data has
* not, and a search's answer would file itself under the workspace.
*/
- const baselineQuery = useEnvironmentQuery(
- pullRequestEnvironmentId === null
- ? null
- : pullRequestEnvironment.list({
- environmentId: pullRequestEnvironmentId,
- input: {
- state: search.state,
- involvement: search.involvement,
- limit: PAGE_SIZE,
- ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
- ...(search.host ? { host: search.host } : {}),
- },
- }),
+ const baselineTargets = useMemo(
+ () =>
+ environmentQueries.map(({ environmentId, projectIds }) => ({
+ environmentId,
+ input: {
+ state: search.state,
+ involvement: search.involvement,
+ limit: PAGE_SIZE,
+ ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
+ ...(projectIds ? { projectIds } : {}),
+ ...(search.host ? { host: search.host } : {}),
+ ...(menuFiltered ? { filters: menuFilters } : {}),
+ } satisfies PullRequestListInput,
+ })),
+ [
+ menuFiltered,
+ menuFilters,
+ environmentQueries,
+ scopedProjectId,
+ search.host,
+ search.involvement,
+ search.state,
+ ],
);
+ const baselineQuery = usePullRequestList(baselineTargets);
// The priority groups' own reads. The feed below is paginated by recency, so an older authored
// or review-requested row can be missing from its first page; partitioned from these
// server-filtered reads instead, the priority view is complete up front and a continuation can
@@ -340,34 +662,35 @@ function PullRequestsRouteView() {
// so no partitions are read for one. These are the same atoms the Authored and Reviewing tabs
// ask for, so switching to either is answered from cache.
const partitionsWanted = search.involvement === "all" && typedQuery.length === 0;
- const authoredQuery = useEnvironmentQuery(
- pullRequestEnvironmentId === null || !partitionsWanted
- ? null
- : pullRequestEnvironment.list({
- environmentId: pullRequestEnvironmentId,
- input: {
- state: search.state,
- involvement: "authored",
- limit: PAGE_SIZE,
- ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
- ...(search.host ? { host: search.host } : {}),
- },
- }),
- );
- const reviewingQuery = useEnvironmentQuery(
- pullRequestEnvironmentId === null || !partitionsWanted
- ? null
- : pullRequestEnvironment.list({
- environmentId: pullRequestEnvironmentId,
- input: {
- state: search.state,
- involvement: "reviewing",
- limit: PAGE_SIZE,
- ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
- ...(search.host ? { host: search.host } : {}),
- },
- }),
- );
+ // Built together so the two reads share one memo, and in the same field order the feed's own
+ // input uses: the atoms are keyed by their input, so the Authored tab then reads this answer.
+ const partitionTargets = useMemo(() => {
+ if (!partitionsWanted) return { authored: NO_LIST_TARGETS, reviewing: NO_LIST_TARGETS };
+ const targetsFor = (involvement: PullRequestInvolvement) =>
+ environmentQueries.map(({ environmentId, projectIds }) => ({
+ environmentId,
+ input: {
+ state: search.state,
+ involvement,
+ limit: PAGE_SIZE,
+ ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
+ ...(projectIds ? { projectIds } : {}),
+ ...(search.host ? { host: search.host } : {}),
+ ...(menuFiltered ? { filters: menuFilters } : {}),
+ } satisfies PullRequestListInput,
+ }));
+ return { authored: targetsFor("authored"), reviewing: targetsFor("reviewing") };
+ }, [
+ menuFiltered,
+ menuFilters,
+ partitionsWanted,
+ environmentQueries,
+ scopedProjectId,
+ search.host,
+ search.state,
+ ]);
+ const authoredQuery = usePullRequestList(partitionTargets.authored);
+ const reviewingQuery = usePullRequestList(partitionTargets.reviewing);
// The header's refresh punches through the server's cache before re-reading; the error and
// empty states retry plainly, because a failure is never cached.
const invalidate = useAtomCommand(pullRequestEnvironment.invalidate, { reportFailure: false });
@@ -382,9 +705,11 @@ function PullRequestsRouteView() {
const refreshFromHost = async () => {
setInvalidating(true);
try {
- if (pullRequestEnvironmentId !== null) {
- await invalidate({ environmentId: pullRequestEnvironmentId, input: {} });
- }
+ // Every environment the page is reading, since what the reader pressed refresh for is the
+ // list in front of them rather than whichever machine happens to be first.
+ await Promise.all(
+ queryEnvironmentIds.map((environmentId) => invalidate({ environmentId, input: {} })),
+ );
} finally {
setInvalidating(false);
}
@@ -402,38 +727,47 @@ function PullRequestsRouteView() {
// out: a longer page reads as growth, and a search shows the rows it already has, narrowed
// here, until the hosts answer for themselves.
const [loaded, setLoaded] = useState<{
- environmentId: EnvironmentId | null;
+ environmentKey: string;
scope: string;
query: string;
- data: PullRequestListResult;
+ data: MergedPullRequestList;
/** The priority groups' own answers, carried so a cold start has whole groups too. */
partitions?: PullRequestPartitionsSnapshot;
} | null>(null);
+ // A longer page is the same list with more on the end, so the rows already read stay where
+ // they were read: each answer is merged onto the last rather than replacing it, and anything
+ // new lands at the bottom. Only a different question — other filters, another search — starts
+ // the order again. Declared here, ahead of the snapshot write below, so that write can read
+ // this round's accumulation rather than only its own slice.
+ const [ordered, setOrdered] = useState<{
+ key: string;
+ entries: ReadonlyArray<EnvironmentPullRequestEntry>;
+ } | null>(null);
// A reload recreates the registry the queries live in, so with nothing held the page would
// cold-start into skeletons even though almost every row is unchanged. The last answer for
- // this environment is kept across reloads and hydrated here as the carried rows: they render
- // at once — narrowed to the current filters like any carried answer — and the live read
+ // this set of environments is kept across reloads and hydrated here as the carried rows: they
+ // render at once — narrowed to the current filters like any carried answer — and the live read
// reconciles them in place by key rather than replacing them with ghosts.
useEffect(() => {
- if (environmentId === null) return;
+ if (environmentKey.length === 0) return;
setLoaded((current) => {
- // Another environment's rows could not even be narrowed — nothing on a row says which
- // environment read it — so its snapshot beats holding them.
- if (current !== null && current.environmentId === environmentId) return current;
+ // Rows read from a different set of environments cannot even be narrowed — one of them may
+ // no longer be connected at all — so that set's own snapshot beats holding them.
+ if (current !== null && current.environmentKey === environmentKey) return current;
const snapshot = readPullRequestListSnapshot(
typeof window === "undefined" ? undefined : window.localStorage,
- environmentId,
+ environmentKey,
);
if (snapshot === null) return null;
return {
- environmentId,
+ environmentKey,
scope: snapshot.scope,
query: "",
data: snapshot.data,
...(snapshot.partitions === undefined ? {} : { partitions: snapshot.partitions }),
};
});
- }, [environmentId]);
+ }, [environmentKey]);
useEffect(() => {
// Only once this query has settled. While a search is being swapped in or out the text has
// already changed and the data has not, so recording them together would file the previous
@@ -450,22 +784,38 @@ function PullRequestsRouteView() {
partitionsWanted && authoredQuery.data !== null && reviewingQuery.data !== null
? { authored: authoredQuery.data.entries, reviewing: reviewingQuery.data.entries }
: current !== null &&
- current.environmentId === environmentId &&
+ current.environmentKey === environmentKey &&
current.scope === scopeKey
? current.partitions
: undefined;
// A search's answer is the search's, not the workspace's, so only unsearched lists
// persist. Written here where the held partitions are in reach, so a feed settling
// ahead of them cannot overwrite a stored snapshot that already had both groups.
- if (environmentId !== null && sentQuery.length === 0) {
+ //
+ // What is written is what the reader is actually looking at, not this round's own
+ // answer: a continuation only asks the environments still paging, so its answer alone is
+ // missing both the rows read on earlier pages and the hosts of whichever environment had
+ // already run out of cursors. `ordered` carries the accumulated rows, and the baseline
+ // read — which never drops an environment for lack of a cursor — carries the full hosts.
+ if (environmentKey.length > 0 && sentQuery.length === 0) {
+ const accumulatedEntries = ordered?.key === filterKey ? ordered.entries : data.entries;
writePullRequestListSnapshot(
typeof window === "undefined" ? undefined : window.localStorage,
- environmentId,
- { scope: scopeKey, data, ...(partitions === undefined ? {} : { partitions }) },
+ environmentKey,
+ {
+ scope: scopeKey,
+ data: {
+ ...data,
+ entries: accumulatedEntries,
+ viewers: baselineQuery.data?.viewers ?? data.viewers,
+ providers: baselineQuery.data?.providers ?? data.providers,
+ },
+ ...(partitions === undefined ? {} : { partitions }),
+ },
);
}
return {
- environmentId,
+ environmentKey,
scope: scopeKey,
query: sentQuery,
data,
@@ -473,7 +823,7 @@ function PullRequestsRouteView() {
};
});
}, [
- environmentId,
+ environmentKey,
scopeKey,
sentQuery,
listQuery.data,
@@ -481,15 +831,18 @@ function PullRequestsRouteView() {
partitionsWanted,
authoredQuery.data,
reviewingQuery.data,
+ ordered,
+ filterKey,
+ baselineQuery.data,
]);
// Changing a filter asks a question nothing has answered yet, and the page is already holding
// perfectly good rows for the last one. Rather than blank out for the round trip, those rows
// are narrowed to the new filters and stay until the answer lands — a subset of it, never a
// row it excludes. Narrowed to nothing there is nothing to carry, and the skeletons below are
- // right after all. Another environment's rows are dropped rather than narrowed: nothing on a
- // row says which environment read it.
+ // right after all. Rows read from a different set of environments are dropped rather than
+ // narrowed: one of those environments may no longer be connected.
const narrowed = useMemo(() => {
- if (loaded === null || loaded.environmentId !== environmentId || loaded.scope === scopeKey) {
+ if (loaded === null || loaded.environmentKey !== environmentKey || loaded.scope === scopeKey) {
return null;
}
const entries = narrowPullRequestsToFilters(loaded.data.entries, {
@@ -498,7 +851,7 @@ function PullRequestsRouteView() {
host: search.host,
});
return entries.length === 0 ? null : { ...loaded.data, entries };
- }, [environmentId, loaded, scopeKey, scopedProjectId, search.host, search.state]);
+ }, [environmentKey, loaded, scopeKey, scopedProjectId, search.host, search.state]);
// With nothing typed and nothing to carry on from, the answer is taken from the read that is
// keyed to exactly that question. Otherwise a search's answer lingers for a render after the
// text has gone — the data cannot say which question it belongs to, but the read it came from
@@ -524,19 +877,16 @@ function PullRequestsRouteView() {
/** Nothing read and nothing to carry, which is the one thing skeletons are for. */
const firstLoad = listQuery.isPending && listData === null;
- // A longer page is the same list with more on the end, so the rows already read stay where
- // they were read: each answer is merged onto the last rather than replacing it, and anything
- // new lands at the bottom. Only a different question — other filters, another search — starts
- // the order again.
- const [ordered, setOrdered] = useState<{
- key: string;
- entries: ReadonlyArray<PullRequestListEntry>;
- } | null>(null);
+ // `ordered` is declared above, ahead of the snapshot write, but grown here from this round's
+ // own answer.
useEffect(() => {
if (!answered) return;
setOrdered((previous) => {
if (previous === null || previous.key !== filterKey) {
- return { key: filterKey, entries: rankPullRequestMatches(answered.entries, sentQuery) };
+ return {
+ key: filterKey,
+ entries: rankPullRequestMatches(answered.entries, sentParsed.text),
+ };
}
if (sentCursors !== null) {
// A continuation is a slice, not the list: it carries only what comes after the rows
@@ -547,7 +897,7 @@ function PullRequestsRouteView() {
const arrived = answered.entries.filter((entry) => !held.has(pullRequestEntryKey(entry)));
const appended = rankPullRequestMatches(
arrived.toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
- sentQuery,
+ sentParsed.text,
);
return { key: filterKey, entries: [...previous.entries, ...appended] };
}
@@ -556,9 +906,9 @@ function PullRequestsRouteView() {
// since the last read at the bottom of the page — below rows a week older — where "the
// latest" is exactly what a refresh was for. The host answers in the order the page
// reads, so its order stands; a row that moved was updated, and moving is the news.
- return { key: filterKey, entries: rankPullRequestMatches(answered.entries, sentQuery) };
+ return { key: filterKey, entries: rankPullRequestMatches(answered.entries, sentParsed.text) };
});
- }, [answered, filterKey, sentCursors, sentQuery]);
+ }, [answered, filterKey, sentCursors, sentParsed.text]);
// Carrying on where the last answer stopped, and only raising the page size for the hosts that
// could not say where that was.
@@ -566,16 +916,27 @@ function PullRequestsRouteView() {
// continuation is a boundary in one listing, and carrying one across a search would ask the
// new question to start where the old one stopped — skipping its newest matches entirely.
const nextCursors = answered?.nextCursors ?? {};
+ // The environments with more rows and no cursor to reach them by. They come along with any
+ // continuation, read again at a page one step larger, which is the only way they grow.
+ const regrown = (answered?.truncatedEnvironments ?? []).filter(
+ (environmentId) => nextCursors[environmentId] === undefined,
+ );
const canContinue = !showingCarried && Object.keys(nextCursors).length > 0;
const loadMore = () => {
if (canContinue) {
- setPage({ key: filterKey, size: pageSize, cursors: nextCursors });
+ setPage({
+ key: filterKey,
+ size: regrown.length === 0 ? pageSize : Math.min(pageSize + PAGE_SIZE, MAX_PAGE_SIZE),
+ cursors: nextCursors,
+ regrown,
+ });
return;
}
setPage({
key: filterKey,
size: Math.min(pageSize + PAGE_SIZE, MAX_PAGE_SIZE),
cursors: null,
+ regrown: [],
});
};
@@ -591,6 +952,7 @@ function PullRequestsRouteView() {
const loadedCount = ordered?.key === filterKey ? ordered.entries.length : pageSize;
setPage({
key: filterKey,
+ regrown: [],
size: Math.min(
Math.max(pageSize, Math.ceil(loadedCount / PAGE_SIZE) * PAGE_SIZE),
MAX_PAGE_SIZE,
@@ -611,7 +973,7 @@ function PullRequestsRouteView() {
authoredQuery.refresh();
reviewingQuery.refresh();
},
- { enabled: pullRequestEnvironmentId !== null },
+ { enabled: pullRequestsSupported },
);
const viewers = baselineQuery.data?.viewers ?? listData?.viewers ?? EMPTY_VIEWERS;
@@ -636,22 +998,39 @@ function PullRequestsRouteView() {
// The local pass stands in for the answer that has not arrived yet, and for the hosts that
// answered without searching at all: Azure DevOps has no text filter, so its rows arrive
// whole and would otherwise sit under a search that never touched them.
- if (typedQuery.length === 0) return involvementEntries;
+ // The rows the hosts could not narrow themselves, for the fields a row actually carries:
+ // a host with no filter of its own answers unnarrowed, and so does one whose answer for the
+ // new filters has not arrived yet. Checks are absent here, because no row carries them.
+ const narrowedEntries = hasLocalFilters
+ ? involvementEntries.filter((entry) =>
+ matchesPullRequestFilters(entry, localFilters, pullRequestEntryViewer(entry, viewers)),
+ )
+ : involvementEntries;
+ // Newest update first once nothing is typed, so a list merged from several hosts reads in
+ // one order rather than in each host's. With a search on, the relevance ranking above is
+ // the order, and re-sorting by date here would undo it.
+ if (typedParsed.text.length === 0) {
+ return narrowedEntries.toSorted((left, right) =>
+ right.updatedAt.localeCompare(left.updatedAt),
+ );
+ }
const answeredLocally = querySettled && !showingCarried;
- return involvementEntries.filter(
+ return narrowedEntries.filter(
(entry) =>
(answeredLocally && searchingHosts.has(entry.host)) ||
- matchesPullRequestQuery(entry, typedQuery),
+ matchesPullRequestQuery(entry, typedParsed.text),
);
}, [
filterKey,
+ hasLocalFilters,
+ localFilters,
listData,
ordered,
querySettled,
search.involvement,
searchingHosts,
showingCarried,
- typedQuery,
+ typedParsed.text,
viewers,
]);
@@ -717,21 +1096,34 @@ function PullRequestsRouteView() {
// authored row older than it. Once the live reads land they take over; with neither,
// the local grouping is still better than nothing.
const held =
- loaded !== null && loaded.environmentId === environmentId && loaded.scope === scopeKey
+ loaded !== null && loaded.environmentKey === environmentKey && loaded.scope === scopeKey
? loaded.partitions
: undefined;
- const authored = partitionsWanted ? (authoredQuery.data?.entries ?? held?.authored) : undefined;
- const reviewing = partitionsWanted
- ? (reviewingQuery.data?.entries ?? held?.reviewing)
- : undefined;
+ // The priority reads answer the same question the feed does, so they take the same local
+ // narrowing: a host that cannot filter for itself would otherwise put rows into Authored
+ // that the filters above just took out of the feed.
+ const narrow = (rows: ReadonlyArray<EnvironmentPullRequestEntry> | undefined) =>
+ rows === undefined || !hasLocalFilters
+ ? rows
+ : rows.filter((entry) =>
+ matchesPullRequestFilters(entry, localFilters, pullRequestEntryViewer(entry, viewers)),
+ );
+ const authored = narrow(
+ partitionsWanted ? (authoredQuery.data?.entries ?? held?.authored) : undefined,
+ );
+ const reviewing = narrow(
+ partitionsWanted ? (reviewingQuery.data?.entries ?? held?.reviewing) : undefined,
+ );
if (authored === undefined || reviewing === undefined) {
return groupPullRequestsByInvolvement(entries, viewers);
}
return partitionPullRequestsWithPriority(entries, authored, reviewing);
}, [
+ hasLocalFilters,
+ localFilters,
authoredQuery.data?.entries,
entries,
- environmentId,
+ environmentKey,
loaded,
partitionsWanted,
reviewingQuery.data?.entries,
@@ -741,75 +1133,51 @@ function PullRequestsRouteView() {
]);
// Keyed by every row being shown — the partitions can hold rows the feed has not paged to —
- // so scrolling further asks only about what is new.
- const statsInput = useMemo(
- () => ({
- refs: groups
- .flatMap((group) => group.entries)
- .map((entry) => ({
+ // so scrolling further asks only about what is new. One read per environment, each asking only
+ // about its own rows: a reference names a project, and a project belongs to one machine.
+ const statsTargets = useMemo(() => {
+ const refsByEnvironment = new Map<
+ EnvironmentId,
+ Array<{ projectId: ProjectId; repository: string; number: number }>
+ >();
+ for (const group of groups) {
+ for (const entry of group.entries) {
+ const refs = refsByEnvironment.get(entry.environmentId) ?? [];
+ refs.push({
projectId: entry.projectId,
repository: entry.repository,
number: entry.number,
- })),
- }),
- [groups],
- );
- const statsQuery = useEnvironmentQuery(
- pullRequestEnvironmentId === null || statsInput.refs.length === 0
- ? null
- : pullRequestEnvironment.listStats({
- environmentId: pullRequestEnvironmentId,
- input: statsInput,
- }),
- );
+ });
+ refsByEnvironment.set(entry.environmentId, refs);
+ }
+ }
+ return [...refsByEnvironment].map(([environmentId, refs]) => ({
+ environmentId,
+ input: { refs },
+ }));
+ }, [groups]);
+ const statsQuery = usePullRequestListStats(statsTargets);
// Adding or removing one row keys a fresh stats query with nothing in it yet, so the counts
// are merged into what is already held rather than rebuilt: every count on screen stays until
// its replacement arrives.
const [statsByRow, setStatsByRow] = useState<PullRequestDiffStats>(() => new Map());
useEffect(() => {
- const stats = statsQuery.data?.stats;
- if (stats === undefined) return;
+ const stats = statsQuery.stats;
+ if (stats === null) return;
setStatsByRow((previous) => mergePullRequestDiffStats(previous, stats));
- }, [statsQuery.data]);
+ }, [statsQuery.stats]);
- // A link from a thread or the sidebar only knows the repository, so the owning project is
- // resolved here; an explicit `projectId` in the URL still wins.
- const projectIdForRepository = useMemo(() => {
- const repository = search.repository?.toLowerCase();
- if (repository === undefined) return undefined;
- const identity = projects.find(
- (project) =>
- project.repositoryIdentity?.owner &&
- project.repositoryIdentity.name &&
- `${project.repositoryIdentity.owner}/${project.repositoryIdentity.name}`.toLowerCase() ===
- repository &&
- // The same `owner/name` can exist on two hosts. Without this the first match wins, and
- // a link that named its host opens the pull request from the other one.
- (search.host === undefined ||
- pullRequestHostOf(
- project.repositoryIdentity,
- project.repositoryIdentity.provider as SourceControlProviderKind,
- ) === search.host.toLowerCase()),
- );
- return identity?.id;
- }, [projects, search.host, search.repository]);
-
- // The selection is resolved the same way the scope is: an id from another environment can
- // never be read here, and one that arrived before the projects did is not yet wrong.
- const linkedProjectId = useMemo(
- () => resolveProjectScope(search.selectedProjectId, projects, projectsKnown),
- [projects, projectsKnown, search.selectedProjectId],
- );
- // The scope filter stands in as a last resort: a link can carry `projectId` with a repository
- // whose identity the inference above cannot match, and refusing to open it because of the
- // weaker signal would ignore the stronger one the URL spelled out.
- const selectedProjectId = linkedProjectId ?? projectIdForRepository ?? scopedProjectId;
const linkedSelection = useMemo(
() =>
- search.repository && search.number && selectedProjectId
- ? { repository: search.repository, number: search.number, projectId: selectedProjectId }
+ search.repository && search.number && selectedProject
+ ? {
+ environmentId: selectedProject.environmentId,
+ repository: search.repository,
+ number: search.number,
+ projectId: selectedProject.id,
+ }
: null,
- [search.number, search.repository, selectedProjectId],
+ [search.number, search.repository, selectedProject],
);
useEffect(() => {
if (!pullRequestsSupported || rightPanelRef === null || linkedSelection === null) return;
@@ -819,6 +1187,7 @@ function PullRequestsRouteView() {
const selected =
rightPanelState.isOpen && activePullRequestSurface !== null
? {
+ environmentId: activePullRequestSurface.environmentId,
repository: activePullRequestSurface.repository,
number: activePullRequestSurface.number,
projectId: activePullRequestSurface.projectId as ProjectId,
@@ -833,6 +1202,9 @@ function PullRequestsRouteView() {
repository: surface.repository,
number: surface.number,
selectedProjectId: surface.projectId as ProjectId,
+ ...(surface.environmentId === undefined
+ ? {}
+ : { selectedEnvironmentId: surface.environmentId as EnvironmentId }),
},
);
@@ -884,13 +1256,15 @@ function PullRequestsRouteView() {
// Stable so the memoized rows can skip re-rendering when the list around them changes.
const selectEntry = useCallback(
- (entry: PullRequestListEntry) => {
+ (entry: EnvironmentPullRequestEntry) => {
+ // The surface carries the row's own server, which is what its detail reads and acts on.
if (rightPanelRef === null) return;
useRightPanelStore.getState().openPullRequest(rightPanelRef, entry);
updateSearch({
repository: entry.repository,
number: entry.number,
selectedProjectId: entry.projectId,
+ selectedEnvironmentId: entry.environmentId,
});
},
[rightPanelRef, updateSearch],
@@ -936,7 +1310,7 @@ function PullRequestsRouteView() {
) : !pullRequestsSupported ? (
<PullRequestsUnavailableState
title="Pull requests unavailable"
- error="Update this environment's T3 Code server to browse pull requests."
+ error="Update your T3 Code servers to browse pull requests."
/>
) : firstLoad ? (
<PullRequestListGhost rows={7} />
@@ -980,14 +1354,20 @@ function PullRequestsRouteView() {
entry={withDiffStat(entry, statsByRow)}
showProjectTitle
showProvider={showProvider}
+ {...(capableEnvironments.length > 1 &&
+ environmentLabels.get(entry.environmentId) !== undefined
+ ? { environmentLabel: environmentLabels.get(entry.environmentId)! }
+ : {})}
// Ten is the floor the ranking gives a row whose own fields say nothing
// about the search: the host matched something this row cannot show.
matchedElsewhere={
- typedQuery.length > 0 &&
- scorePullRequestMatch(entry, typedQuery) <= MATCHED_ELSEWHERE_SCORE
+ typedParsed.text.length > 0 &&
+ scorePullRequestMatch(entry, typedParsed.text) <= MATCHED_ELSEWHERE_SCORE
}
selected={
- selected?.repository === entry.repository && selected.number === entry.number
+ selected?.environmentId === entry.environmentId &&
+ selected.repository === entry.repository &&
+ selected.number === entry.number
}
onSelect={selectEntry}
/>
@@ -1037,6 +1417,16 @@ function PullRequestsRouteView() {
};
}),
];
+ // The same shape the host pills take, so the two groups read as one control. A local
+ // connection wears the screen it is on; every other server wears a server.
+ const serverMenuOptions: ReadonlyArray<PullRequestFilterOption<string>> = [
+ { value: "", label: "All servers", Icon: LayersIcon },
+ ...capableEnvironments.map((environment) => ({
+ value: environment.environmentId,
+ label: environment.label,
+ Icon: environment.displayUrl === null ? MonitorIcon : ServerIcon,
+ })),
+ ];
const filtersMenu = (
<PullRequestFiltersMenu
state={search.state}
@@ -1045,14 +1435,28 @@ function PullRequestsRouteView() {
involvement={search.involvement}
involvementOptions={INVOLVEMENT_TABS}
onInvolvement={(involvement) => updateListScope({ involvement })}
+ filters={menuFilters}
+ onFilters={(next) =>
+ updateListScope({ draft: next.draft, review: next.review, checks: next.checks })
+ }
host={search.host}
hostOptions={hostMenuOptions}
onHost={(host) => updateListScope({ host })}
- environmentId={environmentId}
+ server={scopedEnvironmentId ?? undefined}
+ serverOptions={serverMenuOptions}
+ // Narrowing to one server drops a project scope belonging to another, which would
+ // otherwise narrow the list to nothing with no visible filter to explain it.
+ onServer={(server) => updateListScope({ environmentId: server, projectId: undefined })}
projects={scopedProjects}
projectId={scopedProjectId}
+ projectEnvironmentId={scopedProject?.environmentId}
unavailable={unavailableProjects}
- onProject={(projectId) => updateListScope({ projectId })}
+ // The environment comes along with the project it belongs to, so a duplicate id on
+ // another server never gets narrowed to by mistake; picking "All projects" leaves the
+ // server scope as it was rather than clearing it.
+ onProject={(projectId, environmentId) =>
+ updateListScope(environmentId === undefined ? { projectId } : { projectId, environmentId })
+ }
/>
);
const columnProps = {
@@ -1114,7 +1518,7 @@ function PullRequestsRouteView() {
{pullRequestsSupported && rightPanelState.isOpen ? openPanelControls : null}
<PullRequestsColumn {...columnProps} />
- {rightPanelState.isOpen && activePullRequestSurface && pullRequestEnvironmentId !== null ? (
+ {rightPanelState.isOpen && activePullRequestSurface && panelEnvironmentId !== null ? (
<RightPanelTabs
mode="inline"
widthStorageKey="t3code:pull-request-panel-width"
@@ -1158,7 +1562,7 @@ function PullRequestsRouteView() {
>
<PullRequestDetailPanel
key={activePullRequestSurface.id}
- environmentId={pullRequestEnvironmentId}
+ environmentId={panelEnvironmentId}
reference={{
projectId: activePullRequestSurface.projectId as ProjectId,
repository: activePullRequestSurface.repository,
diff --git a/apps/web/src/state/pullRequests.ts b/apps/web/src/state/pullRequests.ts
index 6d8d2751b..1445ceca0 100644
--- a/apps/web/src/state/pullRequests.ts
+++ b/apps/web/src/state/pullRequests.ts
@@ -1,5 +1,129 @@
+import { useAtomValue } from "@effect/atom-react";
import { createPullRequestEnvironmentAtoms } from "@t3tools/client-runtime/state/pull-requests";
+import type {
+ EnvironmentId,
+ PullRequestListInput,
+ PullRequestListStatsInput,
+} from "@t3tools/contracts";
+import * as Option from "effect/Option";
+import { AsyncResult, Atom } from "effect/unstable/reactivity";
+import { useCallback, useMemo } from "react";
import { connectionAtomRuntime } from "../connection/runtime";
+import { appAtomRegistry } from "../rpc/atomRegistry";
+import {
+ mergePullRequestLists,
+ type EnvironmentPullRequestStat,
+ type MergedPullRequestList,
+} from "../components/pullRequest/pullRequestList.logic";
+import { formatEnvironmentQueryError } from "./query";
export const pullRequestEnvironment = createPullRequestEnvironmentAtoms(connectionAtomRuntime);
+
+export interface EnvironmentQueryTarget<Input> {
+ readonly environmentId: EnvironmentId;
+ readonly input: Input;
+}
+
+interface MergedEnvironmentQueryView<A> {
+ /** One entry per environment that has answered, in the order the targets were given. */
+ readonly values: ReadonlyArray<readonly [EnvironmentId, A]>;
+ /** The first environment that failed. Others may still have answered — this is not fatal. */
+ readonly error: string | null;
+ readonly isPending: boolean;
+}
+
+/**
+ * The same per-environment query read across several environments at once. React cannot subscribe
+ * to a list of atoms whose length changes, so the fan-out happens inside one derived atom keyed by
+ * the targets — the same shape the cross-environment thread search uses.
+ *
+ * An environment that fails contributes nothing rather than blanking the page: the pull request
+ * list is a union, and one unreachable machine should not hide the others' rows.
+ */
+function createMergedEnvironmentQuery<Input, A>(
+ label: string,
+ atomFor: (
+ target: EnvironmentQueryTarget<Input>,
+ ) => Atom.Atom<AsyncResult.AsyncResult<A, unknown>>,
+) {
+ const family = Atom.family((key: string) =>
+ Atom.make((get): MergedEnvironmentQueryView<A> => {
+ const targets = JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>;
+ const values: Array<readonly [EnvironmentId, A]> = [];
+ let error: string | null = null;
+ let isPending = false;
+ for (const target of targets) {
+ const result = get(atomFor(target));
+ isPending ||= result.waiting;
+ if (result._tag === "Failure" && error === null) {
+ error = formatEnvironmentQueryError(result.cause);
+ }
+ const value = Option.getOrNull(AsyncResult.value(result));
+ if (value !== null) values.push([target.environmentId, value]);
+ }
+ return { values, error, isPending };
+ }).pipe(Atom.withLabel(`${label}:${key}`)),
+ );
+ const empty = Atom.make<MergedEnvironmentQueryView<A>>({
+ values: [],
+ error: null,
+ isPending: false,
+ }).pipe(Atom.withLabel(`${label}:empty`));
+ return function useMergedQuery(targets: ReadonlyArray<EnvironmentQueryTarget<Input>>) {
+ const key = JSON.stringify(targets);
+ const view = useAtomValue(targets.length === 0 ? empty : family(key));
+ const refresh = useCallback(() => {
+ for (const target of JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>) {
+ appAtomRegistry.refresh(atomFor(target));
+ }
+ }, [key]);
+ return { ...view, refresh };
+ };
+}
+
+const usePullRequestListsQuery = createMergedEnvironmentQuery(
+ "web-pull-requests:list",
+ pullRequestEnvironment.list,
+);
+
+const usePullRequestStatsQuery = createMergedEnvironmentQuery(
+ "web-pull-requests:list-stats",
+ pullRequestEnvironment.listStats,
+);
+
+export interface MergedPullRequestListView {
+ readonly data: MergedPullRequestList | null;
+ readonly error: string | null;
+ readonly isPending: boolean;
+ readonly refresh: () => void;
+}
+
+/** One listing per environment, merged into the single list the page renders. */
+export function usePullRequestList(
+ targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
+): MergedPullRequestListView {
+ const query = usePullRequestListsQuery(targets);
+ const data = useMemo(() => mergePullRequestLists(query.values), [query.values]);
+ return { data, error: query.error, isPending: query.isPending, refresh: query.refresh };
+}
+
+/** The line counts for the rows on screen, asked of each environment for its own rows. */
+export function usePullRequestListStats(
+ targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListStatsInput>>,
+): {
+ readonly stats: ReadonlyArray<EnvironmentPullRequestStat> | null;
+ readonly refresh: () => void;
+} {
+ const query = usePullRequestStatsQuery(targets);
+ const stats = useMemo(
+ () =>
+ query.values.length === 0
+ ? null
+ : query.values.flatMap(([environmentId, result]) =>
+ result.stats.map((stat) => ({ ...stat, environmentId })),
+ ),
+ [query.values],
+ );
+ return { stats, refresh: query.refresh };
+}
diff --git a/apps/web/src/state/query.ts b/apps/web/src/state/query.ts
index 2610f1724..9bc16b01f 100644
--- a/apps/web/src/state/query.ts
+++ b/apps/web/src/state/query.ts
@@ -14,7 +14,7 @@ export interface EnvironmentQueryView<A> {
readonly refresh: () => void;
}
-function formatError(cause: Cause.Cause<unknown>): string {
+export function formatEnvironmentQueryError(cause: Cause.Cause<unknown>): string {
const error = Cause.squash(cause);
return error instanceof Error && error.message.trim().length > 0
? error.message
@@ -29,7 +29,7 @@ export function useEnvironmentQuery<A, E>(
const refresh = useAtomRefresh(selectedAtom);
return {
data: Option.getOrNull(AsyncResult.value(result)),
- error: result._tag === "Failure" ? formatError(result.cause) : null,
+ error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null,
isPending: atom !== null && result.waiting,
refresh,
};
diff --git a/docs/user/source-control.md b/docs/user/source-control.md
index dc4a80232..1bce11ad5 100644
--- a/docs/user/source-control.md
+++ b/docs/user/source-control.md
@@ -44,6 +44,14 @@ T3 Code works with the platforms your team already uses:
- Open the review directly in your browser with one click
- Check out a teammate's branch to review code locally
+**Fix what you wrote, in place**
+
+- Rewrite a pull request's title and description from the review itself, in Markdown, with a
+ preview before you save
+- Rewrite your own comments the same way, wherever they are shown
+- Works on GitHub, GitLab, and Bitbucket. Azure DevOps takes a new title and description; its
+ comments stay read-only here, as they already were
+
### Know Your Setup at a Glance
The **Source Control settings** page shows you exactly what's connected:
diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.ts
index ad6c13822..7e84f4cb6 100644
--- a/packages/client-runtime/src/state/pullRequests.ts
+++ b/packages/client-runtime/src/state/pullRequests.ts
@@ -102,12 +102,24 @@ export function createPullRequestEnvironmentAtoms<R, E>(
scheduler: commandScheduler,
concurrency: serialPerEnvironment,
}),
+ update: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:pull-requests:update",
+ tag: WS_METHODS.pullRequestsUpdate,
+ scheduler: commandScheduler,
+ concurrency: serialPerEnvironment,
+ }),
comment: createEnvironmentRpcCommand(runtime, {
label: "environment-data:pull-requests:comment",
tag: WS_METHODS.pullRequestsComment,
scheduler: commandScheduler,
concurrency: serialPerEnvironment,
}),
+ updateComment: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:pull-requests:update-comment",
+ tag: WS_METHODS.pullRequestsUpdateComment,
+ scheduler: commandScheduler,
+ concurrency: serialPerEnvironment,
+ }),
submitReview: createEnvironmentRpcCommand(runtime, {
label: "environment-data:pull-requests:submit-review",
tag: WS_METHODS.pullRequestsSubmitReview,
@@ -143,6 +155,12 @@ export function createPullRequestEnvironmentAtoms<R, E>(
scheduler: commandScheduler,
concurrency: serialPerEnvironment,
}),
+ setReaction: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:pull-requests:set-reaction",
+ tag: WS_METHODS.pullRequestsSetReaction,
+ scheduler: commandScheduler,
+ concurrency: serialPerEnvironment,
+ }),
/**
* Explicit refresh: forget the server's cached answers, then re-run the reads. A separate
* request rather than a flag on a read, so only a person's refresh spends host requests
diff --git a/packages/contracts/src/environmentHttp.test.ts b/packages/contracts/src/environmentHttp.test.ts
new file mode 100644
index 000000000..4cd39074f
--- /dev/null
+++ b/packages/contracts/src/environmentHttp.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ EnvironmentAuthInvalidError,
+ EnvironmentInternalError,
+ EnvironmentOperationForbiddenError,
+ EnvironmentRequestInvalidError,
+ EnvironmentResourceNotFoundError,
+ EnvironmentScopeRequiredError,
+} from "./environmentHttp.ts";
+
+const traceId = "trace-1";
+
+describe("environment HTTP errors", () => {
+ // A client squashes the cause and shows `message`; an empty one becomes a generic
+ // "The environment request failed." that names nothing the reader can act on.
+ it("each carries a message that names its reason", () => {
+ const errors = [
+ new EnvironmentRequestInvalidError({
+ code: "invalid_request",
+ reason: "invalid_command",
+ traceId,
+ }),
+ new EnvironmentAuthInvalidError({
+ code: "auth_invalid",
+ reason: "missing_credential",
+ traceId,
+ }),
+ new EnvironmentScopeRequiredError({
+ code: "insufficient_scope",
+ requiredScope: "orchestration:read",
+ traceId,
+ }),
+ new EnvironmentOperationForbiddenError({
+ code: "operation_forbidden",
+ reason: "current_session_revoke_not_allowed",
+ traceId,
+ }),
+ new EnvironmentResourceNotFoundError({
+ code: "not_found",
+ reason: "thread_not_found",
+ traceId,
+ }),
+ new EnvironmentInternalError({
+ code: "internal_error",
+ reason: "orchestration_snapshot_failed",
+ traceId,
+ }),
+ ] as const;
+ const details = [
+ "invalid_command",
+ "missing_credential",
+ "orchestration:read",
+ "current_session_revoke_not_allowed",
+ "thread_not_found",
+ "orchestration_snapshot_failed",
+ ];
+ errors.forEach((error, index) => {
+ expect(error.message).toContain(details[index]);
+ });
+ });
+});
diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts
index d209588b6..e74948622 100644
--- a/packages/contracts/src/environmentHttp.ts
+++ b/packages/contracts/src/environmentHttp.ts
@@ -106,6 +106,10 @@ export class EnvironmentRequestInvalidError extends Schema.TaggedErrorClass<Envi
[HttpServerRespondable.symbol]() {
return HttpServerResponse.schemaJson(EnvironmentRequestInvalidError)(this, { status: 400 });
}
+
+ override get message(): string {
+ return `The environment rejected the request (${this.reason}).`;
+ }
}
export class EnvironmentAuthInvalidError extends Schema.TaggedErrorClass<EnvironmentAuthInvalidError>()(
@@ -120,6 +124,10 @@ export class EnvironmentAuthInvalidError extends Schema.TaggedErrorClass<Environ
[HttpServerRespondable.symbol]() {
return HttpServerResponse.schemaJson(EnvironmentAuthInvalidError)(this, { status: 401 });
}
+
+ override get message(): string {
+ return `The environment rejected this client's credentials (${this.reason}).`;
+ }
}
export class EnvironmentScopeRequiredError extends Schema.TaggedErrorClass<EnvironmentScopeRequiredError>()(
@@ -134,6 +142,10 @@ export class EnvironmentScopeRequiredError extends Schema.TaggedErrorClass<Envir
[HttpServerRespondable.symbol]() {
return HttpServerResponse.schemaJson(EnvironmentScopeRequiredError)(this, { status: 403 });
}
+
+ override get message(): string {
+ return `This request needs the ${this.requiredScope} scope, which this client does not have.`;
+ }
}
export class EnvironmentOperationForbiddenError extends Schema.TaggedErrorClass<EnvironmentOperationForbiddenError>()(
@@ -148,6 +160,10 @@ export class EnvironmentOperationForbiddenError extends Schema.TaggedErrorClass<
[HttpServerRespondable.symbol]() {
return HttpServerResponse.schemaJson(EnvironmentOperationForbiddenError)(this, { status: 403 });
}
+
+ override get message(): string {
+ return `The environment refused this operation (${this.reason}).`;
+ }
}
export class EnvironmentInternalError extends Schema.TaggedErrorClass<EnvironmentInternalError>()(
@@ -162,6 +178,10 @@ export class EnvironmentInternalError extends Schema.TaggedErrorClass<Environmen
[HttpServerRespondable.symbol]() {
return HttpServerResponse.schemaJson(EnvironmentInternalError)(this, { status: 500 });
}
+
+ override get message(): string {
+ return `The environment failed to answer this request (${this.reason}).`;
+ }
}
export const EnvironmentResourceNotFoundReason = Schema.Literals(["thread_not_found"]);
@@ -179,6 +199,10 @@ export class EnvironmentResourceNotFoundError extends Schema.TaggedErrorClass<En
[HttpServerRespondable.symbol]() {
return HttpServerResponse.schemaJson(EnvironmentResourceNotFoundError)(this, { status: 404 });
}
+
+ override get message(): string {
+ return `The environment could not find what this request named (${this.reason}).`;
+ }
}
export const EnvironmentHttpCommonError = Schema.Union([
diff --git a/packages/contracts/src/pullRequest.test.ts b/packages/contracts/src/pullRequest.test.ts
index 1e301b8a3..4e54ca308 100644
--- a/packages/contracts/src/pullRequest.test.ts
+++ b/packages/contracts/src/pullRequest.test.ts
@@ -2,9 +2,12 @@ import * as Schema from "effect/Schema";
import { describe, expect, it } from "vite-plus/test";
import {
+ PullRequestActionInput,
+ PullRequestCapabilities,
PullRequestListInput,
PullRequestListResult,
PullRequestReviewerRequestInput,
+ resolvePullRequestAuthorFilter,
} from "./pullRequest.ts";
const decodeListResult = Schema.decodeUnknownSync(PullRequestListResult);
@@ -153,3 +156,77 @@ describe("PullRequestReviewerRequestInput", () => {
).toEqual(["user", "team"]);
});
});
+
+describe("updating a branch that has fallen behind its base", () => {
+ const decodeAction = Schema.decodeUnknownSync(PullRequestActionInput);
+ const ref = { projectId: "project-1", repository: "acme/web", number: 7 };
+
+ it("carries the way the branch should be brought up to date", () => {
+ expect(decodeAction({ ...ref, action: "update-branch", updateMethod: "rebase" })).toMatchObject(
+ {
+ action: "update-branch",
+ updateMethod: "rebase",
+ },
+ );
+ });
+
+ it("takes the action without a method, which is the host's own default", () => {
+ expect(decodeAction({ ...ref, action: "update-branch" }).updateMethod).toBeUndefined();
+ });
+
+ it("refuses a way no host offers", () => {
+ expect(() =>
+ decodeAction({ ...ref, action: "update-branch", updateMethod: "squash" }),
+ ).toThrow();
+ });
+});
+
+describe("leaving a merge for the host to make once it is ready", () => {
+ const decodeAction = Schema.decodeUnknownSync(PullRequestActionInput);
+ const ref = { projectId: "project-1", repository: "acme/web", number: 7 };
+
+ it("carries the strategy the deferred merge should use, as merging now does", () => {
+ expect(
+ decodeAction({ ...ref, action: "enable-auto-merge", mergeMethod: "squash" }),
+ ).toMatchObject({ action: "enable-auto-merge", mergeMethod: "squash" });
+ });
+
+ it("takes the arming back without a strategy, because there is nothing to choose", () => {
+ expect(decodeAction({ ...ref, action: "disable-auto-merge" }).mergeMethod).toBeUndefined();
+ });
+});
+
+describe("PullRequestCapabilities", () => {
+ const decodeCapabilities = Schema.decodeUnknownSync(PullRequestCapabilities);
+ const base = {
+ diff: true,
+ comment: true,
+ actions: [],
+ mergeMethods: [],
+ search: true,
+ review: { inlineComment: true, reply: true, resolve: true, verdicts: [] },
+ reviewers: { request: true, listCandidates: true },
+ };
+
+ it("decodes a server that says nothing about reactions as a server with none", () => {
+ expect(decodeCapabilities(base).reactions).toBeUndefined();
+ });
+});
+
+describe("naming the reader as the author to narrow by", () => {
+ it("reads me as whoever is signed in, however it is written", () => {
+ expect(resolvePullRequestAuthorFilter("me", "octocat")).toBe("octocat");
+ expect(resolvePullRequestAuthorFilter("@me", "octocat")).toBe("octocat");
+ expect(resolvePullRequestAuthorFilter(" ME ", "octocat")).toBe("octocat");
+ });
+
+ it("leaves any other name as it was typed", () => {
+ expect(resolvePullRequestAuthorFilter(" mercedes ", "octocat")).toBe("mercedes");
+ expect(resolvePullRequestAuthorFilter("me-too", "octocat")).toBe("me-too");
+ });
+
+ it("stands as typed where the host has not said who the reader is", () => {
+ expect(resolvePullRequestAuthorFilter("me", null)).toBe("me");
+ expect(resolvePullRequestAuthorFilter("me", " ")).toBe("me");
+ });
+});
diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts
index 707ec540d..d1b2ba705 100644
--- a/packages/contracts/src/pullRequest.ts
+++ b/packages/contracts/src/pullRequest.ts
@@ -25,15 +25,96 @@ export type PullRequestState = typeof PullRequestState.Type;
export const PullRequestListState = Schema.Literals(["all", "open", "closed", "merged"]);
export type PullRequestListState = typeof PullRequestListState.Type;
+/** Where a review stands overall, as a host that summarises its reviews reports it. */
+export const PullRequestReviewDecision = Schema.Literals([
+ "approved",
+ "changes-requested",
+ "review-required",
+]);
+export type PullRequestReviewDecision = typeof PullRequestReviewDecision.Type;
+
+/** One qualifier's value, bounded because it is written into a host's own search query. */
+const PullRequestQualifierValue = TrimmedNonEmptyString.check(Schema.isMaxLength(200));
+const PullRequestQualifierValues = Schema.Array(PullRequestQualifierValue).check(
+ Schema.isMaxLength(10),
+);
+
+/**
+ * Narrowings beyond state and involvement, each absent by default — an absent field filters
+ * nothing, which is what every listing did before there were any. Optional as a whole so a page
+ * and a server of different ages still speak to each other.
+ *
+ * `checks` is host-side only: no row carries its own check state, so a host that cannot match it
+ * answers unnarrowed rather than the page pretending to know.
+ */
+export const PullRequestListFilters = Schema.Struct({
+ draft: Schema.optional(Schema.Literals(["only", "hide"])),
+ review: Schema.optional(
+ Schema.Literals(["approved", "changes-requested", "review-required", "none"]),
+ ),
+ checks: Schema.optional(Schema.Literals(["passing", "failing"])),
+ /**
+ * Labels as GitHub's own search reads them: each group is one `label:` qualifier, a row must
+ * satisfy every group, and a group holding several names is satisfied by any one of them —
+ * `label:size:S,size:XS` finds either size. Typed rather than picked, since a project's labels
+ * are its own and no menu can list them. Bounded because each becomes a host search qualifier.
+ */
+ labels: Schema.optional(Schema.Array(PullRequestQualifierValues).check(Schema.isMaxLength(10))),
+ excludedLabels: Schema.optional(PullRequestQualifierValues),
+ /** One login, as `author:` names it. */
+ author: Schema.optional(PullRequestQualifierValue),
+});
+export type PullRequestListFilters = typeof PullRequestListFilters.Type;
+
+/** The one-glyph summary of a change request's checks, as its list row wears it. */
+export const PullRequestChecksState = Schema.Literals(["passing", "failing", "pending"]);
+export type PullRequestChecksState = typeof PullRequestChecksState.Type;
+
export const PullRequestMergeability = Schema.Literals(["mergeable", "conflicting", "unknown"]);
export type PullRequestMergeability = typeof PullRequestMergeability.Type;
export const PullRequestMergeMethod = Schema.Literals(["merge", "squash", "rebase"]);
export type PullRequestMergeMethod = typeof PullRequestMergeMethod.Type;
-export const PullRequestAction = Schema.Literals(["merge", "ready", "draft", "close", "reopen"]);
+export const PullRequestAction = Schema.Literals([
+ "merge",
+ "ready",
+ "draft",
+ "close",
+ "reopen",
+ /** Bring the base branch's commits into this one, which is what unblocks a stale branch. */
+ "update-branch",
+ /**
+ * Hand the merge to the host: it waits for whatever it requires — a green pipeline, the
+ * approvals, an unblocked branch — and merges without anybody coming back. Separate from
+ * `merge` because the two answer different questions. `merge` is refused outright by a host
+ * that is not ready yet, and this one is for exactly that moment.
+ */
+ "enable-auto-merge",
+ /** Take the standing instruction back, which leaves the change request where it was. */
+ "disable-auto-merge",
+]);
export type PullRequestAction = typeof PullRequestAction.Type;
+/**
+ * How a stale branch catches up with its base: a merge commit, or a rebase onto it. The two are
+ * the host's own choices, not this page's — GitHub offers both and refuses a rebase it cannot
+ * replay, so what is offered comes from the host and what is allowed comes from the viewer.
+ */
+export const PullRequestUpdateMethod = Schema.Literals(["merge", "rebase"]);
+export type PullRequestUpdateMethod = typeof PullRequestUpdateMethod.Type;
+
+/**
+ * Where the branch stands against the base it would merge into. Separate from `mergeability`,
+ * which answers a different question: a branch can be behind and still merge cleanly, and that
+ * pairing — out of date, no conflicts — is the one an update button exists for.
+ *
+ * "unknown" where the host was not asked or could not say, which is every host but GitHub and
+ * every pull request whose head repository could not be compared.
+ */
+export const PullRequestBaseComparison = Schema.Literals(["up-to-date", "behind", "unknown"]);
+export type PullRequestBaseComparison = typeof PullRequestBaseComparison.Type;
+
export const PullRequestActor = Schema.Struct({
login: TrimmedNonEmptyString,
name: Schema.NullOr(Schema.String),
@@ -66,6 +147,39 @@ export const PullRequestCheck = Schema.Struct({
});
export type PullRequestCheck = typeof PullRequestCheck.Type;
+/**
+ * The reactions a remark can carry. GitHub's eight, which is also what the picker offers: GitLab
+ * accepts any emoji as an award, and the ones outside this set are read as nothing rather than
+ * shown under a name no other host would recognise.
+ */
+export const PullRequestReactionContent = Schema.Literals([
+ "thumbs-up",
+ "thumbs-down",
+ "laugh",
+ "hooray",
+ "confused",
+ "heart",
+ "rocket",
+ "eyes",
+]);
+export type PullRequestReactionContent = typeof PullRequestReactionContent.Type;
+
+/** One reaction and everyone behind it, which is what the hover on a reaction pill says. */
+export const PullRequestReaction = Schema.Struct({
+ content: PullRequestReactionContent,
+ count: PositiveInt,
+ /**
+ * Who reacted, as far as the host named them. A host that reports fewer names than it counts
+ * leaves the rest out, so this is never longer than `count` and may be shorter. When
+ * `viewerHasReacted` is true, the viewer's own login is left out of this list — the page names
+ * them "You" instead — but `count` still counts them along with everyone else.
+ */
+ actors: Schema.Array(TrimmedNonEmptyString),
+ /** The signed-in account is one of them, so pressing the pill takes the reaction back. */
+ viewerHasReacted: Schema.Boolean,
+});
+export type PullRequestReaction = typeof PullRequestReaction.Type;
+
export const PullRequestCommentKind = Schema.Literals([
"issue-comment",
"review-comment",
@@ -82,6 +196,8 @@ export const PullRequestComment = Schema.Struct({
url: Schema.NullOr(Schema.String),
path: Schema.NullOr(Schema.String),
reviewState: Schema.NullOr(Schema.String),
+ /** Absent from a host with no reactions at all, which is a different thing from none on this. */
+ reactions: Schema.optional(Schema.Array(PullRequestReaction)),
});
export type PullRequestComment = typeof PullRequestComment.Type;
@@ -103,6 +219,7 @@ export const PullRequestThreadComment = Schema.Struct({
body: Schema.String,
createdAt: IsoDateTime,
url: Schema.NullOr(Schema.String),
+ reactions: Schema.optional(Schema.Array(PullRequestReaction)),
});
export type PullRequestThreadComment = typeof PullRequestThreadComment.Type;
@@ -197,6 +314,20 @@ export const PullRequestReviewCapabilities = Schema.Struct({
});
export type PullRequestReviewCapabilities = typeof PullRequestReviewCapabilities.Type;
+/**
+ * What a host lets be rewritten after it has been posted. The two are separate because a host can
+ * take one without the other: Azure DevOps takes a new title and description through the same
+ * command that closes a pull request, and has no way to post a remark here at all — so nothing it
+ * shows in a conversation can be rewritten either.
+ */
+export const PullRequestEditCapabilities = Schema.Struct({
+ /** The change request's own title and description can be rewritten. */
+ changeRequest: Schema.Boolean,
+ /** A remark can be rewritten by whoever wrote it. */
+ comment: Schema.Boolean,
+});
+export type PullRequestEditCapabilities = typeof PullRequestEditCapabilities.Type;
+
/**
* What a host can do about who reviews. The two are independent: a host can take a request without
* publishing who may receive one, which is Azure DevOps.
@@ -230,14 +361,33 @@ export const PullRequestCapabilities = Schema.Struct({
actions: Schema.Array(PullRequestAction),
/** Merge strategies the provider itself offers, before repository settings narrow them. */
mergeMethods: Schema.Array(PullRequestMergeMethod),
+ /**
+ * How this host can bring a stale branch up to date. Absent where it cannot at all, which is
+ * every host that has not said otherwise — so a provider that says nothing offers nothing.
+ */
+ updateMethods: Schema.optional(Schema.Array(PullRequestUpdateMethod)),
/**
* The host can narrow a listing by free text. False means it answers unnarrowed and whoever
* asked has to do the narrowing — which is a different promise, so the page is told rather
* than left to show every change request on that host as a search result.
*/
search: Schema.Boolean,
+ /**
+ * Reactions can be read from a remark, and added to one or taken back. One flag for both:
+ * neither host here reports reactions it will not also take, and a surface that could show a
+ * pill it may never press is a surface offering nothing. Optional for the same reason as
+ * `updateMethods` and `edit`: a server that says nothing about reactions has none, which is
+ * what every server before this field was.
+ */
+ reactions: Schema.optional(Schema.Boolean),
review: PullRequestReviewCapabilities,
reviewers: PullRequestReviewerCapabilities,
+ /**
+ * What can be rewritten after the fact. Optional so a page and a server of different ages still
+ * speak to each other: a server that says nothing about rewriting is one that cannot, which is
+ * what every server before this one was.
+ */
+ edit: Schema.optional(PullRequestEditCapabilities),
});
export type PullRequestCapabilities = typeof PullRequestCapabilities.Type;
@@ -262,6 +412,11 @@ export const PullRequestViewerPermissions = Schema.Struct({
verdicts: Schema.Array(PullRequestReviewVerdict),
/** This viewer may ask somebody for a review, and take the request back again. */
requestReviewers: Schema.Boolean,
+ /**
+ * The ways this viewer may bring the branch up to date, narrowed from what the host offers.
+ * Absent or empty means they may not, which is also what a host with no such action says.
+ */
+ updateMethods: Schema.optional(Schema.Array(PullRequestUpdateMethod)),
});
export type PullRequestViewerPermissions = typeof PullRequestViewerPermissions.Type;
@@ -303,6 +458,10 @@ export const PullRequestListEntry = Schema.Struct({
updatedAt: IsoDateTime,
viewerReviewRequested: Schema.Boolean,
labels: Schema.Array(PullRequestLabel),
+ /** Absent where the host does not summarise its reviews, which is every host but GitHub. */
+ reviewDecision: Schema.optional(PullRequestReviewDecision),
+ /** Absent where the host reports no check rollup, or the change request has no checks. */
+ checksState: Schema.optional(PullRequestChecksState),
});
export type PullRequestListEntry = typeof PullRequestListEntry.Type;
@@ -324,7 +483,14 @@ export type PullRequestListCursors = typeof PullRequestListCursors.Type;
export const PullRequestListInput = Schema.Struct({
state: PullRequestListState,
involvement: Schema.optional(PullRequestInvolvement),
+ filters: Schema.optional(PullRequestListFilters),
projectId: Schema.optional(ProjectId),
+ /**
+ * Only these projects, for a client that assigns each shared repository to one of its
+ * connections and asks the others to stay quiet about it. Absent means every project, which
+ * is what every listing asked for before there were several connections to spread across.
+ */
+ projectIds: Schema.optional(Schema.Array(ProjectId).check(Schema.isMaxLength(100))),
/**
* Narrows the listing to one host, named as the host itself rather than as its provider kind:
* github.com and a GitHub Enterprise install are two accounts, and a kind cannot tell them
@@ -499,6 +665,27 @@ export const PullRequestDetail = Schema.Struct({
labels: Schema.Array(PullRequestLabel),
checks: Schema.Array(PullRequestCheck),
mergeCapabilities: PullRequestMergeCapabilities,
+ /**
+ * Who the host says the reader is, which is the one thing a conversation cannot be read without
+ * to tell the reader's own remarks from everybody else's — and rewriting a remark is offered
+ * only where the two names agree. Absent where the host could not say, which offers nothing
+ * rather than everything.
+ */
+ viewer: Schema.optional(TrimmedNonEmptyString),
+ /**
+ * Where the branch stands against its base. Optional so a host that cannot compare says
+ * nothing rather than claiming the branch is current — the page shows a banner only where the
+ * answer is "behind", and silence is not that answer.
+ */
+ baseComparison: Schema.optional(PullRequestBaseComparison),
+ /** How many commits the base is ahead by, where the host counted them. */
+ behindBy: Schema.optional(NonNegativeInt),
+ /**
+ * Whether the host is already armed to merge this on its own. Absent where the host does not
+ * report it, which is not the same as off: a page that reads silence as "not armed" offers to
+ * arm something that is already armed, and a second arming is a write nobody asked for.
+ */
+ autoMergeEnabled: Schema.optional(Schema.Boolean),
});
export type PullRequestDetail = typeof PullRequestDetail.Type;
@@ -527,6 +714,11 @@ export const PullRequestActivity = Schema.Struct({
commentsTruncated: Schema.Boolean,
reviewThreads: Schema.Array(PullRequestReviewThread),
commits: Schema.Array(PullRequestCommit),
+ /**
+ * The change request's own reactions — the ones on its description, which every host counts
+ * against the change request itself rather than against a remark in the conversation.
+ */
+ reactions: Schema.optional(Schema.Array(PullRequestReaction)),
});
export type PullRequestActivity = typeof PullRequestActivity.Type;
@@ -562,6 +754,14 @@ export const PullRequestDiffInput = Schema.Struct({
});
export type PullRequestDiffInput = typeof PullRequestDiffInput.Type;
+/** Real line counts for a file whose hunks the host withheld from the patch. */
+export const PullRequestOmittedFileStat = Schema.Struct({
+ path: TrimmedNonEmptyString,
+ additions: Schema.Number,
+ deletions: Schema.Number,
+});
+export type PullRequestOmittedFileStat = typeof PullRequestOmittedFileStat.Type;
+
export const PullRequestDiffResult = Schema.Struct({
patch: Schema.String,
/**
@@ -571,6 +771,11 @@ export const PullRequestDiffResult = Schema.Struct({
truncated: Schema.Boolean,
/** Where the next slice starts, or null once the diff is whole. */
nextCursor: Schema.NullOr(TrimmedNonEmptyString),
+ /**
+ * The host's own counts for the files whose hunks it withheld, so a file the patch cannot
+ * show still reports what changed instead of a zero the diff never had.
+ */
+ omittedFileStats: Schema.optional(Schema.Array(PullRequestOmittedFileStat)),
});
export type PullRequestDiffResult = typeof PullRequestDiffResult.Type;
@@ -594,7 +799,14 @@ export type PullRequestDiffFileContentsResult = typeof PullRequestDiffFileConten
export const PullRequestActionInput = Schema.Struct({
...PullRequestRef.fields,
action: PullRequestAction,
+ /**
+ * Which strategy the merge uses, read for `merge` and for `enable-auto-merge` alike — a merge
+ * the host performs later is still a merge, and the strategy is chosen when it is armed rather
+ * than at the moment it happens. Absent means the host's own default.
+ */
mergeMethod: Schema.optional(PullRequestMergeMethod),
+ /** Only read for `update-branch`, where absent means the host's own default. */
+ updateMethod: Schema.optional(PullRequestUpdateMethod),
});
export type PullRequestActionInput = typeof PullRequestActionInput.Type;
@@ -610,6 +822,40 @@ export const PullRequestCommentInput = Schema.Struct({
});
export type PullRequestCommentInput = typeof PullRequestCommentInput.Type;
+/**
+ * A change request's own words rewritten: its title, its description, or both. Each is optional
+ * because the page rewrites them apart — a title corrected on its own must not carry a description
+ * nobody opened — and the service refuses a request that carries neither.
+ *
+ * The title is bounded far past what any host takes, GitHub refusing one past 256 characters, so
+ * an oversized one is turned away before it reaches a subprocess. The body is not trimmed for the
+ * same reason a comment is not: it is markdown, where leading spaces open a code block. An empty
+ * one is allowed, which is how a description is cleared.
+ */
+export const PullRequestUpdateInput = Schema.Struct({
+ ...PullRequestRef.fields,
+ title: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(1024))),
+ body: Schema.optional(Schema.String.check(Schema.isMaxLength(65_536))),
+});
+export type PullRequestUpdateInput = typeof PullRequestUpdateInput.Type;
+
+/**
+ * A remark already posted, rewritten by whoever wrote it. The kind travels beside the id because
+ * an id alone does not say which endpoint addresses it: GitHub rewrites a comment on the
+ * conversation and a comment on a line through two different mutations.
+ *
+ * A review's own summary is not among them. The hosts disagree about what one even is — the entry
+ * Bitbucket shows is a vote this page renders as a remark, with no words behind it to rewrite —
+ * and a control that worked on one host and failed on another is worse than one that is not there.
+ */
+export const PullRequestCommentUpdateInput = Schema.Struct({
+ ...PullRequestRef.fields,
+ commentId: TrimmedNonEmptyString,
+ kind: Schema.Literals(["issue-comment", "review-comment"]),
+ body: CommentBody,
+});
+export type PullRequestCommentUpdateInput = typeof PullRequestCommentUpdateInput.Type;
+
/** One remark in a review that has not been sent yet, anchored to a line of the diff. */
export const PullRequestReviewCommentDraft = Schema.Struct({
path: TrimmedNonEmptyString,
@@ -653,6 +899,23 @@ export const PullRequestThreadResolutionInput = Schema.Struct({
});
export type PullRequestThreadResolutionInput = typeof PullRequestThreadResolutionInput.Type;
+/**
+ * Reacting and taking the reaction back are one operation with `reacted` turned around, which is
+ * what pressing the same pill twice is.
+ */
+export const PullRequestReactionInput = Schema.Struct({
+ ...PullRequestRef.fields,
+ /**
+ * Which remark to react to, as it arrived in the conversation. Absent reacts to the change
+ * request itself, which is where its description's reactions live — the id a host uses for
+ * that is its own to work out.
+ */
+ subjectId: Schema.optional(TrimmedNonEmptyString),
+ content: PullRequestReactionContent,
+ reacted: Schema.Boolean,
+});
+export type PullRequestReactionInput = typeof PullRequestReactionInput.Type;
+
/**
* Asking for a review and taking the request back are one operation with `requested` turned
* around, and asking again somebody who has already reviewed is what a re-request is — so that is
@@ -725,6 +988,26 @@ export function pullRequestHostOf(
return host === undefined || host.length === 0 ? kind : host.toLowerCase();
}
+/**
+ * `author:me` names whoever is signed in to the host being read, GitHub's `@me` spelled either
+ * way. A host's own search would answer it, but the page and the server both re-check an author
+ * against the row's login, so the name is resolved before either comparison rather than being
+ * matched as the literal login "me".
+ *
+ * Null viewer where the host has not said who the reader is; the filter then stands as typed,
+ * which is the same answer a search for a user named "me" would give.
+ *
+ * Shared between the server and the page so both narrow by the same login.
+ */
+export function resolvePullRequestAuthorFilter(
+ author: string,
+ viewer: string | null | undefined,
+): string {
+ const trimmed = author.trim();
+ if (!/^@?me$/i.test(trimmed)) return trimmed;
+ return viewer === null || viewer === undefined || viewer.trim().length === 0 ? trimmed : viewer;
+}
+
/**
* What a host needs before it can be read, as a sentence to show wherever that host is reported
* as unusable — the whole page when nothing can be read, and one entry in the host switcher when
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index 8d0f0e5b5..b5bd91cad 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -71,6 +71,7 @@ import {
PullRequestActionInput,
PullRequestActivity,
PullRequestCommentInput,
+ PullRequestCommentUpdateInput,
PullRequestDetail,
PullRequestDiffFileContentsInput,
PullRequestDiffFileContentsResult,
@@ -80,6 +81,7 @@ import {
PullRequestListStatsInput,
PullRequestListStatsResult,
PullRequestOperationError,
+ PullRequestReactionInput,
PullRequestRef,
PullRequestReviewerCandidateList,
PullRequestReviewerRequestInput,
@@ -87,6 +89,7 @@ import {
PullRequestThreadReplyInput,
PullRequestThreadResolutionInput,
PullRequestUnavailableError,
+ PullRequestUpdateInput,
} from "./pullRequest.ts";
import {
RelayClientInstallFailedError,
@@ -279,10 +282,13 @@ export const WS_METHODS = {
pullRequestsActivity: "pullRequests.activity",
pullRequestsDiffFileContents: "pullRequests.diffFileContents",
pullRequestsRunAction: "pullRequests.runAction",
+ pullRequestsUpdate: "pullRequests.update",
pullRequestsComment: "pullRequests.comment",
+ pullRequestsUpdateComment: "pullRequests.updateComment",
pullRequestsSubmitReview: "pullRequests.submitReview",
pullRequestsReplyToThread: "pullRequests.replyToThread",
pullRequestsSetThreadResolution: "pullRequests.setThreadResolution",
+ pullRequestsSetReaction: "pullRequests.setReaction",
pullRequestsInvalidate: "pullRequests.invalidate",
pullRequestsReviewerCandidates: "pullRequests.reviewerCandidates",
pullRequestsRequestReviewers: "pullRequests.requestReviewers",
@@ -507,12 +513,24 @@ export const WsPullRequestsRunActionRpc = Rpc.make(WS_METHODS.pullRequestsRunAct
error: PullRequestRpcError,
});
+export const WsPullRequestsUpdateRpc = Rpc.make(WS_METHODS.pullRequestsUpdate, {
+ payload: PullRequestUpdateInput,
+ success: Schema.Void,
+ error: PullRequestRpcError,
+});
+
export const WsPullRequestsCommentRpc = Rpc.make(WS_METHODS.pullRequestsComment, {
payload: PullRequestCommentInput,
success: Schema.Void,
error: PullRequestRpcError,
});
+export const WsPullRequestsUpdateCommentRpc = Rpc.make(WS_METHODS.pullRequestsUpdateComment, {
+ payload: PullRequestCommentUpdateInput,
+ success: Schema.Void,
+ error: PullRequestRpcError,
+});
+
export const WsPullRequestsSubmitReviewRpc = Rpc.make(WS_METHODS.pullRequestsSubmitReview, {
payload: PullRequestSubmitReviewInput,
success: Schema.Void,
@@ -534,6 +552,12 @@ export const WsPullRequestsSetThreadResolutionRpc = Rpc.make(
},
);
+export const WsPullRequestsSetReactionRpc = Rpc.make(WS_METHODS.pullRequestsSetReaction, {
+ payload: PullRequestReactionInput,
+ success: Schema.Void,
+ error: PullRequestRpcError,
+});
+
export const WsPullRequestsInvalidateRpc = Rpc.make(WS_METHODS.pullRequestsInvalidate, {
payload: PullRequestInvalidateInput,
success: Schema.Void,
@@ -976,10 +1000,13 @@ export const WsRpcGroup = RpcGroup.make(
WsPullRequestsActivityRpc,
WsPullRequestsDiffFileContentsRpc,
WsPullRequestsRunActionRpc,
+ WsPullRequestsUpdateRpc,
WsPullRequestsCommentRpc,
+ WsPullRequestsUpdateCommentRpc,
WsPullRequestsSubmitReviewRpc,
WsPullRequestsReplyToThreadRpc,
WsPullRequestsSetThreadResolutionRpc,
+ WsPullRequestsSetReactionRpc,
WsPullRequestsInvalidateRpc,
WsPullRequestsReviewerCandidatesRpc,
WsPullRequestsRequestReviewersRpc,
diff --git a/packages/contracts/src/vcs.ts b/packages/contracts/src/vcs.ts
index c1090f4f3..a0956e83b 100644
--- a/packages/contracts/src/vcs.ts
+++ b/packages/contracts/src/vcs.ts
@@ -76,6 +76,7 @@ export interface VcsProcessTimeoutFailure {
export const VcsProcessExitFailureKind = Schema.Literals([
"authentication",
"not-found",
+ "rate-limited",
"command-failed",
]);
export type VcsProcessExitFailureKind = typeof VcsProcessExitFailureKind.Type;
@@ -134,13 +135,15 @@ export class VcsProcessExitError extends Schema.TaggedErrorClass<VcsProcessExitE
const detail =
failureKind === "authentication"
? "Authentication failed."
- : failureKind === "not-found"
- ? context.command === "glab"
- ? "Merge request not found."
- : context.command === "gh" || context.command === "az"
- ? "Pull request not found."
- : "VCS resource not found."
- : "Process exited with a non-zero status.";
+ : failureKind === "rate-limited"
+ ? "API rate limit exceeded."
+ : failureKind === "not-found"
+ ? context.command === "glab"
+ ? "Merge request not found."
+ : context.command === "gh" || context.command === "az"
+ ? "Pull request not found."
+ : "VCS resource not found."
+ : "Process exited with a non-zero status.";
return new VcsProcessExitError({
...context,