Compare commits

...
Author SHA1 Message Date
t3-code[bot] ee970aa716 feat(pr): add quick-win filters 2026-08-10 23:19:42 +00:00
18 changed files with 659 additions and 21 deletions

No files matched your search

@@ -144,6 +144,7 @@ export const make = Effect.gen(function* () {
repositoryIdentity: true,
connectionProbe: true,
pullRequests: true,
pullRequestQuickFilters: true,
threadSettlement: true,
threadSnooze: true,
threadPinning: true,
@@ -149,6 +149,7 @@ function searchItem(number: number, repository: string, updatedAt: string) {
createdAt: "2026-07-01T00:00:00Z",
updatedAt,
repository: { nameWithOwner: repository },
reviewDecision: "APPROVED",
reviewRequests: { nodes: [{ requestedReviewer: { login: "hubot" } }] },
labels: { nodes: [{ name: "bug", color: "ff0000" }] },
};
@@ -305,6 +306,71 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
it.effect("carries quick-win filters into GitHub search qualifiers", () =>
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,
reviewStatus: "review-required",
label: "good first issue",
maxSize: "m",
});
expect(searchQueryOfCall(0)).toBe(
'is:pr is:open review:required label:"good first issue" ' +
'label:"size:XS","size:S","size:M" sort:updated-desc repo:acme/web',
);
}),
);
it.effect("leaves no-decision filtering to the shared review-decision predicate", () =>
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,
reviewStatus: "none",
});
expect(searchQueryOfCall(0)).toBe("is:pr is:open sort:updated-desc repo:acme/web");
}),
);
it.effect("uses GitHub's changes-requested spelling in per-repository lists", () =>
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,
reviewStatus: "changes-requested",
});
expect(searchOfCall(0)).toBe("review:changes_requested sort:updated-desc");
}),
);
it.effect("narrows a search to the author, and to merged on the merged tab", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(searchPage([])));
@@ -694,6 +760,46 @@ layer("GitHubPullRequestCli.layer", (it) => {
}),
);
it.effect("keeps quick-win filters on the search-free fallback", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
mockedExecute.mockReturnValueOnce(
Effect.succeed(
output(
pullRequests(3, 1, (number) => ({
reviewDecision: number === 2 ? "APPROVED" : "CHANGES_REQUESTED",
labels:
number === 2
? [
{ name: "quick win", color: "c5def5" },
{ name: "size:S", color: null },
]
: [{ name: "size:L", color: null }],
})),
),
),
);
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,
reviewStatus: "approved",
label: "Quick Win",
maxSize: "m",
});
expect(batch.items.map((item) => item.number)).toEqual([2]);
expect(searchOfCall(1)).toBeUndefined();
assert.isFalse(batch.continues);
}),
);
it.effect("keeps state and involvement filters on the search-free fallback", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
@@ -1472,7 +1578,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,additions,deletions,createdAt,updatedAt,mergedAt,reviewDecision,reviewRequests,labels,body,changedFiles,closedAt,statusCheckRollup",
);
expect(callAt(1).args.at(-1)).toBe("author,comments,reviews,commits");
}),
@@ -10,6 +10,7 @@ import type {
PullRequestListState,
PullRequestMergeMethod,
PullRequestReviewCommentDraft,
PullRequestReviewStatus,
PullRequestReviewVerdict,
PullRequestReviewerCandidateList,
PullRequestReviewerKind,
@@ -289,6 +290,9 @@ export class GitHubPullRequestCli extends Context.Service<
readonly limit: number;
/** Free text for `--search`, matched as one literal phrase. */
readonly query?: string | undefined;
readonly reviewStatus?: PullRequestReviewStatus | undefined;
readonly label?: string | undefined;
readonly maxSize?: "m" | undefined;
/** Where to carry on from, as a `updated:` qualifier on the same search. */
readonly cursor?: ProviderListCursor | undefined;
}) => Effect.Effect<GitHubPullRequestListBatch, GitHubPullRequestCliError>;
@@ -308,6 +312,9 @@ export class GitHubPullRequestCli extends Context.Service<
readonly viewer: string;
readonly limit: number;
readonly query?: string | undefined;
readonly reviewStatus?: PullRequestReviewStatus | undefined;
readonly label?: string | undefined;
readonly maxSize?: "m" | undefined;
readonly cursor?: ProviderListCursor | undefined;
}) => Effect.Effect<GitHubPullRequestSearchBatch, GitHubPullRequestCliError>;
@@ -501,11 +508,38 @@ function searchPhrase(query: string): string {
return `"${query.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
}
function quickWinSearchTerms(input: {
readonly reviewStatus?: PullRequestReviewStatus | undefined;
readonly label?: string | undefined;
readonly maxSize?: "m" | undefined;
}): ReadonlyArray<string> {
const review =
input.reviewStatus === undefined
? undefined
: {
approved: "approved",
"changes-requested": "changes_requested",
"review-required": "required",
// GitHub's `review:none` means no submitted reviews, while this field is the overall
// review decision and maps a missing decision to `none`. Leave it to the shared local
// predicate so indexed and fallback reads agree.
none: undefined,
}[input.reviewStatus];
return [
...(review === undefined ? [] : [`review:${review}`]),
...(input.label === undefined ? [] : [`label:${searchPhrase(input.label)}`]),
...(input.maxSize === "m" ? ['label:"size:XS","size:S","size:M"'] : []),
];
}
function involvementArgs(input: {
readonly state: PullRequestListState;
readonly involvement: PullRequestInvolvement;
readonly viewer: string;
readonly query?: string | undefined;
readonly reviewStatus?: PullRequestReviewStatus | undefined;
readonly label?: string | undefined;
readonly maxSize?: "m" | undefined;
/** Where to carry on from, which only a search can express. */
readonly cursor?: ProviderListCursor | undefined;
/**
@@ -527,6 +561,7 @@ function involvementArgs(input: {
...(input.involvement === "reviewing" ? [`review-requested:${input.viewer}`] : []),
...(input.state === "closed" ? ["is:unmerged"] : []),
...(query.length === 0 ? [] : [searchPhrase(query)]),
...quickWinSearchTerms(input),
// The instant the last slice ended on, and everything before it. Inclusive, because rows
// 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.
@@ -550,6 +585,9 @@ function matchesUnsortedListing(
readonly state: PullRequestListState;
readonly involvement: PullRequestInvolvement;
readonly viewer: string;
readonly reviewStatus?: PullRequestReviewStatus | undefined;
readonly label?: string | undefined;
readonly maxSize?: "m" | undefined;
},
): boolean {
const matchesState = input.state === "all" || item.state === input.state;
@@ -560,7 +598,14 @@ function matchesUnsortedListing(
? item.author?.login.toLowerCase() === viewer
: item.hasTeamReviewRequest ||
item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer));
return matchesState && matchesInvolvement;
const labels = new Set(item.labels.map((label) => label.name.trim().toLowerCase()));
const matchesReview =
input.reviewStatus === undefined || item.reviewStatus === input.reviewStatus;
const matchesLabel = input.label === undefined || labels.has(input.label.trim().toLowerCase());
const matchesSize =
input.maxSize === undefined ||
["size:xs", "size:s", "size:m"].some((label) => labels.has(label));
return matchesState && matchesInvolvement && matchesReview && matchesLabel && matchesSize;
}
/** What a repository selector may hold before it goes into a search as itself. */
@@ -586,6 +631,9 @@ function searchQuery(input: {
readonly involvement: PullRequestInvolvement;
readonly viewer: string;
readonly query?: string | undefined;
readonly reviewStatus?: PullRequestReviewStatus | undefined;
readonly label?: string | undefined;
readonly maxSize?: "m" | undefined;
readonly cursor?: ProviderListCursor | undefined;
}): string | null {
if (input.repositories.length === 0) return null;
@@ -601,6 +649,7 @@ function searchQuery(input: {
...(input.involvement === "authored" ? [`author:${input.viewer}`] : []),
...(input.involvement === "reviewing" ? [`review-requested:${input.viewer}`] : []),
...(query.length === 0 ? [] : [searchPhrase(query)]),
...quickWinSearchTerms(input),
// Inclusive, and de-duplicated by the caller, for the reason the per-repository read gives.
...(input.cursor === undefined ? [] : [`updated:<=${input.cursor.updatedBefore}`]),
// The order the page reads its rows in, and the only order a continuation can carry on from.
@@ -82,6 +82,7 @@ describe("gitHubViewerPermissions", () => {
updatedAt: "2026-07-02T00:00:00Z",
reviewRequestLogins: [],
hasTeamReviewRequest: false,
reviewStatus: "none",
labels: [],
body: "",
changedFiles: 1,
@@ -122,6 +123,7 @@ describe("getChangeRequest commits", () => {
updatedAt: "2026-07-02T00:00:00Z",
reviewRequestLogins: [],
hasTeamReviewRequest: false,
reviewStatus: "none",
labels: [],
body: "",
changedFiles: 1,
@@ -128,6 +128,9 @@ export const make = Effect.gen(function* () {
viewer: input.viewer,
limit: input.limit,
query: input.query,
reviewStatus: input.reviewStatus,
label: input.label,
maxSize: input.maxSize,
cursor: input.cursor,
})
.pipe(
@@ -171,6 +174,9 @@ export const make = Effect.gen(function* () {
viewer: input.viewer,
limit: input.limit,
query: input.query,
reviewStatus: input.reviewStatus,
label: input.label,
maxSize: input.maxSize,
cursor: input.cursor,
})
.pipe(
@@ -14,6 +14,7 @@ import type {
PullRequestMergeMethod,
PullRequestMergeability,
PullRequestReviewCommentDraft,
PullRequestReviewStatus,
PullRequestReviewThread,
PullRequestReviewVerdict,
PullRequestReviewerCandidateList,
@@ -63,6 +64,8 @@ export interface ProviderChangeRequest {
readonly updatedAt: string;
/** Accounts with a review requested. Team-level requests are excluded by each provider. */
readonly reviewRequestLogins: ReadonlyArray<string>;
/** Overall review decision when the provider exposes one. */
readonly reviewStatus?: PullRequestReviewStatus | null;
readonly labels: ReadonlyArray<PullRequestLabel>;
}
@@ -211,6 +214,9 @@ export interface PullRequestProviderApi {
* rather than a wrong one.
*/
readonly query?: string | undefined;
readonly reviewStatus?: PullRequestReviewStatus | undefined;
readonly label?: string | undefined;
readonly maxSize?: "m" | undefined;
/**
* Where to carry on from, rather than reading this repository from its newest row. Absent
* asks for the first slice, which is every listing that has not been continued.
@@ -243,6 +249,9 @@ export interface PullRequestProviderApi {
readonly viewer: string;
readonly limit: number;
readonly query?: string | undefined;
readonly reviewStatus?: PullRequestReviewStatus | undefined;
readonly label?: string | undefined;
readonly maxSize?: "m" | undefined;
readonly cursor?: ProviderListCursor | undefined;
}) => Effect.Effect<ProviderBatchedChangeRequestPage, PullRequestProviderError>;
@@ -242,6 +242,67 @@ it.effect("asks for a whole page of a host, and for the reader's own size when g
}),
);
it.effect("forwards and enforces review, label, and size filters", () =>
Effect.gen(function* () {
const requested: Array<{
readonly reviewStatus: string | undefined;
readonly label: string | undefined;
readonly maxSize: string | undefined;
}> = [];
const service = yield* makeService({
projects: [
project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }),
],
providers: [
fakeProvider("github", {
listChangeRequests: (input) => {
requested.push({
reviewStatus: input.reviewStatus,
label: input.label,
maxSize: input.maxSize,
});
return Effect.succeed({
items: [
{
...changeRequest(1, "2026-07-03T00:00:00Z"),
reviewStatus: "approved" as const,
labels: [
{ name: "Bug", color: null },
{ name: "size:S", color: null },
],
},
{
...changeRequest(2, "2026-07-02T00:00:00Z"),
reviewStatus: "changes-requested" as const,
labels: [
{ name: "bug", color: null },
{ name: "size:L", color: null },
],
},
],
truncated: false,
continues: true,
});
},
}),
],
});
const result = yield* service.list({
state: "open",
reviewStatus: "approved",
label: "bug",
maxSize: "m",
});
assert.deepStrictEqual(requested, [{ reviewStatus: "approved", label: "bug", maxSize: "m" }]);
assert.deepStrictEqual(
result.entries.map((entry) => ({ number: entry.number, reviewStatus: entry.reviewStatus })),
[{ number: 1, reviewStatus: "approved" }],
);
}),
);
it.effect("says where each repository carries on, and from nothing it has run out of", () =>
Effect.gen(function* () {
const service = yield* makeService({
@@ -561,10 +561,24 @@ export const make = Effect.gen(function* () {
viewerReviewRequested:
input.item.author?.login.toLowerCase() !== viewer &&
input.item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer),
reviewStatus: input.item.reviewStatus ?? null,
labels: input.item.labels,
};
};
const matchesQuickWinFilters = (
item: ProviderChangeRequest,
input: PullRequestListInput,
): boolean => {
const labels = new Set(item.labels.map((label) => label.name.trim().toLowerCase()));
return (
(input.reviewStatus === undefined || item.reviewStatus === input.reviewStatus) &&
(input.label === undefined || labels.has(input.label.trim().toLowerCase())) &&
(input.maxSize === undefined ||
["size:xs", "size:s", "size:m"].some((label) => labels.has(label)))
);
};
const listUncached: PullRequestService["Service"]["list"] = (input) =>
Effect.gen(function* () {
const involvement = input.involvement ?? "all";
@@ -685,6 +699,9 @@ 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,
reviewStatus: input.reviewStatus,
label: input.label,
maxSize: input.maxSize,
// 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
@@ -698,7 +715,7 @@ export const make = Effect.gen(function* () {
// The boundary instant was asked for inclusively, so the rows already sent at it
// come back with the slice. Dropping them here rather than asking for strictly
// older is what keeps their neighbours at the same instant from being skipped.
const items =
const available =
cursor === undefined
? page.items
: page.items.filter(
@@ -706,6 +723,7 @@ export const make = Effect.gen(function* () {
item.updatedAt !== cursor.updatedBefore ||
!cursor.seenAt.includes(item.number),
);
const items = available.filter((item) => matchesQuickWinFilters(item, input));
return {
key,
entries: items.map((item) => toEntry({ project, item, viewer })),
@@ -713,7 +731,7 @@ export const make = Effect.gen(function* () {
truncated: page.truncated,
nextCursor:
page.continues && page.truncated
? nextListCursor(cursor, page.items, items, page.cursorAdvance)
? nextListCursor(cursor, page.items, available, page.cursorAdvance)
: null,
};
}),
@@ -766,6 +784,9 @@ export const make = Effect.gen(function* () {
viewer,
limit,
query: input.query,
reviewStatus: input.reviewStatus,
label: input.label,
maxSize: input.maxSize,
...(cursor === undefined
? {}
: { cursor: { updatedBefore: cursor.updatedBefore, delivered: cursor.delivered } }),
@@ -801,7 +822,7 @@ export const make = Effect.gen(function* () {
return readRepository(project);
}
const cursorHere = cursorOf(project);
const items =
const available =
cursorHere === undefined
? fetched
: fetched.filter(
@@ -809,6 +830,7 @@ export const make = Effect.gen(function* () {
item.updatedAt !== cursorHere.updatedBefore ||
!cursorHere.seenAt.includes(item.number),
);
const items = available.filter((item) => matchesQuickWinFilters(item, input));
return Effect.succeed({
key: listCursorKey(project.host, project.repository),
entries: items.map((item) => toEntry({ project, item, viewer })),
@@ -816,7 +838,7 @@ export const make = Effect.gen(function* () {
truncated: page.truncated,
nextCursor:
page.truncated && boundary !== null
? listCursorAt(cursorHere, boundary, fetched, items.length)
? listCursorAt(cursorHere, boundary, fetched, available.length)
: null,
});
},
@@ -1458,14 +1480,27 @@ 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,
projectId,
host,
reviewStatus,
label,
maxSize,
limit,
query,
cursorEntries,
] = JSON.parse(key) as [
number,
string,
string | null,
string | null,
string | null,
string | null,
string | null,
string | null,
number | null,
string | null,
ReadonlyArray<[string, string]> | null,
@@ -1475,6 +1510,9 @@ export const make = Effect.gen(function* () {
...(involvement === null ? {} : { involvement }),
...(projectId === null ? {} : { projectId }),
...(host === null ? {} : { host }),
...(reviewStatus === null ? {} : { reviewStatus }),
...(label === null ? {} : { label }),
...(maxSize === null ? {} : { maxSize }),
...(limit === null ? {} : { limit }),
...(query === null ? {} : { query }),
...(cursorEntries === null ? {} : { cursors: Object.fromEntries(cursorEntries) }),
@@ -1496,6 +1534,9 @@ export const make = Effect.gen(function* () {
input.involvement ?? null,
input.projectId ?? null,
input.host ?? null,
input.reviewStatus ?? null,
input.label ?? null,
input.maxSize ?? null,
input.limit ?? null,
input.query ?? null,
input.cursors === undefined
@@ -8,6 +8,7 @@ import {
decodePullRequestDetailJson,
decodePullRequestFilesJson,
decodePullRequestListJson,
decodePullRequestSearchJson,
decodeRepositoryAccessJson,
decodeReviewerCandidatesJson,
decodeReviewThreadCommentsJson,
@@ -67,6 +68,52 @@ describe("pull request list decoding", () => {
expect(entry?.reviewRequestLogins).toEqual(["octocat"]);
});
it("normalizes review decisions and keeps no decision distinct", () => {
const batch = expectSuccess(
decodePullRequestListJson(
listJson([
{ reviewDecision: "APPROVED" },
{ reviewDecision: "CHANGES_REQUESTED" },
{ reviewDecision: "REVIEW_REQUIRED" },
{ reviewDecision: null },
]),
),
);
expect(batch.items.map((entry) => entry.reviewStatus)).toEqual([
"approved",
"changes-requested",
"review-required",
"none",
]);
});
it("keeps review decisions on rows returned by cross-repository search", () => {
const batch = expectSuccess(
decodePullRequestSearchJson(
JSON.stringify({
data: {
search: {
nodes: [
{
number: 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",
reviewDecision: "APPROVED",
repository: { nameWithOwner: "pingdotgg/t3code" },
},
],
},
},
}),
),
);
expect(batch.items[0]?.reviewStatus).toBe("approved");
});
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));
@@ -12,6 +12,7 @@ import type {
PullRequestMergeCapabilities,
PullRequestMergeability,
PullRequestReviewCommentDraft,
PullRequestReviewStatus,
PullRequestReviewThread,
PullRequestReviewVerdict,
PullRequestReviewerCandidate,
@@ -66,6 +67,7 @@ const RawListItemSchema = Schema.Struct({
createdAt: Schema.String,
updatedAt: Schema.String,
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
reviewDecision: Schema.optional(Schema.NullOr(Schema.String)),
reviewRequests: Schema.optional(Schema.Array(RawReviewRequestSchema)),
labels: Schema.optional(Schema.Array(RawLabelSchema)),
});
@@ -88,6 +90,7 @@ const RawSearchItemSchema = Schema.Struct({
createdAt: Schema.String,
updatedAt: Schema.String,
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
reviewDecision: Schema.optional(Schema.NullOr(Schema.String)),
repository: Schema.optional(Schema.NullOr(Schema.Struct({ nameWithOwner: Schema.String }))),
reviewRequests: Schema.optional(
Schema.NullOr(
@@ -384,7 +387,7 @@ 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,additions,deletions,createdAt,updatedAt,mergedAt,reviewDecision,reviewRequests,labels";
export const PULL_REQUEST_DETAIL_JSON_FIELDS = `${PULL_REQUEST_LIST_JSON_FIELDS},body,changedFiles,closedAt,statusCheckRollup`;
export const PULL_REQUEST_ACTIVITY_JSON_FIELDS = "author,comments,reviews,commits";
@@ -432,9 +435,10 @@ export function pullRequestSearchGraphQlQuery(rows: number): string {
createdAt
updatedAt
mergedAt
reviewDecision
repository { nameWithOwner }
reviewRequests(first: 20) { nodes { requestedReviewer { ... on User { login } } } }
labels(first: 20) { nodes { name color } }
labels(first: 100) { nodes { name color } }
}
}
}
@@ -631,6 +635,7 @@ export interface GitHubPullRequestListItem {
readonly createdAt: string;
readonly updatedAt: string;
readonly reviewRequestLogins: ReadonlyArray<string>;
readonly reviewStatus: PullRequestReviewStatus;
/** At least one outstanding request targets a team rather than an individual login. */
readonly hasTeamReviewRequest: boolean;
readonly labels: ReadonlyArray<PullRequestLabel>;
@@ -882,6 +887,19 @@ function toCommits(
}));
}
function toReviewStatus(value: string | null | undefined): PullRequestReviewStatus {
switch (value?.trim().toUpperCase()) {
case "APPROVED":
return "approved";
case "CHANGES_REQUESTED":
return "changes-requested";
case "REVIEW_REQUIRED":
return "review-required";
default:
return "none";
}
}
function toListItem(raw: Schema.Schema.Type<typeof RawListItemSchema>): GitHubPullRequestListItem {
return {
authorId: trimmed(raw.author?.id),
@@ -899,6 +917,7 @@ function toListItem(raw: Schema.Schema.Type<typeof RawListItemSchema>): GitHubPu
createdAt: raw.createdAt,
updatedAt: raw.updatedAt,
reviewRequestLogins: toReviewRequestLogins(raw.reviewRequests),
reviewStatus: toReviewStatus(raw.reviewDecision),
hasTeamReviewRequest: hasTeamReviewRequest(raw.reviewRequests),
labels: toLabels(raw.labels),
};
@@ -53,6 +53,15 @@ function menu(overrides: Partial<Parameters<typeof PullRequestFiltersMenu>[0]>)
involvement: "all",
involvementOptions: [{ value: "all", label: "All", Icon: CircleIcon }],
onInvolvement: () => undefined,
reviewStatus: undefined,
reviewStatusOptions: [{ value: "", label: "Any review status", Icon: CircleIcon }],
onReviewStatus: () => undefined,
maxSize: undefined,
sizeOptions: [{ value: "", label: "Any size", Icon: CircleIcon }],
onMaxSize: () => undefined,
label: undefined,
labelOptions: [{ value: "", label: "Any label", Icon: CircleIcon }],
onLabel: () => undefined,
host: undefined,
hostOptions: [],
onHost: () => undefined,
@@ -62,6 +71,7 @@ function menu(overrides: Partial<Parameters<typeof PullRequestFiltersMenu>[0]>)
unavailable: new Map(),
onProject: () => undefined,
...overrides,
quickFiltersSupported: overrides.quickFiltersSupported ?? true,
});
}
@@ -79,6 +89,48 @@ describe("pull request filters menu", () => {
expect(onState).toHaveBeenCalledWith("closed");
});
it("hides quick filters when the server does not advertise support", () => {
const view = menu({ quickFiltersSupported: false });
expect(findLabeledGroup(view, "Review")).toBeUndefined();
expect(findLabeledGroup(view, "Size")).toBeUndefined();
expect(findLabeledGroup(view, "Label")).toBeUndefined();
});
it("maps the review, size, and label any options back to no filter", () => {
const onReviewStatus = vi.fn();
const onMaxSize = vi.fn();
const onLabel = vi.fn();
const view = menu({
reviewStatus: "approved",
reviewStatusOptions: [
{ value: "", label: "Any review status", Icon: CircleIcon },
{ value: "approved", label: "Approved", Icon: CircleIcon },
],
maxSize: "m",
sizeOptions: [
{ value: "", label: "Any size", Icon: CircleIcon },
{ value: "m", label: "Size ≤ M", Icon: CircleIcon },
],
label: "bug",
labelOptions: [
{ value: "", label: "Any label", Icon: CircleIcon },
{ value: "bug", label: "bug", Icon: CircleIcon },
],
onReviewStatus,
onMaxSize,
onLabel,
});
findValueChange(findLabeledGroup(view, "Review"))?.props.onValueChange("");
findValueChange(findLabeledGroup(view, "Size"))?.props.onValueChange("");
findValueChange(findLabeledGroup(view, "Label"))?.props.onValueChange("");
expect(onReviewStatus).toHaveBeenCalledWith(undefined);
expect(onMaxSize).toHaveBeenCalledWith(undefined);
expect(onLabel).toHaveBeenCalledWith(undefined);
});
it("does not emit a change when the selected project is chosen again", () => {
const projectId = "project-1" as ProjectId;
const onProject = vi.fn();
@@ -3,6 +3,7 @@ import type {
ProjectId,
PullRequestInvolvement,
PullRequestListState,
PullRequestReviewStatus,
SourceControlProviderKind,
} from "@t3tools/contracts";
import { FolderGit2Icon, LayersIcon, ListFilterIcon, LoaderIcon, SearchIcon } from "lucide-react";
@@ -147,6 +148,16 @@ export function PullRequestFiltersMenu({
involvement,
involvementOptions,
onInvolvement,
quickFiltersSupported,
reviewStatus,
reviewStatusOptions,
onReviewStatus,
maxSize,
sizeOptions,
onMaxSize,
label,
labelOptions,
onLabel,
host,
hostOptions,
onHost,
@@ -162,6 +173,16 @@ export function PullRequestFiltersMenu({
involvement: PullRequestInvolvement;
involvementOptions: ReadonlyArray<PullRequestFilterOption<PullRequestInvolvement>>;
onInvolvement: (involvement: PullRequestInvolvement) => void;
quickFiltersSupported: boolean;
reviewStatus: PullRequestReviewStatus | undefined;
reviewStatusOptions: ReadonlyArray<PullRequestFilterOption<string>>;
onReviewStatus: (status: PullRequestReviewStatus | undefined) => void;
maxSize: "m" | undefined;
sizeOptions: ReadonlyArray<PullRequestFilterOption<string>>;
onMaxSize: (size: "m" | undefined) => void;
label: string | undefined;
labelOptions: ReadonlyArray<PullRequestFilterOption<string>>;
onLabel: (label: string | undefined) => void;
host: string | undefined;
/**
* Includes the "all hosts" entry, whose value is the empty string. With fewer than two real
@@ -186,7 +207,12 @@ export function PullRequestFiltersMenu({
onProject: (projectId: ProjectId | undefined) => void;
}) {
const filtered =
state !== "open" || involvement !== "all" || host !== undefined || projectId !== undefined;
state !== "open" ||
involvement !== "all" ||
(quickFiltersSupported &&
(reviewStatus !== undefined || maxSize !== undefined || label !== undefined)) ||
host !== undefined ||
projectId !== undefined;
return (
<Menu>
<MenuTrigger
@@ -195,7 +221,7 @@ export function PullRequestFiltersMenu({
"relative inline-flex size-9 shrink-0 items-center justify-center rounded-lg border border-input text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground sm:size-8",
filtered && "text-foreground",
)}
aria-label="Filter pull requests"
aria-label={filtered ? "Filter pull requests, filters active" : "Filter pull requests"}
>
<ListFilterIcon className="size-4" />
{filtered ? (
@@ -219,6 +245,33 @@ export function PullRequestFiltersMenu({
options={involvementOptions}
onChange={onInvolvement}
/>
{quickFiltersSupported ? (
<>
<MenuSeparator />
<PullRequestFilterRadioGroup
label="Review"
value={reviewStatus ?? ""}
options={reviewStatusOptions}
onChange={(next) =>
onReviewStatus(next === "" ? undefined : (next as PullRequestReviewStatus))
}
/>
<MenuSeparator />
<PullRequestFilterRadioGroup
label="Size"
value={maxSize ?? ""}
options={sizeOptions}
onChange={(next) => onMaxSize(next === "" ? undefined : "m")}
/>
<MenuSeparator />
<PullRequestFilterRadioGroup
label="Label"
value={label ?? ""}
options={labelOptions}
onChange={(next) => onLabel(next === "" ? undefined : next)}
/>
</>
) : null}
{hostOptions.length > 2 ? (
<>
<MenuSeparator />
@@ -71,6 +71,24 @@ function PullRequestRowImpl({
</span>
{showProjectTitle ? <span className="truncate">{entry.repository}</span> : null}
<PullRequestActorLabel actor={entry.author} className="max-w-40 shrink-0" />
{entry.reviewStatus && entry.reviewStatus !== "none" ? (
<span
className={cn(
"shrink-0 rounded-full border px-1.5 text-[10px] font-medium",
entry.reviewStatus === "approved"
? "border-green-500/35 bg-green-500/10 text-green-700 dark:text-green-400"
: entry.reviewStatus === "changes-requested"
? "border-amber-500/35 bg-amber-500/10 text-amber-700 dark:text-amber-400"
: "border-border/60 text-muted-foreground",
)}
>
{entry.reviewStatus === "approved"
? "approved"
: entry.reviewStatus === "changes-requested"
? "changes requested"
: "review required"}
</span>
) : null}
<span className="truncate" title={`${entry.headBranch} to ${entry.baseBranch}`}>
{entry.headBranch}
</span>
@@ -170,13 +170,26 @@ describe("carrying rows already read into filters nothing has answered yet", ()
entry({ number: 3, state: "closed" }),
entry({ number: 4, host: "github.acme.dev" }),
entry({ number: 5, projectId: "project-2" as PullRequestListEntry["projectId"] }),
entry({
number: 6,
reviewStatus: "approved",
labels: [
{ name: "Quick Win", color: null },
{ name: "size:S", color: null },
],
}),
entry({
number: 7,
reviewStatus: "changes-requested",
labels: [{ name: "size:L", color: null }],
}),
];
const everything = { state: "all", projectId: undefined, host: undefined } as const;
it("never lets a merged pull request sit under Open", () => {
expect(
narrowPullRequestsToFilters(rows, { ...everything, state: "open" }).map((row) => row.number),
).toEqual([1, 4, 5]);
).toEqual([1, 4, 5, 6, 7]);
});
it("keeps only the state that was asked for", () => {
@@ -203,6 +216,28 @@ describe("carrying rows already read into filters nothing has answered yet", ()
).toEqual([5]);
});
it("narrows to a review outcome", () => {
expect(
narrowPullRequestsToFilters(rows, { ...everything, reviewStatus: "approved" }).map(
(row) => row.number,
),
).toEqual([6]);
});
it("matches labels case-insensitively and exactly", () => {
expect(
narrowPullRequestsToFilters(rows, { ...everything, label: "quick win" }).map(
(row) => row.number,
),
).toEqual([6]);
});
it("treats size at most M as the XS, S, and M label family", () => {
expect(
narrowPullRequestsToFilters(rows, { ...everything, maxSize: "m" }).map((row) => row.number),
).toEqual([6]);
});
it("holds on to everything when nothing narrows it", () => {
expect(narrowPullRequestsToFilters(rows, everything)).toEqual(rows);
});
@@ -1,7 +1,11 @@
import * as Schema from "effect/Schema";
import { PullRequestListEntry, PullRequestListResult } from "@t3tools/contracts";
import type { PullRequestInvolvement, PullRequestListState } from "@t3tools/contracts";
import type {
PullRequestInvolvement,
PullRequestListState,
PullRequestReviewStatus,
} from "@t3tools/contracts";
export type PullRequestGroupKey = "reviewRequested" | "authored" | "others";
@@ -81,14 +85,23 @@ export function narrowPullRequestsToFilters(
readonly state: PullRequestListState;
readonly projectId: string | undefined;
readonly host: string | undefined;
readonly reviewStatus?: PullRequestReviewStatus | undefined;
readonly label?: string | undefined;
readonly maxSize?: "m" | undefined;
},
): ReadonlyArray<PullRequestListEntry> {
return entries.filter(
(entry) =>
return entries.filter((entry) => {
const labels = new Set(entry.labels.map((label) => label.name.trim().toLowerCase()));
return (
(filters.state === "all" || entry.state === filters.state) &&
(filters.projectId === undefined || entry.projectId === filters.projectId) &&
(filters.host === undefined || entry.host === filters.host),
);
(filters.host === undefined || entry.host === filters.host) &&
(filters.reviewStatus === undefined || entry.reviewStatus === filters.reviewStatus) &&
(filters.label === undefined || labels.has(filters.label.trim().toLowerCase())) &&
(filters.maxSize === undefined ||
["size:xs", "size:s", "size:m"].some((label) => labels.has(label)))
);
});
}
/**
+110 -2
View File
@@ -7,20 +7,26 @@ import type {
PullRequestListEntry,
PullRequestListResult,
PullRequestListState,
PullRequestReviewStatus,
SourceControlProviderKind,
} from "@t3tools/contracts";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import {
ChevronDownIcon,
CircleCheckBigIcon,
CircleDashedIcon,
EyeIcon,
GaugeIcon,
GitMergeIcon,
GitPullRequestClosedIcon,
GitPullRequestIcon,
LayersIcon,
PenLineIcon,
LoaderIcon,
MessageSquareWarningIcon,
RefreshCwIcon,
SearchIcon,
TagIcon,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
@@ -92,6 +98,9 @@ export interface PullRequestsSearch {
* accounts, and their shared provider kind cannot tell them apart. Absent means every host.
*/
readonly host?: string;
readonly reviewStatus?: PullRequestReviewStatus;
readonly label?: string;
readonly maxSize?: "m";
readonly repository?: string;
readonly number?: number;
readonly selectedProjectId?: ProjectId;
@@ -112,6 +121,19 @@ const STATE_TABS = [
{ value: "merged", label: "Merged", Icon: GitMergeIcon },
] as const satisfies ReadonlyArray<PullRequestFilterOption<PullRequestListState>>;
const REVIEW_OPTIONS = [
{ value: "", label: "Any review status", Icon: LayersIcon },
{ value: "approved", label: "Approved", Icon: CircleCheckBigIcon },
{ value: "changes-requested", label: "Changes requested", Icon: MessageSquareWarningIcon },
{ value: "review-required", label: "Review required", Icon: CircleDashedIcon },
{ value: "none", label: "No review decision", Icon: CircleDashedIcon },
] as const satisfies ReadonlyArray<PullRequestFilterOption<string>>;
const SIZE_OPTIONS = [
{ value: "", label: "Any size", Icon: LayersIcon },
{ value: "m", label: "Size ≤ M", Icon: GaugeIcon },
] as const satisfies ReadonlyArray<PullRequestFilterOption<string>>;
/** Long enough that a keystroke does not become a request, short enough to feel answered. */
const SEARCH_DEBOUNCE_MS = 250;
/** What `scorePullRequestMatch` gives a row none of whose own fields carry the search text. */
@@ -148,6 +170,14 @@ export const Route = createFileRoute("/_chat/pull-requests")({
? { projectId: raw.projectId as ProjectId }
: {}),
...(typeof raw.host === "string" && raw.host ? { host: raw.host.slice(0, 200) } : {}),
...(raw.reviewStatus === "approved" ||
raw.reviewStatus === "changes-requested" ||
raw.reviewStatus === "review-required" ||
raw.reviewStatus === "none"
? { reviewStatus: raw.reviewStatus }
: {}),
...(typeof raw.label === "string" && raw.label ? { label: raw.label.slice(0, 100) } : {}),
...(raw.maxSize === "m" ? { maxSize: "m" as const } : {}),
...(typeof raw.selectedProjectId === "string" && raw.selectedProjectId
? { selectedProjectId: raw.selectedProjectId as ProjectId }
: {}),
@@ -164,6 +194,11 @@ function PullRequestsRouteView() {
const capabilityKnown = primaryEnvironment !== null && primaryEnvironment.serverConfig !== null;
const pullRequestsSupported =
primaryEnvironment?.serverConfig?.environment.capabilities.pullRequests === true;
const quickFiltersSupported =
primaryEnvironment?.serverConfig?.environment.capabilities.pullRequestQuickFilters === true;
const reviewStatus = quickFiltersSupported ? search.reviewStatus : undefined;
const label = quickFiltersSupported ? search.label : undefined;
const maxSize = quickFiltersSupported ? search.maxSize : undefined;
// 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;
@@ -235,6 +270,9 @@ function PullRequestsRouteView() {
...(next.number ? { number: next.number } : {}),
...(next.projectId ? { projectId: next.projectId } : {}),
...(next.host ? { host: next.host } : {}),
...(next.reviewStatus ? { reviewStatus: next.reviewStatus } : {}),
...(next.label ? { label: next.label } : {}),
...(next.maxSize ? { maxSize: next.maxSize } : {}),
...(next.selectedProjectId ? { selectedProjectId: next.selectedProjectId } : {}),
...(next.q ? { q: next.q } : {}),
};
@@ -269,7 +307,7 @@ function PullRequestsRouteView() {
const querySettled = typedQuery === sentQuery;
// 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 = `${environmentId ?? ""}:${search.state}:${search.involvement}:${scopedProjectId ?? ""}:${search.host ?? ""}:${reviewStatus ?? ""}:${label ?? ""}:${maxSize ?? ""}`;
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
@@ -303,6 +341,9 @@ function PullRequestsRouteView() {
limit: pageSize,
...(scopedProjectId ? { projectId: scopedProjectId } : {}),
...(search.host ? { host: search.host } : {}),
...(reviewStatus ? { reviewStatus } : {}),
...(label ? { label } : {}),
...(maxSize ? { maxSize } : {}),
...(sentQuery ? { query: sentQuery } : {}),
...(sentCursors ? { cursors: sentCursors } : {}),
},
@@ -330,6 +371,27 @@ function PullRequestsRouteView() {
limit: PAGE_SIZE,
...(scopedProjectId ? { projectId: scopedProjectId } : {}),
...(search.host ? { host: search.host } : {}),
...(reviewStatus ? { reviewStatus } : {}),
...(label ? { label } : {}),
...(maxSize ? { maxSize } : {}),
},
}),
);
// Once a label is selected, keep the menu sourced from the same scope without that label.
// Otherwise the selected result set would replace the menu and make unrelated labels vanish.
const labelOptionsQuery = useEnvironmentQuery(
pullRequestEnvironmentId === null || label === undefined
? null
: pullRequestEnvironment.list({
environmentId: pullRequestEnvironmentId,
input: {
state: search.state,
involvement: search.involvement,
limit: PAGE_SIZE,
...(scopedProjectId ? { projectId: scopedProjectId } : {}),
...(search.host ? { host: search.host } : {}),
...(reviewStatus ? { reviewStatus } : {}),
...(maxSize ? { maxSize } : {}),
},
}),
);
@@ -351,6 +413,9 @@ function PullRequestsRouteView() {
limit: PAGE_SIZE,
...(scopedProjectId ? { projectId: scopedProjectId } : {}),
...(search.host ? { host: search.host } : {}),
...(reviewStatus ? { reviewStatus } : {}),
...(label ? { label } : {}),
...(maxSize ? { maxSize } : {}),
},
}),
);
@@ -365,6 +430,9 @@ function PullRequestsRouteView() {
limit: PAGE_SIZE,
...(scopedProjectId ? { projectId: scopedProjectId } : {}),
...(search.host ? { host: search.host } : {}),
...(reviewStatus ? { reviewStatus } : {}),
...(label ? { label } : {}),
...(maxSize ? { maxSize } : {}),
},
}),
);
@@ -496,9 +564,22 @@ function PullRequestsRouteView() {
state: search.state,
projectId: scopedProjectId,
host: search.host,
reviewStatus,
label,
maxSize,
});
return entries.length === 0 ? null : { ...loaded.data, entries };
}, [environmentId, loaded, scopeKey, scopedProjectId, search.host, search.state]);
}, [
environmentId,
loaded,
scopeKey,
scopedProjectId,
search.host,
label,
maxSize,
reviewStatus,
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
@@ -953,6 +1034,9 @@ function PullRequestsRouteView() {
filtered={
search.state !== "open" ||
search.involvement !== "all" ||
reviewStatus !== undefined ||
maxSize !== undefined ||
label !== undefined ||
scopedProjectId !== undefined ||
search.host !== undefined
}
@@ -1037,14 +1121,38 @@ function PullRequestsRouteView() {
};
}),
];
const labelNames = [
...new Set(
[
...(labelOptionsQuery.data?.entries ?? []),
...(baselineQuery.data?.entries ?? []),
...(listData?.entries ?? []),
].flatMap((entry) => entry.labels.map((label) => label.name)),
),
].toSorted((left, right) => left.localeCompare(right));
if (label && !labelNames.includes(label)) labelNames.unshift(label);
const labelOptions: ReadonlyArray<PullRequestFilterOption<string>> = [
{ value: "", label: "Any label", Icon: LayersIcon },
...labelNames.map((label) => ({ value: label, label, Icon: TagIcon })),
];
const filtersMenu = (
<PullRequestFiltersMenu
state={search.state}
quickFiltersSupported={quickFiltersSupported}
stateOptions={STATE_TABS}
onState={(state) => updateListScope({ state })}
involvement={search.involvement}
involvementOptions={INVOLVEMENT_TABS}
onInvolvement={(involvement) => updateListScope({ involvement })}
reviewStatus={reviewStatus}
reviewStatusOptions={REVIEW_OPTIONS}
onReviewStatus={(reviewStatus) => updateListScope({ reviewStatus })}
maxSize={maxSize}
sizeOptions={SIZE_OPTIONS}
onMaxSize={(maxSize) => updateListScope({ maxSize })}
label={label}
labelOptions={labelOptions}
onLabel={(label) => updateListScope({ label })}
host={search.host}
hostOptions={hostMenuOptions}
onHost={(host) => updateListScope({ host })}
+2
View File
@@ -51,6 +51,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
/** Server exposes the pull-request list, detail, activity, diff, and mutation APIs. Absent on
servers from before the pull-request workspace shipped, so clients must not probe them. */
pullRequests: Schema.optionalKey(Schema.Boolean),
/** Server accepts quick-win pull-request filters and reports list review status. */
pullRequestQuickFilters: Schema.optionalKey(Schema.Boolean),
/** Server understands thread.settle / thread.unsettle commands. Absent on
pre-settlement servers, so clients treat missing as unsupported and
never send the commands under version skew. */
+16
View File
@@ -272,6 +272,14 @@ export const PullRequestMergeCapabilities = Schema.Struct({
});
export type PullRequestMergeCapabilities = typeof PullRequestMergeCapabilities.Type;
export const PullRequestReviewStatus = Schema.Literals([
"approved",
"changes-requested",
"review-required",
"none",
]);
export type PullRequestReviewStatus = typeof PullRequestReviewStatus.Type;
export const PullRequestListEntry = Schema.Struct({
provider: SourceControlProviderKind,
/**
@@ -302,6 +310,8 @@ export const PullRequestListEntry = Schema.Struct({
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
viewerReviewRequested: Schema.Boolean,
/** Overall review decision when the provider reports one. Absent in older cached snapshots. */
reviewStatus: Schema.optional(Schema.NullOr(PullRequestReviewStatus)),
labels: Schema.Array(PullRequestLabel),
});
export type PullRequestListEntry = typeof PullRequestListEntry.Type;
@@ -331,6 +341,12 @@ export const PullRequestListInput = Schema.Struct({
* apart. Absent means every host the workspace has.
*/
host: Schema.optional(TrimmedNonEmptyString),
/** Overall review decision reported by the host. */
reviewStatus: Schema.optional(PullRequestReviewStatus),
/** Exact label name, compared case-insensitively. */
label: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(100))),
/** Quick-win size shortcut, backed by the repository's XS, S, and M labels. */
maxSize: Schema.optional(Schema.Literal("m")),
/** Rows to return per repository, which with a continuation is rows per slice. */
limit: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 500 }))),
/**