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