Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 55 additions & 23 deletions apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -847,7 +847,20 @@ describe("source control tools", () => {
changedFiles: 1,
labels: [],
reviewers: [],
checks: [{ name: "CI", status: "success", description: null, url: null }],
checks: [
{ name: "CI", status: "success", description: null, url: null },
{ name: "Lint", status: "failure", description: null, url: null },
{ name: "E2E", status: "cancelled", description: null, url: null },
{ name: "Deploy", status: "pending", description: null, url: null },
{
name: "Approval",
status: "action-required",
description: null,
url: null,
placeholder: true,
},
{ name: "Docs", status: "skipped", description: null, url: null },
],
} as unknown as PullRequestDetail;
const reviewThread = (id: string, isResolved: boolean) => ({
id,
Expand All @@ -866,34 +879,51 @@ describe("source control tools", () => {
commits: [],
};

it.effect("reads the thread's branch PR, only the sections asked, without resolved threads", () =>
it.effect("reads the thread's branch PR compactly, adding only the sections asked", () =>
Effect.gen(function* () {
const asked: Array<PullRequestRef> = [];
let reviewThreadsTruncated = false;
const harness = yield* makeHarness({
thread: branchThread,
pullRequests: {
detail: (ref) => Effect.sync(() => asked.push(ref)).pipe(Effect.as(detail)),
activity: () => Effect.succeed(activity),
activity: () => Effect.sync(() => ({ ...activity, reviewThreadsTruncated })),
},
});
const result = yield* harness.call("pull_request_read", {
sections: ["summary", "conversation"],
const compact = yield* harness.call("pull_request_read", {});
expect(compact).toMatchObject({
headSha: "abc123",
checks: { passed: 2, pending: 1, failed: ["Lint", "E2E"], incomplete: true },
unresolvedThreads: 1,
});
expect(asked).toEqual([
{
projectId: PROJECT_ID,
host: "github.com",
repository: "t3tools/t3code",
number: 42,
allowStale: false,
},
]);
expect(result.summary?.headSha).toBe("abc123");
expect(result.checks).toBeUndefined();
expect(result.conversation?.reviewThreads.map((thread) => thread.id)).toEqual([
expect(compact.body).toBeUndefined();
expect(compact.checkRuns).toBeUndefined();
expect(compact.conversation).toBeUndefined();
expect(compact.unresolvedThreadsTruncated).toBeUndefined();
const result = yield* harness.call("pull_request_read", { include: ["body", "threads"] });
expect(asked[1]).toEqual({
projectId: PROJECT_ID,
host: "github.com",
repository: "t3tools/t3code",
number: 42,
allowStale: false,
});
expect(result.body).toBe("Adds tools.");
expect(result.checkRuns).toBeUndefined();
expect(result.conversation?.comments).toBeUndefined();
expect(result.conversation?.reviewThreads?.map((thread) => thread.id)).toEqual([
"open-thread",
]);
expect(result.conversation?.hiddenResolvedThreads).toBe(1);
// Unfetched threads may be unresolved, so the compact count says it is partial.
reviewThreadsTruncated = true;
expect(yield* harness.call("pull_request_read", {})).toMatchObject({
unresolvedThreads: 1,
unresolvedThreadsTruncated: true,
});
const commentsOnly = yield* harness.call("pull_request_read", { include: ["comments"] });
expect(commentsOnly.conversation?.truncated).toBe(false);
const threadsOnly = yield* harness.call("pull_request_read", { include: ["threads"] });
expect(threadsOnly.conversation?.truncated).toBe(true);
}),
);

Expand All @@ -910,6 +940,7 @@ describe("source control tools", () => {
const harness = yield* makeHarness({
thread: branchThread,
pullRequests: {
detail: () => Effect.succeed(detail),
activity: () =>
Effect.sync(() => ({
...activity,
Expand Down Expand Up @@ -942,7 +973,7 @@ describe("source control tools", () => {
),
},
});
const first = yield* harness.call("pull_request_read", { sections: ["conversation"] });
const first = yield* harness.call("pull_request_read", { include: ["threads"] });
expect(first.conversation?.reviewThreads).toMatchObject([
{ id: "first", moreComments: false, comments: [{}, { body: "reply" }] },
]);
Expand All @@ -951,12 +982,12 @@ describe("source control tools", () => {
// The agent resolves what it read; the next page still starts at the next thread.
firstResolved = true;
const second = yield* harness.call("pull_request_read", { cursor: cursor! });
expect(second.summary).toBeUndefined();
expect(second.conversation?.reviewThreads.map((thread) => thread.id)).toEqual(["second"]);
expect(second.conversation?.comments).toBeUndefined();
expect(second.conversation?.reviewThreads?.map((thread) => thread.id)).toEqual(["second"]);
expect(second.conversation?.nextCursor).toBeNull();
// A cursor past the current end finishes instead of repeating an empty page.
const stale = Base64Url.encode(
JSON.stringify({ threads: 99, comments: 99, includeResolved: false }),
JSON.stringify({ threads: 99, comments: null, includeResolved: false }),
);
const past = yield* harness.call("pull_request_read", { cursor: stale });
expect(past.conversation).toMatchObject({ reviewThreads: [], nextCursor: null });
Expand Down Expand Up @@ -991,10 +1022,11 @@ describe("source control tools", () => {
pullRequests: {
summary: () => Effect.succeed({ state: "open", headBranch } as never),
detail: (ref) => Effect.sync(() => asked.push(ref)).pipe(Effect.as(detail)),
activity: () => Effect.succeed(activity),
},
});
const harness = yield* opened("tools");
yield* harness.call("pull_request_read", { sections: ["summary"] });
yield* harness.call("pull_request_read", {});
expect(asked).toMatchObject([{ number: 43 }]);

// Before sync, the host says which branch it came from; another branch's is not this one.
Expand Down
170 changes: 97 additions & 73 deletions apps/server/src/mcp/toolkits/pullRequests/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
PullRequestListCursors,
type PullRequestRef,
type PullRequestReviewCommentDraft,
type PullRequestCheck,
type PullRequestReviewThread,
type OrchestrationProjectShell,
type PullRequestState,
Expand Down Expand Up @@ -70,9 +71,10 @@ import {

const ReadCursor = Schema.Union([
Schema.Struct({ diff: TrimmedNonEmptyString }),
// Null marks a list the read did not ask for.
Schema.Struct({
threads: NonNegativeInt,
comments: NonNegativeInt,
threads: Schema.NullOr(NonNegativeInt),
comments: Schema.NullOr(NonNegativeInt),
includeResolved: Schema.Boolean,
}),
]);
Expand Down Expand Up @@ -116,16 +118,16 @@ const REVIEW_DIFF_PAGES = 10;

function conversationPage(
activity: PullRequestActivity,
start: { readonly threads: number; readonly comments: number },
start: { readonly threads: number | null; readonly comments: number | null },
includeResolved: boolean,
) {
// Offsets index the unfiltered lists, whose order resolving a thread does not change.
const { reviewThreads, comments } = activity;
const pageThreads: Array<PullRequestReviewThread> = [];
const pageComments: Array<PullRequestActivity["comments"][number]> = [];
let size = 0;
let thread = Math.min(start.threads, reviewThreads.length);
let comment = Math.min(start.comments, comments.length);
let thread = start.threads === null ? null : Math.min(start.threads, reviewThreads.length);
let comment = start.comments === null ? null : Math.min(start.comments, comments.length);
const fits = (item: unknown) => {
const next = size + JSON.stringify(item).length;
if (next > CONVERSATION_PAGE_CHARS && pageThreads.length + pageComments.length > 0) {
Expand All @@ -135,30 +137,42 @@ function conversationPage(
return true;
};
// Review threads come first: they hold the feedback an agent acts on.
while (thread < reviewThreads.length) {
while (thread !== null && thread < reviewThreads.length) {
const next = reviewThreads[thread]!;
if (includeResolved || !next.isResolved) {
if (!fits(next)) break;
pageThreads.push(next);
}
thread += 1;
}
if (thread === reviewThreads.length) {
while (comment < comments.length && fits(comments[comment])) {
const threadsDone = thread === null || thread === reviewThreads.length;
if (threadsDone) {
while (comment !== null && comment < comments.length && fits(comments[comment])) {
pageComments.push(comments[comment++]!);
}
}
const done = thread === reviewThreads.length && comment === comments.length;
const done = threadsDone && (comment === null || comment === comments.length);
return {
threads: pageThreads,
comments: pageComments,
hiddenResolvedThreads: includeResolved
? 0
: reviewThreads.filter((candidate) => candidate.isResolved).length,
next: done ? null : { threads: thread, comments: comment, includeResolved },
};
}

function checksSummary(checks: ReadonlyArray<PullRequestCheck>) {
let passed = 0;
let pending = 0;
let incomplete = false;
const failed: Array<string> = [];
for (const check of checks) {
if (check.placeholder === true) incomplete = true;
else if (check.status === "failure" || check.status === "cancelled") failed.push(check.name);
else if (check.status === "pending" || check.status === "action-required") pending += 1;
else passed += 1;
}
return { passed, pending, failed, ...(incomplete ? { incomplete: true as const } : {}) };
}

function entryOf(
link: ThreadPullRequestLink,
chains: ReturnType<typeof resolveThreadPullRequestChains>,
Expand Down Expand Up @@ -570,10 +584,8 @@ const make = Effect.gen(function* () {
const [detail, activity, diff] = yield* Effect.all(
[
// Agents pin merges to this headSha, so it must not come from a stale snapshot.
wants("summary") || wants("checks")
? pullRequests.detail({ ...ref, allowStale: false }).pipe(Effect.asSome)
: Effect.succeedNone,
wants("conversation") ? pullRequests.activity(ref).pipe(Effect.asSome) : Effect.succeedNone,
pullRequests.detail({ ...ref, allowStale: false }),
pullRequests.activity(ref),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
wants("diff")
? pullRequests
.diff({ ...ref, ...(diffCursor === undefined ? {} : { cursor: diffCursor }) })
Expand All @@ -582,70 +594,79 @@ const make = Effect.gen(function* () {
],
{ concurrency: "unbounded" },
).pipe(Effect.mapError(forgeFailure));
const page = Option.map(activity, (value) =>
conversationPage(
value,
cursor !== undefined && "threads" in cursor ? cursor : { threads: 0, comments: 0 },
includeResolved,
),
);
const wantsThreads = wants("threads");
const wantsComments = wants("comments");
const page =
wantsThreads || wantsComments
? Option.some(
conversationPage(
activity,
cursor !== undefined && "threads" in cursor
? cursor
: { threads: wantsThreads ? 0 : null, comments: wantsComments ? 0 : null },
includeResolved,
),
)
: Option.none();
const threadRests = Option.isSome(page)
? yield* Effect.forEach(page.value.threads, (thread) => restOfThread(ref, thread), {
concurrency: 4,
})
: [];
const result: Omit<ReadPullRequestResult, "host" | "repository" | "number" | "url"> = {
...(Option.isSome(detail) && wants("summary")
? {
summary: {
title: detail.value.title,
body: detail.value.body,
state: detail.value.state,
isDraft: detail.value.isDraft,
author: detail.value.author?.login ?? null,
headBranch: detail.value.headBranch,
baseBranch: detail.value.baseBranch,
headSha: detail.value.headSha ?? null,
mergeability: detail.value.mergeability,
behindBy: detail.value.behindBy ?? null,
autoMergeEnabled: detail.value.autoMergeEnabled ?? null,
additions: detail.value.additions,
deletions: detail.value.deletions,
changedFiles: detail.value.changedFiles,
labels: detail.value.labels.map((label) => label.name),
reviewers: detail.value.reviewers.map((reviewer) => reviewer.login),
},
}
: {}),
...(Option.isSome(detail) && wants("checks") ? { checks: detail.value.checks } : {}),
...(Option.isSome(activity) && Option.isSome(page)
title: detail.title,
state: detail.state,
isDraft: detail.isDraft,
author: detail.author?.login ?? null,
headBranch: detail.headBranch,
baseBranch: detail.baseBranch,
headSha: detail.headSha ?? null,
mergeability: detail.mergeability,
behindBy: detail.behindBy ?? null,
autoMergeEnabled: detail.autoMergeEnabled ?? null,
checks: checksSummary(detail.checks),
unresolvedThreads: activity.reviewThreads.filter((thread) => !thread.isResolved).length,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
...(activity.reviewThreadsTruncated === true ? { unresolvedThreadsTruncated: true } : {}),
...(wants("body") ? { body: detail.body } : {}),
...(wants("checks") ? { checkRuns: detail.checks } : {}),
...(Option.isSome(page)
? {
conversation: {
comments: page.value.comments.map((comment) => ({
id: comment.id,
kind: comment.kind,
author: comment.author?.login ?? null,
body: comment.body,
createdAt: comment.createdAt,
path: comment.path,
reviewState: comment.reviewState,
})),
reviewThreads: page.value.threads.map((thread, index) => ({
id: thread.id,
path: thread.path,
line: thread.line,
isResolved: thread.isResolved,
isOutdated: thread.isOutdated,
comments: [...thread.comments, ...threadRests[index]!.comments].map((comment) => ({
author: comment.author?.login ?? null,
body: comment.body,
createdAt: comment.createdAt,
})),
moreComments: threadRests[index]!.moreComments,
})),
hiddenResolvedThreads: page.value.hiddenResolvedThreads,
...(wantsThreads
? {
reviewThreads: page.value.threads.map((thread, index) => ({
id: thread.id,
path: thread.path,
line: thread.line,
isResolved: thread.isResolved,
isOutdated: thread.isOutdated,
comments: [...thread.comments, ...threadRests[index]!.comments].map(
(comment) => ({
author: comment.author?.login ?? null,
body: comment.body,
createdAt: comment.createdAt,
}),
),
moreComments: threadRests[index]!.moreComments,
})),
}
: {}),
...(wantsComments
? {
comments: page.value.comments.map((comment) => ({
id: comment.id,
kind: comment.kind,
author: comment.author?.login ?? null,
body: comment.body,
createdAt: comment.createdAt,
path: comment.path,
reviewState: comment.reviewState,
})),
}
: {}),
truncated:
activity.value.commentsTruncated || activity.value.reviewThreadsTruncated === true,
(wantsComments && activity.commentsTruncated) ||
(wantsThreads && activity.reviewThreadsTruncated === true),
nextCursor: page.value.next === null ? null : readCursors.encode(page.value.next),
},
}
Expand Down Expand Up @@ -958,10 +979,13 @@ const make = Effect.gen(function* () {
// A cursor continues the one section it came from, with that read's options.
const sections: ReadonlyArray<PullRequestReadSection> =
cursor === undefined
? (input.sections ?? ["summary", "checks"])
? (input.include ?? [])
: "diff" in cursor
? ["diff"]
: ["conversation"];
: [
...(cursor.threads === null ? [] : (["threads"] as const)),
...(cursor.comments === null ? [] : (["comments"] as const)),
];
const includeResolved =
cursor !== undefined && "includeResolved" in cursor
? cursor.includeResolved
Expand Down
Loading
Loading