Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

pullRequestDetail.logic.test.ts

1,267 lines41.9 KB

1import {
2 PullRequestAction,
3 type PullRequestCheck,
4 type PullRequestComment,
5 type PullRequestDetailView,
6 type PullRequestReviewThread,
7} from "@t3tools/contracts";
8import { describe, expect, it } from "vite-plus/test";
9​
10import {
11 buildAddSelectionToAgentHandoff,
12 buildAskAboutPullRequestHandoff,
13 buildExplainPullRequestHandoff,
14 buildFixFindingHandoff,
15 buildFixFindingsHandoff,
16 groupPullRequestTimelineConversations,
17 handoffPrompt,
18 handoffReviewComments,
19 isPullRequestVerdictStale,
20 isStackedPullRequestBase,
21 isThreadOwnPullRequest,
22 latestPullRequestReviewOutcomes,
23 newestPullRequestCommitAt,
24 mergePullRequestThreadComments,
25 orderPullRequestComments,
26 pullRequestActionMenuHasGroup,
27 pullRequestActionNeedsHostRefresh,
28 pullRequestCheckoutCommand,
29 pullRequestComposerTarget,
30 pullRequestFindingKey,
31 pullRequestHandoffLabels,
32 pullRequestReviewOutcome,
33 readableFailure,
34 shouldRefreshPullRequestActivity,
35 resolveBaseFreshness,
36 buildPullRequestTimeline,
37 describePullRequestState,
38 editPullRequestThreadComment,
39} from "./pullRequestDetail.logic";
40import type { ReviewCommentContext } from "~/reviewCommentContext";
41​
42describe("pull request checkout commands", () => {
43 it.each([
44 ["github", "feature", null, "gh pr checkout 42"],
45 ["gitlab", "feature", null, "glab mr checkout 42"],
46 ["azure-devops", "feature", null, "az repos pr checkout --id 42"],
47 [
48 "bitbucket",
49 "feature/checkout",
50 "maria/t3code",
51 "git clone --single-branch --branch feature/checkout https://bitbucket.org/maria/t3code.git t3code-pr-42",
52 ],
53 ["unknown", "feature", null, null],
54 ] as const)("builds the %s command", (provider, branch, repository, expected) => {
55 expect(pullRequestCheckoutCommand(provider, 42, branch, repository)).toBe(expected);
56 });
57});
58​
59const TIMELINE_SOURCE: Pick<
60 PullRequestDetailView,
61 "createdAt" | "author" | "commits" | "comments" | "mergedAt" | "closedAt"
62> = {
63 createdAt: "2026-07-01T00:00:00Z",
64 author: { login: "octocat", name: null, avatarUrl: null },
65 commits: [
66 { oid: "1baf7bdcafe", messageHeadline: "add the page", committedDate: "2026-07-02T00:00:00Z" },
67 ],
68 comments: [
69 {
70 id: "c1",
71 kind: "issue-comment",
72 author: { login: "bilal", name: null, avatarUrl: null },
73 body: "looks good",
74 createdAt: "2026-07-03T00:00:00Z",
75 url: null,
76 path: null,
77 reviewState: null,
78 },
79 ],
80 mergedAt: null,
81 closedAt: null,
82};
83​
84describe("pull request activity refresh", () => {
85 const first = {
86 key: "project:acme/web#7",
87 updatedAt: "2026-08-13T13:00:00Z",
88 };
89​
90 it("refreshes activity only after the same pull request changes", () => {
91 expect(
92 shouldRefreshPullRequestActivity(first, {
93 ...first,
94 updatedAt: "2026-08-13T13:01:00Z",
95 }),
96 ).toBe(true);
97 });
98​
99 it("does not duplicate the first activity read or carry a revision across pull requests", () => {
100 expect(shouldRefreshPullRequestActivity(null, first)).toBe(false);
101 expect(shouldRefreshPullRequestActivity(first, first)).toBe(false);
102 expect(
103 shouldRefreshPullRequestActivity(first, {
104 key: "project:acme/web#8",
105 updatedAt: "2026-08-13T13:01:00Z",
106 }),
107 ).toBe(false);
108 });
109});
110describe("review thread comment pages", () => {
111 it("appends new comments once and keeps refreshed base comments", () => {
112 expect(
113 mergePullRequestThreadComments(
114 [
115 { id: "c1", body: "refreshed" },
116 { id: "c2", body: "already in base" },
117 ],
118 [
119 { id: "c2", body: "stale page copy" },
120 { id: "c3", body: "next page" },
121 ],
122 ),
123 ).toEqual([
124 { id: "c1", body: "refreshed" },
125 { id: "c2", body: "already in base" },
126 { id: "c3", body: "next page" },
127 ]);
128 });
129​
130 it("keeps a loaded comment after its body is edited", () => {
131 const loaded = [
132 { id: "c2", body: "old body" },
133 { id: "c3", body: "another loaded comment" },
134 ];
135​
136 expect(editPullRequestThreadComment(loaded, "c2", "saved body")).toEqual([
137 { id: "c2", body: "saved body" },
138 { id: "c3", body: "another loaded comment" },
139 ]);
140 });
141});
142​
143describe("pull request action menu", () => {
144 it("keeps the group divider when auto-merge is the only action", () => {
145 expect(pullRequestActionMenuHasGroup(false, true, false)).toBe(true);
146 });
147});
148​
149describe("pull request state description", () => {
150 it("keeps draft and conflicts orthogonal to the terminal states", () => {
151 expect(describePullRequestState("open", true)).toBe("Draft");
152 expect(describePullRequestState("open", false)).toBe("Ready for review");
153 expect(describePullRequestState("merged", true)).toBe("Merged");
154 expect(describePullRequestState("closed", false)).toBe("Closed");
155 });
156});
157​
158describe("pull request handoff labels", () => {
159 it("names the open thread when actions write to its composer", () => {
160 expect(pullRequestHandoffLabels(true)).toEqual({
161 fixFinding: "Fix in this thread",
162 fixCheck: "Fix in this thread",
163 fixFindings: "Fix findings in this thread",
164 });
165 });
166​
167 it("keeps the standalone pull request page labels", () => {
168 expect(pullRequestHandoffLabels(false)).toEqual({
169 fixFinding: "Fix in a thread",
170 fixCheck: "Fix",
171 fixFindings: "Fix findings in a thread",
172 });
173 });
174});
175​
176describe("pull request composer target", () => {
177 it("rejects a page composer so agent comments cannot open another thread", () => {
178 const target = { environmentId: "env-1", threadId: "thread-1" };
179​
180 expect(pullRequestComposerTarget("page", target)).toBeNull();
181 expect(pullRequestComposerTarget("thread", target)).toBe(target);
182 });
183});
184​
185describe("stacked pull request classification", () => {
186 it("requires a known default branch", () => {
187 expect(isStackedPullRequestBase("main", [{ name: "main", isDefault: false }])).toBe(false);
188 });
189​
190 it("recognizes local and remote forms of the default branch", () => {
191 expect(
192 isStackedPullRequestBase("main", [{ name: "main", isDefault: true, isRemote: false }]),
193 ).toBe(false);
194 expect(
195 isStackedPullRequestBase("main", [
196 { name: "origin/main", isDefault: true, isRemote: true, remoteName: "origin" },
197 ]),
198 ).toBe(false);
199 });
200​
201 it("classifies a non-default base as stacked once the default is known", () => {
202 expect(
203 isStackedPullRequestBase("feature-base", [
204 { name: "origin/main", isDefault: true, isRemote: true, remoteName: "origin" },
205 ]),
206 ).toBe(true);
207 });
208​
209 it("does not mistake a nested branch suffix for the default branch", () => {
210 expect(
211 isStackedPullRequestBase("main", [
212 {
213 name: "origin/feature/main",
214 isDefault: true,
215 isRemote: true,
216 remoteName: "origin",
217 },
218 ]),
219 ).toBe(true);
220 expect(
221 isStackedPullRequestBase("1.0", [{ name: "release/1.0", isDefault: true, isRemote: false }]),
222 ).toBe(true);
223 });
224});
225​
226describe("ordering comments", () => {
227 it("reverses the chronological list for newest first, and leaves oldest first alone", () => {
228 const comments = [{ createdAt: "a" }, { createdAt: "b" }, { createdAt: "c" }];
229 expect(orderPullRequestComments(comments, "newest")).toEqual([
230 { createdAt: "c" },
231 { createdAt: "b" },
232 { createdAt: "a" },
233 ]);
234 expect(orderPullRequestComments(comments, "oldest")).toEqual(comments);
235 // The source array is chronological input, not a mutation target.
236 expect(comments).toEqual([{ createdAt: "a" }, { createdAt: "b" }, { createdAt: "c" }]);
237 });
238});
239​
240describe("review verdicts", () => {
241 it("reads the same three verdicts however a host spells them", () => {
242 expect(pullRequestReviewOutcome("APPROVED")).toBe("approved");
243 expect(pullRequestReviewOutcome("approved")).toBe("approved");
244 expect(pullRequestReviewOutcome("CHANGES_REQUESTED")).toBe("changes-requested");
245 expect(pullRequestReviewOutcome("changes_requested")).toBe("changes-requested");
246 expect(pullRequestReviewOutcome("DISMISSED")).toBe("dismissed");
247 });
248​
249 it("is not a verdict where the review only carried remarks", () => {
250 expect(pullRequestReviewOutcome("COMMENTED")).toBeNull();
251 expect(pullRequestReviewOutcome("PENDING")).toBeNull();
252 expect(pullRequestReviewOutcome(null)).toBeNull();
253 });
254​
255 it("keeps each reviewer's last word, whatever order the host returned them in", () => {
256 const review = (
257 id: string,
258 login: string,
259 reviewState: string,
260 createdAt: string,
261 ): PullRequestComment => ({
262 id,
263 kind: "review",
264 author: { login, name: null, avatarUrl: null },
265 body: "",
266 createdAt,
267 url: null,
268 path: null,
269 reviewState,
270 });
271​
272 expect(
273 latestPullRequestReviewOutcomes([
274 review("r3", "bilal", "APPROVED", "2026-07-03T00:00:00Z"),
275 review("r1", "bilal", "CHANGES_REQUESTED", "2026-07-01T00:00:00Z"),
276 review("r2", "octocat", "CHANGES_REQUESTED", "2026-07-02T00:00:00Z"),
277 // Not a verdict, so it neither adds a reviewer nor overwrites one.
278 review("r4", "octocat", "COMMENTED", "2026-07-04T00:00:00Z"),
279 ]).map((entry) => [entry.actor?.login, entry.outcome]),
280 ).toEqual([
281 ["bilal", "approved"],
282 ["octocat", "changes-requested"],
283 ]);
284 });
285​
286 it("keeps two deleted accounts apart rather than counting them as one reviewer", () => {
287 expect(
288 latestPullRequestReviewOutcomes([
289 {
290 ...TIMELINE_SOURCE.comments[0]!,
291 id: "r1",
292 kind: "review",
293 author: null,
294 reviewState: "APPROVED",
295 createdAt: "2026-07-01T00:00:00Z",
296 },
297 {
298 ...TIMELINE_SOURCE.comments[0]!,
299 id: "r2",
300 kind: "review",
301 author: null,
302 reviewState: "APPROVED",
303 createdAt: "2026-07-02T00:00:00Z",
304 },
305 ]),
306 ).toHaveLength(2);
307 });
308​
309 it("gives every entry a key that separates the reviewers it kept apart", () => {
310 const entries = latestPullRequestReviewOutcomes([
311 {
312 ...TIMELINE_SOURCE.comments[0]!,
313 id: "r1",
314 kind: "review",
315 author: null,
316 reviewState: "APPROVED",
317 createdAt: "2026-07-01T00:00:00Z",
318 },
319 {
320 ...TIMELINE_SOURCE.comments[0]!,
321 id: "r2",
322 kind: "review",
323 author: null,
324 reviewState: "APPROVED",
325 createdAt: "2026-07-01T00:00:00Z",
326 },
327 ]);
328 // Same author (none) and the same instant, so only the review's own id tells them apart.
329 expect(new Set(entries.map((entry) => entry.key)).size).toBe(2);
330 });
331​
332 it("calls a verdict stale once commits land after it, and current before that", () => {
333 const commits = [
334 { oid: "c0ffee", messageHeadline: "later work", committedDate: "2026-07-05T00:00:00Z" },
335 ];
336 const review = (createdAt: string): PullRequestComment => ({
337 ...TIMELINE_SOURCE.comments[0]!,
338 kind: "review",
339 reviewState: "APPROVED",
340 createdAt,
341 });
342​
343 expect(
344 latestPullRequestReviewOutcomes([review("2026-07-01T00:00:00Z")], commits)[0]?.stale,
345 ).toBe(true);
346 expect(
347 latestPullRequestReviewOutcomes([review("2026-07-06T00:00:00Z")], commits)[0]?.stale,
348 ).toBe(false);
349 // Nothing to be overtaken by, so nothing is stale.
350 expect(latestPullRequestReviewOutcomes([review("2026-07-01T00:00:00Z")], [])[0]?.stale).toBe(
351 false,
352 );
353 });
354​
355 it("measures staleness against the newest commit, not the last one listed", () => {
356 expect(
357 newestPullRequestCommitAt([
358 { oid: "a", messageHeadline: "", committedDate: "2026-07-09T00:00:00Z" },
359 { oid: "b", messageHeadline: "", committedDate: "2026-07-02T00:00:00Z" },
360 ]),
361 ).toBe("2026-07-09T00:00:00Z");
362 expect(newestPullRequestCommitAt([])).toBeNull();
363 });
364​
365 it("orders instants rather than their text, so a UTC offset cannot invert them", () => {
366 // 01:00+02:00 is 23:00 the previous day, so as text it sorts after the Z stamp and in time
367 // it falls well before it.
368 expect(
369 newestPullRequestCommitAt([
370 { oid: "a", messageHeadline: "", committedDate: "2026-07-05T00:30:00Z" },
371 { oid: "b", messageHeadline: "", committedDate: "2026-07-05T01:00:00+02:00" },
372 ]),
373 ).toBe("2026-07-05T00:30:00Z");
374 expect(isPullRequestVerdictStale("2026-07-05T00:30:00Z", "2026-07-05T01:00:00+02:00")).toBe(
375 false,
376 );
377 // A timestamp nothing can parse is not a position, so it settles nothing either way.
378 expect(isPullRequestVerdictStale("2026-07-01T00:00:00Z", "not a date")).toBe(false);
379 expect(
380 newestPullRequestCommitAt([{ oid: "a", messageHeadline: "", committedDate: "not a date" }]),
381 ).toBeNull();
382 });
383​
384 it("shows nothing for a reviewer whose verdict was dismissed", () => {
385 expect(
386 latestPullRequestReviewOutcomes([
387 {
388 ...TIMELINE_SOURCE.comments[0]!,
389 kind: "review",
390 reviewState: "APPROVED",
391 createdAt: "2026-07-01T00:00:00Z",
392 },
393 {
394 ...TIMELINE_SOURCE.comments[0]!,
395 id: "c2",
396 kind: "review",
397 reviewState: "DISMISSED",
398 createdAt: "2026-07-02T00:00:00Z",
399 },
400 ]),
401 ).toEqual([]);
402 });
403});
404​
405describe("pull request timeline", () => {
406 it("orders creation, commits and comments newest first", () => {
407 // What happened last is what the reader opening the tab is asking about.
408 expect(buildPullRequestTimeline(TIMELINE_SOURCE).map((event) => event.id)).toEqual([
409 "c1",
410 "1baf7bdcafe",
411 "created",
412 ]);
413 });
414​
415 it("carries the comment url, and leaves the events the host cannot address without one", () => {
416 const events = buildPullRequestTimeline({
417 ...TIMELINE_SOURCE,
418 comments: [{ ...TIMELINE_SOURCE.comments[0]!, url: "https://example.test/pull/1#c1" }],
419 });
420 expect(events.map((event) => event.url)).toEqual([
421 "https://example.test/pull/1#c1",
422 null,
423 null,
424 ]);
425 });
426​
427 it("carries actors and review context into the presentation model", () => {
428 const commitAuthors = [
429 { login: "octocat", name: null, avatarUrl: "https://example.test/octocat.png" },
430 { login: "pair", name: "Pair Author", avatarUrl: null },
431 ];
432 const events = buildPullRequestTimeline({
433 ...TIMELINE_SOURCE,
434 commits: [{ ...TIMELINE_SOURCE.commits[0]!, authors: commitAuthors }],
435 comments: [
436 {
437 ...TIMELINE_SOURCE.comments[0]!,
438 kind: "review",
439 path: "src/app.ts",
440 reviewState: "APPROVED",
441 },
442 ],
443 });
444​
445 expect(events.find((event) => event.kind === "commit")?.commitAuthors).toEqual(commitAuthors);
446 expect(events.find((event) => event.kind === "review")).toMatchObject({
447 actor: TIMELINE_SOURCE.comments[0]?.author,
448 path: "src/app.ts",
449 reviewState: "APPROVED",
450 });
451 });
452​
453 it("carries each commit's line counts into its timeline event", () => {
454 const events = buildPullRequestTimeline({
455 ...TIMELINE_SOURCE,
456 commits: [{ ...TIMELINE_SOURCE.commits[0]!, additions: 12, deletions: 4 }],
457 });
458​
459 expect(events.find((event) => event.kind === "commit")).toMatchObject({
460 additions: 12,
461 deletions: 4,
462 });
463 });
464​
465 it("drops a body that is nothing but a bot's HTML comment, and keeps one that says more", () => {
466 const events = buildPullRequestTimeline({
467 ...TIMELINE_SOURCE,
468 comments: [
469 { ...TIMELINE_SOURCE.comments[0]!, body: "<!-- MURMUR_IGNORE -->" },
470 {
471 ...TIMELINE_SOURCE.comments[0]!,
472 id: "c2",
473 body: "<!-- summarize by coderabbit.ai -->\nNeeds a test.",
474 createdAt: "2026-07-04T00:00:00Z",
475 },
476 ],
477 });
478 expect(events.find((event) => event.id === "c1")?.body).toBeNull();
479 // Kept whole: the renderer drops the marker itself, and stripping it here would also
480 // strip an HTML comment a reviewer quoted inside a code fence.
481 expect(events.find((event) => event.id === "c2")?.body).toBe(
482 "<!-- summarize by coderabbit.ai -->\nNeeds a test.",
483 );
484 });
485​
486 it("calls a comment markdown and a commit headline plain text", () => {
487 const events = buildPullRequestTimeline(TIMELINE_SOURCE);
488 // A headline reading `fix: drop *legacy* path` is not asking for emphasis.
489 expect(events.map((event) => [event.title.startsWith("Commit"), event.markdown])).toEqual(
490 expect.arrayContaining([[true, false]]),
491 );
492 expect(events.find((event) => event.id === "c1")?.markdown).toBe(true);
493 });
494​
495 it("reports a merge rather than the close GitHub records alongside it", () => {
496 const events = buildPullRequestTimeline({
497 ...TIMELINE_SOURCE,
498 mergedAt: "2026-07-04T00:00:00Z",
499 closedAt: "2026-07-04T00:00:00Z",
500 });
501 // Newest first, so the terminal event opens the list rather than ending it.
502 expect(events[0]?.id).toBe("merged");
503 expect(events.some((event) => event.id === "closed")).toBe(false);
504 });
505​
506 it("groups conversation sections without crossing commits or PR updates", () => {
507 const events = buildPullRequestTimeline({
508 ...TIMELINE_SOURCE,
509 comments: [
510 {
511 ...TIMELINE_SOURCE.comments[0]!,
512 id: "new-comment-1",
513 createdAt: "2026-07-04T00:00:00Z",
514 },
515 {
516 ...TIMELINE_SOURCE.comments[0]!,
517 id: "new-comment-2",
518 createdAt: "2026-07-03T00:00:00Z",
519 },
520 {
521 ...TIMELINE_SOURCE.comments[0]!,
522 id: "old-comment-1",
523 createdAt: "2026-07-01T12:00:00Z",
524 },
525 {
526 ...TIMELINE_SOURCE.comments[0]!,
527 id: "old-comment-2",
528 createdAt: "2026-07-01T06:00:00Z",
529 },
530 ],
531 mergedAt: "2026-07-05T00:00:00Z",
532 });
533​
534 const rows = groupPullRequestTimelineConversations(events);
535 expect(
536 rows.map((row) =>
537 row.kind === "comments"
538 ? [row.kind, ...row.events.map((event) => event.id)]
539 : [row.kind, row.event.id],
540 ),
541 ).toEqual([
542 ["event", "merged"],
543 ["comments", "new-comment-1", "new-comment-2"],
544 ["event", "1baf7bdcafe"],
545 ["comments", "old-comment-1", "old-comment-2"],
546 ["event", "created"],
547 ]);
548 });
549​
550 it("keeps a verdict out of the collapsed conversation it was submitted in", () => {
551 const events = buildPullRequestTimeline({
552 ...TIMELINE_SOURCE,
553 comments: [
554 { ...TIMELINE_SOURCE.comments[0]!, id: "chatter-1", createdAt: "2026-07-05T00:00:00Z" },
555 {
556 ...TIMELINE_SOURCE.comments[0]!,
557 id: "approval",
558 kind: "review",
559 body: "",
560 reviewState: "APPROVED",
561 createdAt: "2026-07-04T00:00:00Z",
562 },
563 { ...TIMELINE_SOURCE.comments[0]!, id: "chatter-2", createdAt: "2026-07-03T00:00:00Z" },
564 // A review without a verdict is ordinary conversation and still groups.
565 {
566 ...TIMELINE_SOURCE.comments[0]!,
567 id: "remark",
568 kind: "review",
569 reviewState: "COMMENTED",
570 createdAt: "2026-07-02T12:00:00Z",
571 },
572 ],
573 });
574​
575 const rows = groupPullRequestTimelineConversations(events);
576 expect(
577 rows.map((row) =>
578 row.kind === "comments"
579 ? [row.kind, ...row.events.map((event) => event.id)]
580 : [row.kind, row.event.id],
581 ),
582 ).toEqual([
583 ["comments", "chatter-1"],
584 ["event", "approval"],
585 ["comments", "chatter-2", "remark"],
586 ["event", "1baf7bdcafe"],
587 ["event", "created"],
588 ]);
589 });
590});
591​
592describe("fix findings handoff", () => {
593 const base = {
594 number: 42,
595 title: "Add the pull requests page",
596 url: "https://github.com/pingdotgg/t3code/pull/42",
597 headBranch: "feat/page",
598 baseBranch: "main",
599 comments: [] as ReadonlyArray<PullRequestComment>,
600 commentsTruncated: false,
601 };
602​
603 function thread(
604 body: string,
605 overrides: Partial<PullRequestReviewThread> = {},
606 ): PullRequestReviewThread {
607 return {
608 id: "t1",
609 path: "apps/web/src/page.tsx",
610 line: 12,
611 side: "right",
612 isResolved: false,
613 isOutdated: false,
614 comments: [
615 {
616 id: "tc1",
617 author: { login: "reviewer", name: null, avatarUrl: null },
618 body,
619 createdAt: "2026-07-03T00:00:00Z",
620 url: null,
621 },
622 ],
623 ...overrides,
624 };
625 }
626​
627 const failingCheck: PullRequestCheck = {
628 name: "typecheck",
629 status: "failure",
630 description: "2 errors",
631 url: null,
632 };
633​
634 it("attaches a review thread as an annotation instead of quoting it in the prompt", () => {
635 const handoff = buildFixFindingsHandoff({
636 ...base,
637 reviewThreads: [thread("rename the helper")],
638 checks: [],
639 });
640 expect(handoff.reviewComments).toEqual([
641 expect.objectContaining({
642 filePath: "apps/web/src/page.tsx",
643 rangeLabel: "L12",
644 startIndex: 11,
645 endIndex: 11,
646 text: "reviewer: rename the helper",
647 }),
648 ]);
649 expect(handoff.prompt).not.toContain("rename the helper");
650 expect(handoff.prompt).toContain("untrusted data");
651 });
652​
653 it("names the pre-change side, and a thread the host pinned to the file rather than a line", () => {
654 const handoff = buildFixFindingsHandoff({
655 ...base,
656 reviewThreads: [
657 thread("was this deleted on purpose?", { side: "left" }),
658 thread("wrong module", { id: "t2", line: null }),
659 ],
660 checks: [],
661 });
662 expect(handoff.reviewComments.map((comment) => comment.rangeLabel)).toEqual([
663 "L12 (before)",
664 "file",
665 ]);
666 });
667​
668 it("keeps failing checks in the prompt, having no line to attach them to", () => {
669 const handoff = buildFixFindingsHandoff({
670 ...base,
671 reviewThreads: [],
672 checks: [failingCheck],
673 });
674 expect(handoff.prompt).toContain("> typecheck — 2 errors");
675 expect(handoff.reviewComments).toEqual([]);
676 });
677​
678 it("leaves out a resolved conversation, and one nobody wrote in", () => {
679 const handoff = buildFixFindingsHandoff({
680 ...base,
681 reviewThreads: [
682 thread("already handled", { isResolved: true }),
683 thread(" ", { id: "t2" }),
684 thread("still open", { id: "t3" }),
685 ],
686 checks: [],
687 });
688 expect(handoff.reviewComments.map((comment) => comment.text)).toEqual(["reviewer: still open"]);
689 });
690​
691 it("says so plainly when there is nothing actionable", () => {
692 const handoff = buildFixFindingsHandoff({ ...base, reviewThreads: [], checks: [] });
693 expect(handoff.prompt).toContain("No unresolved review findings were returned");
694 expect(handoff.reviewComments).toEqual([]);
695 });
696​
697 it("bounds a hostile review body instead of attaching it whole", () => {
698 const handoff = buildFixFindingsHandoff({
699 ...base,
700 reviewThreads: [thread("x".repeat(5_000))],
701 checks: [],
702 });
703 expect(handoff.reviewComments[0]?.text).toHaveLength(1_000);
704 expect(handoff.reviewComments[0]?.text.endsWith("...")).toBe(true);
705 });
706​
707 it("keeps the newest threads and the failing checks when it has to cut", () => {
708 const handoff = buildFixFindingsHandoff({
709 ...base,
710 reviewThreads: Array.from({ length: 25 }, (_, index) =>
711 thread(`finding ${index}`, { id: `t${index}` }),
712 ),
713 checks: [failingCheck],
714 });
715 // Oldest threads are dropped rather than the current failure and the recent feedback.
716 const texts = handoff.reviewComments.map((comment) => comment.text);
717 expect(texts).toHaveLength(19);
718 expect(texts.at(-1)).toBe("reviewer: finding 24");
719 expect(texts).not.toContain("reviewer: finding 0");
720 expect(handoff.prompt).toContain("typecheck");
721 expect(handoff.prompt).toContain("6 further findings were omitted");
722 });
723});
724​
725describe("findings that cannot be attached", () => {
726 const base = {
727 number: 42,
728 title: "Add the pull requests page",
729 url: "https://github.com/pingdotgg/t3code/pull/42",
730 headBranch: "feat/page",
731 baseBranch: "main",
732 reviewThreads: [] as ReadonlyArray<PullRequestReviewThread>,
733 checks: [] as ReadonlyArray<PullRequestCheck>,
734 commentsTruncated: false,
735 };
736​
737 const review: PullRequestComment = {
738 id: "r1",
739 kind: "review",
740 author: { login: "julius", name: null, avatarUrl: null },
741 body: "This breaks SSO auth, revert the middleware change.",
742 createdAt: "2026-07-01T00:00:00Z",
743 url: null,
744 path: null,
745 reviewState: "CHANGES_REQUESTED",
746 };
747​
748 it("carries a review submitted with words but no line, which has nothing to attach to", () => {
749 const handoff = buildFixFindingsHandoff({ ...base, comments: [review] });
750​
751 // It has no file and no line, so it travels the way a failing check does rather than
752 // being dropped for lacking somewhere to point.
753 expect(handoff.reviewComments).toEqual([]);
754 expect(handoff.prompt).toContain("revert the middleware change");
755 expect(handoff.prompt).not.toContain("No unresolved review findings");
756 });
757​
758 it("carries a host's line comments when it reports no threads at all", () => {
759 // Azure DevOps has no diff to pin a conversation to, so every remark arrives this way.
760 const handoff = buildFixFindingsHandoff({
761 ...base,
762 comments: [{ ...review, id: "a1", kind: "review-comment", path: "src/app.ts" }],
763 });
764​
765 expect(handoff.prompt).toContain("src/app.ts");
766 expect(handoff.prompt).toContain("revert the middleware change");
767 });
768​
769 it("does not repeat a remark that was already attached as a thread", () => {
770 const attachedId = "t1c1";
771 const handoff = buildFixFindingsHandoff({
772 ...base,
773 reviewThreads: [
774 {
775 id: "t1",
776 path: "src/app.ts",
777 line: 12,
778 side: "right",
779 isResolved: false,
780 isOutdated: false,
781 comments: [
782 {
783 id: attachedId,
784 author: { login: "julius", name: null, avatarUrl: null },
785 body: "rename the helper",
786 createdAt: "2026-07-01T00:00:00Z",
787 url: null,
788 },
789 ],
790 },
791 ],
792 comments: [{ ...review, id: attachedId, kind: "review-comment", body: "rename the helper" }],
793 });
794​
795 expect(handoff.reviewComments).toHaveLength(1);
796 expect(handoff.prompt).not.toContain("rename the helper");
797 });
798});
799​
800describe("one finding handed over on its own", () => {
801 const base = {
802 number: 42,
803 title: "Add the pull requests page",
804 url: "https://github.com/pingdotgg/t3code/pull/42",
805 headBranch: "feat/page",
806 baseBranch: "main",
807 };
808​
809 const reviewThread: PullRequestReviewThread = {
810 id: "t1",
811 path: "apps/web/src/page.tsx",
812 line: 12,
813 side: "right",
814 isResolved: true,
815 isOutdated: false,
816 comments: [
817 {
818 id: "tc1",
819 author: { login: "reviewer", name: null, avatarUrl: null },
820 body: "rename the helper",
821 createdAt: "2026-07-03T00:00:00Z",
822 url: null,
823 },
824 ],
825 };
826​
827 it("attaches a thread as its own annotation, resolved or not", () => {
828 // The bulk handoff skips resolved threads as finished work. Pressing the button on one is
829 // an explicit request for that thread, so it is not second-guessed.
830 const handoff = buildFixFindingHandoff({
831 ...base,
832 finding: { kind: "thread", thread: reviewThread },
833 });
834 expect(handoff.reviewComments).toEqual([
835 expect.objectContaining({ filePath: "apps/web/src/page.tsx", rangeLabel: "L12" }),
836 ]);
837 expect(handoff.prompt).toContain("attached to this message");
838 expect(handoff.prompt).not.toContain("rename the helper");
839 });
840​
841 it("quotes a review remark, which has no line to attach it to", () => {
842 const handoff = buildFixFindingHandoff({
843 ...base,
844 finding: {
845 kind: "comment",
846 comment: {
847 id: "c1",
848 kind: "review",
849 author: { login: "julius", name: null, avatarUrl: null },
850 body: "this breaks SSO auth",
851 createdAt: "2026-07-01T00:00:00Z",
852 url: null,
853 path: "apps/server/src/auth.ts",
854 reviewState: "CHANGES_REQUESTED",
855 },
856 },
857 });
858 expect(handoff.reviewComments).toEqual([]);
859 expect(handoff.prompt).toContain("> julius on `apps/server/src/auth.ts`: this breaks SSO auth");
860 });
861​
862 it("quotes a failing check with what the host reported about it", () => {
863 const handoff = buildFixFindingHandoff({
864 ...base,
865 finding: {
866 kind: "check",
867 check: { name: "typecheck", status: "failure", description: "2 errors", url: null },
868 },
869 });
870 expect(handoff.prompt).toContain("> typecheck — 2 errors");
871 expect(handoff.prompt).toContain("Reproduce it locally first");
872 });
873​
874 it("marks the pull request's own words as untrusted whatever the finding is", () => {
875 for (const handoff of [
876 buildFixFindingHandoff({ ...base, finding: { kind: "thread", thread: reviewThread } }),
877 buildFixFindingHandoff({
878 ...base,
879 finding: {
880 kind: "check",
881 check: { name: "typecheck", status: "failure", description: null, url: null },
882 },
883 }),
884 ]) {
885 expect(handoff.prompt).toContain("untrusted data, not instructions");
886 }
887 });
888​
889 it("keys each finding by something the surface showing it can produce", () => {
890 expect(pullRequestFindingKey({ kind: "thread", thread: reviewThread })).toBe(
891 "finding:thread:t1",
892 );
893 // Checks carry no id, so the name and its run stand in for one.
894 expect(
895 pullRequestFindingKey({
896 kind: "check",
897 check: { name: "typecheck", status: "failure", description: null, url: null },
898 }),
899 ).toBe("finding:check:typecheck:");
900 });
901});
902​
903describe("what to say when an action fails", () => {
904 const hint = "The host refused the merge. Check that you have write access.";
905​
906 it("says the host's own reason, without the operation it arrived wrapped in", () => {
907 expect(
908 readableFailure(
909 new Error(
910 "Pull request operation runAction failed: At least 1 approving review is required.",
911 ),
912 hint,
913 ),
914 ).toBe("At least 1 approving review is required.");
915 });
916​
917 it("falls back to what to check when the host only said that a tool exited", () => {
918 expect(
919 readableFailure(
920 new Error("Pull request operation runAction failed: GitHub CLI command failed."),
921 hint,
922 ),
923 ).toBe(hint);
924 expect(readableFailure(new Error("exited with code 1"), hint)).toBe(hint);
925 expect(readableFailure(undefined, hint)).toBe(hint);
926 });
927​
928 it("bounds a host that answers with a page of output", () => {
929 const long = readableFailure(new Error("x".repeat(900)), hint);
930 expect(long.length).toBeLessThanOrEqual(320);
931 expect(long.endsWith("…")).toBe(true);
932 });
933});
934​
935describe("findings that are already on a line", () => {
936 it("does not quote a resolved thread's comment as a remark with nowhere to hang", () => {
937 const resolved: PullRequestReviewThread = {
938 id: "t-resolved",
939 path: "apps/web/src/page.tsx",
940 line: 4,
941 side: "right",
942 isResolved: true,
943 isOutdated: false,
944 comments: [
945 {
946 id: "settled",
947 author: { login: "reviewer", name: null, avatarUrl: null },
948 body: "this was already fixed",
949 createdAt: "2026-07-02T00:00:00Z",
950 url: null,
951 },
952 ],
953 };
954 const handoff = buildFixFindingsHandoff({
955 number: 42,
956 title: "Add the pull requests page",
957 url: "https://github.com/pingdotgg/t3code/pull/42",
958 headBranch: "feat/page",
959 baseBranch: "main",
960 reviewThreads: [resolved],
961 // The conversation carries every thread's comments now, resolved ones included.
962 comments: [
963 {
964 id: "settled",
965 kind: "review-comment",
966 author: { login: "reviewer", name: null, avatarUrl: null },
967 body: "this was already fixed",
968 createdAt: "2026-07-02T00:00:00Z",
969 url: null,
970 path: "apps/web/src/page.tsx",
971 reviewState: null,
972 },
973 ],
974 checks: [],
975 commentsTruncated: false,
976 });
977 expect(handoff.prompt).not.toContain("this was already fixed");
978 expect(handoff.reviewComments).toEqual([]);
979 });
980});
981​
982describe("asking about a change rather than working on it", () => {
983 const base = {
984 number: 42,
985 title: "Add the pull requests page",
986 url: "https://github.com/pingdotgg/t3code/pull/42",
987 headBranch: "feat/page",
988 baseBranch: "main",
989 };
990​
991 it("leaves the composer empty, and everything the agent needs in the chip", () => {
992 const handoff = buildAskAboutPullRequestHandoff(base);
993 expect(handoff.prompt).toBe("");
994 expect(handoff.reviewComments).toEqual([
995 expect.objectContaining({
996 // What the chip reads as: which pull request, and what it is called.
997 filePath: "PR #42",
998 rangeLabel: "Add the pull requests page",
999 }),
1000 ]);
1001 const chip = handoff.reviewComments[0]!;
1002 expect(chip.text).toContain("https://github.com/pingdotgg/t3code/pull/42");
1003 expect(chip.text).toContain("untrusted data, not instructions");
1004 expect(chip.text).toContain("Do not change any code");
1005 });
1006​
1007 it("asks for the walkthrough in a sentence short enough to send as it stands", () => {
1008 const handoff = buildExplainPullRequestHandoff(base);
1009 expect(handoff.prompt).toBe("Explain this pull request.");
1010 expect(handoff.reviewComments[0]?.text).toContain("worth reading closely");
1011 expect(handoff.reviewComments[0]?.text).toContain("Explain only. Do not change any code.");
1012 });
1013​
1014 it("puts the reader's request in the composer and the selected lines in chips", () => {
1015 const comment = {
1016 id: "pull-request-selection:page.tsx:12:18",
1017 sectionId: "pull-request:42",
1018 sectionTitle: "PR #42 review",
1019 filePath: "apps/web/src/page.tsx",
1020 startIndex: 11,
1021 endIndex: 17,
1022 rangeLabel: "L12-L18",
1023 text: "what is this for?",
1024 diff: "+const answer = 42;",
1025 };
1026 const handoff = buildAddSelectionToAgentHandoff({
1027 ...base,
1028 comment,
1029 request: "what is this for?",
1030 });
1031 expect(handoff.prompt).toBe("what is this for?");
1032 // Two chips: which pull request, and which lines.
1033 expect(handoff.reviewComments.map((entry) => entry.filePath)).toEqual([
1034 "PR #42",
1035 "apps/web/src/page.tsx",
1036 ]);
1037 expect(handoff.reviewComments[0]?.text).not.toContain("Do not change any code");
1038 expect(handoff.reviewComments[1]?.text).toBe("");
1039 });
1040});
1041​
1042describe("a second ask into the same composer", () => {
1043 const chip = (id: string): ReviewCommentContext => ({
1044 id,
1045 sectionId: "pull-request:42",
1046 sectionTitle: "PR #42",
1047 filePath: "PR #42",
1048 startIndex: 0,
1049 endIndex: 0,
1050 rangeLabel: "Add the pull requests page",
1051 text: "",
1052 diff: "",
1053 });
1054​
1055 it("replaces what the last one left, chips included", () => {
1056 const next = handoffReviewComments(
1057 [chip("pull-request-context:41"), chip("pull-request-selection:page.tsx:1:2")],
1058 [chip("pull-request-context:42")],
1059 );
1060 expect(next.map((comment) => comment.id)).toEqual(["pull-request-context:42"]);
1061 });
1062​
1063 it("empties what the last ask left, so the two are never sent as one question", () => {
1064 const handed = "Explain this pull request.";
1065 expect(handoffPrompt({ prompt: handed, lastHandoffPrompt: handed }, "")).toBe("");
1066 });
1067​
1068 it("replaces the last ask's prompt with this one's", () => {
1069 const handed = "Explain this pull request.";
1070 expect(handoffPrompt({ prompt: handed, lastHandoffPrompt: handed }, "Why the cache key?")).toBe(
1071 "Why the cache key?",
1072 );
1073 });
1074​
1075 it("leaves a sentence the reader typed themselves where it is", () => {
1076 expect(
1077 handoffPrompt({ prompt: "check the migration first", lastHandoffPrompt: undefined }, ""),
1078 ).toBe("check the migration first");
1079 });
1080​
1081 it("keeps what the reader wrote next to the chip an earlier ask left", () => {
1082 // The chip is still there, but these words are not the ones the hand-off wrote.
1083 expect(
1084 handoffPrompt({ prompt: "why is the cache keyed on the branch?", lastHandoffPrompt: "" }, ""),
1085 ).toBe("why is the cache keyed on the branch?");
1086 });
1087​
1088 it("keeps an edit the reader made to the sentence they were handed", () => {
1089 expect(
1090 handoffPrompt(
1092 prompt: "Explain this pull request, the caching especially.",
1093 lastHandoffPrompt: "Explain this pull request.",
1094 },
1095 "",
1096 ),
1097 ).toBe("Explain this pull request, the caching especially.");
1098 });
1099​
1100 it("puts an ask under what the reader typed rather than over it", () => {
1101 expect(
1102 handoffPrompt(
1103 { prompt: "check the migration first", lastHandoffPrompt: undefined },
1104 "Explain this pull request.",
1105 ),
1106 ).toBe("check the migration first\n\nExplain this pull request.");
1107 });
1108​
1109 it("replaces only its own sentence under text the reader typed", () => {
1110 expect(
1111 handoffPrompt(
1113 prompt: "check the migration first\n\nExplain this pull request.",
1114 lastHandoffPrompt: "Explain this pull request.",
1115 },
1116 "Why the cache key?",
1117 ),
1118 ).toBe("check the migration first\n\nWhy the cache key?");
1119 });
1120​
1121 it("takes back only its own sentence when the next ask is empty", () => {
1122 expect(
1123 handoffPrompt(
1125 prompt: "check the migration first\n\nExplain this pull request.",
1126 lastHandoffPrompt: "Explain this pull request.",
1127 },
1128 "",
1129 ),
1130 ).toBe("check the migration first");
1131 });
1132​
1133 it("keeps the lines the reader marked up in the thread themselves", () => {
1134 const own = chip("file-comment:3");
1135 const next = handoffReviewComments(
1136 [own, chip("pull-request-finding:t1")],
1137 [chip("pull-request-context:42")],
1138 );
1139 expect(next.map((comment) => comment.id)).toEqual([
1140 "file-comment:3",
1141 "pull-request-context:42",
1142 ]);
1143 });
1144});
1145​
1146describe("how the branch stands against its base", () => {
1147 const detail = (overrides: Record<string, unknown> = {}) =>
1148 ({
1149 state: "open",
1150 mergeability: "mergeable",
1151 baseComparison: "behind",
1152 behindBy: 12,
1153 capabilities: { updateMethods: ["merge", "rebase"] },
1154 viewerPermissions: { updateMethods: ["merge", "rebase"] },
1155 ...overrides,
1156 }) as Parameters<typeof resolveBaseFreshness>[0];
1157​
1158 it("offers both ways where the host and the reader both allow them", () => {
1159 expect(resolveBaseFreshness(detail())).toEqual({ behindBy: 12, methods: ["merge", "rebase"] });
1160 });
1161​
1162 it("says nothing about a branch that is already current", () => {
1163 expect(resolveBaseFreshness(detail({ baseComparison: "up-to-date" }))).toBeNull();
1164 });
1165​
1166 it("says nothing where the host could not compare, rather than claiming it is current", () => {
1167 expect(resolveBaseFreshness(detail({ baseComparison: "unknown" }))).toBeNull();
1168 expect(resolveBaseFreshness(detail({ baseComparison: undefined }))).toBeNull();
1169 });
1170​
1171 it("leaves a conflicting branch to the conflicts row", () => {
1172 expect(resolveBaseFreshness(detail({ mergeability: "conflicting" }))).toBeNull();
1173 });
1174​
1175 it("says nothing where the host has no merge verdict yet", () => {
1176 expect(resolveBaseFreshness(detail({ mergeability: "unknown" }))).toBeNull();
1177 });
1178​
1179 it("says nothing about a merged or closed pull request", () => {
1180 expect(resolveBaseFreshness(detail({ state: "merged" }))).toBeNull();
1181 expect(resolveBaseFreshness(detail({ state: "closed" }))).toBeNull();
1182 });
1183​
1184 it("narrows to what this reader may actually take", () => {
1185 expect(
1186 resolveBaseFreshness(detail({ viewerPermissions: { updateMethods: ["merge"] } }))?.methods,
1187 ).toEqual(["merge"]);
1188 });
1189​
1190 it("still reports the news where the reader may take none of it", () => {
1191 // Somebody reading another account's pull request is told why it is blocked without being
1192 // offered a button the host would refuse.
1193 expect(resolveBaseFreshness(detail({ viewerPermissions: {} }))).toEqual({
1194 behindBy: 12,
1195 methods: [],
1196 });
1197 });
1198​
1199 it("reports a count only where the host counted", () => {
1200 expect(resolveBaseFreshness(detail({ behindBy: undefined }))?.behindBy).toBeNull();
1201 });
1202});
1203​
1204describe("whether the panel is showing the thread's own pull request", () => {
1205 const surface = { projectId: "proj-a", repository: "acme/app", number: 7 };
1206​
1207 it("matches on project, repository and number together", () => {
1208 expect(
1209 isThreadOwnPullRequest({ projectId: "proj-a", repository: "acme/app", number: 7 }, surface),
1210 ).toBe(true);
1211 });
1212​
1213 it("rejects a second checkout of the same repository under another project", () => {
1214 expect(
1215 isThreadOwnPullRequest({ projectId: "proj-b", repository: "acme/app", number: 7 }, surface),
1216 ).toBe(false);
1217 });
1218​
1219 it("rejects another repository or another number", () => {
1220 expect(
1221 isThreadOwnPullRequest({ projectId: "proj-a", repository: "acme/web", number: 7 }, surface),
1222 ).toBe(false);
1223 expect(
1224 isThreadOwnPullRequest({ projectId: "proj-a", repository: "acme/app", number: 8 }, surface),
1225 ).toBe(false);
1226 });
1227​
1228 it("rejects a thread with no project or no pull request of its own", () => {
1229 expect(
1230 isThreadOwnPullRequest({ projectId: null, repository: "acme/app", number: 7 }, surface),
1231 ).toBe(false);
1232 expect(
1233 isThreadOwnPullRequest(
1234 { projectId: "proj-a", repository: "acme/app", number: null },
1235 surface,
1236 ),
1237 ).toBe(false);
1238 });
1239});
1240​
1241describe("which actions need the host read again after they run", () => {
1242 it("classifies every action the contract knows about", () => {
1243 // Imported from the contract rather than hand-listed, so a new PullRequestAction fails this
1244 // test until somebody decides which side of the diff it belongs on.
1245 expect(PullRequestAction.literals.map(pullRequestActionNeedsHostRefresh)).toEqual(
1246 PullRequestAction.literals.map((action) => action === "update-branch"),
1247 );
1248 });
1249​
1250 it("sends update-branch back to the host, having moved the head commit", () => {
1251 expect(pullRequestActionNeedsHostRefresh("update-branch")).toBe(true);
1252 });
1253​
1254 it("leaves every action that only changes metadata to the cheaper detail refresh", () => {
1255 for (const action of [
1256 "ready",
1257 "draft",
1258 "close",
1259 "reopen",
1260 "enable-auto-merge",
1261 "disable-auto-merge",
1262 "merge",
1263 ] as const) {
1264 expect(pullRequestActionNeedsHostRefresh(action)).toBe(false);
1266 });
1267});