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