@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 2,065 lines 70.2 KB
Raw
1 import { SourceControlProviderKind } from "@t3tools/contracts";
2 import {
3 GitCommandError,
4 ProjectId,
5 type PullRequestCheck,
6 type PullRequestComment,
7 type PullRequestDetail,
8 type PullRequestDetailView,
9 type PullRequestRef,
10 type PullRequestReviewThread,
11 type PullRequestState,
12 type RepositoryIdentity,
13 type ThreadPullRequestLink,
14 } from "@t3tools/contracts";
15 import { describe, expect, it } from "vite-plus/test";
16 import {
17 formatComposerContextReference,
18 projectComposerContextForProvider,
19 } from "@t3tools/shared/composerContextReferences";
20 import {
21 reviewCommentContextLabel,
22 reviewCommentContextRecord,
23 } from "~/lib/composerContextRecords";
24
25 import {
26 buildAddSelectionToAgentHandoff,
27 buildAskAboutPullRequestHandoff,
28 buildExplainPullRequestHandoff,
29 buildResolveConflictsPrompt,
30 resolveThreadPanelPullRequestAction,
31 buildPullRequestCommentContext,
32 buildFixFindingHandoff,
33 canDeletePullRequestBranch,
34 buildFixFindingsHandoff,
35 groupPullRequestTimelineConversations,
36 filterPullRequestConversationItems,
37 pagePullRequestConversationItems,
38 pullRequestConversationItemComments,
39 pullRequestConversationItems,
40 appendHandoff,
41 isPullRequestVerdictStale,
42 isStackedPullRequestBase,
43 loadingPullRequestCheckoutCommand,
44 pullRequestPanelContext,
45 threadPullRequestPanelTarget,
46 latestPullRequestReviewOutcomes,
47 newestPullRequestCommitAt,
48 mergePullRequestThreadComments,
49 orderPullRequestComments,
50 pullRequestCheckoutCommand,
51 checkoutFailureDescription,
52 readPullRequestDetailSnapshot,
53 resolveDisplayedPullRequestDetail,
54 resolvePullRequestReferenceHost,
55 resolvePullRequestPrimaryControl,
56 allowsSinglePullRequestMerge,
57 shouldRefreshPullRequestActivity,
58 resolveBaseFreshness,
59 buildPullRequestTimeline,
60 pullRequestLinkSubject,
61 writePullRequestDetailSnapshot,
62 readableFailure,
63 } from "./pullRequestDetail.logic";
64 import type { ReviewCommentContext } from "~/reviewCommentContext";
65
66 describe("pull request checkout commands", () => {
67 it("quotes shell metacharacters in Forgejo repository URLs", () => {
68 expect(
69 pullRequestCheckoutCommand(
70 SourceControlProviderKind.make("forgejo"),
71 42,
72 "feature",
73 null,
74 "https://forgejo.local/maria/repo'$(echo nope)",
75 ),
76 ).toBe(
77 "git fetch 'https://forgejo.local/maria/repo'\\''$(echo nope)' refs/pull/42/head && git checkout -B pulls/42 FETCH_HEAD",
78 );
79 });
80
81 const reference = (host?: string): PullRequestRef => ({
82 projectId: ProjectId.make("project-1"),
83 ...(host === undefined ? {} : { host }),
84 repository: "acme/web",
85 number: 42,
86 });
87 const identity = (provider: string, canonicalKey: string): RepositoryIdentity => ({
88 canonicalKey,
89 locator: {
90 source: "git-remote",
91 remoteName: "origin",
92 remoteUrl: "git@github.com:acme/web.git",
93 },
94 provider: SourceControlProviderKind.make(provider),
95 });
96
97 it("uses a matching enterprise identity and rejects an explicit host mismatch", () => {
98 const enterprise = identity("github", "github.example.test/acme/web");
99 expect(loadingPullRequestCheckoutCommand(reference("github.example.test"), enterprise)).toBe(
100 "gh pr checkout 42",
101 );
102 expect(loadingPullRequestCheckoutCommand(reference("github.com"), enterprise)).toBeNull();
103 });
104
105 // regression: #12721 loading layout showed a checkout command guessed from the PR number alone
106 it("does not infer a number-only command without a trusted provider", () => {
107 expect(loadingPullRequestCheckoutCommand(reference(), undefined)).toBeNull();
108 expect(
109 loadingPullRequestCheckoutCommand(
110 reference("github.com"),
111 identity("gitlab", "gitlab.com/acme/web"),
112 ),
113 ).toBeNull();
114 });
115 });
116
117 const TIMELINE_SOURCE: Pick<
118 PullRequestDetailView,
119 "provider" | "createdAt" | "author" | "commits" | "comments" | "mergedAt" | "closedAt"
120 > = {
121 provider: SourceControlProviderKind.make("github"),
122 createdAt: "2026-07-01T00:00:00Z",
123 author: { login: "octocat", name: null, avatarUrl: null },
124 commits: [
125 { oid: "1baf7bdcafe", messageHeadline: "add the page", committedDate: "2026-07-02T00:00:00Z" },
126 ],
127 comments: [
128 {
129 id: "c1",
130 kind: "issue-comment",
131 author: { login: "bilal", name: null, avatarUrl: null },
132 body: "looks good",
133 createdAt: "2026-07-03T00:00:00Z",
134 url: null,
135 path: null,
136 reviewState: null,
137 },
138 ],
139 mergedAt: null,
140 closedAt: null,
141 };
142
143 describe("pull request activity refresh", () => {
144 const first = {
145 key: "project:acme/web#7",
146 updatedAt: "2026-08-13T13:00:00Z",
147 };
148
149 it("does not duplicate the first activity read or carry a revision across pull requests", () => {
150 expect(shouldRefreshPullRequestActivity(null, first)).toBe(false);
151 expect(shouldRefreshPullRequestActivity(first, first)).toBe(false);
152 expect(
153 shouldRefreshPullRequestActivity(first, {
154 key: "project:acme/web#8",
155 updatedAt: "2026-08-13T13:01:00Z",
156 }),
157 ).toBe(false);
158 });
159 });
160 describe("review thread comment pages", () => {
161 it("appends new comments once and keeps refreshed base comments", () => {
162 expect(
163 mergePullRequestThreadComments(
164 [
165 { id: "c1", body: "refreshed" },
166 { id: "c2", body: "already in base" },
167 ],
168 [
169 { id: "c2", body: "stale page copy" },
170 { id: "c3", body: "next page" },
171 ],
172 ),
173 ).toEqual([
174 { id: "c1", body: "refreshed" },
175 { id: "c2", body: "already in base" },
176 { id: "c3", body: "next page" },
177 ]);
178 });
179 });
180
181 describe("pull request primary control", () => {
182 const open = {
183 state: "open" as const,
184 isDraft: false,
185 mergeability: "mergeable" as const,
186 checksState: "passing" as const,
187 autoMergeEnabled: false,
188 hasMergeMethod: true,
189 canMerge: true,
190 canMarkReady: true,
191 canEnableAutoMerge: true,
192 };
193
194 // regression: #9188 pending/failing checks offered Merge instead of auto-merge
195 it("moves pending and failing checks to auto-merge", () => {
196 expect(resolvePullRequestPrimaryControl({ ...open, checksState: "pending" })).toBe(
197 "enable-auto-merge",
198 );
199 expect(resolvePullRequestPrimaryControl({ ...open, checksState: "failing" })).toBe(
200 "enable-auto-merge",
201 );
202 });
203
204 it("does not offer auto-merge while the host state is unknown", () => {
205 expect(
206 resolvePullRequestPrimaryControl({
207 ...open,
208 checksState: "pending",
209 autoMergeEnabled: undefined,
210 }),
211 ).toBe("merge");
212 });
213 });
214
215 describe("stacked pull request classification", () => {
216 it("does not mistake a nested branch suffix for the default branch", () => {
217 expect(
218 isStackedPullRequestBase("main", [
219 {
220 name: "origin/feature/main",
221 isDefault: true,
222 isRemote: true,
223 remoteName: "origin",
224 },
225 ]),
226 ).toBe(true);
227 expect(
228 isStackedPullRequestBase("1.0", [{ name: "release/1.0", isDefault: true, isRemote: false }]),
229 ).toBe(true);
230 });
231 });
232
233 describe("review verdicts", () => {
234 it("keeps each reviewer's last word, whatever order the host returned them in", () => {
235 const review = (
236 id: string,
237 login: string,
238 reviewState: string,
239 createdAt: string,
240 ): PullRequestComment => ({
241 id,
242 kind: "review",
243 author: { login, name: null, avatarUrl: null },
244 body: "",
245 createdAt,
246 url: null,
247 path: null,
248 reviewState,
249 });
250
251 expect(
252 latestPullRequestReviewOutcomes([
253 review("r3", "bilal", "APPROVED", "2026-07-03T00:00:00Z"),
254 review("r1", "bilal", "CHANGES_REQUESTED", "2026-07-01T00:00:00Z"),
255 review("r2", "octocat", "CHANGES_REQUESTED", "2026-07-02T00:00:00Z"),
256 review("r4", "octocat", "COMMENTED", "2026-07-04T00:00:00Z"),
257 ]).map((entry) => [entry.actor?.login, entry.outcome]),
258 ).toEqual([
259 ["bilal", "approved"],
260 ["octocat", "changes-requested"],
261 ]);
262 });
263
264 it("calls a verdict stale once commits land after it, and current before that", () => {
265 const commits = [
266 { oid: "c0ffee", messageHeadline: "later work", committedDate: "2026-07-05T00:00:00Z" },
267 ];
268 const review = (createdAt: string): PullRequestComment => ({
269 ...TIMELINE_SOURCE.comments[0]!,
270 kind: "review",
271 reviewState: "APPROVED",
272 createdAt,
273 });
274
275 expect(
276 latestPullRequestReviewOutcomes([review("2026-07-01T00:00:00Z")], commits)[0]?.stale,
277 ).toBe(true);
278 expect(
279 latestPullRequestReviewOutcomes([review("2026-07-06T00:00:00Z")], commits)[0]?.stale,
280 ).toBe(false);
281 expect(latestPullRequestReviewOutcomes([review("2026-07-01T00:00:00Z")], [])[0]?.stale).toBe(
282 false,
283 );
284 });
285
286 it("orders instants rather than their text, so a UTC offset cannot invert them", () => {
287 expect(
288 newestPullRequestCommitAt([
289 { oid: "a", messageHeadline: "", committedDate: "2026-07-05T00:30:00Z" },
290 { oid: "b", messageHeadline: "", committedDate: "2026-07-05T01:00:00+02:00" },
291 ]),
292 ).toBe("2026-07-05T00:30:00Z");
293 expect(isPullRequestVerdictStale("2026-07-05T00:30:00Z", "2026-07-05T01:00:00+02:00")).toBe(
294 false,
295 );
296 expect(isPullRequestVerdictStale("2026-07-01T00:00:00Z", "not a date")).toBe(false);
297 expect(
298 newestPullRequestCommitAt([{ oid: "a", messageHeadline: "", committedDate: "not a date" }]),
299 ).toBeNull();
300 });
301
302 it("shows nothing for a reviewer whose verdict was dismissed", () => {
303 expect(
304 latestPullRequestReviewOutcomes([
305 {
306 ...TIMELINE_SOURCE.comments[0]!,
307 kind: "review",
308 reviewState: "APPROVED",
309 createdAt: "2026-07-01T00:00:00Z",
310 },
311 {
312 ...TIMELINE_SOURCE.comments[0]!,
313 id: "c2",
314 kind: "review",
315 reviewState: "DISMISSED",
316 createdAt: "2026-07-02T00:00:00Z",
317 },
318 ]),
319 ).toEqual([]);
320 });
321 });
322
323 describe("pull request timeline", () => {
324 it("names the comment or commit a link points at for its hover card", () => {
325 const pr = "https://github.com/o/r/pull/1";
326 const sha = "a".repeat(40);
327 const activity = {
328 comments: [
329 {
330 ...TIMELINE_SOURCE.comments[0]!,
331 url: `${pr}#issuecomment-5`,
332 body: "<!-- bot -->\n> [!NOTE]\n> **Looks** good, see `run()` ![shot](x.png)",
333 },
334 ],
335 reviewThreads: [
336 {
337 id: "t",
338 path: "a.ts",
339 line: 1,
340 side: "right" as const,
341 isResolved: false,
342 isOutdated: false,
343 comments: [
344 {
345 id: "r1",
346 author: { login: "reviewer", name: null, avatarUrl: null },
347 body: "nit",
348 createdAt: "2026-07-03T00:00:00Z",
349 url: `${pr}#discussion_r1`,
350 reviewUrl: `${pr}#pullrequestreview-9`,
351 },
352 ],
353 },
354 ],
355 commits: [{ oid: sha, messageHeadline: "fix it", committedDate: "2026-07-02T00:00:00Z" }],
356 };
357 expect(pullRequestLinkSubject(`${pr}#issuecomment-5`, activity)).toMatchObject({
358 kind: "comment",
359 excerpt: "Looks good, see run()",
360 });
361 // A review with no text of its own is shown through the comment it posted.
362 expect(pullRequestLinkSubject(`${pr}#pullrequestreview-9`, activity)).toMatchObject({
363 kind: "comment",
364 author: { login: "reviewer" },
365 excerpt: "nit",
366 });
367 expect(pullRequestLinkSubject(`${pr}/commits/${sha}`, activity)).toMatchObject({
368 kind: "commit",
369 commit: { messageHeadline: "fix it" },
370 });
371 for (const url of [pr, `${pr}/files`, `${pr}/checks`, `${pr}#issuecomment-6`]) {
372 expect(pullRequestLinkSubject(url, activity), url).toBeNull();
373 }
374 // An emoji straddling the cut is dropped whole rather than split into a lone surrogate.
375 const long = {
376 ...activity,
377 comments: [{ ...activity.comments[0]!, body: `${"i ".repeat(139)}😀bb` }],
378 };
379 const cut = pullRequestLinkSubject(`${pr}#issuecomment-5`, long);
380 const excerpt = cut && "excerpt" in cut ? cut.excerpt : null;
381 expect(excerpt).toMatch(/^(?:i ?)+…$/u);
382 });
383
384 it("orders host timestamps by instant across offsets and fractional seconds", () => {
385 const events = buildPullRequestTimeline({
386 ...TIMELINE_SOURCE,
387 createdAt: "2026-07-05T01:00:00+02:00",
388 commits: [{ oid: "commit", messageHeadline: "", committedDate: "2026-07-05T00:30:00Z" }],
389 comments: [{ ...TIMELINE_SOURCE.comments[0]!, createdAt: "2026-07-05T00:30:00.5Z" }],
390 mergedAt: null,
391 closedAt: null,
392 });
393
394 expect(events.map((event) => event.id)).toEqual(["c1", "commit", "created"]);
395 });
396
397 it("drops a body that is nothing but a bot's HTML comment, and keeps one that says more", () => {
398 const events = buildPullRequestTimeline({
399 ...TIMELINE_SOURCE,
400 comments: [
401 { ...TIMELINE_SOURCE.comments[0]!, body: "<!-- MURMUR_IGNORE -->" },
402 {
403 ...TIMELINE_SOURCE.comments[0]!,
404 id: "c2",
405 body: "<!-- summarize by coderabbit.ai -->\nNeeds a test.",
406 createdAt: "2026-07-04T00:00:00Z",
407 },
408 ],
409 });
410 expect(events.find((event) => event.id === "c1")?.body).toBeNull();
411 expect(events.find((event) => event.id === "c2")?.body).toBe(
412 "<!-- summarize by coderabbit.ai -->\nNeeds a test.",
413 );
414 });
415
416 it("reports a merge rather than the close GitHub records alongside it", () => {
417 const events = buildPullRequestTimeline({
418 ...TIMELINE_SOURCE,
419 mergedAt: "2026-07-04T00:00:00Z",
420 closedAt: "2026-07-04T00:00:00Z",
421 });
422 expect(events[0]?.id).toBe("merged");
423 expect(events.some((event) => event.id === "closed")).toBe(false);
424 });
425
426 it("names the change request in its host's own term", () => {
427 const titles = (provider: string) =>
428 buildPullRequestTimeline({
429 ...TIMELINE_SOURCE,
430 provider: SourceControlProviderKind.make(provider),
431 closedAt: "2026-07-04T00:00:00Z",
432 })
433 .filter((event) => event.kind === "opened" || event.kind === "closed")
434 .map((event) => event.title);
435 expect(titles("github")).toEqual(["Pull request closed", "opened this pull request"]);
436 expect(titles("gitlab")).toEqual(["Merge request closed", "opened this merge request"]);
437 });
438
439 it("groups conversation sections without crossing commits or PR updates", () => {
440 const events = buildPullRequestTimeline({
441 ...TIMELINE_SOURCE,
442 comments: [
443 {
444 ...TIMELINE_SOURCE.comments[0]!,
445 id: "new-comment-1",
446 createdAt: "2026-07-04T00:00:00Z",
447 },
448 {
449 ...TIMELINE_SOURCE.comments[0]!,
450 id: "new-comment-2",
451 createdAt: "2026-07-03T00:00:00Z",
452 },
453 {
454 ...TIMELINE_SOURCE.comments[0]!,
455 id: "old-comment-1",
456 createdAt: "2026-07-01T12:00:00Z",
457 },
458 {
459 ...TIMELINE_SOURCE.comments[0]!,
460 id: "old-comment-2",
461 createdAt: "2026-07-01T06:00:00Z",
462 },
463 ],
464 mergedAt: "2026-07-05T00:00:00Z",
465 });
466
467 const rows = groupPullRequestTimelineConversations(events);
468 expect(
469 rows.map((row) =>
470 row.kind === "comments"
471 ? [row.kind, ...row.events.map((event) => event.id)]
472 : [row.kind, row.event.id],
473 ),
474 ).toEqual([
475 ["event", "merged"],
476 ["comments", "new-comment-1", "new-comment-2"],
477 ["event", "1baf7bdcafe"],
478 ["comments", "old-comment-1", "old-comment-2"],
479 ["event", "created"],
480 ]);
481 });
482
483 it("keeps a verdict out of the collapsed conversation it was submitted in", () => {
484 const events = buildPullRequestTimeline({
485 ...TIMELINE_SOURCE,
486 comments: [
487 { ...TIMELINE_SOURCE.comments[0]!, id: "chatter-1", createdAt: "2026-07-05T00:00:00Z" },
488 {
489 ...TIMELINE_SOURCE.comments[0]!,
490 id: "approval",
491 kind: "review",
492 body: "",
493 reviewState: "APPROVED",
494 createdAt: "2026-07-04T00:00:00Z",
495 },
496 { ...TIMELINE_SOURCE.comments[0]!, id: "chatter-2", createdAt: "2026-07-03T00:00:00Z" },
497 {
498 ...TIMELINE_SOURCE.comments[0]!,
499 id: "remark",
500 kind: "review",
501 reviewState: "COMMENTED",
502 createdAt: "2026-07-02T12:00:00Z",
503 },
504 ],
505 });
506
507 const rows = groupPullRequestTimelineConversations(events);
508 expect(
509 rows.map((row) =>
510 row.kind === "comments"
511 ? [row.kind, ...row.events.map((event) => event.id)]
512 : [row.kind, row.event.id],
513 ),
514 ).toEqual([
515 ["comments", "chatter-1"],
516 ["event", "approval"],
517 ["comments", "chatter-2", "remark"],
518 ["event", "1baf7bdcafe"],
519 ["event", "created"],
520 ]);
521 });
522 });
523
524 describe("review thread conversations", () => {
525 const bot = { login: "review[bot]", name: null, avatarUrl: null, isBot: true };
526 const comment = (id: string, day: number): PullRequestComment => ({
527 ...TIMELINE_SOURCE.comments[0]!,
528 id,
529 kind: "review-comment",
530 body: `Current ${id}`,
531 createdAt: `2026-07-0${day}T12:00:00Z`,
532 url: `https://example.test/pull/1#${id}`,
533 path: "src/a.ts",
534 });
535 const finding = { ...comment("finding", 2), author: bot };
536 const reply = {
537 ...comment("reply", 4),
538 reactions: [
539 { content: "thumbs-up" as const, count: 2, actors: ["author"], viewerHasReacted: true },
540 ],
541 };
542 const lastReply = comment("last-reply", 6);
543 const loose = TIMELINE_SOURCE.comments[0]!;
544 const comments = [finding, loose, reply, lastReply];
545 const thread: PullRequestReviewThread = {
546 id: "thread",
547 path: "src/a.ts",
548 line: 7,
549 side: "right",
550 isResolved: false,
551 isOutdated: true,
552 comments: [lastReply, { ...finding, body: "Stale finding" }, reply],
553 };
554
555 it("keeps a timeline finding and its replies in one row at the finding time", () => {
556 const events = buildPullRequestTimeline({
557 ...TIMELINE_SOURCE,
558 comments,
559 reviewThreads: [thread],
560 });
561 expect(events.map((event) => event.id)).toEqual(["c1", "finding", "1baf7bdcafe", "created"]);
562 expect(events[1]).toMatchObject({
563 id: finding.id,
564 at: finding.createdAt,
565 body: finding.body,
566 url: finding.url,
567 thread: {
568 path: thread.path,
569 line: 7,
570 isOutdated: true,
571 replies: [
572 { id: reply.id, body: reply.body, url: reply.url, reactions: reply.reactions },
573 { id: lastReply.id, body: lastReply.body, url: lastReply.url },
574 ],
575 },
576 });
577 expect(groupPullRequestTimelineConversations(events).map((row) => row.kind)).toEqual([
578 "comments",
579 "event",
580 "event",
581 "event",
582 ]);
583 expect(events[0]).toEqual(buildPullRequestTimeline(TIMELINE_SOURCE)[0]);
584 });
585
586 it("orders and pages whole Summary conversations while retaining editable comment copies", () => {
587 const earlier = { ...loose, id: "earlier", createdAt: "2026-07-01T00:00:00Z" };
588 const items = pullRequestConversationItems([earlier, ...comments], [thread]);
589 expect(orderPullRequestComments(items, "oldest").map((item) => item.id)).toEqual([
590 "earlier",
591 "thread",
592 "c1",
593 ]);
594 expect(orderPullRequestComments(items, "newest").map((item) => item.id)).toEqual([
595 "c1",
596 "thread",
597 "earlier",
598 ]);
599 const page = pagePullRequestConversationItems(items, 2);
600 expect(page.hidden).toBe(1);
601 const grouped = page.shown[0]!;
602 expect(grouped.createdAt).toBe(finding.createdAt);
603 expect(pullRequestConversationItemComments(grouped)).toEqual([finding, reply, lastReply]);
604 expect(pullRequestConversationItemComments(grouped)[0]).toBe(finding);
605 expect(pullRequestConversationItemComments(grouped)[1]).toBe(reply);
606 expect(pagePullRequestConversationItems(items, 1)).toEqual({ shown: [items[2]], hidden: 2 });
607 expect(pullRequestConversationItemComments(items[2]!)).toEqual([loose]);
608 expect(pullRequestConversationItems(comments, []).map((item) => item.id)).toEqual(
609 comments.map((entry) => entry.id),
610 );
611 });
612
613 it("filters whole conversations when any member matches, including resolved and dismissed reviews", () => {
614 const botOnly = { ...comment("bot-only", 7), author: bot };
615 const dismissed = {
616 ...comment("dismissed", 8),
617 kind: "review" as const,
618 reviewState: "DISMISSED",
619 };
620 const items = pullRequestConversationItems(
621 [...comments, botOnly, dismissed],
622 [thread, { ...thread, id: "bot-thread", comments: [botOnly] }],
623 );
624 const kept = filterPullRequestConversationItems(items, { bots: false, resolved: false });
625 expect(kept.map((item) => item.id)).toEqual(["thread", "c1"]);
626 expect(pullRequestConversationItemComments(kept[0]!)).toEqual([finding, reply, lastReply]);
627 expect(filterPullRequestConversationItems(items, { bots: true, resolved: true })).toEqual(
628 items,
629 );
630 const resolved = pullRequestConversationItems(comments, [{ ...thread, isResolved: true }]);
631 expect(
632 filterPullRequestConversationItems(resolved, { bots: true, resolved: false }).map(
633 (item) => item.id,
634 ),
635 ).toEqual(["c1"]);
636 expect(filterPullRequestConversationItems(resolved, { bots: false, resolved: true })).toEqual(
637 resolved,
638 );
639 });
640
641 it("keeps bot review verdicts when bot comments are hidden", () => {
642 const review = (id: string, reviewState: string) => ({
643 ...comment(id, 9),
644 author: bot,
645 kind: "review" as const,
646 reviewState,
647 });
648 const items = pullRequestConversationItems(
649 [
650 review("approved", "APPROVED"),
651 review("changes", "CHANGES_REQUESTED"),
652 review("commented", "COMMENTED"),
653 ],
654 [],
655 );
656 expect(
657 filterPullRequestConversationItems(items, { bots: false, resolved: false }).map(
658 (item) => item.id,
659 ),
660 ).toEqual(["approved", "changes"]);
661 });
662
663 it("distinguishes unloaded replies from complete threads, even when the host only supplies a cursor", () => {
664 const timeline = (reviewThread: PullRequestReviewThread) =>
665 buildPullRequestTimeline({
666 ...TIMELINE_SOURCE,
667 comments,
668 reviewThreads: [reviewThread],
669 }).find((event) => event.id === finding.id)?.thread;
670 expect(timeline({ ...thread, commentCount: 5 })).toMatchObject({
671 moreReplies: 2,
672 hasMoreReplies: true,
673 url: finding.url,
674 });
675 expect(timeline({ ...thread, nextCommentsCursor: "next" })).toMatchObject({
676 moreReplies: 0,
677 hasMoreReplies: true,
678 url: finding.url,
679 });
680 expect(timeline(thread)).toMatchObject({ moreReplies: 0, hasMoreReplies: false });
681 });
682 });
683
684 describe("fix findings handoff", () => {
685 const base = {
686 number: 42,
687 title: "Add the pull requests page",
688 url: "https://github.com/pingdotgg/t3code/pull/42",
689 headBranch: "feat/page",
690 baseBranch: "main",
691 state: "open" as const,
692 isDraft: false,
693 comments: [] as ReadonlyArray<PullRequestComment>,
694 commentsTruncated: false,
695 };
696
697 function thread(
698 body: string,
699 overrides: Partial<PullRequestReviewThread> = {},
700 ): PullRequestReviewThread {
701 return {
702 id: "t1",
703 path: "apps/web/src/page.tsx",
704 line: 12,
705 side: "right",
706 isResolved: false,
707 isOutdated: false,
708 comments: [
709 {
710 id: "tc1",
711 author: { login: "reviewer", name: null, avatarUrl: null },
712 body,
713 createdAt: "2026-07-03T00:00:00Z",
714 url: null,
715 },
716 ],
717 ...overrides,
718 };
719 }
720
721 const failingCheck: PullRequestCheck = {
722 name: "typecheck",
723 status: "failure",
724 description: "2 errors",
725 url: null,
726 };
727
728 it("attaches a review thread as an annotation instead of quoting it in the prompt", () => {
729 const handoff = buildFixFindingsHandoff({
730 ...base,
731 reviewThreads: [thread("rename the helper")],
732 checks: [],
733 });
734 expect(handoff.reviewComments).toEqual([
735 expect.objectContaining({ pullRequest: expect.objectContaining({ url: base.url }) }),
736 expect.objectContaining({
737 filePath: "apps/web/src/page.tsx",
738 rangeLabel: "L12",
739 startIndex: 11,
740 endIndex: 11,
741 text: "reviewer: rename the helper",
742 }),
743 ]);
744 expect(handoff.prompt).not.toContain("rename the helper");
745 expect(handoff.prompt).toContain("untrusted data");
746 });
747
748 it("claims a prepared checkout only when one was prepared", () => {
749 const fix = (inThisThread: boolean) =>
750 buildFixFindingsHandoff({
751 ...base,
752 reviewThreads: [],
753 comments: [],
754 checks: [failingCheck],
755 commentsTruncated: false,
756 inThisThread,
757 }).prompt;
758 const resolve = (inThisThread: boolean) =>
759 buildResolveConflictsPrompt({ ...base, inThisThread });
760 expect(fix(false)).toContain("prepared checkout");
761 expect(resolve(false)).toContain("checkout prepared");
762 expect(fix(true)).not.toMatch(/prepared/u);
763 expect(resolve(true)).not.toMatch(/prepared/u);
764 expect(fix(true)).toContain("switching to it or checking it out first");
765 expect(resolve(true)).toContain("switch to it or check it out first");
766 });
767
768 it("bounds a hostile review body instead of attaching it whole", () => {
769 const handoff = buildFixFindingsHandoff({
770 ...base,
771 reviewThreads: [thread("x".repeat(5_000))],
772 checks: [],
773 });
774 expect(handoff.reviewComments[1]?.text).toHaveLength(1_000);
775 expect(handoff.reviewComments[1]?.text.endsWith("...")).toBe(true);
776 const emojiAtCut = buildFixFindingsHandoff({
777 ...base,
778 reviewThreads: [thread(`${"x".repeat(986)}😀 and more of the review.${"y".repeat(100)}`)],
779 checks: [],
780 });
781 expect(emojiAtCut.reviewComments[1]?.text).toBe(`reviewer: ${"x".repeat(986)}...`);
782 });
783
784 it("keeps the newest threads and the failing checks when it has to cut", () => {
785 const handoff = buildFixFindingsHandoff({
786 ...base,
787 reviewThreads: Array.from({ length: 25 }, (_, index) =>
788 thread(`finding ${index}`, { id: `t${index}` }),
789 ),
790 checks: [failingCheck],
791 });
792 const texts = handoff.reviewComments.map((comment) => comment.text);
793 expect(texts).toHaveLength(20);
794 expect(texts.at(-1)).toBe("reviewer: finding 24");
795 expect(texts).not.toContain("reviewer: finding 0");
796 expect(handoff.prompt).toContain("typecheck");
797 expect(handoff.prompt).toContain("6 further findings were omitted");
798 });
799
800 it("names a GitLab merge request as one", () => {
801 const handoff = buildFixFindingsHandoff({
802 ...base,
803 title: "Add the page",
804 url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
805 reviewThreads: [],
806 checks: [],
807 });
808 expect(handoff.prompt).toContain("Fix the actionable findings on MR #42");
809 expect(handoff.prompt).toContain("The MR branch is `feat/page`");
810 expect(handoff.prompt).toContain("inspect the merge request and its failing checks");
811 expect(handoff.prompt).not.toMatch(/\bPR\b|pull request/u);
812 });
813 });
814
815 describe("findings that cannot be attached", () => {
816 const base = {
817 number: 42,
818 title: "Add the pull requests page",
819 url: "https://github.com/pingdotgg/t3code/pull/42",
820 headBranch: "feat/page",
821 baseBranch: "main",
822 state: "open" as const,
823 isDraft: false,
824 reviewThreads: [] as ReadonlyArray<PullRequestReviewThread>,
825 checks: [] as ReadonlyArray<PullRequestCheck>,
826 commentsTruncated: false,
827 };
828
829 const review: PullRequestComment = {
830 id: "r1",
831 kind: "review",
832 author: { login: "julius", name: null, avatarUrl: null },
833 body: "This breaks SSO auth, revert the middleware change.",
834 createdAt: "2026-07-01T00:00:00Z",
835 url: null,
836 path: null,
837 reviewState: "CHANGES_REQUESTED",
838 };
839
840 it("carries a review submitted with words but no line, which has nothing to attach to", () => {
841 const handoff = buildFixFindingsHandoff({ ...base, comments: [review] });
842
843 expect(handoff.reviewComments).toEqual([
844 expect.objectContaining({ pullRequest: expect.objectContaining({ url: base.url }) }),
845 ]);
846 expect(handoff.prompt).toContain("revert the middleware change");
847 expect(handoff.prompt).not.toContain("No unresolved review findings");
848 });
849
850 it("does not repeat a remark that was already attached as a thread", () => {
851 const attachedId = "t1c1";
852 const handoff = buildFixFindingsHandoff({
853 ...base,
854 reviewThreads: [
855 {
856 id: "t1",
857 path: "src/app.ts",
858 line: 12,
859 side: "right",
860 isResolved: false,
861 isOutdated: false,
862 comments: [
863 {
864 id: attachedId,
865 author: { login: "julius", name: null, avatarUrl: null },
866 body: "rename the helper",
867 createdAt: "2026-07-01T00:00:00Z",
868 url: null,
869 },
870 ],
871 },
872 ],
873 comments: [{ ...review, id: attachedId, kind: "review-comment", body: "rename the helper" }],
874 });
875
876 expect(handoff.reviewComments).toHaveLength(2);
877 expect(handoff.prompt).not.toContain("rename the helper");
878 });
879 });
880
881 describe("one finding handed over on its own", () => {
882 const base = {
883 number: 42,
884 title: "Add the pull requests page",
885 url: "https://github.com/pingdotgg/t3code/pull/42",
886 headBranch: "feat/page",
887 baseBranch: "main",
888 state: "open" as const,
889 isDraft: false,
890 };
891
892 const reviewThread: PullRequestReviewThread = {
893 id: "t1",
894 path: "apps/web/src/page.tsx",
895 line: 12,
896 side: "right",
897 isResolved: true,
898 isOutdated: false,
899 comments: [
900 {
901 id: "tc1",
902 author: { login: "reviewer", name: null, avatarUrl: null },
903 body: "rename the helper",
904 createdAt: "2026-07-03T00:00:00Z",
905 url: null,
906 },
907 ],
908 };
909
910 it("keeps the pull request chip free of ask instructions when a fix and an ask share a draft", () => {
911 const metadata = { ...base, state: "open" as const, isDraft: false };
912 const ask = buildAskAboutPullRequestHandoff(metadata);
913 for (const fix of [
914 buildFixFindingHandoff({ ...metadata, finding: { kind: "thread", thread: reviewThread } }),
915 buildFixFindingHandoff({
916 ...metadata,
917 finding: {
918 kind: "check",
919 check: { name: "lint", status: "failure", description: null, url: null },
920 },
921 }),
922 buildFixFindingHandoff({
923 ...metadata,
924 finding: {
925 kind: "comment",
926 comment: {
927 id: "review",
928 kind: "review",
929 reviewState: null,
930 author: null,
931 body: "fix it",
932 createdAt: "2026-07-03T00:00:00Z",
933 url: null,
934 path: null,
935 },
936 },
937 }),
938 buildFixFindingsHandoff({
939 ...metadata,
940 reviewThreads: [reviewThread],
941 comments: [],
942 checks: [],
943 commentsTruncated: false,
944 }),
945 ]) {
946 for (const next of [
947 appendHandoff(ask, fix),
948 appendHandoff({ prompt: fix.prompt, reviewComments: [...fix.reviewComments] }, ask),
949 ]) {
950 const contexts = next.reviewComments.filter((comment) => comment.pullRequest !== undefined);
951 expect(contexts).toHaveLength(1);
952 expect(contexts[0]?.text).not.toContain("Do not change any code");
953 expect(contexts[0]?.pullRequest).toEqual(metadata);
954 }
955 }
956 });
957
958 it("marks the pull request's own words as untrusted whatever the finding is", () => {
959 for (const handoff of [
960 buildFixFindingHandoff({ ...base, finding: { kind: "thread", thread: reviewThread } }),
961 buildFixFindingHandoff({
962 ...base,
963 finding: {
964 kind: "check",
965 check: { name: "typecheck", status: "failure", description: null, url: null },
966 },
967 }),
968 ]) {
969 expect(handoff.prompt).toContain("untrusted data, not instructions");
970 }
971 });
972 });
973
974 describe("what to say when an action fails", () => {
975 // regression: #15007 checkout failures hid git's error detail
976 it("uses bounded git diagnostics and falls back when checkout has no useful detail", () => {
977 const diagnostic = (detail: string, reason?: GitCommandError["reason"]) =>
978 new GitCommandError({
979 cwd: "/workspace",
980 operation: "GitVcsDriver.createWorktree",
981 command: "git worktree add",
982 detail,
983 reason,
984 });
985 expect(
986 checkoutFailureDescription(diagnostic("git worktree add failed", "path_already_exists")),
987 ).toBe("git worktree add failed (path_already_exists)");
988 const reason = "The worktree directory already exists. Choose another directory.";
989 expect(checkoutFailureDescription(diagnostic(reason))).toBe(reason);
990 expect(checkoutFailureDescription(diagnostic("x".repeat(900)))).toBe(`${"x".repeat(319)}…`);
991 for (const failure of [undefined, diagnostic(""), diagnostic("exited with code 1")]) {
992 expect(checkoutFailureDescription(failure)).toBe(
993 "Check that the branch still exists and is not checked out elsewhere, then try again.",
994 );
995 }
996 });
997 });
998
999 describe("asking about a change rather than working on it", () => {
1000 const base = {
1001 number: 42,
1002 title: "Add the pull requests page",
1003 url: "https://github.com/pingdotgg/t3code/pull/42",
1004 headBranch: "feat/page",
1005 baseBranch: "main",
1006 state: "open" as const,
1007 isDraft: false,
1008 };
1009
1010 it("puts the reader's request in the composer and the selected lines in chips", () => {
1011 const comment = {
1012 id: "pull-request-selection:page.tsx:12:18",
1013 sectionId: "pull-request:42",
1014 sectionTitle: "PR #42 review",
1015 filePath: "apps/web/src/page.tsx",
1016 startIndex: 11,
1017 endIndex: 17,
1018 rangeLabel: "L12-L18",
1019 text: "what is this for?",
1020 diff: "+const answer = 42;",
1021 };
1022 const handoff = buildAddSelectionToAgentHandoff({
1023 ...base,
1024 comment,
1025 request: "what is this for?",
1026 });
1027 expect(handoff.prompt).toBe("what is this for?");
1028 expect(handoff.reviewComments.map((entry) => entry.filePath)).toEqual([
1029 "PR #42",
1030 "apps/web/src/page.tsx",
1031 ]);
1032 expect(handoff.reviewComments[0]?.text).not.toContain("Do not change any code");
1033 expect(handoff.reviewComments[1]?.text).toBe("");
1034 });
1035
1036 it("keeps both pull requests when two repositories share a number", () => {
1037 const selection = (id: string, line = 12) => ({
1038 id,
1039 sectionId: "pull-request:42",
1040 sectionTitle: "PR #42 review",
1041 filePath: "apps/web/src/page.tsx",
1042 startIndex: line - 1,
1043 endIndex: line + 5,
1044 rangeLabel: `L${line}-L${line + 6}`,
1045 text: "",
1046 diff: "+const answer = 42;",
1047 });
1048 const otherUrl = "https://github.com/acme/other/pull/42";
1049 const first = buildAddSelectionToAgentHandoff({
1050 ...base,
1051 comment: selection("pull-request-selection:page.tsx:12:18"),
1052 request: "why?",
1053 });
1054 const second = buildAddSelectionToAgentHandoff({
1055 ...base,
1056 url: otherUrl,
1057 comment: selection("pull-request-selection:page.tsx:12:18"),
1058 request: "and here?",
1059 });
1060 const third = buildAddSelectionToAgentHandoff({
1061 ...base,
1062 comment: selection("pull-request-selection:page.tsx:20:26", 20),
1063 request: "and this other range in the first pull request?",
1064 });
1065 const draft = appendHandoff(
1066 appendHandoff(appendHandoff({ prompt: "", reviewComments: [] }, first), second),
1067 third,
1068 );
1069 expect(draft.reviewComments.map((comment) => comment.pullRequest?.url)).toEqual([
1070 base.url,
1071 undefined,
1072 otherUrl,
1073 undefined,
1074 undefined,
1075 ]);
1076 expect(
1077 draft.reviewComments
1078 .filter((comment) => comment.diff !== "")
1079 .map((comment) => {
1080 const record = reviewCommentContextRecord(comment);
1081 return projectComposerContextForProvider({
1082 text: formatComposerContextReference(record),
1083 records: [record],
1084 });
1085 }),
1086 ).toEqual([
1087 expect.stringContaining(base.url),
1088 expect.stringContaining(otherUrl),
1089 expect.stringContaining(base.url),
1090 ]);
1091 });
1092
1093 it("explains a GitLab merge request in its own term", () => {
1094 const handoff = buildExplainPullRequestHandoff({
1095 ...base,
1096 title: "Add the page",
1097 url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
1098 });
1099 expect(handoff.prompt).toBe("Explain this merge request.");
1100 expect(handoff.reviewComments[0]?.text).toContain("The merge request is #42");
1101 expect(handoff.reviewComments[0]?.text).not.toContain("pull request");
1102 expect(
1103 buildResolveConflictsPrompt({
1104 ...base,
1105 url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
1106 }),
1107 ).toMatch(/^MR #42 /u);
1108 });
1109 });
1110
1111 describe("adding a remark to the chat", () => {
1112 const pullRequest = {
1113 number: 42,
1114 url: "https://github.com/pingdotgg/t3code/pull/42",
1115 reviewThreads: [],
1116 };
1117 const remark = (id: string, body: string): PullRequestComment => ({
1118 id,
1119 kind: "issue-comment",
1120 author: { login: "octocat", name: null, avatarUrl: null },
1121 body,
1122 createdAt: "2026-07-03T00:00:00Z",
1123 url: null,
1124 path: null,
1125 reviewState: null,
1126 });
1127
1128 it("reads as the remark's author rather than as the pull request itself", () => {
1129 const context = buildPullRequestCommentContext(pullRequest, {
1130 kind: "comment",
1131 comment: remark("c1", "Why not reuse the existing parser?"),
1132 });
1133
1134 expect(context && reviewCommentContextLabel(context)).toBe("#42 @octocat comment");
1135 expect(context?.text).toBe("octocat: Why not reuse the existing parser?");
1136 });
1137
1138 it("keeps a review summary longer than a fix finding's bound whole", () => {
1139 const summary = `No critical issues. ${"One misplaced doc comment inline. ".repeat(80)}End.`;
1140 const context = buildPullRequestCommentContext(pullRequest, {
1141 kind: "comment",
1142 comment: remark("c1", summary),
1143 });
1144
1145 expect(context?.text).toBe(`octocat: ${summary.trim()}`);
1146 });
1147
1148 it("gives a GitHub review summary its link and the line comments it posted", () => {
1149 const url = "https://github.com/pingdotgg/t3code/pull/42";
1150 const review: PullRequestComment = {
1151 ...remark("r9", "One misplaced doc comment inline."),
1152 kind: "review",
1153 url: `${url}#pullrequestreview-9`,
1154 reviewState: "COMMENTED",
1155 };
1156 const lineComment = (id: string, reviewUrl: string, body: string) => ({
1157 id,
1158 author: { login: "octocat", name: null, avatarUrl: null },
1159 body,
1160 createdAt: "2026-07-03T00:00:00Z",
1161 url: `${url}#discussion_${id}`,
1162 reviewUrl,
1163 });
1164 const reviewThreads = [
1165 {
1166 id: "t1",
1167 path: "src/main.rs",
1168 line: 12,
1169 side: "right" as const,
1170 isResolved: false,
1171 isOutdated: false,
1172 comments: [
1173 lineComment("r1", `${url}#pullrequestreview-9`, "This doc comment belongs below."),
1174 lineComment("r2", `${url}#pullrequestreview-10`, "Moved."),
1175 ],
1176 },
1177 ];
1178
1179 expect(
1180 buildPullRequestCommentContext(
1181 { ...pullRequest, reviewThreads, reviewThreadsTruncated: false },
1182 { kind: "comment", comment: review },
1183 )?.text,
1184 ).toBe(
1185 [
1186 "octocat: One misplaced doc comment inline.",
1187 `Review: ${url}#pullrequestreview-9`,
1188 "Line comments in this review:\n\noctocat on `src/main.rs` line 12: This doc comment belongs below.",
1189 ].join("\n\n"),
1190 );
1191 expect(
1192 buildPullRequestCommentContext(
1193 { ...pullRequest, reviewThreadsTruncated: false },
1194 { kind: "comment", comment: review },
1195 )?.text,
1196 ).toBe(
1197 [
1198 "octocat: One misplaced doc comment inline.",
1199 `Review: ${url}#pullrequestreview-9`,
1200 "This review posted no line comments.",
1201 ].join("\n\n"),
1202 );
1203 // A failed or partial thread read must not read as a review with no line comments.
1204 expect(
1205 buildPullRequestCommentContext(
1206 { ...pullRequest, reviewThreadsTruncated: true },
1207 { kind: "comment", comment: review },
1208 )?.text,
1209 ).toBe(
1210 [
1211 "octocat: One misplaced doc comment inline.",
1212 `Review: ${url}#pullrequestreview-9`,
1213 "No line comments from this review were loaded.",
1214 "More may exist; see the review link.",
1215 ].join("\n\n"),
1216 );
1217
1218 const beforeContext = buildPullRequestCommentContext(
1219 {
1220 ...pullRequest,
1221 reviewThreads: reviewThreads.map((thread) => ({ ...thread, side: "left" as const })),
1222 reviewThreadsTruncated: false,
1223 },
1224 { kind: "comment", comment: review },
1225 )!;
1226 const beforeRecord = reviewCommentContextRecord(beforeContext);
1227 const beforePrompt = projectComposerContextForProvider({
1228 text: formatComposerContextReference(beforeRecord),
1229 records: [beforeRecord],
1230 });
1231 expect(beforePrompt).toContain("`src/main.rs` line 12 (before)");
1232
1233 const sent = reviewCommentContextRecord(
1234 buildPullRequestCommentContext(
1235 { ...pullRequest, reviewThreads, reviewThreadsTruncated: false },
1236 { kind: "comment", comment: { ...review, body: `Summary ${"x".repeat(15_990)}` } },
1237 )!,
1238 ).text;
1239 expect(sent).toContain(`Review: ${url}#pullrequestreview-9`);
1240 expect(sent).toContain("This doc comment belongs below.");
1241 expect(sent).toContain("more characters of the review summary are omitted");
1242 });
1243
1244 it("keeps every added remark when a later hand-off lands", () => {
1245 const added = ["c1", "c2"].flatMap(
1246 (id) =>
1247 buildPullRequestCommentContext(pullRequest, {
1248 kind: "comment",
1249 comment: remark(id, "why?"),
1250 }) ?? [],
1251 );
1252 const handedOff = buildAskAboutPullRequestHandoff({
1253 number: 42,
1254 title: "Add the pull requests page",
1255 url: "https://github.com/pingdotgg/t3code/pull/42",
1256 headBranch: "feature",
1257 baseBranch: "main",
1258 state: "open",
1259 isDraft: false,
1260 });
1261
1262 expect(
1263 appendHandoff({ prompt: "", reviewComments: added }, handedOff).reviewComments.map(
1264 (comment) => comment.id,
1265 ),
1266 ).toEqual([
1267 "pr-comment:https://github.com/pingdotgg/t3code/pull/42:comment:c1",
1268 "pr-comment:https://github.com/pingdotgg/t3code/pull/42:comment:c2",
1269 "pull-request-context:https://github.com/pingdotgg/t3code/pull/42",
1270 ]);
1271 });
1272
1273 it("drops a bot's bookkeeping so it cannot crowd the remark out of the bound", () => {
1274 const context = buildPullRequestCommentContext(pullRequest, {
1275 kind: "comment",
1276 comment: remark(
1277 "c1",
1278 `<!-- ${"state".repeat(400)} -->\nThis leaks the token.\n\n\`\`\`html\n<!-- kept -->\n\`\`\``,
1279 ),
1280 });
1281
1282 expect(context?.text).toBe("octocat: This leaks the token.\n\n```html\n<!-- kept -->\n```");
1283 });
1284
1285 it("keeps comments inside a quoted fence as code", () => {
1286 const context = buildPullRequestCommentContext(pullRequest, {
1287 kind: "comment",
1288 comment: remark("c1", "> ```html\n> <!-- open\n> ```\n> Quoted. <!-- bot -->\nMine."),
1289 });
1290
1291 expect(context?.text).toBe("octocat: > ```html\n> <!-- open\n> ```\n> Quoted. \nMine.");
1292 });
1293
1294 it("holds a fence open over a deeper quoted fence and closes it with its blockquote", () => {
1295 const nested = buildPullRequestCommentContext(pullRequest, {
1296 kind: "comment",
1297 comment: remark("c1", "```md\n> ```\n<!-- kept -->\n```\nMine. <!-- bot -->"),
1298 });
1299 const unquoted = buildPullRequestCommentContext(pullRequest, {
1300 kind: "comment",
1301 comment: remark("c2", "> ```\n> code\nMine. <!-- bot -->"),
1302 });
1303
1304 expect(nested?.text).toBe("octocat: ```md\n> ```\n<!-- kept -->\n```\nMine.");
1305 expect(unquoted?.text).toBe("octocat: > ```\n> code\nMine.");
1306 });
1307
1308 it("keeps a fence written inside a hidden comment hidden", () => {
1309 const context = buildPullRequestCommentContext(pullRequest, {
1310 kind: "comment",
1311 comment: remark("c1", '<!-- state\n```json\n{"secret": 1}\n```\n-->\nLooks good.'),
1312 });
1313
1314 expect(context?.text).toBe("octocat: Looks good.");
1315 });
1316
1317 it("closes a fence written with CRLF line endings", () => {
1318 const context = buildPullRequestCommentContext(pullRequest, {
1319 kind: "comment",
1320 comment: remark("c1", "```ts\r\nconst x = 1;\r\n```\r\n<!-- bot -->\r\nRename x."),
1321 });
1322
1323 expect(context?.text).toBe("octocat: ```ts\nconst x = 1;\n```\nRename x.");
1324 });
1325
1326 it("reads inline code at the start of a line as prose, not as a fence", () => {
1327 const context = buildPullRequestCommentContext(pullRequest, {
1328 kind: "comment",
1329 comment: remark("c1", "```x``` is unused <!-- bot -->\nRemove it."),
1330 });
1331
1332 expect(context?.text).toBe("octocat: ```x``` is unused \nRemove it.");
1333 });
1334
1335 it("keeps remarks from two repositories apart when their host ids match", () => {
1336 const other = { ...pullRequest, url: "https://github.com/octocat/fork/pull/42" };
1337 const ids = [pullRequest, other].map(
1338 (target) =>
1339 buildPullRequestCommentContext(target, { kind: "comment", comment: remark("c1", "why?") })
1340 ?.id,
1341 );
1342
1343 expect(new Set(ids).size).toBe(2);
1344 });
1345
1346 it("brings nothing for a remark an unfinished comment hides", () => {
1347 expect(
1348 buildPullRequestCommentContext(pullRequest, {
1349 kind: "comment",
1350 comment: remark("c1", "<!-- bot state left open"),
1351 }),
1352 ).toBeNull();
1353 });
1354
1355 it("brings nothing for a remark with no words in it", () => {
1356 expect(
1357 buildPullRequestCommentContext(pullRequest, {
1358 kind: "comment",
1359 comment: remark("c1", "<!-- bot bookkeeping -->"),
1360 }),
1361 ).toBeNull();
1362 });
1363
1364 it("brings nothing for a conversation with no words in it", () => {
1365 const {
1366 kind: _kind,
1367 path: _path,
1368 reviewState: _reviewState,
1369 ...bookkeeping
1370 } = remark("tc1", "<!-- bot bookkeeping -->");
1371 expect(
1372 buildPullRequestCommentContext(pullRequest, {
1373 kind: "thread",
1374 thread: {
1375 id: "t1",
1376 path: "src/app.ts",
1377 line: 3,
1378 side: "right",
1379 isResolved: false,
1380 isOutdated: false,
1381 comments: [bookkeeping],
1382 },
1383 }),
1384 ).toBeNull();
1385 });
1386 });
1387
1388 describe("a second handoff into the same composer", () => {
1389 const chip = (id: string): ReviewCommentContext => ({
1390 id,
1391 sectionId: "pull-request:42",
1392 sectionTitle: "PR #42",
1393 filePath: "PR #42",
1394 startIndex: 0,
1395 endIndex: 0,
1396 rangeLabel: "Add the pull requests page",
1397 text: "",
1398 diff: "",
1399 });
1400 const ids = (comments: ReadonlyArray<ReviewCommentContext>) => comments.map((c) => c.id);
1401
1402 it("keeps the earlier findings and their chips", () => {
1403 const next = appendHandoff(
1404 {
1405 prompt: "Fix the first finding.",
1406 reviewComments: [chip("pull-request-finding:t1")],
1407 },
1408 { prompt: "Fix the second finding.", reviewComments: [chip("pull-request-finding:t2")] },
1409 );
1410 expect(next.prompt).toBe("Fix the first finding.\n\nFix the second finding.");
1411 expect(ids(next.reviewComments)).toEqual([
1412 "pull-request-finding:t1",
1413 "pull-request-finding:t2",
1414 ]);
1415 });
1416
1417 it("keeps earlier diff selections when another is added", () => {
1418 const next = appendHandoff(
1419 {
1420 prompt: "why this?",
1421 reviewComments: [
1422 chip("pull-request-context:42"),
1423 chip("pull-request-selection:page.tsx:1:2"),
1424 ],
1425 },
1426 {
1427 prompt: "and this?",
1428 reviewComments: [
1429 chip("pull-request-context:42"),
1430 chip("pull-request-selection:page.tsx:8:9"),
1431 ],
1432 },
1433 );
1434 expect(next.prompt).toBe("why this?\n\nand this?");
1435 expect(ids(next.reviewComments)).toEqual([
1436 "pull-request-context:42",
1437 "pull-request-selection:page.tsx:1:2",
1438 "pull-request-selection:page.tsx:8:9",
1439 ]);
1440 });
1441
1442 it("swaps in the newer copy of a chip it already holds", () => {
1443 const stale = { ...chip("pull-request-context:42"), text: "Explain only." };
1444 const fresh = { ...chip("pull-request-context:42"), text: "" };
1445 const next = appendHandoff(
1446 { prompt: "Explain this pull request.", reviewComments: [stale, chip("file-comment:3")] },
1447 { prompt: "why this?", reviewComments: [fresh] },
1448 );
1449 expect(next.reviewComments).toEqual([fresh, chip("file-comment:3")]);
1450 });
1451
1452 it("preserves a multiline request even when its lines already occur in the draft", () => {
1453 const prompt = "keep this line\nchange the middle\nkeep this line";
1454 const incoming = "keep this line\nnew middle\nkeep this line";
1455 expect(appendHandoff({ prompt, reviewComments: [] }, { prompt: incoming }).prompt).toBe(
1456 `${prompt}\n\n${incoming}`,
1457 );
1458 const reordered = "change the middle\nkeep this line";
1459 expect(appendHandoff({ prompt, reviewComments: [] }, { prompt: reordered }).prompt).toBe(
1460 `${prompt}\n\n${reordered}`,
1461 );
1462 });
1463
1464 it("changes nothing when the same handoff lands twice", () => {
1465 const handoff = {
1466 prompt: "Fix the review finding attached to this message. \nThe pull request is #42.",
1467 reviewComments: [chip("pull-request-finding:t1")],
1468 };
1469 const once = appendHandoff({ prompt: "", reviewComments: [] }, handoff);
1470 expect(appendHandoff(once, handoff)).toEqual(once);
1471 });
1472
1473 it("keeps each finding prompt intact, including its preamble", () => {
1474 const preamble = "The pull request is #42.\nIts branch is `feature`.";
1475 const next = appendHandoff(
1476 {
1477 prompt: `Fix the review remark quoted below.\n${preamble}\n> reviewer: rename it`,
1478 reviewComments: [],
1479 },
1480 { prompt: `Fix the review remark quoted below.\n${preamble}\n> reviewer: add a test` },
1481 );
1482 expect(next.prompt).toBe(
1483 `Fix the review remark quoted below.\n${preamble}\n> reviewer: rename it\n\nFix the review remark quoted below.\n${preamble}\n> reviewer: add a test`,
1484 );
1485 });
1486
1487 it("keeps a second pull request's failing checks when they share a name", () => {
1488 const fixFindings = (number: number) =>
1489 buildFixFindingsHandoff({
1490 number,
1491 title: "Add the pull requests page",
1492 url: `https://github.com/pingdotgg/t3code/pull/${number}`,
1493 state: "open",
1494 isDraft: false,
1495 headBranch: `feat/${number}`,
1496 baseBranch: "main",
1497 reviewThreads: [],
1498 comments: [],
1499 checks: [{ name: "lint", status: "failure", description: null, url: null }],
1500 commentsTruncated: false,
1501 });
1502 const first = appendHandoff({ prompt: "", reviewComments: [] }, fixFindings(42)).prompt;
1503 const both = appendHandoff({ prompt: first, reviewComments: [] }, fixFindings(43)).prompt;
1504 expect(both.slice(first.length)).toContain("Failing checks:\n> lint");
1505 });
1506
1507 it("keeps what the reader typed, trailing line breaks aside", () => {
1508 expect(
1509 appendHandoff(
1510 { prompt: "check the migration first\n", reviewComments: [chip("file-comment:3")] },
1511 { prompt: "", reviewComments: [chip("pull-request-context:42")] },
1512 ),
1513 ).toEqual({
1514 prompt: "check the migration first\n",
1515 reviewComments: [chip("file-comment:3"), chip("pull-request-context:42")],
1516 });
1517 expect(
1518 appendHandoff(
1519 { prompt: "check the migration first\n", reviewComments: [] },
1520 { prompt: "Explain this pull request.", reviewComments: [] },
1521 ).prompt,
1522 ).toBe("check the migration first\n\nExplain this pull request.");
1523 });
1524 });
1525
1526 describe("how the branch stands against its base", () => {
1527 const detail = (overrides: Record<string, unknown> = {}) =>
1528 ({
1529 state: "open",
1530 mergeability: "mergeable",
1531 baseComparison: "behind",
1532 behindBy: 12,
1533 capabilities: { updateMethods: ["merge", "rebase"] },
1534 viewerPermissions: { updateMethods: ["merge", "rebase"] },
1535 ...overrides,
1536 }) as Parameters<typeof resolveBaseFreshness>[0];
1537
1538 it("says nothing where the host could not compare, rather than claiming it is current", () => {
1539 expect(resolveBaseFreshness(detail({ baseComparison: "unknown" }))).toBeNull();
1540 expect(resolveBaseFreshness(detail({ baseComparison: undefined }))).toBeNull();
1541 });
1542
1543 it("narrows to what this reader may actually take", () => {
1544 expect(
1545 resolveBaseFreshness(detail({ viewerPermissions: { updateMethods: ["merge"] } }))?.methods,
1546 ).toEqual(["merge"]);
1547 });
1548 });
1549
1550 describe("pull request panel context beside a thread", () => {
1551 const link = (
1552 number: number,
1553 overrides: Partial<ThreadPullRequestLink> = {},
1554 ): ThreadPullRequestLink => ({
1555 host: "github.com",
1556 repository: "pingdotgg/t3code",
1557 number,
1558 url: `https://github.com/pingdotgg/t3code/pull/${number}`,
1559 source: "manual",
1560 linkedAt: "2026-09-09T00:00:00Z",
1561 snapshot: null,
1562 stack: null,
1563 ...overrides,
1564 });
1565 const surface = (
1566 number: number,
1567 overrides: Partial<Parameters<typeof pullRequestPanelContext>[1]> = {},
1568 ) => ({
1569 projectId: "proj-a",
1570 host: "github.com",
1571 repository: "pingdotgg/t3code",
1572 number,
1573 ...overrides,
1574 });
1575 const stackThread = {
1576 projectId: "proj-a",
1577 pullRequests: [
1578 link(10856),
1579 link(10832, { source: "stack" }),
1580 link(10677, { source: "stack" }),
1581 link(10854, { source: "stack" }),
1582 link(10855, { source: "stack" }),
1583 ],
1584 linkedPullRequest: {
1585 projectId: "proj-a",
1586 repository: "pingdotgg/t3code",
1587 number: 10856,
1588 url: "https://github.com/pingdotgg/t3code/pull/10856",
1589 },
1590 };
1591
1592 it("treats every layer of the thread's stack as its own, not only the one the legacy field names", () => {
1593 for (const number of [10856, 10832, 10677, 10854, 10855]) {
1594 expect(pullRequestPanelContext(stackThread, surface(number)), `#${number}`).toBe("thread");
1595 }
1596 });
1597
1598 it("does not let the legacy field decide when the thread holds a link list", () => {
1599 const thread = {
1600 projectId: "proj-a",
1601 pullRequests: [link(11101, { source: "created" }), link(11105, { source: "stack" })],
1602 linkedPullRequest: {
1603 projectId: "proj-a",
1604 repository: "pingdotgg/t3code",
1605 number: 11105,
1606 url: "https://github.com/pingdotgg/t3code/pull/11105",
1607 },
1608 };
1609 expect(pullRequestPanelContext(thread, surface(11101))).toBe("thread");
1610 expect(pullRequestPanelContext(thread, surface(11105))).toBe("thread");
1611 expect(pullRequestPanelContext({ ...thread, linkedPullRequest: null }, surface(11101))).toBe(
1612 "thread",
1613 );
1614 });
1615
1616 // regression: #12320 PR panel actions escaped the current thread
1617 it("is the page for a pull request the thread is not linked to", () => {
1618 expect(pullRequestPanelContext(stackThread, surface(12320))).toBe("page");
1619 expect(pullRequestPanelContext(stackThread, surface(10856, { repository: "acme/web" }))).toBe(
1620 "page",
1621 );
1622 });
1623
1624 // regression: #12320 PR panel actions escaped the current thread
1625 it("is the page under another project's checkout of the same repository", () => {
1626 expect(pullRequestPanelContext(stackThread, surface(10856, { projectId: "proj-b" }))).toBe(
1627 "page",
1628 );
1629 });
1630
1631 it("recognizes an unsynced manual link, and matches host and repository case-insensitively", () => {
1632 const thread = { projectId: "proj-a", pullRequests: [link(7, { host: "GitHub.com" })] };
1633 expect(pullRequestPanelContext(thread, surface(7, { repository: "PingDotGG/T3Code" }))).toBe(
1634 "thread",
1635 );
1636 expect(pullRequestPanelContext(thread, surface(7, { host: undefined }))).toBe("thread");
1637 expect(pullRequestPanelContext(thread, surface(7, { host: "gitlab.com" }))).toBe("page");
1638 });
1639
1640 it("ignores a dismissed stack member the reader chose not to see", () => {
1641 const thread = {
1642 projectId: "proj-a",
1643 pullRequests: [link(1), link(2, { source: "stack-dismissed" })],
1644 };
1645 expect(pullRequestPanelContext(thread, surface(2))).toBe("page");
1646 });
1647
1648 it("falls back to the legacy fields only for a thread with no link list", () => {
1649 const legacy = {
1650 projectId: "proj-a",
1651 repository: "pingdotgg/t3code",
1652 number: 3,
1653 url: "https://github.com/pingdotgg/t3code/pull/3",
1654 };
1655 expect(
1656 pullRequestPanelContext({ projectId: "proj-a", linkedPullRequest: legacy }, surface(3)),
1657 ).toBe("thread");
1658 expect(
1659 pullRequestPanelContext({ projectId: "proj-a", branchPullRequest: legacy }, surface(3)),
1660 ).toBe("thread");
1661 expect(pullRequestPanelContext({ projectId: "proj-a", pullRequests: [] }, surface(3))).toBe(
1662 "page",
1663 );
1664 expect(pullRequestPanelContext({ projectId: null }, surface(3))).toBe("page");
1665 });
1666
1667 describe("the Pull request entry's target", () => {
1668 const legacy = (number: number) => ({
1669 projectId: ProjectId.make("proj-a"),
1670 repository: "pingdotgg/t3code",
1671 number,
1672 url: `https://github.com/pingdotgg/t3code/pull/${number}`,
1673 });
1674
1675 it("opens a linked pull request the legacy field never named, ahead of the branch PR", () => {
1676 expect(
1677 threadPullRequestPanelTarget({
1678 projectId: "proj-a",
1679 pullRequests: [link(15046, { source: "agent" })],
1680 linkedPullRequest: null,
1681 branchPullRequest: legacy(30),
1682 }),
1683 ).toEqual({ ...legacy(15046), host: "github.com" });
1684 });
1685
1686 it("reuses the legacy reference only for the same pull request on the same host", () => {
1687 const linkedPullRequest = legacy(15046);
1688 const onHost = (host: string) =>
1689 threadPullRequestPanelTarget({
1690 projectId: "proj-a",
1691 pullRequests: [link(15046, { host, url: `https://${host}/pingdotgg/t3code/pull/15046` })],
1692 linkedPullRequest,
1693 });
1694 expect(onHost("github.com")).toBe(linkedPullRequest);
1695 expect(onHost("github.example.com")).toMatchObject({ host: "github.example.com" });
1696 });
1697
1698 // regression: #15061 Pull request panel entry ignored the branch PR
1699 it("falls back to the branch pull request when the thread holds no link", () => {
1700 expect(
1701 threadPullRequestPanelTarget({ projectId: "proj-a", branchPullRequest: legacy(3) }),
1702 ).toEqual(legacy(3));
1703 expect(threadPullRequestPanelTarget({ projectId: "proj-a", pullRequests: [] })).toBeNull();
1704 });
1705 });
1706 });
1707
1708 describe("when the source branch can be deleted", () => {
1709 const branchDetail = (
1710 state: PullRequestState,
1711 overrides: { deleteBranch?: boolean; allowed?: boolean } = {},
1712 ) => ({
1713 state,
1714 capabilities: {
1715 deleteBranch: overrides.deleteBranch ?? true,
1716 actions: ["delete-branch" as const],
1717 },
1718 viewerPermissions: {
1719 actions: overrides.allowed === false ? [] : (["delete-branch"] as const),
1720 },
1721 });
1722
1723 it("needs both the host capability and the viewer's permission", () => {
1724 expect(canDeletePullRequestBranch(branchDetail("merged", { deleteBranch: false }))).toBe(false);
1725 expect(canDeletePullRequestBranch(branchDetail("merged", { allowed: false }))).toBe(false);
1726 });
1727 });
1728
1729 describe("the compact row's single action slot", () => {
1730 const check = (status: PullRequestCheck["status"]): PullRequestCheck => ({
1731 name: "ci",
1732 status,
1733 description: null,
1734 url: null,
1735 });
1736 const openDetail = (
1737 overrides: Partial<Parameters<typeof resolveThreadPanelPullRequestAction>[0] & object> = {},
1738 ) =>
1739 ({
1740 state: "open",
1741 isDraft: false,
1742 mergeability: "mergeable",
1743 capabilities: {
1744 actions: ["merge", "ready", "draft", "close", "reopen"],
1745 mergeMethods: ["merge", "squash"],
1746 } as unknown as PullRequestDetailView["capabilities"],
1747 viewerPermissions: {
1748 actions: ["merge", "ready", "draft", "close", "reopen"],
1749 } as unknown as PullRequestDetailView["viewerPermissions"],
1750 mergeCapabilities: { merge: true, squash: true, rebase: false },
1751 checks: [check("success")],
1752 ...overrides,
1753 }) as NonNullable<Parameters<typeof resolveThreadPanelPullRequestAction>[0]>;
1754
1755 it("holds the slot while checks run rather than offering a merge that races them", () => {
1756 expect(
1757 resolveThreadPanelPullRequestAction(
1758 openDetail({ checks: [check("success"), check("pending")] }),
1759 ),
1760 ).toBeNull();
1761 expect(
1762 resolveThreadPanelPullRequestAction(openDetail({ checks: [check("action-required")] })),
1763 ).toBeNull();
1764 });
1765
1766 it("ranks conflicts above everything, then draft, then failing checks", () => {
1767 expect(
1768 resolveThreadPanelPullRequestAction(
1769 openDetail({ mergeability: "conflicting", isDraft: true, checks: [check("failure")] }),
1770 ),
1771 ).toBe("resolve");
1772 expect(
1773 resolveThreadPanelPullRequestAction(
1774 openDetail({ isDraft: true, checks: [check("failure")] }),
1775 ),
1776 ).toBe("ready");
1777 expect(
1778 resolveThreadPanelPullRequestAction(
1779 openDetail({ checks: [check("failure"), check("pending")] }),
1780 ),
1781 ).toBe("fix");
1782 });
1783
1784 it("offers nothing the viewer may not do, and nothing on settled pull requests", () => {
1785 expect(
1786 resolveThreadPanelPullRequestAction(
1787 openDetail({
1788 viewerPermissions: {
1789 actions: [],
1790 } as unknown as PullRequestDetailView["viewerPermissions"],
1791 }),
1792 ),
1793 ).toBeNull();
1794 expect(resolveThreadPanelPullRequestAction(openDetail({ state: "merged" }))).toBeNull();
1795 expect(resolveThreadPanelPullRequestAction(null)).toBeNull();
1796 });
1797 });
1798
1799 describe("cached pull request detail", () => {
1800 const reference = { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 7 };
1801 const detail = (overrides: Partial<PullRequestDetail> = {}): PullRequestDetail =>
1802 ({
1803 provider: SourceControlProviderKind.make("github"),
1804 capabilities: {
1805 diff: true,
1806 comment: true,
1807 actions: ["merge"],
1808 mergeMethods: ["merge"],
1809 search: true,
1810 review: {
1811 inlineComment: true,
1812 reply: true,
1813 resolve: true,
1814 verdicts: ["comment", "approve", "request-changes"],
1815 },
1816 reviewers: { request: true, listCandidates: true },
1817 },
1818 viewerPermissions: {
1819 actions: ["merge"],
1820 comment: true,
1821 resolve: true,
1822 verdicts: ["comment", "approve", "request-changes"],
1823 requestReviewers: true,
1824 },
1825 projectId: "project-1",
1826 projectTitle: "web",
1827 workspaceRoot: "/repo",
1828 repository: "acme/web",
1829 number: 7,
1830 title: "Cache the title",
1831 body: "who made it",
1832 url: "https://github.com/acme/web/pull/7",
1833 author: { login: "octocat", name: null, avatarUrl: "https://avatars.example/octocat" },
1834 state: "open",
1835 isDraft: false,
1836 mergeability: "mergeable",
1837 additions: 12,
1838 deletions: 3,
1839 changedFiles: 2,
1840 headBranch: "feat/cache",
1841 baseBranch: "main",
1842 createdAt: "2026-07-01T00:00:00.000Z",
1843 updatedAt: "2026-07-02T00:00:00.000Z",
1844 mergedAt: null,
1845 closedAt: null,
1846 reviewers: [],
1847 labels: [],
1848 checks: [],
1849 mergeCapabilities: { merge: true, squash: true, rebase: true },
1850 ...overrides,
1851 }) as PullRequestDetail;
1852
1853 const makeStorage = () => {
1854 const held = new Map<string, string>();
1855 return {
1856 getItem: (key: string) => held.get(key) ?? null,
1857 setItem: (key: string, value: string) => void held.set(key, value),
1858 removeItem: (key: string) => void held.delete(key),
1859 size: () => held.size,
1860 };
1861 };
1862
1863 it("keeps only the 20 most recently saved pull requests", () => {
1864 const storage = makeStorage();
1865 const numbered = (number: number) => ({ ...reference, number });
1866 for (let number = 1; number <= 21; number += 1) {
1867 writePullRequestDetailSnapshot(storage, "env-1", numbered(number), detail({ number }));
1868 }
1869 expect(readPullRequestDetailSnapshot(storage, "env-1", numbered(1))).toBeNull();
1870 expect(readPullRequestDetailSnapshot(storage, "env-1", numbered(2))?.number).toBe(2);
1871 expect(readPullRequestDetailSnapshot(storage, "env-1", numbered(21))?.number).toBe(21);
1872 expect(storage.size()).toBe(21);
1873 });
1874
1875 it("saving a pull request again keeps it as the newest without growing the list", () => {
1876 const storage = makeStorage();
1877 const numbered = (number: number) => ({ ...reference, number });
1878 for (let number = 1; number <= 20; number += 1) {
1879 writePullRequestDetailSnapshot(storage, "env-1", numbered(number), detail({ number }));
1880 }
1881 writePullRequestDetailSnapshot(storage, "env-1", numbered(1), detail({ number: 1 }));
1882 writePullRequestDetailSnapshot(storage, "env-1", numbered(21), detail({ number: 21 }));
1883 expect(readPullRequestDetailSnapshot(storage, "env-1", numbered(1))?.number).toBe(1);
1884 expect(readPullRequestDetailSnapshot(storage, "env-1", numbered(2))).toBeNull();
1885 expect(storage.size()).toBe(21);
1886 });
1887
1888 it("reuses a host-qualified snapshot when reopening a thread link without a host", () => {
1889 const storage = makeStorage();
1890 writePullRequestDetailSnapshot(
1891 storage,
1892 "env-1",
1893 { ...reference, host: "github.com" },
1894 detail(),
1895 );
1896 const resolved = resolvePullRequestReferenceHost(reference, {
1897 canonicalKey: "github.com/acme/web",
1898 locator: {
1899 source: "git-remote",
1900 remoteName: "origin",
1901 remoteUrl: "https://github.com/acme/web.git",
1902 },
1903 provider: SourceControlProviderKind.make("github"),
1904 });
1905 expect(readPullRequestDetailSnapshot(storage, "env-1", resolved)?.title).toBe(
1906 "Cache the title",
1907 );
1908 const explicit = { ...reference, host: "github.example.com" };
1909 expect(
1910 resolvePullRequestReferenceHost(explicit, {
1911 canonicalKey: "github.com/acme/web",
1912 locator: {
1913 source: "git-remote",
1914 remoteName: "origin",
1915 remoteUrl: "https://github.com/acme/web.git",
1916 },
1917 }),
1918 ).toBe(explicit);
1919 });
1920
1921 it("hydrates legacy hostless snapshots only for the matching host", () => {
1922 const storage = makeStorage();
1923 writePullRequestDetailSnapshot(storage, "env-1", reference, detail());
1924 expect(
1925 readPullRequestDetailSnapshot(storage, "env-1", { ...reference, host: "github.com" })?.title,
1926 ).toBe("Cache the title");
1927 expect(
1928 readPullRequestDetailSnapshot(storage, "env-1", {
1929 ...reference,
1930 host: "github.example.com",
1931 }),
1932 ).toBeNull();
1933 });
1934
1935 it("keeps Forgejo ports isolated when recovering legacy snapshots", () => {
1936 const storage = makeStorage();
1937 const cached = detail({
1938 provider: SourceControlProviderKind.make("forgejo"),
1939 url: "https://forge.example:8443/acme/web/pulls/7",
1940 });
1941 writePullRequestDetailSnapshot(storage, "env-1", reference, cached);
1942 const resolved = { ...reference, host: "forge.example:8443" };
1943 expect(readPullRequestDetailSnapshot(storage, "env-1", resolved)?.title).toBe(cached.title);
1944 expect(
1945 readPullRequestDetailSnapshot(storage, "env-1", {
1946 ...reference,
1947 host: "forge.example:9443",
1948 }),
1949 ).toBeNull();
1950 expect(
1951 readPullRequestDetailSnapshot(storage, "env-1", {
1952 ...reference,
1953 host: "forge.example",
1954 }),
1955 ).toBeNull();
1956 });
1957
1958 // regression: #12168 cached PR details were missed across entry points on custom ports
1959 it.each(["github", "gitlab"] as const)(
1960 "retains portless %s snapshot identities for custom web ports",
1961 (providerName) => {
1962 const provider = SourceControlProviderKind.make(providerName);
1963 const storage = makeStorage();
1964 const host = `${provider}.example.com`;
1965 const hosted = { ...reference, host };
1966 const cached = detail({
1967 provider,
1968 url: `https://${host}:8443/acme/web/${provider === "github" ? "pull" : "-/merge_requests"}/7`,
1969 });
1970 writePullRequestDetailSnapshot(storage, "env-1", hosted, cached);
1971 expect(readPullRequestDetailSnapshot(storage, "env-1", hosted)?.title).toBe(cached.title);
1972 },
1973 );
1974
1975 it("does not paint another change request's snapshot", () => {
1976 expect(
1977 resolveDisplayedPullRequestDetail({
1978 live: null,
1979 cached: detail({ number: 8 }),
1980 reference,
1981 }),
1982 ).toBeNull();
1983 expect(readPullRequestDetailSnapshot(makeStorage(), "env-2", reference)).toBeNull();
1984 });
1985
1986 it("isolates stored and displayed details between hosts with the same repository and number", () => {
1987 const storage = makeStorage();
1988 const publicRef = { ...reference, host: "github.com" };
1989 const enterpriseRef = { ...reference, host: "ghe.example.com" };
1990 const publicDetail = detail();
1991 const enterpriseDetail = detail({
1992 title: "Enterprise change",
1993 url: "https://ghe.example.com/acme/web/pull/7",
1994 });
1995 writePullRequestDetailSnapshot(storage, "env-1", publicRef, publicDetail);
1996 expect(readPullRequestDetailSnapshot(storage, "env-1", enterpriseRef)).toBeNull();
1997 writePullRequestDetailSnapshot(storage, "env-1", enterpriseRef, enterpriseDetail);
1998 expect(readPullRequestDetailSnapshot(storage, "env-1", publicRef)?.title).toBe(
1999 publicDetail.title,
2000 );
2001 expect(readPullRequestDetailSnapshot(storage, "env-1", enterpriseRef)?.title).toBe(
2002 enterpriseDetail.title,
2003 );
2004 expect(
2005 resolveDisplayedPullRequestDetail({
2006 live: null,
2007 cached: publicDetail,
2008 reference: enterpriseRef,
2009 }),
2010 ).toBeNull();
2011 expect(
2012 resolveDisplayedPullRequestDetail({
2013 live: null,
2014 cached: enterpriseDetail,
2015 reference: enterpriseRef,
2016 }),
2017 ).toBe(enterpriseDetail);
2018 writePullRequestDetailSnapshot(storage, "env-1", enterpriseRef, publicDetail);
2019 expect(readPullRequestDetailSnapshot(storage, "env-1", enterpriseRef)).toBeNull();
2020 });
2021
2022 // regression: #9294 corrupt cached PR chrome broke reopening
2023 it("shrugs off corrupt storage and no storage at all", () => {
2024 const storage = makeStorage();
2025 storage.setItem("t3.pullRequests.detail:env-1:project-1:acme/web#7", "{not json");
2026 expect(readPullRequestDetailSnapshot(storage, "env-1", reference)).toBeNull();
2027 expect(readPullRequestDetailSnapshot(undefined, "env-1", reference)).toBeNull();
2028 const hosted = { ...reference, host: "github.com" };
2029 writePullRequestDetailSnapshot(storage, "env-1", hosted, detail({ url: "invalid url" }));
2030 expect(readPullRequestDetailSnapshot(storage, "env-1", hosted)).toBeNull();
2031 });
2032 });
2033
2034 describe("single-PR merge compatibility during stack discovery", () => {
2035 it.each([
2036 [false, true, false, null, true],
2037 [false, false, true, null, true],
2038 [true, false, true, null, false],
2039 [true, false, false, "Lookup failed", false],
2040 [true, true, false, null, false],
2041 [true, false, false, null, true],
2042 ] as const)(
2043 "capability=%s stack=%s pending=%s error=%s permits=%s",
2044 (supportsStackActions, hasStack, stackPending, stackError, allowed) => {
2045 expect(
2046 allowsSinglePullRequestMerge({ supportsStackActions, hasStack, stackPending, stackError }),
2047 ).toBe(allowed);
2048 },
2049 );
2050 });
2051
2052 describe("readableFailure", () => {
2053 it("replaces a host tool's bare failure with the hint, for every host", () => {
2054 for (const message of [
2055 "GitHub CLI failed.",
2056 "Azure DevOps API failed",
2057 "Forgejo command failed",
2058 ]) {
2059 expect(readableFailure(new Error(message), "Try again.")).toBe("Try again.");
2060 }
2061 expect(readableFailure(new Error("Branch is protected."), "Try again.")).toBe(
2062 "Branch is protected.",
2063 );
2064 });
2065 });