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