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