Skip to content
TypeScript

feat(web): apply and remove labels from the pull request tab (#9313)

Julius Marminge9ebbeda5a03f
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index c1eb8b15764..0a86a0835d8 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -75,6 +75,8 @@ export const RPC_REQUIRED_SCOPES = {
// write like every other one.
[WS_METHODS.pullRequestsReviewerCandidates]: AuthOrchestrationReadScope,
[WS_METHODS.pullRequestsRequestReviewers]: AuthOrchestrationOperateScope,
+ [WS_METHODS.pullRequestsLabelCandidates]: AuthOrchestrationReadScope,
+ [WS_METHODS.pullRequestsSetLabels]: AuthOrchestrationOperateScope,
[WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
[WS_METHODS.sourceControlCloneRepository]: AuthOrchestrationOperateScope,
[WS_METHODS.sourceControlPublishRepository]: AuthOrchestrationOperateScope,
diff --git a/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts b/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts
index 3db5c8884f3..1e6ca0ed43a 100644
--- a/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts
+++ b/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts
@@ -2726,7 +2726,12 @@ layer("GitHubPullRequestCli.layer", (it) => {
// One request, because both answers hang off the same repository object.
assert.strictEqual(mockedExecute.mock.calls.length, 1);
expect(callAt(0).args).toContain("number=7");
- expect(access).toEqual({ canWrite: false, canUpdate: true, didAuthor: true });
+ expect(access).toEqual({
+ canWrite: false,
+ canTriage: false,
+ canUpdate: true,
+ didAuthor: true,
+ });
}),
);
@@ -2889,7 +2894,12 @@ layer("GitHubPullRequestCli.layer", (it) => {
});
assert.strictEqual(mockedExecute.mock.calls.length, 2);
- expect(access).toEqual({ canWrite: false, canUpdate: true, didAuthor: true });
+ expect(access).toEqual({
+ canWrite: false,
+ canTriage: false,
+ canUpdate: true,
+ didAuthor: true,
+ });
yield* TestClock.setTime(Date.parse("2100-01-01T00:00:00Z"));
}),
);
@@ -3029,4 +3039,56 @@ layer("GitHubPullRequestCli.layer", (it) => {
]);
}),
);
+
+ it.effect("puts labels on by posting to the issue's own collection, all at once", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ yield* cli.setLabels({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ labels: ["bug", "size:XL"],
+ applied: true,
+ });
+
+ assert.strictEqual(mockedExecute.mock.calls.length, 1);
+ const call = callAt(0);
+ expect(call.args).toEqual([
+ "api",
+ "--method",
+ "POST",
+ "--hostname",
+ "github.com",
+ "repos/acme/web/issues/7/labels",
+ "--input",
+ "-",
+ ]);
+ // @effect-diagnostics-next-line preferSchemaOverJson:off - asserting the raw gh request body.
+ expect(JSON.parse(call.stdin ?? "")).toEqual({ labels: ["bug", "size:XL"] });
+ }),
+ );
+
+ it.effect("takes labels off one at a time, naming each in the path encoded", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(Effect.succeed(output("[]")));
+ const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;
+
+ yield* cli.setLabels({
+ cwd: "/w",
+ repository: "acme/web",
+ host: "github.com",
+ number: 7,
+ labels: ["good first issue", "area/web"],
+ applied: false,
+ });
+
+ assert.strictEqual(mockedExecute.mock.calls.length, 2);
+ expect(callAt(0).args).toContain("repos/acme/web/issues/7/labels/good%20first%20issue");
+ expect(callAt(0).args).toContain("DELETE");
+ expect(callAt(1).args).toContain("repos/acme/web/issues/7/labels/area%2Fweb");
+ }),
+ );
});
diff --git a/apps/server/src/pullRequest/GitHubPullRequestCli.ts b/apps/server/src/pullRequest/GitHubPullRequestCli.ts
index c418fd0d37e..3dc41896037 100644
--- a/apps/server/src/pullRequest/GitHubPullRequestCli.ts
+++ b/apps/server/src/pullRequest/GitHubPullRequestCli.ts
@@ -18,6 +18,7 @@ import {
type PullRequestReviewVerdict,
type PullRequestReviewerCandidateList,
type PullRequestReviewerKind,
+ type PullRequestLabelCandidateList,
type PullRequestThreadCommentsResult,
type PullRequestUpdateMethod,
} from "@t3tools/contracts";
@@ -42,6 +43,9 @@ import {
decodeReactionSubjectScopeJson,
decodeRepositoryAccessJson,
decodeReviewerCandidatesJson,
+ decodeLabelCandidatesJson,
+ buildLabelRequestJson,
+ LABEL_CANDIDATES_GRAPHQL_QUERY,
decodeReviewDismissalsJson,
decodeReviewThreadCommentsJson,
decodeReviewThreadsJson,
@@ -597,6 +601,24 @@ export class GitHubPullRequestCli extends Context.Service<
readonly requested: boolean;
}) => Effect.Effect<void, GitHubPullRequestCliError>;
+ /** The repository's labels, and which of them this pull request already wears. */
+ readonly listLabelCandidates: (input: {
+ readonly cwd: string;
+ readonly repository: string;
+ readonly host: string;
+ readonly number: number;
+ }) => Effect.Effect<PullRequestLabelCandidateList, GitHubPullRequestCliError>;
+
+ readonly setLabels: (input: {
+ readonly cwd: string;
+ readonly repository: string;
+ readonly host: string;
+ readonly number: number;
+ readonly labels: ReadonlyArray<string>;
+ /** False takes each label off; true adds each to whatever is already there. */
+ readonly applied: boolean;
+ }) => Effect.Effect<void, GitHubPullRequestCliError>;
+
readonly runPullRequestAction: (input: {
readonly cwd: string;
readonly repository: string;
@@ -1977,6 +1999,56 @@ export const make = Effect.gen(function* () {
.pipe(Effect.asVoid);
},
+ listLabelCandidates: (input) => {
+ const { owner, name } = parseRepositorySelector(input.repository);
+ return graphqlRead({
+ cwd: input.cwd,
+ host: input.host,
+ operation: "listLabelCandidates",
+ allowReserve: true,
+ variables: [
+ ["-f", `owner=${owner}`],
+ ["-f", `name=${name}`],
+ ["-F", `number=${input.number}`],
+ ],
+ query: LABEL_CANDIDATES_GRAPHQL_QUERY,
+ decode: decodeLabelCandidatesJson,
+ });
+ },
+
+ setLabels: (input) => {
+ const { owner, name } = parseRepositorySelector(input.repository);
+ // A pull request is an issue to the labels API. Adding posts a list and leaves what was
+ // already there; taking off is one delete per label, since the endpoint names one in its
+ // path. The name goes into the path encoded, because a label may carry a space or a slash.
+ const issue = `repos/${owner}/${name}/issues/${input.number}/labels`;
+ if (input.applied) {
+ return github
+ .execute({
+ cwd: input.cwd,
+ args: ["api", "--method", "POST", "--hostname", input.host, issue, "--input", "-"],
+ stdin: buildLabelRequestJson(input.labels),
+ })
+ .pipe(Effect.asVoid);
+ }
+ return Effect.forEach(
+ input.labels,
+ (label) =>
+ github.execute({
+ cwd: input.cwd,
+ args: [
+ "api",
+ "--method",
+ "DELETE",
+ "--hostname",
+ input.host,
+ `${issue}/${encodeURIComponent(label)}`,
+ ],
+ }),
+ { concurrency: 1, discard: true },
+ );
+ },
+
runPullRequestAction: (input) => {
if (input.action === "revert") {
return pullRequestNodeId({ ...input, operation: "revertPullRequest" }).pipe(
diff --git a/apps/server/src/pullRequest/GitHubPullRequestProvider.test.ts b/apps/server/src/pullRequest/GitHubPullRequestProvider.test.ts
index 7e6016288af..8fd0f09dd3e 100644
--- a/apps/server/src/pullRequest/GitHubPullRequestProvider.test.ts
+++ b/apps/server/src/pullRequest/GitHubPullRequestProvider.test.ts
@@ -47,7 +47,14 @@ it.effect("uses one narrow read for a linked pull request summary", () =>
describe("gitHubViewerPermissions", () => {
it("offers everything to a viewer who can write to the repository", () => {
- expect(gitHubViewerPermissions({ canWrite: true, canUpdate: true, didAuthor: false })).toEqual({
+ expect(
+ gitHubViewerPermissions({
+ canWrite: true,
+ canTriage: true,
+ canUpdate: true,
+ didAuthor: false,
+ }),
+ ).toEqual({
// Arming a merge for later is the merge, so it travels with it.
actions: [
"merge",
@@ -64,6 +71,7 @@ describe("gitHubViewerPermissions", () => {
resolve: true,
verdicts: ["comment", "approve", "request-changes"],
requestReviewers: true,
+ labels: true,
});
});
@@ -71,7 +79,12 @@ describe("gitHubViewerPermissions", () => {
// Every open-source pull request somebody else opened: GitHub says no to all five actions
// and to resolving, and yes to commenting and to every verdict.
expect(
- gitHubViewerPermissions({ canWrite: false, canUpdate: false, didAuthor: false }),
+ gitHubViewerPermissions({
+ canWrite: false,
+ canTriage: false,
+ canUpdate: false,
+ didAuthor: false,
+ }),
).toEqual({
actions: [],
comment: true,
@@ -79,11 +92,31 @@ describe("gitHubViewerPermissions", () => {
verdicts: ["comment", "approve", "request-changes"],
// Asking somebody else to review is the one thing read access never stretches to.
requestReviewers: false,
+ labels: false,
+ });
+ });
+
+ it("lets a triager label without letting them merge or ask for a review", () => {
+ const permissions = gitHubViewerPermissions({
+ canWrite: false,
+ canTriage: true,
+ canUpdate: false,
+ didAuthor: false,
});
+ expect(permissions.labels).toBe(true);
+ expect(permissions.requestReviewers).toBe(false);
+ expect(permissions.actions).toEqual([]);
});
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({
+ expect(
+ gitHubViewerPermissions({
+ canWrite: false,
+ canTriage: false,
+ canUpdate: true,
+ didAuthor: true,
+ }),
+ ).toEqual({
// 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,
@@ -91,6 +124,7 @@ describe("gitHubViewerPermissions", () => {
// GitHub refuses an author's approval of their own change, so the page does not offer one.
verdicts: ["comment"],
requestReviewers: false,
+ labels: false,
});
});
@@ -110,6 +144,7 @@ describe("gitHubViewerPermissions", () => {
resolve: false,
verdicts: ["comment", "approve", "request-changes"],
requestReviewers: false,
+ labels: false,
});
expect(detail.workflowApprovalsRequired).toBeUndefined();
expect(detail.checks).toContainEqual({
@@ -158,7 +193,12 @@ describe("gitHubViewerPermissions", () => {
mergeCapabilities: { merge: true, squash: true, rebase: true },
}),
getViewerAccess: () =>
- Effect.succeed({ canWrite: false, canUpdate: true, didAuthor: false }),
+ Effect.succeed({
+ canWrite: false,
+ canTriage: false,
+ canUpdate: true,
+ didAuthor: false,
+ }),
}),
),
),
@@ -254,7 +294,7 @@ describe("gitHubViewerPermissions", () => {
mergeCapabilities: { merge: true, squash: true, rebase: true },
}),
getViewerAccess: () =>
- Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
+ Effect.succeed({ canWrite: true, canTriage: true, canUpdate: true, didAuthor: false }),
}),
),
),
@@ -318,7 +358,7 @@ it.effect("does not classify same-repository gates as fork workflow approvals",
mergeCapabilities: { merge: true, squash: true, rebase: true },
}),
getViewerAccess: () =>
- Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
+ Effect.succeed({ canWrite: true, canTriage: true, canUpdate: true, didAuthor: false }),
}),
),
),
@@ -365,7 +405,7 @@ it.effect("keeps an unsafe workflow approval scope visible as unknown", () =>
mergeCapabilities: { merge: true, squash: true, rebase: true },
}),
getViewerAccess: () =>
- Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
+ Effect.succeed({ canWrite: true, canTriage: true, canUpdate: true, didAuthor: false }),
}),
),
),
@@ -404,7 +444,7 @@ it.effect("propagates workflow discovery rate limits", () =>
mergeCapabilities: { merge: true, squash: true, rebase: true },
}),
getViewerAccess: () =>
- Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
+ Effect.succeed({ canWrite: true, canTriage: true, canUpdate: true, didAuthor: false }),
}),
),
),
@@ -420,7 +460,8 @@ describe("getViewerPermissions", () => {
Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({
getPullRequestDetail: () => Effect.succeed(openDetail),
getPullRequestBaseComparison: () => comparison,
- getViewerAccess: () => Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
+ getViewerAccess: () =>
+ Effect.succeed({ canWrite: true, canTriage: true, canUpdate: true, didAuthor: false }),
});
it.effect("offers update-branch when the comparison grants it", () =>
@@ -466,7 +507,7 @@ describe("getViewerPermissions", () => {
getViewerAccess: (input) =>
Effect.sync(() => {
viewerAllowReserve = input.allowReserve;
- return { canWrite: true, canUpdate: true, didAuthor: false };
+ return { canWrite: true, canTriage: true, canUpdate: true, didAuthor: false };
}),
}),
),
@@ -501,7 +542,7 @@ describe("getViewerPermissions", () => {
}),
),
getViewerAccess: () =>
- Effect.succeed({ canWrite: true, canUpdate: true, didAuthor: false }),
+ Effect.succeed({ canWrite: true, canTriage: true, canUpdate: true, didAuthor: false }),
}),
),
),
diff --git a/apps/server/src/pullRequest/GitHubPullRequestProvider.ts b/apps/server/src/pullRequest/GitHubPullRequestProvider.ts
index 5288040de25..5315dd2ed5d 100644
--- a/apps/server/src/pullRequest/GitHubPullRequestProvider.ts
+++ b/apps/server/src/pullRequest/GitHubPullRequestProvider.ts
@@ -47,6 +47,7 @@ const CAPABILITIES: PullRequestCapabilities = {
},
reviewers: { request: true, listCandidates: true },
edit: { changeRequest: true, comment: true },
+ labels: true,
};
/**
@@ -93,6 +94,8 @@ export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequest
verdicts: access.didAuthor ? (["comment"] as const) : CAPABILITIES.review.verdicts,
requestReviewers: access.canWrite,
...(access.canUpdateBranch === true ? { updateMethods: CAPABILITIES.updateMethods } : {}),
+ // Triage is the one role that labels without writing, which is what triage is for.
+ labels: access.canTriage,
};
}
@@ -526,6 +529,21 @@ export const make = Effect.gen(function* () {
})
.pipe(Effect.mapError(fail("setReviewerRequest"))),
+ listLabelCandidates: (input) =>
+ cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),
+
+ setLabels: (input) =>
+ cli
+ .setLabels({
+ cwd: input.cwd,
+ repository: input.repository,
+ host: input.host,
+ number: input.number,
+ labels: input.labels,
+ applied: input.applied,
+ })
+ .pipe(Effect.mapError(fail("setLabels"))),
+
runAction: (input) =>
cli
.runPullRequestAction({
diff --git a/apps/server/src/pullRequest/PullRequestProvider.ts b/apps/server/src/pullRequest/PullRequestProvider.ts
index 155bf64109c..1459d7cec92 100644
--- a/apps/server/src/pullRequest/PullRequestProvider.ts
+++ b/apps/server/src/pullRequest/PullRequestProvider.ts
@@ -26,6 +26,7 @@ import type {
PullRequestReviewVerdict,
PullRequestReviewerCandidateList,
PullRequestReviewerKind,
+ PullRequestLabelCandidateList,
PullRequestState,
PullRequestUpdateMethod,
PullRequestViewerPermissions,
@@ -469,6 +470,23 @@ export interface PullRequestProviderApi {
},
) => Effect.Effect<void, PullRequestProviderError>;
+ /**
+ * The repository's labels, with the ones already on the change request marked. Present with
+ * `setLabels` only where `capabilities.labels` is true; the service refuses both without it.
+ */
+ readonly listLabelCandidates?: (
+ input: ProviderRepositoryRef & { readonly number: number },
+ ) => Effect.Effect<PullRequestLabelCandidateList, PullRequestProviderError>;
+
+ /** Puts labels on the change request, or takes them off. One call for both directions. */
+ readonly setLabels?: (
+ input: ProviderRepositoryRef & {
+ readonly number: number;
+ readonly labels: ReadonlyArray<string>;
+ readonly applied: boolean;
+ },
+ ) => Effect.Effect<void, PullRequestProviderError>;
+
/** Only called when `capabilities.review.reply` is true. */
readonly replyToThread: (
input: ProviderRepositoryRef & {
diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts
index 28c44e8d1b2..0a4d17280ad 100644
--- a/apps/server/src/pullRequest/PullRequestService.test.ts
+++ b/apps/server/src/pullRequest/PullRequestService.test.ts
@@ -2284,6 +2284,125 @@ it.effect("hands the host's own candidate list back, and asks for it with the ch
}),
);
+it.effect("refuses a label change on a host that has not said it takes one", () =>
+ Effect.gen(function* () {
+ let changed = false;
+ const service = yield* makeService({
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
+ providers: [
+ fakeProvider("github", {
+ // The method is there; the capability that would let it be called is not.
+ setLabels: () => {
+ changed = true;
+ return Effect.void;
+ },
+ }),
+ ],
+ });
+
+ const error = yield* Effect.flip(
+ service.setLabels({
+ projectId: "p1" as ProjectId,
+ repository: "acme/web",
+ number: 1,
+ labels: ["bug"],
+ applied: true,
+ }),
+ );
+
+ assert.strictEqual(error._tag, "PullRequestOperationError");
+ assert.include(error.message, "cannot change the labels");
+ assert.isFalse(changed);
+ }),
+);
+
+it.effect("refuses a label change this viewer may not make, and says what access it takes", () =>
+ Effect.gen(function* () {
+ let changed = false;
+ const service = yield* makeService({
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
+ providers: [
+ fakeProvider("github", {
+ capabilities: { ...fakeProvider("github").capabilities, labels: true },
+ getViewerPermissions: () =>
+ Effect.succeed({
+ actions: [],
+ comment: true,
+ resolve: false,
+ verdicts: ["comment", "approve", "request-changes"],
+ requestReviewers: false,
+ labels: false,
+ }),
+ listLabelCandidates: () => Effect.die("must not be called"),
+ setLabels: () => {
+ changed = true;
+ return Effect.void;
+ },
+ }),
+ ],
+ });
+
+ const listError = yield* Effect.flip(
+ service.labelCandidates({ projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }),
+ );
+ assert.include(listError.message, "You need triage access on this repository");
+
+ const error = yield* Effect.flip(
+ service.setLabels({
+ projectId: "p1" as ProjectId,
+ repository: "acme/web",
+ number: 1,
+ labels: ["bug"],
+ applied: true,
+ }),
+ );
+ assert.include(error.message, "You need triage access on this repository");
+ assert.isFalse(changed);
+ }),
+);
+
+it.effect("hands a label change to the host, and reads the labels back for the menu", () =>
+ Effect.gen(function* () {
+ let received: { labels: ReadonlyArray<string>; applied: boolean } | null = null;
+ const service = yield* makeService({
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
+ providers: [
+ fakeProvider("github", {
+ capabilities: { ...fakeProvider("github").capabilities, labels: true },
+ listLabelCandidates: () =>
+ Effect.succeed({
+ candidates: [{ name: "bug", color: null, description: null, isApplied: false }],
+ truncated: false,
+ }),
+ setLabels: (input) => {
+ received = { labels: input.labels, applied: input.applied };
+ return Effect.void;
+ },
+ }),
+ ],
+ });
+
+ const list = yield* service.labelCandidates({
+ projectId: "p1" as ProjectId,
+ repository: "acme/web",
+ number: 4,
+ });
+ assert.deepStrictEqual(
+ list.candidates.map((label) => label.name),
+ ["bug"],
+ );
+
+ yield* service.setLabels({
+ projectId: "p1" as ProjectId,
+ repository: "acme/web",
+ number: 4,
+ labels: ["bug"],
+ applied: false,
+ });
+ assert.deepStrictEqual(received, { labels: ["bug"], applied: false });
+ }),
+);
+
it.effect("answers a repeated listing from cache, and concurrent readers share one request", () =>
Effect.gen(function* () {
let hostCalls = 0;
diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts
index 752cdf1aa5e..116087eb8f7 100644
--- a/apps/server/src/pullRequest/PullRequestService.ts
+++ b/apps/server/src/pullRequest/PullRequestService.ts
@@ -38,6 +38,8 @@ import {
type PullRequestReviewVerdict,
type PullRequestReviewerCandidateList,
type PullRequestReviewerRequestInput,
+ type PullRequestLabelCandidateList,
+ type PullRequestLabelChangeInput,
type PullRequestSubmitReviewInput,
type PullRequestSummary,
type PullRequestThreadReplyInput,
@@ -170,6 +172,12 @@ export class PullRequestService extends Context.Service<
readonly requestReviewers: (
input: PullRequestReviewerRequestInput,
) => Effect.Effect<void, PullRequestError>;
+ readonly labelCandidates: (
+ input: PullRequestRef,
+ ) => Effect.Effect<PullRequestLabelCandidateList, PullRequestError>;
+ readonly setLabels: (
+ input: PullRequestLabelChangeInput,
+ ) => Effect.Effect<void, PullRequestError>;
readonly invalidate: (input: PullRequestInvalidateInput) => Effect.Effect<void>;
}
>()("t3/pullRequest/PullRequestService") {}
@@ -213,6 +221,7 @@ const ACTION_ACCESS_REFUSALS: Record<PullRequestAction, string> = {
* sentence is only ever the answer where a host said no.
*/
const REVIEWER_REQUEST_REFUSAL = "You need write access on this repository to ask for a review.";
+const LABEL_CHANGE_REFUSAL = "You need triage access on this repository to change its labels.";
/** A project this page can read: its remote is on a host with an implementation. */
interface SupportedProject {
@@ -473,6 +482,10 @@ function withRateLimitBackoff(
submitReview: interactive("submitReview", api.submitReview),
listReviewerCandidates: interactive("listReviewerCandidates", api.listReviewerCandidates),
setReviewerRequest: interactive("setReviewerRequest", api.setReviewerRequest),
+ ...(api.listLabelCandidates === undefined
+ ? {}
+ : { listLabelCandidates: interactive("listLabelCandidates", api.listLabelCandidates) }),
+ ...(api.setLabels === undefined ? {} : { setLabels: interactive("setLabels", api.setLabels) }),
replyToThread: interactive("replyToThread", api.replyToThread),
setReaction: interactive("setReaction", api.setReaction),
setThreadResolution: interactive("setThreadResolution", api.setThreadResolution),
@@ -1843,6 +1856,78 @@ export const make = Effect.gen(function* () {
}),
);
+ /**
+ * The labels, like the reviewer candidates, are wanted only by somebody about to change them,
+ * so the same permission guards the list and the change.
+ */
+ const labelCandidates: PullRequestService["Service"]["labelCandidates"] = (input) =>
+ requireProject(input).pipe(
+ Effect.flatMap((project): Effect.Effect<PullRequestLabelCandidateList, PullRequestError> => {
+ const list = project.api.listLabelCandidates;
+ if (project.api.capabilities.labels !== true || list === undefined) {
+ return Effect.fail(
+ new PullRequestOperationError({
+ operation: "labelCandidates",
+ detail: "This host cannot change the labels on a change request.",
+ }),
+ );
+ }
+ return viewerPermissionsOf(project, input, "labelCandidates").pipe(
+ Effect.flatMap(
+ (viewer): Effect.Effect<PullRequestLabelCandidateList, PullRequestError> =>
+ viewer.labels === false
+ ? Effect.fail(
+ new PullRequestOperationError({
+ operation: "labelCandidates",
+ detail: LABEL_CHANGE_REFUSAL,
+ }),
+ )
+ : list({
+ cwd: project.project.workspaceRoot,
+ repository: project.repository,
+ host: project.host,
+ number: input.number,
+ }).pipe(Effect.mapError(toPullRequestError("labelCandidates"))),
+ ),
+ );
+ }),
+ );
+
+ const setLabels: PullRequestService["Service"]["setLabels"] = (input) =>
+ requireProject(input).pipe(
+ Effect.flatMap((project): Effect.Effect<void, PullRequestError> => {
+ const change = project.api.setLabels;
+ if (project.api.capabilities.labels !== true || change === undefined) {
+ return Effect.fail(
+ new PullRequestOperationError({
+ operation: "setLabels",
+ detail: "This host cannot change the labels on a change request.",
+ }),
+ );
+ }
+ return viewerPermissionsOf(project, input, "setLabels").pipe(
+ Effect.flatMap(
+ (viewer): Effect.Effect<void, PullRequestError> =>
+ viewer.labels === false
+ ? Effect.fail(
+ new PullRequestOperationError({
+ operation: "setLabels",
+ detail: LABEL_CHANGE_REFUSAL,
+ }),
+ )
+ : change({
+ cwd: project.project.workspaceRoot,
+ repository: project.repository,
+ host: project.host,
+ number: input.number,
+ labels: input.labels,
+ applied: input.applied,
+ }).pipe(Effect.mapError(toPullRequestError("setLabels"))),
+ ),
+ );
+ }),
+ );
+
/**
* The line counts for rows already on the page, which the listing left out because on GitHub
* they cost more than everything else on the row put together.
@@ -2336,6 +2421,8 @@ export const make = Effect.gen(function* () {
// The candidate list is deliberately read fresh per menu-open, so it stays uncached.
reviewerCandidates,
requestReviewers: invalidatedByMutation(requestReviewers),
+ labelCandidates,
+ setLabels: invalidatedByMutation(setLabels),
invalidate,
});
});
diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts
index 000dbada204..f6f5957f587 100644
--- a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts
+++ b/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts
@@ -11,6 +11,7 @@ import {
decodePullRequestListJson,
decodePullRequestNodeIdJson,
decodePullRequestSearchJson,
+ decodeLabelCandidatesJson,
decodeRepositoryAccessJson,
decodeReviewerCandidatesJson,
decodeReviewThreadCommentsJson,
@@ -832,7 +833,7 @@ describe("viewer permission decoding", () => {
}),
),
),
- ).toEqual({ canWrite: false, canUpdate: true, didAuthor: true });
+ ).toEqual({ canWrite: false, canTriage: false, canUpdate: true, didAuthor: true });
});
it("says no to a passer-by on a repository they can only read", () => {
@@ -845,7 +846,7 @@ describe("viewer permission decoding", () => {
}),
),
),
- ).toEqual({ canWrite: false, canUpdate: false, didAuthor: false });
+ ).toEqual({ canWrite: false, canTriage: false, canUpdate: false, didAuthor: false });
});
it("reads silence as permission, but not as authorship", () => {
@@ -854,10 +855,79 @@ describe("viewer permission decoding", () => {
// and claiming it for someone who did not is how an author's own rules get handed out.
expect(expectSuccess(decodeViewerPermissionsJson(viewerJson({ pullRequest: null })))).toEqual({
canWrite: false,
+ canTriage: false,
canUpdate: true,
didAuthor: false,
});
});
+
+ it("reads triage as enough to label, and not enough to write", () => {
+ const access = expectSuccess(
+ decodeViewerPermissionsJson(
+ viewerJson({
+ viewerPermission: "TRIAGE",
+ pullRequest: { viewerCanUpdate: false, viewerDidAuthor: false },
+ }),
+ ),
+ );
+ expect(access.canTriage).toBe(true);
+ expect(access.canWrite).toBe(false);
+ });
+});
+
+describe("label candidate decoding", () => {
+ const labelsJson = (input: {
+ readonly defined: ReadonlyArray<Record<string, unknown>>;
+ readonly applied?: ReadonlyArray<string>;
+ readonly hasNextPage?: boolean;
+ }) =>
+ JSON.stringify({
+ data: {
+ repository: {
+ labels: {
+ pageInfo: { hasNextPage: input.hasNextPage ?? false },
+ nodes: input.defined,
+ },
+ pullRequest: { labels: { nodes: (input.applied ?? []).map((name) => ({ name })) } },
+ },
+ },
+ });
+
+ it("marks the labels the pull request already wears", () => {
+ const list = expectSuccess(
+ decodeLabelCandidatesJson(
+ labelsJson({
+ defined: [
+ { name: "bug", color: "d73a4a", description: "Something is broken" },
+ { name: "size:XL", color: "e4572e", description: null },
+ ],
+ applied: ["size:XL"],
+ }),
+ ),
+ );
+ expect(list.candidates).toEqual([
+ { name: "bug", color: "d73a4a", description: "Something is broken", isApplied: false },
+ { name: "size:XL", color: "e4572e", description: null, isApplied: true },
+ ]);
+ expect(list.truncated).toBe(false);
+ });
+
+ it("keeps a worn label the repository no longer defines, so it can be taken off", () => {
+ const list = expectSuccess(
+ decodeLabelCandidatesJson(labelsJson({ defined: [{ name: "bug" }], applied: ["legacy"] })),
+ );
+ expect(list.candidates.map((label) => [label.name, label.isApplied])).toEqual([
+ ["legacy", true],
+ ["bug", false],
+ ]);
+ });
+
+ it("says so when the repository defines more labels than the read asked for", () => {
+ expect(
+ expectSuccess(decodeLabelCandidatesJson(labelsJson({ defined: [], hasNextPage: true })))
+ .truncated,
+ ).toBe(true);
+ });
});
describe("review thread decoding", () => {
diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.ts
index 9cc21b42939..12fb376d3ed 100644
--- a/apps/server/src/pullRequest/gitHubPullRequestJson.ts
+++ b/apps/server/src/pullRequest/gitHubPullRequestJson.ts
@@ -24,6 +24,8 @@ import type {
PullRequestReviewerCandidate,
PullRequestReviewerCandidateList,
PullRequestReviewerKind,
+ PullRequestLabelCandidate,
+ PullRequestLabelCandidateList,
PullRequestState,
PullRequestThreadComment,
} from "@t3tools/contracts";
@@ -1994,6 +1996,11 @@ function toCanWrite(viewerPermission: string | null | undefined): boolean {
}
}
+/** Triage is the least role GitHub lets label a pull request; it is not a write. */
+function toCanTriage(viewerPermission: string | null | undefined): boolean {
+ return viewerPermission?.trim().toUpperCase() === "TRIAGE" || toCanWrite(viewerPermission);
+}
+
export function decodeRepositoryAccessJson(
raw: string,
): Result.Result<GitHubRepositoryAccess, DecodeFailure> {
@@ -2222,6 +2229,99 @@ export function buildReviewerRequestJson(
});
}
+export const LABEL_CANDIDATES_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
+ repository(owner: $owner, name: $name) {
+ labels(first: ${GRAPHQL_PAGE_SIZE}, orderBy: { field: NAME, direction: ASC }) {
+ pageInfo { hasNextPage }
+ nodes { name color description }
+ }
+ pullRequest(number: $number) {
+ labels(first: ${GRAPHQL_PAGE_SIZE}) { nodes { name } }
+ }
+ }
+}`;
+
+const RawLabelCandidatesSchema = Schema.Struct({
+ data: Schema.Struct({
+ repository: Schema.Struct({
+ labels: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({
+ pageInfo: Schema.optional(RawPageInfoSchema),
+ nodes: Schema.Array(
+ Schema.NullOr(
+ Schema.Struct({
+ ...RawLabelSchema.fields,
+ description: Schema.optional(Schema.NullOr(Schema.String)),
+ }),
+ ),
+ ),
+ }),
+ ),
+ ),
+ /** Null for a number that names no pull request the viewer can see. */
+ pullRequest: Schema.NullOr(
+ Schema.Struct({
+ labels: Schema.optional(
+ Schema.NullOr(Schema.Struct({ nodes: Schema.Array(Schema.NullOr(RawLabelSchema)) })),
+ ),
+ }),
+ ),
+ }),
+ }),
+});
+
+const decodeLabelCandidates = decodeJsonResult(RawLabelCandidatesSchema);
+
+/**
+ * The repository's labels, with the ones already on this pull request marked. A label the pull
+ * request wears that the repository no longer defines — deleted since, or past the page — leads
+ * the list anyway, because a label that cannot be seen cannot be taken off.
+ */
+export function decodeLabelCandidatesJson(
+ raw: string,
+): Result.Result<PullRequestLabelCandidateList, DecodeFailure> {
+ const decoded = decodeLabelCandidates(raw);
+ if (!Result.isSuccess(decoded)) {
+ return Result.fail(decoded.failure);
+ }
+ const repository = decoded.success.data.repository;
+ const applied = new Set(
+ (repository.pullRequest?.labels?.nodes ?? []).flatMap((label) => {
+ const name = trimmed(label?.name);
+ return name === null ? [] : [name];
+ }),
+ );
+ const candidates = new Map<string, PullRequestLabelCandidate>();
+ for (const node of repository.labels?.nodes ?? []) {
+ const name = trimmed(node?.name);
+ if (name === null) continue;
+ candidates.set(name, {
+ name,
+ color: trimmed(node?.color),
+ description: trimmed(node?.description),
+ isApplied: applied.has(name),
+ });
+ }
+ const missing = [...applied].filter((name) => !candidates.has(name));
+ return Result.succeed({
+ candidates: [
+ ...missing.map((name) => ({ name, color: null, description: null, isApplied: true })),
+ ...candidates.values(),
+ ],
+ truncated: repository.labels?.pageInfo?.hasNextPage === true,
+ });
+}
+
+/** The body of `POST /repos/{owner}/{repo}/issues/{number}/labels`, which adds to what is there. */
+const LabelRequestSchema = Schema.Struct({ labels: Schema.Array(Schema.String) });
+
+const encodeLabelRequest = Schema.encodeSync(Schema.fromJsonString(LabelRequestSchema));
+
+export function buildLabelRequestJson(labels: ReadonlyArray<string>): string {
+ return encodeLabelRequest({ labels });
+}
+
/**
* Everything GitHub says about what the signed-in account may do here. `canWrite` is about the
* repository, the other two about this pull request in particular — which is why an author with
@@ -2229,6 +2329,11 @@ export function buildReviewerRequestJson(
*/
export interface GitHubViewerAccess {
readonly canWrite: boolean;
+ /**
+ * The viewer's role reaches triage, which is the least that may label. Everyone who can write
+ * can triage; a triager is the one role that can label without being able to merge.
+ */
+ readonly canTriage: boolean;
/** GitHub's own `viewerCanUpdate`, true for the author as well as for anyone with write. */
readonly canUpdate: boolean;
readonly didAuthor: boolean;
@@ -2275,6 +2380,7 @@ export function decodeViewerPermissionsJson(
const repository = decoded.success.data.repository;
return Result.succeed({
canWrite: toCanWrite(repository.viewerPermission),
+ canTriage: toCanTriage(repository.viewerPermission),
...toPullRequestViewerFields(repository.pullRequest),
});
}
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 28ade015f8b..cb00bbee73f 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -1976,6 +1976,16 @@ const makeWsRpcLayer = (
pullRequests.requestReviewers(input),
{ "rpc.aggregate": "pull-requests" },
),
+ [WS_METHODS.pullRequestsLabelCandidates]: (input) =>
+ observeRpcEffect(
+ WS_METHODS.pullRequestsLabelCandidates,
+ pullRequests.labelCandidates(input),
+ { "rpc.aggregate": "pull-requests" },
+ ),
+ [WS_METHODS.pullRequestsSetLabels]: (input) =>
+ observeRpcEffect(WS_METHODS.pullRequestsSetLabels, pullRequests.setLabels(input), {
+ "rpc.aggregate": "pull-requests",
+ }),
[WS_METHODS.sourceControlLookupRepository]: (input) =>
observeRpcEffect(
WS_METHODS.sourceControlLookupRepository,
diff --git a/apps/web/src/components/pullRequest/PullRequestCandidatePicker.tsx b/apps/web/src/components/pullRequest/PullRequestCandidatePicker.tsx
new file mode 100644
index 00000000000..b42061628d1
--- /dev/null
+++ b/apps/web/src/components/pullRequest/PullRequestCandidatePicker.tsx
@@ -0,0 +1,136 @@
+/**
+ * The menu shell the reviewer and label pickers share: an icon trigger, a search box, and a
+ * scrolling body that says when the list is loading, could not be read, is empty, or is not all
+ * of it. The rows and the words are the caller's; the frame is the same either way.
+ */
+import type { ReactNode } from "react";
+
+import { Button } from "../ui/button";
+import { Input } from "../ui/input";
+import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { PullRequestPeopleGhost } from "./PullRequestGhosts";
+
+export function PullRequestCandidatePicker<T>({
+ icon,
+ label,
+ allowed,
+ disabledReason,
+ open,
+ onOpenChange,
+ query,
+ onQueryChange,
+ searchLabel,
+ isPending,
+ error,
+ candidates,
+ emptyLabel,
+ noMatchLabel,
+ errorLabel,
+ truncated,
+ truncatedLabel,
+ candidateKey,
+ disabled,
+ onSelect,
+ children,
+}: {
+ icon: ReactNode;
+ /** The trigger's accessible name; the button carries an icon alone. */
+ label: string;
+ /** False where the host would refuse this account's change. Disabled with the reason rather
+ * than hidden: a control that vanishes teaches nobody why. */
+ allowed: boolean;
+ disabledReason: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ query: string;
+ onQueryChange: (query: string) => void;
+ searchLabel: string;
+ isPending: boolean;
+ error: string | null;
+ /** Already narrowed by the query; the shell only decides which state to show. */
+ candidates: ReadonlyArray<T>;
+ emptyLabel: string;
+ noMatchLabel: string;
+ /** Leads the host's own message, which follows it in the same sentence. */
+ errorLabel: string;
+ /** The host has more than the read asked for, so a name missing here may still be askable. */
+ truncated: boolean;
+ truncatedLabel: string;
+ candidateKey: (candidate: T) => string;
+ /** Every row locks while one change is in flight, so a second press cannot race the first. */
+ disabled: boolean;
+ onSelect: (candidate: T) => void;
+ children: (candidate: T) => ReactNode;
+}) {
+ if (!allowed) {
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button size="icon-xs" variant="ghost" disabled aria-label={label}>
+ {icon}
+ </Button>
+ }
+ />
+ <TooltipPopup side="bottom">{disabledReason}</TooltipPopup>
+ </Tooltip>
+ );
+ }
+
+ return (
+ <Menu open={open} onOpenChange={onOpenChange}>
+ <MenuTrigger
+ render={
+ <Button size="icon-xs" variant="ghost" aria-label={label}>
+ {icon}
+ </Button>
+ }
+ />
+ <MenuPopup align="start" side="bottom" className="w-72 p-0">
+ <div className="border-b border-border/60 p-2">
+ <Input
+ autoFocus
+ value={query}
+ onChange={(event) => onQueryChange(event.currentTarget.value)}
+ placeholder={searchLabel}
+ aria-label={searchLabel}
+ size="compact"
+ />
+ </div>
+ <div className="max-h-72 overflow-y-auto p-1">
+ {isPending ? (
+ <PullRequestPeopleGhost rows={4} />
+ ) : error !== null ? (
+ <p className="p-2 text-xs text-muted-foreground">
+ {errorLabel} {error}
+ </p>
+ ) : candidates.length === 0 ? (
+ <p className="p-2 text-xs text-muted-foreground">
+ {query.length > 0 ? noMatchLabel : emptyLabel}
+ </p>
+ ) : (
+ candidates.map((candidate) => (
+ // Stays open on press: a change is confirmed by the row's own check turning over,
+ // and a second label or reviewer is usually wanted right after the first.
+ <MenuItem
+ key={candidateKey(candidate)}
+ closeOnClick={false}
+ disabled={disabled}
+ onClick={() => onSelect(candidate)}
+ className="min-h-0 py-1.5 text-xs sm:min-h-0 sm:text-xs"
+ >
+ {children(candidate)}
+ </MenuItem>
+ ))
+ )}
+ {truncated ? (
+ // Typing filters what arrived; it does not ask the host again, so this says what the
+ // list is rather than offering a search that would find nothing further.
+ <p className="px-2 py-1.5 text-xs text-muted-foreground">{truncatedLabel}</p>
+ ) : null}
+ </div>
+ </MenuPopup>
+ </Menu>
+ );
+}
diff --git a/apps/web/src/components/pullRequest/PullRequestLabelPicker.tsx b/apps/web/src/components/pullRequest/PullRequestLabelPicker.tsx
new file mode 100644
index 00000000000..f1e5fc6a1da
--- /dev/null
+++ b/apps/web/src/components/pullRequest/PullRequestLabelPicker.tsx
@@ -0,0 +1,132 @@
+/**
+ * Putting a label on, and taking one off, from the row that says which it already wears.
+ *
+ * The repository's labels are read only once this menu opens, for the reason the reviewer menu
+ * reads its people then: they are worth a request when somebody wants them and worth nothing on
+ * every pull request they merely open.
+ */
+import type { EnvironmentId, PullRequestLabelCandidate, PullRequestRef } from "@t3tools/contracts";
+import { CheckIcon, TagIcon } from "lucide-react";
+import { useMemo, useState } from "react";
+
+import { pullRequestEnvironment } from "~/state/pullRequests";
+import { useEnvironmentQuery } from "~/state/query";
+import { useAtomCommand } from "~/state/use-atom-command";
+import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+
+import { toastManager } from "../ui/toast";
+import { PullRequestCandidatePicker } from "./PullRequestCandidatePicker";
+import { readableFailure } from "./pullRequestDetail.logic";
+import { pullRequestLabelColor } from "./pullRequestList.logic";
+
+/** Narrows only what arrived: the host is asked once, when the menu opens. */
+function matches(candidate: PullRequestLabelCandidate, query: string): boolean {
+ if (query.length === 0) return true;
+ const needle = query.toLowerCase();
+ return (
+ candidate.name.toLowerCase().includes(needle) ||
+ (candidate.description ?? "").toLowerCase().includes(needle)
+ );
+}
+
+export function PullRequestLabelPicker({
+ environmentId,
+ reference,
+ allowed,
+ onChanged,
+}: {
+ environmentId: EnvironmentId;
+ reference: PullRequestRef;
+ /** False where the host would refuse this account's change. Disabled with the reason rather
+ * than hidden, like the reviewer control beside it. */
+ allowed: boolean;
+ /** The detail carries the labels, so it is re-read once the host has taken the change. */
+ onChanged: () => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [pending, setPending] = useState<string | null>(null);
+
+ // Mounted with the menu closed, so nothing is asked of the host until it opens.
+ const candidatesQuery = useEnvironmentQuery(
+ open ? pullRequestEnvironment.labelCandidates({ environmentId, input: reference }) : null,
+ );
+ const setLabels = useAtomCommand(pullRequestEnvironment.setLabels, { reportFailure: false });
+
+ const candidates = useMemo(
+ () => (candidatesQuery.data?.candidates ?? []).filter((entry) => matches(entry, query)),
+ [candidatesQuery.data, query],
+ );
+
+ const toggle = async (candidate: PullRequestLabelCandidate) => {
+ if (pending !== null) return;
+ setPending(candidate.name);
+ const result = await setLabels({
+ environmentId,
+ input: { ...reference, labels: [candidate.name], applied: !candidate.isApplied },
+ });
+ setPending(null);
+ if (result._tag === "Failure") {
+ toastManager.add({
+ type: "error",
+ title: candidate.isApplied
+ ? `Could not take ${candidate.name} off`
+ : `Could not put ${candidate.name} on`,
+ description: readableFailure(
+ squashAtomCommandFailure(result),
+ "The host refused it. Check that you have triage access on this repository.",
+ ),
+ });
+ return;
+ }
+ onChanged();
+ candidatesQuery.refresh();
+ };
+
+ return (
+ <PullRequestCandidatePicker
+ icon={<TagIcon className="size-3.5" />}
+ label="Change labels"
+ allowed={allowed}
+ disabledReason="Changing labels needs triage access on this repository"
+ open={open}
+ onOpenChange={setOpen}
+ query={query}
+ onQueryChange={setQuery}
+ searchLabel="Search labels"
+ isPending={candidatesQuery.isPending}
+ error={candidatesQuery.error}
+ candidates={candidates}
+ emptyLabel="This repository has no labels."
+ noMatchLabel="No label matches that."
+ errorLabel="The labels could not be read."
+ truncated={candidatesQuery.data?.truncated === true}
+ truncatedLabel="This repository has more labels than are listed here. Apply the rest on the host."
+ candidateKey={(candidate) => candidate.name}
+ disabled={pending !== null}
+ onSelect={(candidate) => void toggle(candidate)}
+ >
+ {(candidate) => {
+ const dot = pullRequestLabelColor(candidate.color);
+ return (
+ <>
+ <span
+ aria-hidden
+ className="size-2 shrink-0 rounded-full bg-muted-foreground"
+ {...(dot ? { style: { backgroundColor: dot } } : {})}
+ />
+ <span className="min-w-0 flex-1 truncate">
+ {candidate.name}
+ {candidate.description ? (
+ <span className="text-muted-foreground"> · {candidate.description}</span>
+ ) : null}
+ </span>
+ {candidate.isApplied ? (
+ <CheckIcon aria-label="Applied" className="size-3.5 shrink-0" />
+ ) : null}
+ </>
+ );
+ }}
+ </PullRequestCandidatePicker>
+ );
+}
diff --git a/apps/web/src/components/pullRequest/PullRequestReviewerPicker.tsx b/apps/web/src/components/pullRequest/PullRequestReviewerPicker.tsx
index 8330c87a929..a4da0d99514 100644
--- a/apps/web/src/components/pullRequest/PullRequestReviewerPicker.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestReviewerPicker.tsx
@@ -18,12 +18,8 @@ import { useEnvironmentQuery } from "~/state/query";
import { useAtomCommand } from "~/state/use-atom-command";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
-import { Button } from "../ui/button";
-import { Input } from "../ui/input";
-import { Menu, MenuPopup, MenuTrigger } from "../ui/menu";
-import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { toastManager } from "../ui/toast";
-import { PullRequestPeopleGhost } from "./PullRequestGhosts";
+import { PullRequestCandidatePicker } from "./PullRequestCandidatePicker";
import { PullRequestActorLabel } from "./pullRequestPresentation";
import { readableFailure } from "./pullRequestDetail.logic";
@@ -104,85 +100,40 @@ export function PullRequestReviewerPicker({
candidatesQuery.refresh();
};
- if (!allowed) {
- return (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button size="icon-xs" variant="ghost" disabled aria-label="Request a review">
- <UserPlusIcon className="size-3.5" />
- </Button>
- }
- />
- <TooltipPopup side="bottom">
- Asking someone to review needs write access on this repository
- </TooltipPopup>
- </Tooltip>
- );
- }
-
return (
- <Menu open={open} onOpenChange={setOpen}>
- <MenuTrigger
- render={
- <Button size="icon-xs" variant="ghost" aria-label="Request a review">
- <UserPlusIcon className="size-3.5" />
- </Button>
- }
- />
- <MenuPopup align="start" side="bottom" className="w-72 p-0">
- <div className="border-b border-border/60 p-2">
- <Input
- autoFocus
- value={query}
- onChange={(event) => setQuery(event.currentTarget.value)}
- placeholder="Search people with access"
- aria-label="Search people with access"
- size="compact"
- />
- </div>
- <div className="max-h-72 overflow-y-auto p-1">
- {candidatesQuery.isPending ? (
- <PullRequestPeopleGhost rows={4} />
- ) : candidatesQuery.error !== null ? (
- <p className="p-2 text-xs text-muted-foreground">
- The people with access could not be read. {candidatesQuery.error}
- </p>
- ) : candidates.length === 0 ? (
- <p className="p-2 text-xs text-muted-foreground">
- {query.length > 0
- ? "Nobody with access matches that."
- : "Nobody else has access to this repository."}
- </p>
- ) : (
- candidates.map((candidate) => (
- <button
- key={`${candidate.kind}:${candidate.id}`}
- type="button"
- disabled={pending !== null}
- onClick={() => void toggle(candidate)}
- className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs hover:bg-accent/60 disabled:opacity-60"
- >
- <PullRequestActorLabel actor={candidate} className="min-w-0 flex-1 truncate" />
- {candidate.kind === "team" ? (
- <span className="shrink-0 text-muted-foreground">team</span>
- ) : null}
- {candidate.isRequested ? (
- <CheckIcon aria-label="Already asked" className="size-3.5 shrink-0" />
- ) : null}
- </button>
- ))
- )}
- {candidatesQuery.data?.truncated ? (
- // Typing filters what arrived; it does not ask the host again, so this says what the
- // list is rather than offering a search that would find nothing further.
- <p className="px-2 py-1.5 text-xs text-muted-foreground">
- This repository has more people with access than are listed here. Ask for the rest on
- the host.
- </p>
+ <PullRequestCandidatePicker
+ icon={<UserPlusIcon className="size-3.5" />}
+ label="Request a review"
+ allowed={allowed}
+ disabledReason="Asking someone to review needs write access on this repository"
+ open={open}
+ onOpenChange={setOpen}
+ query={query}
+ onQueryChange={setQuery}
+ searchLabel="Search people with access"
+ isPending={candidatesQuery.isPending}
+ error={candidatesQuery.error}
+ candidates={candidates}
+ emptyLabel="Nobody else has access to this repository."
+ noMatchLabel="Nobody with access matches that."
+ errorLabel="The people with access could not be read."
+ truncated={candidatesQuery.data?.truncated === true}
+ truncatedLabel="This repository has more people with access than are listed here. Ask for the rest on the host."
+ candidateKey={(candidate) => `${candidate.kind}:${candidate.id}`}
+ disabled={pending !== null}
+ onSelect={(candidate) => void toggle(candidate)}
+ >
+ {(candidate) => (
+ <>
+ <PullRequestActorLabel actor={candidate} className="min-w-0 flex-1 truncate" />
+ {candidate.kind === "team" ? (
+ <span className="shrink-0 text-muted-foreground">team</span>
+ ) : null}
+ {candidate.isRequested ? (
+ <CheckIcon aria-label="Already asked" className="size-3.5 shrink-0" />
) : null}
- </div>
- </MenuPopup>
- </Menu>
+ </>
+ )}
+ </PullRequestCandidatePicker>
);
}
diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
index 5a3144dadce..eccd9de9b1f 100644
--- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
@@ -41,6 +41,7 @@ import {
pullRequestReviewOutcomeRingClassName,
pullRequestReviewOutcomeStaleLabel,
} from "./pullRequestPresentation";
+import { PullRequestLabelPicker } from "./PullRequestLabelPicker";
import { PullRequestReviewerPicker } from "./PullRequestReviewerPicker";
import { PullRequestActivityUnavailableState } from "./PullRequestActivityUnavailableState";
import {
@@ -664,25 +665,39 @@ export function PullRequestSummaryTab({
) : null}
</span>
</MetaRow>
- {detail.labels.length > 0 ? (
+ {/* The row is shown empty only where a label could be put on it from here; on a host
+ with none to offer, an empty row is a row about nothing. */}
+ {detail.labels.length > 0 || detail.capabilities.labels === true ? (
<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 = pullRequestLabelColor(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"
- >
+ {detail.labels.length === 0 ? (
+ <span className="text-muted-foreground">None</span>
+ ) : (
+ detail.labels.map((label) => {
+ const dot = pullRequestLabelColor(label.color);
+ return (
<span
- aria-hidden
- className="size-2 shrink-0 rounded-full bg-muted-foreground"
- {...(dot ? { style: { backgroundColor: dot } } : {})}
- />
- <span className="truncate">{label.name}</span>
- </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>
+ );
+ })
+ )}
+ {detail.capabilities.labels === true ? (
+ <PullRequestLabelPicker
+ environmentId={environmentId}
+ reference={reference}
+ allowed={detail.viewerPermissions.labels !== false}
+ onChanged={onRefresh}
+ />
+ ) : null}
</span>
</MetaRow>
) : null}
diff --git a/docs/user/source-control.md b/docs/user/source-control.md
index 1573a151ce5..10d1995fa66 100644
--- a/docs/user/source-control.md
+++ b/docs/user/source-control.md
@@ -73,6 +73,8 @@ T3 Code works with the platforms your team already uses:
- 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
+- On GitHub, put a label on a pull request or take one off from the **Labels** row of the review.
+ Changing labels needs triage access or better on the repository
### Know Your Setup at a Glance
diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.ts
index b98524e0482..28c85ffe5c1 100644
--- a/packages/client-runtime/src/state/pullRequests.ts
+++ b/packages/client-runtime/src/state/pullRequests.ts
@@ -204,6 +204,18 @@ export function createPullRequestEnvironmentAtoms<R, E>(
scheduler: commandScheduler,
concurrency: serialPerEnvironment,
}),
+ /** Read when the label menu opens, and kept for a minute, like the reviewer candidates. */
+ labelCandidates: createEnvironmentRpcQueryAtomFamily(runtime, {
+ label: "environment-data:pull-requests:label-candidates",
+ tag: WS_METHODS.pullRequestsLabelCandidates,
+ staleTimeMs: 60_000,
+ }),
+ setLabels: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:pull-requests:set-labels",
+ tag: WS_METHODS.pullRequestsSetLabels,
+ scheduler: commandScheduler,
+ concurrency: serialPerEnvironment,
+ }),
setThreadResolution: createEnvironmentRpcCommand(runtime, {
label: "environment-data:pull-requests:set-thread-resolution",
tag: WS_METHODS.pullRequestsSetThreadResolution,
diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts
index 9cf7dbfd668..04c9d53cf77 100644
--- a/packages/contracts/src/pullRequest.ts
+++ b/packages/contracts/src/pullRequest.ts
@@ -291,6 +291,21 @@ export const PullRequestReviewerCandidateList = Schema.Struct({
});
export type PullRequestReviewerCandidateList = typeof PullRequestReviewerCandidateList.Type;
+/** A label the repository defines, with whether this change request already wears it. */
+export const PullRequestLabelCandidate = Schema.Struct({
+ ...PullRequestLabel.fields,
+ description: Schema.NullOr(Schema.String),
+ isApplied: Schema.Boolean,
+});
+export type PullRequestLabelCandidate = typeof PullRequestLabelCandidate.Type;
+
+export const PullRequestLabelCandidateList = Schema.Struct({
+ candidates: Schema.Array(PullRequestLabelCandidate),
+ /** The repository defines more labels than the read asked for; the list is not all of them. */
+ truncated: Schema.Boolean,
+});
+export type PullRequestLabelCandidateList = typeof PullRequestLabelCandidateList.Type;
+
export const PullRequestCommit = Schema.Struct({
oid: TrimmedNonEmptyString,
messageHeadline: Schema.String,
@@ -397,6 +412,12 @@ export const PullRequestCapabilities = Schema.Struct({
* what every server before this one was.
*/
edit: Schema.optional(PullRequestEditCapabilities),
+ /**
+ * The repository's labels can be listed, and one put on a change request or taken off it.
+ * Optional for the same reason `edit` is: a server that says nothing about labels has no way
+ * to change them, which is what every server before this field was.
+ */
+ labels: Schema.optional(Schema.Boolean),
});
export type PullRequestCapabilities = typeof PullRequestCapabilities.Type;
@@ -426,6 +447,12 @@ export const PullRequestViewerPermissions = Schema.Struct({
* Absent or empty means they may not, which is also what a host with no such action says.
*/
updateMethods: Schema.optional(Schema.Array(PullRequestUpdateMethod)),
+ /**
+ * This viewer may put a label on the change request, and take one off. Absent is granted, like
+ * every permission here; the capability beside it is what decides whether a label can be
+ * changed on this host at all.
+ */
+ labels: Schema.optional(Schema.Boolean),
});
export type PullRequestViewerPermissions = typeof PullRequestViewerPermissions.Type;
@@ -998,6 +1025,18 @@ export const PullRequestReviewerRequestInput = Schema.Struct({
});
export type PullRequestReviewerRequestInput = typeof PullRequestReviewerRequestInput.Type;
+/**
+ * Putting a label on and taking it off are one operation with `applied` turned around, which is
+ * what pressing the same row in the menu twice is. Named by the label's own name, which is how
+ * GitHub addresses one.
+ */
+export const PullRequestLabelChangeInput = Schema.Struct({
+ ...PullRequestRef.fields,
+ labels: Schema.Array(TrimmedNonEmptyString).check(Schema.isMinLength(1), Schema.isMaxLength(25)),
+ applied: Schema.Boolean,
+});
+export type PullRequestLabelChangeInput = typeof PullRequestLabelChangeInput.Type;
+
export const PullRequestUnavailableReason = Schema.Literals([
"cli-missing",
"cli-unauthenticated",
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index 9c009baabcc..1e964dc3771 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -100,6 +100,8 @@ import {
PullRequestSummary,
PullRequestReviewerCandidateList,
PullRequestReviewerRequestInput,
+ PullRequestLabelCandidateList,
+ PullRequestLabelChangeInput,
PullRequestSubmitReviewInput,
PullRequestThreadCommentsInput,
PullRequestThreadCommentsResult,
@@ -319,6 +321,8 @@ export const WS_METHODS = {
pullRequestsInvalidate: "pullRequests.invalidate",
pullRequestsReviewerCandidates: "pullRequests.reviewerCandidates",
pullRequestsRequestReviewers: "pullRequests.requestReviewers",
+ pullRequestsLabelCandidates: "pullRequests.labelCandidates",
+ pullRequestsSetLabels: "pullRequests.setLabels",
// Source control methods
sourceControlLookupRepository: "sourceControl.lookupRepository",
@@ -630,6 +634,19 @@ export const WsPullRequestsRequestReviewersRpc = Rpc.make(WS_METHODS.pullRequest
error: PullRequestRpcError,
});
+/** Read when the label menu opens, for the same reason the reviewer candidates are. */
+export const WsPullRequestsLabelCandidatesRpc = Rpc.make(WS_METHODS.pullRequestsLabelCandidates, {
+ payload: PullRequestRef,
+ success: PullRequestLabelCandidateList,
+ error: PullRequestRpcError,
+});
+
+export const WsPullRequestsSetLabelsRpc = Rpc.make(WS_METHODS.pullRequestsSetLabels, {
+ payload: PullRequestLabelChangeInput,
+ success: Schema.Void,
+ error: PullRequestRpcError,
+});
+
export const WsSourceControlLookupRepositoryRpc = Rpc.make(
WS_METHODS.sourceControlLookupRepository,
{
@@ -1087,6 +1104,8 @@ export const WsRpcGroup = RpcGroup.make(
WsPullRequestsInvalidateRpc,
WsPullRequestsReviewerCandidatesRpc,
WsPullRequestsRequestReviewersRpc,
+ WsPullRequestsLabelCandidatesRpc,
+ WsPullRequestsSetLabelsRpc,
WsSourceControlLookupRepositoryRpc,
WsSourceControlCloneRepositoryRpc,
WsSourceControlPublishRepositoryRpc,