Open History to see the last commit
1import { scopedProjectKey } from "@t3tools/client-runtime/environment";
2import {
3 AuthOrchestrationOperateScope,
4 AuthSourceControlWriteScope,
5 EnvironmentId,
6 ProjectId,
7 SourceControlProviderKind,
8 ThreadId,
9 type PullRequestDetailView,
10} from "@t3tools/contracts";
11import { expect, it, vi } from "vite-plus/test";
12import { page, userEvent } from "vite-plus/test/browser";
13import appCss from "~/index.css?inline";
14import { BackgroundThreadContext } from "~/components/chat/backgroundThread";
15import { ToastProvider } from "~/components/ui/toast";
16import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
17import { isMacPlatform } from "~/lib/utils";
18import { act, fakeTimers, render } from "../../../test/render";
19
20const { command, newThread, permissions, prepareThread, reads, shown } = vi.hoisted(() => ({
21 command: vi.fn(),
22 newThread: vi.fn(),
23 permissions: { checkout: true, operate: true },
24 prepareThread: vi.fn(),
25 reads: { diff: [] as unknown[] },
26 shown: { detail: null as PullRequestDetailView | null },
27}));
28
29vi.mock(import("~/hooks/useHandleNewThread"), () => ({
30 useNewThreadHandler: (() => newThread) as never,
31}));
32vi.mock(import("~/state/session"), async (original) => ({
33 ...(await original()),
34 useEnvironmentScope: (_environmentId: unknown, scope: unknown) =>
35 scope === AuthOrchestrationOperateScope ? permissions.operate : permissions.checkout,
36 readEnvironmentScope: (_environmentId: unknown, scope: unknown) =>
37 scope === AuthOrchestrationOperateScope ? permissions.operate : permissions.checkout,
38}));
39vi.mock(import("~/state/sourceControlActions"), async (original) => ({
40 ...(await original()),
41 usePreparePullRequestThreadAction: (() => ({
42 isAllowed: permissions.checkout,
43 run: prepareThread,
44 error: null,
45 })) as never,
46}));
47vi.mock(import("./usePullRequestDetail"), async (original) => ({
48 ...(await original()),
49 usePullRequestDetail: (() => ({
50 canWriteSourceControl: permissions.checkout,
51 detailQuery: { isPending: false, refresh: vi.fn() },
52 activityQuery: { isPending: false, refresh: vi.fn(), error: null },
53 activity: null,
54 sharedSummary: shown.detail,
55 coreDetail: shown.detail,
56 detail: shown.detail,
57 })) as never,
58}));
59vi.mock(import("~/state/usePullRequestStack"), async (original) => ({
60 ...(await original()),
61 usePullRequestStack: (() => ({
62 data: null,
63 isFresh: true,
64 isPending: false,
65 error: null,
66 refresh: vi.fn(),
67 })) as never,
68}));
69vi.mock(import("~/state/pullRequests"), async (original) => {
70 const actual = await original();
71 return {
72 ...actual,
73 pullRequestEnvironment: {
74 ...actual.pullRequestEnvironment,
75 diff: ((target: unknown) => {
76 reads.diff.push(target);
77 return actual.pullRequestEnvironment.diff(target as never);
78 }) as never,
79 },
80 };
81});
82vi.mock(import("~/state/use-atom-command"), async (original) => ({
83 ...(await original()),
84 useAtomCommand: (() => command) as never,
85}));
86
87import { createWorkspaceFocusController, workspaceAreaProps } from "~/lib/workspaceFocus";
88import { CommandDialog, CommandDialogPopup } from "../ui/command";
89import { useGuideRunStore } from "./guide/guideRunStore";
90import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
91
92const detail: PullRequestDetailView = {
93 provider: SourceControlProviderKind.make("github"),
94 projectId: ProjectId.make("project"),
95 projectTitle: "Project",
96 workspaceRoot: "/workspace",
97 repository: "owner/repo",
98 number: 1,
99 title: "Test pull request",
100 body: "Original description",
101 url: "https://github.com/owner/repo/pull/1",
102 author: { login: "author", name: null, avatarUrl: null },
103 viewer: "author",
104 state: "open",
105 isDraft: false,
106 mergeability: "conflicting",
107 additions: 1,
108 deletions: 0,
109 changedFiles: 1,
110 headBranch: "feature",
111 baseBranch: "main",
112 createdAt: "2026-09-01T00:00:00Z",
113 updatedAt: "2026-09-01T00:00:00Z",
114 mergedAt: null,
115 closedAt: null,
116 reviewers: [],
117 labels: [],
118 checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
119 comments: [],
120 commentCount: 0,
121 commentsTruncated: false,
122 reviewThreads: [],
123 commits: [],
124 mergeCapabilities: { merge: false, squash: false, rebase: false },
125 capabilities: {
126 diff: true,
127 comment: false,
128 search: true,
129 actions: [],
130 mergeMethods: [],
131 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
132 reviewers: { request: false, listCandidates: false },
133 edit: { changeRequest: true, comment: false },
134 },
135 viewerPermissions: {
136 actions: [],
137 comment: false,
138 resolve: false,
139 verdicts: [],
140 requestReviewers: false,
141 },
142};
143
144const environmentId = EnvironmentId.make("environment");
145const draftId = DraftId.make("conflicts-draft");
146const panel = (attach = false, reference = detail, shortcutsEnabled = false, tabOnPage = false) => (
147 <PullRequestDetailPanel
148 environmentId={environmentId}
149 reference={reference}
150 context="page"
151 tabOnPage={tabOnPage}
152 shortcutsEnabled={shortcutsEnabled}
153 getShortcutContext={() => ({
154 terminalFocus: false,
155 terminalOpen: false,
156 previewFocus: false,
157 previewOpen: false,
158 isWeb: true,
159 isDesktop: false,
160 })}
161 {...(attach ? { composerDraftTarget: draftId } : {})}
162 />
163);
164
165function setup() {
166 permissions.checkout = true;
167 permissions.operate = true;
168 reads.diff = [];
169 shown.detail = detail;
170 command.mockReset();
171 newThread.mockReset();
172 prepareThread.mockReset();
173 useComposerDraftStore.setState({ draftsByThreadKey: {} });
174 useGuideRunStore.setState(useGuideRunStore.getInitialState());
175}
176
177it.each([AuthSourceControlWriteScope, AuthOrchestrationOperateScope])(
178 "disables conflict checkout when the connection loses %s",
179 async (scope) => {
180 setup();
181 await using screen = await render(panel());
182 const resolve = screen.getByRole("button", { name: "Resolve conflicts" });
183 await expect.element(resolve).toBeEnabled();
184 if (scope === AuthSourceControlWriteScope) permissions.checkout = false;
185 else permissions.operate = false;
186 await screen.rerender(panel());
187 await expect.element(resolve).toBeDisabled();
188 },
189);
190
191it("can still add conflict resolution to an existing composer without checkout scopes", async () => {
192 setup();
193 permissions.checkout = false;
194 permissions.operate = false;
195 await using screen = await render(panel(true));
196 const resolve = screen.getByRole("button", { name: "Resolve conflicts" });
197 await expect.element(resolve).toBeEnabled();
198 await act(() => resolve.click());
199 const draft = useComposerDraftStore.getState().getComposerDraft(draftId);
200 expect(draft?.prompt).toContain("conflicts");
201 expect(draft?.prompt).toContain(detail.url);
202});
203
204it("keeps a merge and a review on the head the reader was shown until they load new commits", async () => {
205 setup();
206 command.mockResolvedValue({ _tag: "Success", value: undefined });
207 const at = (headSha: string): PullRequestDetailView => ({
208 ...detail,
209 headSha,
210 mergeability: "mergeable",
211 mergeCapabilities: { merge: false, squash: true, rebase: false },
212 capabilities: {
213 ...detail.capabilities,
214 actions: ["merge"],
215 mergeMethods: ["squash"],
216 review: { ...detail.capabilities.review, verdicts: ["approve"] },
217 },
218 viewerPermissions: { ...detail.viewerPermissions, actions: ["merge"], verdicts: ["approve"] },
219 });
220 const sent = (key: "action" | "verdict") =>
221 command.mock.calls.flatMap(([call]) =>
222 call?.input?.[key] === undefined ? [] : [call.input.expectedHeadSha],
223 );
224 const merge = async () => {
225 await screen.getByRole("button", { name: "Squash and merge" }).click();
226 await screen.getByRole("button", { name: "Confirm merge?" }).click();
227 };
228 shown.detail = at("shown-head");
229 await using screen = await render(panel());
230 await expect.element(screen.getByRole("button", { name: "Squash and merge" })).toBeVisible();
231 // A background refresh brings a push the reader has not looked at.
232 shown.detail = at("pushed-head");
233 await screen.rerender(panel());
234 await expect.element(screen.getByText(/still applies to shown-h/)).toBeVisible();
235 await merge();
236 await screen.getByRole("button", { name: "Review pull request" }).click();
237 // The composer popup is portalled outside the rendered tree.
238 await page.getByRole("button", { name: "Submit review" }).click();
239 await vi.waitFor(() => expect(sent("verdict")).toEqual(["shown-head"]));
240 expect(sent("action")).toEqual(["shown-head"]);
241
242 // The pin moves once the reload has been asked of the host, not at the click.
243 const reload = Promise.withResolvers<{ _tag: "Success"; value: undefined }>();
244 command.mockImplementation((call) =>
245 call?.input?.reference === undefined
246 ? Promise.resolve({ _tag: "Success", value: undefined })
247 : reload.promise,
248 );
249 await screen.getByRole("button", { name: "Load new commits" }).click();
250 await merge();
251 await vi.waitFor(() => expect(sent("action")).toEqual(["shown-head", "shown-head"]));
252 reload.resolve({ _tag: "Success", value: undefined });
253 await expect.element(screen.getByText(/still applies to/)).not.toBeInTheDocument();
254 await merge();
255 await vi.waitFor(() =>
256 expect(sent("action")).toEqual(["shown-head", "shown-head", "pushed-head"]),
257 );
258});
259
260it("reads the first diff page once the pointer rests on the Code tab", async () => {
261 setup();
262 await using screen = await render(panel());
263 using _timers = fakeTimers({ now: 0 });
264 const code = screen.getByRole("button", { name: "Code", exact: true });
265 await expect.element(code).toBeVisible();
266
267 // userEvent advances fake timers while it runs (vitest#11242), blurring the 150 ms boundary.
268 await act(() => code.element().dispatchEvent(new PointerEvent("pointerover", { bubbles: true })));
269 await act(() => vi.advanceTimersByTime(149));
270 expect(reads.diff).toEqual([]);
271 await act(() => vi.advanceTimersByTime(1));
272 // The page the Code tab reads first, keyed as the tab keys it, so a click paints from it.
273 expect(reads.diff).toContainEqual({
274 environmentId,
275 input: { projectId: detail.projectId, repository: detail.repository, number: detail.number },
276 });
277});
278
279it("keeps a screen reader's place when scrolling the description condenses the header", async () => {
280 setup();
281 shown.detail = {
282 ...detail,
283 body: Array.from({ length: 80 }, (_, line) => `Line ${line}`).join("\n\n"),
284 };
285 const style = document.createElement("style");
286 style.textContent = appCss;
287 document.head.append(style);
288 using _style = { [Symbol.dispose]: () => style.remove() };
289 const controller = createWorkspaceFocusController(document);
290 using _controller = { [Symbol.dispose]: () => controller.dispose() };
291 await using screen = await render(
292 <div {...workspaceAreaProps("pull-requests", 1)} className="flex h-[600px] flex-col">
293 {panel()}
294 </div>,
295 );
296 const openOnHost = screen.getByRole("button", { name: "Open pull request #1 on host" });
297 await expect.element(openOnHost).toBeVisible();
298 const expanded = openOnHost.element() as HTMLButtonElement;
299 expanded.focus();
300 await expect.element(screen.getByText("Line 79")).toBeInTheDocument();
301 let scroller = screen.getByText("Line 79").element().parentElement;
302 while (scroller && getComputedStyle(scroller).overflowY !== "auto") {
303 scroller = scroller.parentElement;
304 }
305 using _timers = fakeTimers();
306 using moves = vi.spyOn(HTMLElement.prototype, "focus");
307 // Browse mode scrolls a heading into view without moving DOM focus.
308 await act(() => {
309 scroller!.scrollTop = scroller!.scrollHeight;
310 });
311 await vi.waitFor(() => expect(expanded.closest("[inert]")).not.toBeNull());
312 await act(() => vi.advanceTimersToNextFrame());
313 // A programmatic focus() pulls the screen reader's browse cursor back to the header.
314 expect(moves).not.toHaveBeenCalled();
315});
316
317it("leaves the copy-number shortcut alone in background threads and keybinding capture fields", async () => {
318 setup();
319 const received: boolean[] = [];
320 const mod = isMacPlatform(navigator.platform) ? "Meta" : "Control";
321 const shortcut = `{${mod}>}{Shift>}K{/Shift}{/${mod}}`;
322 const onKeyDown = (event: { key: string; defaultPrevented: boolean }) => {
323 if (event.key.toLowerCase() === "k") received.push(event.defaultPrevented);
324 };
325 const view = (background: boolean) => (
326 <>
327 <BackgroundThreadContext value={background}>
328 {panel(false, detail, true)}
329 </BackgroundThreadContext>
330 <input aria-label="Keybinding" data-keybinding-capture="" readOnly onKeyDown={onKeyDown} />
331 <button type="button" onKeyDown={onKeyDown}>
332 Outside
333 </button>
334 </>
335 );
336
337 await using screen = await render(view(false));
338 using write = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue(undefined);
339 const outside = screen.getByRole("button", { name: "Outside" });
340 const capture = screen.getByRole("textbox", { name: "Keybinding" });
341
342 await userEvent.click(outside);
343 await userEvent.keyboard(shortcut);
344 await vi.waitFor(() => expect(write).toHaveBeenCalledWith("#1"));
345 expect(received).toEqual([]);
346
347 write.mockClear();
348 await userEvent.click(capture);
349 await userEvent.keyboard(shortcut);
350 expect(write).not.toHaveBeenCalled();
351 expect(received).toEqual([false]);
352
353 await screen.rerender(view(true));
354 await userEvent.click(outside);
355 await userEvent.keyboard(shortcut);
356 expect(write).not.toHaveBeenCalled();
357 expect(received).toEqual([false, false]);
358});
359
360it("keeps each pull request's selected detail tab when switching pull requests on the page", async () => {
361 setup();
362 const pr1: PullRequestDetailView = { ...detail, number: 101 };
363 const pr2: PullRequestDetailView = { ...detail, number: 102 };
364 const show = (pr: PullRequestDetailView) => {
365 shown.detail = pr;
366 return <div key={pr.number}>{panel(false, pr, false, true)}</div>;
367 };
368
369 await using screen = await render(show(pr1));
370 const tabButton = (name: "Summary" | "Timeline" | "Code") =>
371 screen.getByRole("button", { name, exact: true });
372 await expect.element(tabButton("Summary")).toHaveAttribute("aria-pressed", "true");
373 await tabButton("Code").click();
374 await expect.element(tabButton("Code")).toHaveAttribute("aria-pressed", "true");
375
376 await screen.rerender(show(pr2));
377 await expect.element(tabButton("Summary")).toHaveAttribute("aria-pressed", "true");
378 await tabButton("Timeline").click();
379 await expect.element(tabButton("Timeline")).toHaveAttribute("aria-pressed", "true");
380
381 await screen.rerender(show(pr1));
382 await expect.element(tabButton("Code")).toHaveAttribute("aria-pressed", "true");
383
384 await screen.rerender(show(pr2));
385 await expect.element(tabButton("Timeline")).toHaveAttribute("aria-pressed", "true");
386});
387
388it("closes the pull request composer when a command dialog opens and keeps the draft", async () => {
389 setup();
390 shown.detail = {
391 ...detail,
392 capabilities: { ...detail.capabilities, comment: true },
393 viewerPermissions: { ...detail.viewerPermissions, comment: true },
394 };
395 const view = (dialogOpen: boolean) => (
396 <>
397 {panel()}
398 <CommandDialog open={dialogOpen}>
399 <CommandDialogPopup aria-label="Command palette" />
400 </CommandDialog>
401 </>
402 );
403 await using screen = await render(view(false));
404
405 const trigger = page.getByRole("button", { name: "Comment on pull request" });
406 await userEvent.click(trigger);
407 const commentField = page.getByLabelText("Comment on this pull request");
408 await expect.element(commentField).toBeVisible();
409 await userEvent.type(commentField, "Draft comment check");
410 await expect.element(commentField).toHaveValue("Draft comment check");
411
412 await screen.rerender(view(true));
413 await vi.waitFor(() => {
414 const composer = document.querySelector('[aria-label="Pull request composer"]');
415 expect(composer).not.toBeNull();
416 expect(composer).not.toHaveAttribute("data-open");
417 });
418
419 await screen.rerender(view(false));
420 await vi.waitFor(() => {
421 expect(document.querySelector('[data-slot="command-dialog-popup"]')).toBeNull();
422 });
423 await userEvent.click(trigger);
424 await expect.element(commentField).toBeVisible();
425 await expect.element(commentField).toHaveValue("Draft comment check");
426});
427
428it("stops a detail-panel checkout handoff when its loading toast is dismissed", async () => {
429 setup();
430 const checkoutDraftId = DraftId.make("detail-dismiss-draft");
431 const checkoutThreadId = ThreadId.make("detail-dismiss-thread");
432 const prepared = Promise.withResolvers<{
433 _tag: "Success";
434 value: {
435 branch: string;
436 worktreePath: string;
437 isOnPullRequestHead: boolean;
438 pullRequest: { url: string };
439 };
440 }>();
441 newThread.mockImplementation(async (projectRef) => {
442 useComposerDraftStore
443 .getState()
444 .setLogicalProjectDraftThreadId(scopedProjectKey(projectRef), projectRef, checkoutDraftId, {
445 threadId: checkoutThreadId,
446 });
447 return { draftId: checkoutDraftId, threadId: checkoutThreadId };
448 });
449 prepareThread.mockReturnValueOnce(prepared.promise);
450
451 await using screen = await render(<ToastProvider>{panel()}</ToastProvider>);
452 const resolve = screen.getByRole("button", { name: "Resolve conflicts" });
453 await userEvent.click(resolve);
454 const toast = page.getByRole("dialog", { name: "Preparing the pull request checkout..." });
455 await expect.element(toast).toBeVisible();
456 await vi.waitFor(() => {
457 expect(prepareThread).toHaveBeenCalledTimes(1);
458 });
459 await userEvent.click(toast.getByText("Preparing the pull request checkout..."));
460 await expect.element(toast).toHaveFocus();
461 await userEvent.keyboard("{Escape}");
462 await expect.element(toast).not.toBeInTheDocument();
463
464 await act(async () => {
465 prepared.resolve({
466 _tag: "Success",
467 value: {
468 branch: "feature",
469 worktreePath: "/workspace-worktrees/feature",
470 isOnPullRequestHead: true,
471 pullRequest: { url: detail.url },
472 },
473 });
474 await prepared.promise;
475 });
476
477 await expect.element(resolve).toBeEnabled();
478 await vi.waitFor(() => {
479 expect(
480 useComposerDraftStore.getState().getDraftSession(checkoutDraftId)?.branch ?? null,
481 ).toBeNull();
482 expect(useComposerDraftStore.getState().getComposerDraft(checkoutDraftId)?.prompt ?? "").toBe(
483 "",
484 );
485 });
486});