Open History to see the last commit
1import type { EnvironmentProject } from "@t3tools/client-runtime/state/models";
2import {
3 EnvironmentId,
4 ProjectId,
5 SourceControlProviderKind,
6 type PullRequestListResult,
7} from "@t3tools/contracts";
8import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
9import { createRef, type RefObject, useState } from "react";
10import { page, userEvent } from "vite-plus/test/browser";
11import { describe, expect, it, vi } from "vite-plus/test";
12import { mergePullRequestLists, type MergedPullRequestList } from "./pullRequestList.logic";
13import type { PullRequestsSearch } from "./usePullRequestListView";
14
15const prPageState = vi.hoisted(() => ({
16 noop: () => {},
17 search: { involvement: "all", state: "open" } as PullRequestsSearch,
18 environments: {
19 environments: [
20 {
21 environmentId: "env-1",
22 label: "Local",
23 connection: { phase: "connected" },
24 serverConfig: {
25 environment: { capabilities: { pullRequests: true }, platform: { machine: "linux" } },
26 },
27 },
28 ],
29 },
30 projects: [] as ReadonlyArray<EnvironmentProject>,
31 hostList: {
32 data: {
33 entries: [],
34 providers: [] as PullRequestListResult["providers"],
35 viewers: {},
36 errors: [],
37 truncated: false,
38 nextCursors: {},
39 truncatedEnvironments: [],
40 refinedProjectKeys: new Set<string>(),
41 } as MergedPullRequestList,
42 error: null,
43 isPending: false,
44 observations: [],
45 refresh: () => {},
46 retry: () => {},
47 },
48 stats: {
49 stats: null,
50 isPending: false,
51 refresh: () => {},
52 },
53 turnRefreshes: [] as ReadonlyArray<never>,
54}));
55
56vi.mock(import("@tanstack/react-router"), async (original) => ({
57 ...(await original()),
58 useNavigate: (() => prPageState.noop) as never,
59 useSearch: (() => prPageState.search) as never,
60}));
61vi.mock(import("~/state/server"), async (original) => {
62 const { Atom } = await import("effect/reactivity");
63 return {
64 ...(await original()),
65 primaryServerKeybindingsAtom: Atom.make(DEFAULT_RESOLVED_KEYBINDINGS) as never,
66 };
67});
68vi.mock(import("~/state/environments"), async (original) => ({
69 ...(await original()),
70 useEnvironments: (() => prPageState.environments) as never,
71}));
72vi.mock(import("~/state/entities"), async (original) => ({
73 ...(await original()),
74 useProjects: () => prPageState.projects,
75 useAllEnvironmentShellsBootstrapped: () => true,
76}));
77vi.mock(import("~/state/pullRequests"), async (original) => ({
78 ...(await original()),
79 usePullRequestHostList: (() => prPageState.hostList) as never,
80 usePullRequestListStats: (() => prPageState.stats) as never,
81 usePullRequestTurnRefreshes: (() => prPageState.turnRefreshes) as never,
82 useSharedPullRequestSummary: () => null,
83}));
84
85import { act, render } from "../../../test/render";
86import {
87 PULL_REQUESTS_PANEL_REF,
88 selectThreadRightPanelState,
89 useRightPanelStore,
90} from "~/rightPanelStore";
91import { registerCommands } from "../../shortcuts/dispatcher";
92import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
93import { PullRequestChecksPopover } from "./PullRequestChecksPopover";
94import { PullRequestFiltersMenu, PullRequestSearchInput } from "./PullRequestListFilters";
95import { PullRequestsColumn } from "./PullRequestsColumn";
96import { PullRequestsPage } from "./PullRequestsPage";
97
98import "~/index.css";
99
100function createColumn(maximizedAway: boolean, scrollRef: RefObject<HTMLDivElement | null>) {
101 return (
102 <PullRequestsColumn
103 refreshing={false}
104 onRefresh={() => {}}
105 searchValue=""
106 involvement="all"
107 state="open"
108 host={undefined}
109 hostMenuOptions={[]}
110 onInvolvement={() => {}}
111 onState={() => {}}
112 onHost={() => {}}
113 searchInput={<input aria-label="Search pull requests" />}
114 sortMenu={null}
115 filtersMenu={null}
116 savedViewsMenu={null}
117 rightPanelControl={null}
118 titlebarControls={null}
119 rightPanelOpen={maximizedAway}
120 maximizedAway={maximizedAway}
121 listBody={null}
122 scrollRef={scrollRef}
123 />
124 );
125}
126
127function dispatchFindShortcut(target: EventTarget = window) {
128 const event = new KeyboardEvent("keydown", {
129 key: "f",
130 ctrlKey: true,
131 bubbles: true,
132 cancelable: true,
133 });
134 target.dispatchEvent(event);
135 return event;
136}
137
138describe("PullRequestsColumn find shortcut", () => {
139 it("leaves Cmd/Ctrl+F to the browser while the detail panel is maximized", async () => {
140 const scrollRef = createRef<HTMLDivElement>();
141 await using screen = await render(createColumn(false, scrollRef));
142
143 await screen.rerender(createColumn(true, scrollRef));
144 expect(dispatchFindShortcut().defaultPrevented).toBe(false);
145
146 await screen.rerender(createColumn(false, scrollRef));
147 expect(dispatchFindShortcut().defaultPrevented).toBe(true);
148 await expect
149 .element(screen.getByRole("textbox", { name: "Search pull requests" }))
150 .toHaveFocus();
151 });
152
153 it("ignores Cmd/Ctrl+F while a dialog is open", async () => {
154 const scrollRef = createRef<HTMLDivElement>();
155 await using screen = await render(
156 <>
157 {createColumn(false, scrollRef)}
158 <div role="dialog">
159 <input aria-label="View name" />
160 </div>
161 </>,
162 );
163 const dialogInput = screen.getByRole("textbox", { name: "View name" });
164 await userEvent.click(dialogInput);
165 expect(dispatchFindShortcut(dialogInput.element()).defaultPrevented).toBe(false);
166 await expect.element(dialogInput).toHaveFocus();
167 });
168
169 it("ignores Cmd/Ctrl+F while a menu is open", async () => {
170 const scrollRef = createRef<HTMLDivElement>();
171 await using screen = await render(
172 <>
173 {createColumn(false, scrollRef)}
174 <Menu>
175 <MenuTrigger>Sort</MenuTrigger>
176 <MenuPopup>
177 <MenuItem>Newest</MenuItem>
178 </MenuPopup>
179 </Menu>
180 </>,
181 );
182 await userEvent.click(screen.getByRole("button", { name: "Sort" }));
183 const menu = page.getByRole("menu");
184 await expect.element(menu).toHaveFocus();
185
186 expect(dispatchFindShortcut(menu.element()).defaultPrevented).toBe(false);
187 await expect.element(menu).toHaveFocus();
188 await expect
189 .element(screen.getByRole("textbox", { name: "Search pull requests" }))
190 .not.toHaveFocus();
191 });
192});
193
194function CondensedSearchColumn({
195 scrollRef,
196 onSubmit,
197}: {
198 scrollRef: RefObject<HTMLDivElement | null>;
199 onSubmit: (value: string) => void;
200}) {
201 const [query, setQuery] = useState("label:bug");
202 return (
203 <div style={{ display: "flex", height: 400 }}>
204 <PullRequestsColumn
205 refreshing={false}
206 onRefresh={() => {}}
207 searchValue={query}
208 involvement="all"
209 state="open"
210 host={undefined}
211 hostMenuOptions={[]}
212 onInvolvement={() => {}}
213 onState={() => {}}
214 onHost={() => {}}
215 searchInput={
216 <PullRequestSearchInput
217 value={query}
218 label="Search pull requests"
219 placeholder="Search pull requests"
220 onChange={setQuery}
221 onSubmit={onSubmit}
222 />
223 }
224 sortMenu={null}
225 filtersMenu={null}
226 savedViewsMenu={null}
227 rightPanelControl={null}
228 titlebarControls={null}
229 rightPanelOpen={false}
230 maximizedAway={false}
231 listBody={<div style={{ height: 2000 }} />}
232 scrollRef={scrollRef}
233 />
234 <button type="button">Elsewhere</button>
235 </div>
236 );
237}
238
239describe("PullRequestsColumn condensed search", () => {
240 it("Escape clears the topbar search before the page's Escape leaves", async () => {
241 const onSubmit = vi.fn();
242 const scrollRef = createRef<HTMLDivElement>();
243 await using _screen = await render(
244 <CondensedSearchColumn scrollRef={scrollRef} onSubmit={onSubmit} />,
245 );
246 // Mirrors the /pull-requests observer, which leaves on an unclaimed Escape.
247 const leave = vi.fn();
248 using stack = new DisposableStack();
249 stack.defer(
250 registerCommands(
251 {},
252 {
253 observe: (event, consumed) => {
254 if (!consumed && !event.repeat && !event.isComposing && event.key === "Escape") leave();
255 },
256 },
257 ),
258 );
259 scrollRef.current?.scrollTo({ top: 1000 });
260 const searches = page.getByRole("searchbox", { name: "Search pull requests" });
261 // The topbar copy comes first and mounts once the header condenses.
262 await expect.element(searches.nth(1)).toBeInTheDocument();
263 const search = searches.nth(0);
264 // Safari ends the composition just before the confirming keydown, reporting only keyCode 229.
265 const pressDuringComposition = (key: string) =>
266 act(() => {
267 for (const composition of [{ isComposing: true }, { keyCode: 229 }]) {
268 search.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true }));
269 search
270 .element()
271 .dispatchEvent(new KeyboardEvent("keydown", { key, ...composition, bubbles: true }));
272 }
273 });
274
275 await userEvent.click(search);
276 await pressDuringComposition("Enter");
277 await pressDuringComposition("Escape");
278 expect(onSubmit).not.toHaveBeenCalled();
279 expect(leave).not.toHaveBeenCalled();
280 await expect.element(search).toHaveValue("label:bug");
281
282 await userEvent.keyboard("{Escape}");
283 await expect.element(search).toHaveValue("");
284 await expect.element(search).toHaveFocus();
285 expect(leave).not.toHaveBeenCalled();
286
287 await userEvent.keyboard("{Escape}");
288 expect(leave).toHaveBeenCalledOnce();
289
290 await userEvent.click(page.getByRole("button", { name: "Elsewhere" }));
291 await expect
292 .element(page.getByRole("button", { name: "Search pull requests" }))
293 .toBeInTheDocument();
294 });
295});
296
297describe("PullRequestChecksPopover", () => {
298 it("keeps clicks inside the popover from selecting the parent row", async () => {
299 const onSelect = vi.fn();
300 await using screen = await render(
301 <button type="button" onClick={onSelect}>
302 <span>Open PR</span>
303 <PullRequestChecksPopover
304 checksState="failing"
305 checks={[
306 { name: "Lint", status: "failure", description: null, url: null },
307 { name: "Test", status: "success", description: null, url: null },
308 ]}
309 />
310 </button>,
311 );
312
313 await userEvent.click(
314 screen.getByRole("button", { name: "Checks: Some checks were not successful" }),
315 );
316 await userEvent.click(page.getByRole("button", { name: "Show all" }));
317 await expect.element(page.getByText("Test", { exact: true })).toBeInTheDocument();
318 expect(onSelect).not.toHaveBeenCalled();
319
320 await userEvent.keyboard("{Escape}");
321 await userEvent.click(screen.getByText("Open PR", { exact: true }));
322 expect(onSelect).toHaveBeenCalledOnce();
323 });
324});
325
326describe("PullRequestsPage shortcuts", () => {
327 it("ignores right panel shortcuts while a menu is open", async () => {
328 useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} });
329 useRightPanelStore.getState().openPullRequest(PULL_REQUESTS_PANEL_REF, {
330 environmentId: "env-1",
331 projectId: "project-1",
332 repository: "owner/repo",
333 number: 7,
334 });
335 using _cleanup = {
336 [Symbol.dispose]: () =>
337 useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} }),
338 };
339 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
340 await using screen = await render(<PullRequestsPage />);
341 const panelState = () =>
342 selectThreadRightPanelState(
343 useRightPanelStore.getState().byThreadKey,
344 PULL_REQUESTS_PANEL_REF,
345 );
346 await vi.waitFor(() => expect(panelState().isOpen).toBe(true));
347
348 await userEvent.click(screen.getByRole("button", { name: /^Sort pull requests:/ }));
349 const menu = page.getByRole("menu");
350 await expect.element(menu).toBeVisible();
351
352 await act(() => {
353 for (const init of [
354 { key: "b", ctrlKey: true, altKey: true },
355 { key: "w", ctrlKey: true },
356 ]) {
357 document.body.dispatchEvent(
358 new KeyboardEvent("keydown", { ...init, bubbles: true, cancelable: true }),
359 );
360 }
361 });
362
363 await expect.element(menu).toBeVisible();
364 await vi.waitFor(() => {
365 const panel = panelState();
366 expect(panel.isOpen).toBe(true);
367 expect(panel.surfaces).toHaveLength(1);
368 });
369 });
370});
371
372describe("PullRequestsPage host filter", () => {
373 it("keeps other workspace hosts in the provider menu when mounted with a saved host filter", async () => {
374 const previousSearch = prPageState.search;
375 const previousEnvironments = prPageState.environments.environments;
376 const previousProjects = prPageState.projects;
377 const previousData = prPageState.hostList.data;
378 const env1 = EnvironmentId.make("env-1");
379 const env2 = EnvironmentId.make("env-2");
380 const project = (
381 environmentId: EnvironmentId,
382 id: string,
383 title: string,
384 host: string,
385 provider: string,
386 ): EnvironmentProject => ({
387 id: ProjectId.make(id),
388 environmentId,
389 title,
390 workspaceRoot: `/tmp/${title}`,
391 defaultModelSelection: null,
392 scripts: [],
393 createdAt: "2026-01-01T00:00:00.000Z",
394 updatedAt: "2026-01-01T00:00:00.000Z",
395 repositoryIdentity: {
396 canonicalKey: `${host}/example/${title}`,
397 locator: {
398 source: "git-remote",
399 remoteName: "origin",
400 remoteUrl: `https://${host}/example/${title}.git`,
401 },
402 provider: SourceControlProviderKind.make(provider),
403 displayName: `example/${title}`,
404 },
405 });
406 const answer = (providers: PullRequestListResult["providers"]): PullRequestListResult => ({
407 entries: [],
408 providers,
409 viewers: {},
410 errors: [],
411 truncated: false,
412 nextCursors: {},
413 });
414 const githubSummary = (projectId: string): PullRequestListResult["providers"][number] => ({
415 host: "github.com",
416 kind: SourceControlProviderKind.make("github"),
417 searchesOnHost: true,
418 actions: ["close", "merge"],
419 projectCount: 1,
420 projectIds: [ProjectId.make(projectId)],
421 configured: true,
422 detail: null,
423 });
424 prPageState.environments.environments = [
425 ...previousEnvironments,
426 {
427 environmentId: "env-2",
428 label: "Remote",
429 connection: { phase: "connected" },
430 serverConfig: {
431 environment: { capabilities: { pullRequests: true }, platform: { machine: "linux" } },
432 },
433 },
434 ];
435 prPageState.search = { involvement: "all", state: "open", host: "github.com" };
436 prPageState.projects = [
437 project(env1, "project-1", "alpha", "github.com", "github"),
438 project(env1, "project-2", "beta", "gitlab.com", "gitlab"),
439 project(env1, "project-3", "work", "github-work", "github"),
440 project(env2, "project-1", "gamma", "dev.azure.com", "azure-devops"),
441 project(env2, "project-2", "other", "github-other", "github"),
442 ];
443 prPageState.hostList.data = mergePullRequestLists([
444 [env1, answer([githubSummary("project-3")])],
445 [env2, answer([githubSummary("project-2")])],
446 ])!;
447 using _restore = {
448 [Symbol.dispose]: () => {
449 prPageState.search = previousSearch;
450 prPageState.environments.environments = previousEnvironments;
451 prPageState.projects = previousProjects;
452 prPageState.hostList.data = previousData;
453 },
454 };
455
456 await using screen = await render(<PullRequestsPage />);
457
458 await userEvent.click(screen.getByRole("button", { name: "Filter by provider: GitHub" }));
459 await expect.element(page.getByRole("menuitemradio", { name: "GitHub" })).toBeVisible();
460 await expect.element(page.getByRole("menuitemradio", { name: "GitLab" })).toBeVisible();
461 await expect.element(page.getByRole("menuitemradio", { name: "Azure DevOps" })).toBeVisible();
462 await expect
463 .element(page.getByRole("menuitemradio", { name: "github-work" }))
464 .not.toBeInTheDocument();
465 await expect
466 .element(page.getByRole("menuitemradio", { name: "github-other" }))
467 .not.toBeInTheDocument();
468
469 await userEvent.keyboard("{Escape}");
470 prPageState.search = { involvement: "all", state: "open", host: "gitlab.com" };
471 prPageState.hostList.data = mergePullRequestLists([
472 [
473 env1,
474 answer([
475 {
476 host: "gitlab.com",
477 kind: SourceControlProviderKind.make("gitlab"),
478 searchesOnHost: true,
479 actions: ["close", "merge"],
480 projectCount: 1,
481 configured: true,
482 detail: null,
483 },
484 ]),
485 ],
486 ])!;
487 await screen.rerender(<PullRequestsPage />);
488
489 await userEvent.click(screen.getByRole("button", { name: "Filter by provider: GitLab" }));
490 await expect.element(page.getByRole("menuitemradio", { name: "GitHub" })).toBeVisible();
491 await expect.element(page.getByRole("menuitemradio", { name: "GitLab" })).toBeVisible();
492 await expect
493 .element(page.getByRole("menuitemradio", { name: "github-work" }))
494 .not.toBeInTheDocument();
495 await expect
496 .element(page.getByRole("menuitemradio", { name: "github-other" }))
497 .not.toBeInTheDocument();
498
499 await userEvent.keyboard("{Escape}");
500 prPageState.search = {
501 involvement: "all",
502 state: "open",
503 host: "github.com",
504 projectId: ProjectId.make("project-1"),
505 };
506 prPageState.hostList.data = mergePullRequestLists([
507 [env1, answer([githubSummary("project-1")])],
508 ])!;
509 await screen.rerender(<PullRequestsPage />);
510
511 await userEvent.click(screen.getByRole("button", { name: "Filter by provider: GitHub" }));
512 await expect.element(page.getByRole("menuitemradio", { name: "GitHub" })).toBeVisible();
513 await expect
514 .element(page.getByRole("menuitemradio", { name: "GitLab" }))
515 .not.toBeInTheDocument();
516 await expect
517 .element(page.getByRole("menuitemradio", { name: "Azure DevOps" }))
518 .not.toBeInTheDocument();
519
520 await userEvent.keyboard("{Escape}");
521 prPageState.search = {
522 involvement: "all",
523 state: "open",
524 host: "dev.azure.com",
525 environmentId: env2,
526 projectId: ProjectId.make("project-1"),
527 };
528 prPageState.hostList.data = mergePullRequestLists([[env2, answer([])]])!;
529 await screen.rerender(<PullRequestsPage />);
530
531 await userEvent.click(screen.getByRole("button", { name: "Filter by provider: Azure DevOps" }));
532 await expect.element(page.getByRole("menuitemradio", { name: "Azure DevOps" })).toBeVisible();
533 await expect
534 .element(page.getByRole("menuitemradio", { name: "GitHub" }))
535 .not.toBeInTheDocument();
536 });
537});
538
539describe("PullRequestFiltersMenu keyboard focus", () => {
540 it("focuses Author and Labels search inputs when opened from the keyboard", async () => {
541 const onFilters = vi.fn();
542 const Icon = () => null;
543 await using screen = await render(
544 <PullRequestFiltersMenu
545 state="open"
546 stateOptions={[{ value: "open", label: "Open", Icon }]}
547 onState={() => {}}
548 involvement="all"
549 involvementOptions={[{ value: "all", label: "All", Icon }]}
550 onInvolvement={() => {}}
551 filters={{}}
552 onFilters={onFilters}
553 authorOptions={[
554 { actor: { login: "alice", name: null, avatarUrl: null }, count: 1, mergedCount: 0 },
555 { actor: { login: "julius", name: null, avatarUrl: null }, count: 2, mergedCount: 2 },
556 ]}
557 labelOptions={[
558 { name: "bug", color: "d73a4a", count: 3 },
559 { name: "docs", color: "0075ca", count: 1 },
560 ]}
561 optionScope={[]}
562 host={undefined}
563 hostOptions={[]}
564 onHost={() => {}}
565 server={undefined}
566 serverOptions={[]}
567 onServer={() => {}}
568 projects={[]}
569 projectId={undefined}
570 projectEnvironmentId={undefined}
571 unavailable={new Map()}
572 onProject={() => {}}
573 />,
574 { router: false },
575 );
576
577 const filtersButton = screen.getByRole("button", { name: "Filters" });
578 filtersButton.element().focus();
579 await expect.element(filtersButton).toHaveFocus();
580 await userEvent.keyboard("{Enter}");
581
582 const authorTrigger = page.getByRole("menuitem", { name: /Author/ });
583 const labelsTrigger = page.getByRole("menuitem", { name: /Labels/ });
584 await expect.element(authorTrigger).toBeVisible();
585
586 await userEvent.keyboard("{ArrowDown}{ArrowDown}");
587 await expect.element(authorTrigger).toHaveFocus();
588 await userEvent.keyboard("{ArrowRight}");
589
590 const authorSearch = page.getByPlaceholder("Search authors");
591 await expect.element(authorSearch).toHaveFocus();
592
593 await userEvent.keyboard("{ArrowLeft}");
594 await expect.element(authorSearch).not.toBeInTheDocument();
595 await expect.element(authorTrigger).toHaveFocus();
596
597 await userEvent.keyboard("{ArrowRight}");
598 await expect.element(authorSearch).toHaveFocus();
599 await userEvent.keyboard("jul");
600 await expect.element(page.getByRole("menuitemradio", { name: /julius/ })).toBeVisible();
601 await expect
602 .element(page.getByRole("menuitemradio", { name: /alice/ }))
603 .not.toBeInTheDocument();
604
605 await userEvent.keyboard("{ArrowLeft}");
606 await vi.waitFor(() => {
607 expect((authorSearch.element() as HTMLInputElement).selectionStart).toBe(2);
608 });
609
610 await userEvent.keyboard("{ArrowDown}{ArrowDown}{Enter}");
611 await vi.waitFor(() => {
612 expect(onFilters).toHaveBeenLastCalledWith({ author: "julius" });
613 });
614
615 await userEvent.keyboard("{Escape}");
616 await expect.element(authorTrigger).toHaveFocus();
617
618 await userEvent.keyboard("{ArrowDown}");
619 await expect.element(labelsTrigger).toHaveFocus();
620 await userEvent.keyboard("{Enter}");
621
622 const labelsSearch = page.getByPlaceholder("Search labels");
623 await expect.element(labelsSearch).toHaveFocus();
624 await userEvent.keyboard("docs");
625 await expect.element(page.getByRole("menuitemcheckbox", { name: /docs/ })).toBeVisible();
626 await expect
627 .element(page.getByRole("menuitemcheckbox", { name: /bug/ }))
628 .not.toBeInTheDocument();
629
630 await userEvent.keyboard("{ArrowDown}{Enter}");
631 await vi.waitFor(() => {
632 expect(onFilters).toHaveBeenLastCalledWith({ labels: [["docs"]] });
633 });
634
635 await userEvent.keyboard("{Escape}");
636 await expect.element(labelsTrigger).toHaveFocus();
637 });
638});