@devries-cameron20 / t3code Mirror · read-only / commits / 35b056638f
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 22, 20:45 UTC

refactor(web): the pull requests route only validates its search; the page lives under components (#22706)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 21, 2026 at 01:28 UTC 35b056638f6daf23494a191307979913f5bafb63
2 files changed +1555 -1556
apps/web/src/components/pullRequest/PullRequestsPage.tsx new
+1548
@@ -0,0 +1,1548 @@
1 +import { applyPullRequestDraftFilterChange } from "@t3tools/client-runtime/pull-request-query";
2 +import { Spinner } from "~/components/ui/spinner";
3 +import type { PullRequestSpeedActionResult } from "~/components/pullRequest/PullRequestSpeedActions";
4 +import { usePullRequestCloseBatch } from "~/components/pullRequest/usePullRequestActions";
5 +import { SidebarPointerSensor } from "~/components/Sidebar.pointer";
6 +import { resolveSidebarSweepKeys } from "~/components/Sidebar.logic";
7 +import { sortProjectsByGroupOrder } from "@t3tools/client-runtime/state/project-grouping";
8 +import { pullRequestHostOf, resolveEnvironmentMachineKind } from "@t3tools/contracts";
9 +import type {
10 + EnvironmentId,
11 + ProjectId,
12 + PullRequestAction,
13 + PullRequestInvolvement,
14 + PullRequestListCursors,
15 + PullRequestListInput,
16 + PullRequestListResult,
17 + PullRequestListState,
18 + SourceControlProviderKind,
19 +} from "@t3tools/contracts";
20 +import { useAtomValue } from "@effect/atom-react";
21 +import { useNavigate, useSearch } from "@tanstack/react-router";
22 +import { ArrowDownUpIcon, LayersIcon, Plug2Icon } from "lucide-react";
23 +import { useEffect, useEffectEvent, useRef, useState, type ComponentProps } from "react";
24 +
25 +import {
26 + collectPullRequestListFacets,
27 + narrowPullRequestsToFilters,
28 + mergePullRequestDiffStats,
29 + pullRequestEntryKey,
30 + rankPullRequestMatches,
31 + readPullRequestListSnapshot,
32 + writePullRequestListSnapshot,
33 + pullRequestStatsRefreshBatches,
34 + pullRequestStatsRequestBatches,
35 + retainVisiblePullRequestStatsBatches,
36 + type EnvironmentPullRequestEntry,
37 + type MergedPullRequestList,
38 + type PullRequestDiffStats,
39 + type PullRequestStatsBatch,
40 + type PullRequestStatsPolicy,
41 + type PullRequestStatsScope,
42 + type PullRequestPartitionsSnapshot,
43 + type PullRequestListOverride,
44 + pullRequestOverrideAfterAction,
45 + reusePullRequestEntries,
46 + settlePullRequestOverrides,
47 + largestPullRequestReadCount,
48 +} from "./pullRequestList.logic";
49 +import {
50 + pullRequestListPreferences,
51 + type PullRequestListPreferencePatch,
52 + writePullRequestListPreferences,
53 +} from "./pullRequestListPreferences";
54 +import { environmentMachineIcon } from "../EnvironmentMachineIcon";
55 +import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
56 +import {
57 + PullRequestFiltersMenu,
58 + PullRequestSearchInput,
59 + pullRequestHostLabel,
60 + pullRequestProjectKey,
61 + type PullRequestFilterOption,
62 +} from "./PullRequestListFilters";
63 +import { PullRequestCompactFilterMenu } from "./PullRequestCompactFilterMenu";
64 +import { INVOLVEMENT_TABS, SORT_OPTIONS, STATE_TABS } from "./pullRequestListOptions";
65 +import { PullRequestsColumn } from "./PullRequestsColumn";
66 +import { PullRequestListGroups } from "./PullRequestListGroups";
67 +import {
68 + pullRequestGroups,
69 + pullRequestListEntryId,
70 + usePullRequestDisplayGroups,
71 + usePullRequestQueryFilters,
72 + usePullRequestScope,
73 + type PullRequestsSearch,
74 +} from "./usePullRequestListView";
75 +import { PullRequestListEmptyState } from "./PullRequestListEmptyState";
76 +import { PullRequestListGhost } from "./PullRequestGhosts";
77 +import { type PullRequestRowTarget } from "./PullRequestRow";
78 +import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";
79 +import { RightPanelTabs } from "../RightPanelTabs";
80 +import { isCommandPaletteOpen } from "~/commandPaletteBus";
81 +import { isElectron } from "~/env";
82 +import { resolveShortcutCommand, shortcutLabelForCommand } from "~/keybindings";
83 +import { isTerminalFocused } from "~/lib/terminalFocus";
84 +import { PanelLayoutControls, RightPanelMaximizeControl } from "../chat/PanelLayoutControls";
85 +import { Button } from "../ui/button";
86 +import { SidebarInset } from "../ui/sidebar";
87 +import { useLiveRefresh } from "~/hooks/useLiveRefresh";
88 +import { useStableCallback } from "~/hooks/useStableCallback";
89 +import { useOpenPanelPullRequestUrl } from "~/hooks/useOpenPanelPullRequestUrl";
90 +import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
91 +import { toastManager } from "../ui/toast";
92 +import { useEscapeToGoBack } from "~/hooks/useNavigateBack";
93 +import { usePanelAnimationSettings, usePanelPresence } from "~/panelAnimations";
94 +import {
95 + PULL_REQUESTS_PANEL_REF,
96 + selectActiveRightPanelSurface,
97 + selectSelectedRightPanelSurface,
98 + selectThreadRightPanelState,
99 + useRightPanelStore,
100 + type PullRequestSurface,
101 +} from "~/rightPanelStore";
102 +import { useSidebarProjectGroups } from "~/hooks/useSidebarProjectGroups";
103 +import {
104 + pullRequestEnvironment,
105 + usePullRequestList,
106 + usePullRequestListStats,
107 + usePullRequestTurnRefreshes,
108 + type EnvironmentQueryTarget,
109 +} from "~/state/pullRequests";
110 +import { useAtomCommand } from "~/state/use-atom-command";
111 +import { cn } from "~/lib/utils";
112 +import { primaryServerKeybindingsAtom } from "~/state/server";
113 +import { getSourceControlPresentationForKind } from "~/sourceControlPresentation";
114 +
115 +function getShortcutContext() {
116 + return {
117 + terminalFocus: isTerminalFocused(),
118 + terminalOpen: false,
119 + previewFocus: false,
120 + previewOpen: false,
121 + modelPickerOpen: false,
122 + isWeb: !isElectron,
123 + isDesktop: isElectron,
124 + };
125 +}
126 +
127 +/**
128 + * One whole page from the host and no more: every provider asks for one row beyond the page as
129 + * its "is there more" probe, and GitHub serves a hundred per request — so asking for ninety-nine
130 + * costs one round trip where a hundred costs two.
131 + */
132 +const PAGE_SIZE = 99;
133 +const MAX_PAGE_SIZE = 500;
134 +const EMPTY_VIEWERS: PullRequestListResult["viewers"] = {};
135 +const EMPTY_PARTITIONS: PullRequestPartitionsSnapshot = { authored: [], reviewing: [] };
136 +const NO_LIST_TARGETS: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>> = [];
137 +const EMPTY_PREVIEW_SESSIONS = {};
138 +const EMPTY_PREVIEW_DESKTOP_STATE = {};
139 +const EMPTY_TERMINAL_LABELS = new Map<string, string>();
140 +const EMPTY_PENDING_SURFACES = new Set<string>();
141 +export function PullRequestsPage() {
142 + useEscapeToGoBack();
143 + const search = useSearch({ from: "/_chat/pull-requests" });
144 + const sort = search.sort ?? "ready";
145 + const statsPolicy: PullRequestStatsPolicy =
146 + sort === "ready" || sort === "largest" || sort === "smallest" ? "eager" : "visible";
147 + const navigate = useNavigate({ from: "/pull-requests" });
148 + const keybindings = useAtomValue(primaryServerKeybindingsAtom);
149 + const {
150 + capableEnvironments,
151 + scopedEnvironmentId,
152 + environmentKey,
153 + capabilityKnown,
154 + pullRequestsSupported,
155 + projects,
156 + environmentLabels,
157 + scopedProjectId,
158 + scopedProject,
159 + scopedProjects,
160 + selectedProject,
161 + queryEnvironmentIds,
162 + environmentQueries,
163 + assignmentKey,
164 + linkedSelection,
165 + expectedHosts,
166 + projectsKnown,
167 + } = usePullRequestScope(search);
168 + const rightPanelRef = capableEnvironments.length === 0 ? null : PULL_REQUESTS_PANEL_REF;
169 + const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(rightPanelRef);
170 + const rightPanelState = useRightPanelStore((state) =>
171 + selectThreadRightPanelState(state.byThreadKey, rightPanelRef),
172 + );
173 + const selectedRightPanelSurface = useRightPanelStore((state) =>
174 + selectSelectedRightPanelSurface(state.byThreadKey, rightPanelRef),
175 + );
176 + const selectedPullRequestSurface =
177 + selectedRightPanelSurface?.kind === "pull-request" ? selectedRightPanelSurface : null;
178 + const activePullRequestSurface = rightPanelState.isOpen ? selectedPullRequestSurface : null;
179 + const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
180 + usePanelAnimationSettings();
181 + const rightPanelPresenceValue = {
182 + activeSurface: selectedPullRequestSurface,
183 + surfaces: rightPanelState.surfaces,
184 + };
185 + const rightPanelPresence = usePanelPresence(
186 + rightPanelState.isOpen && selectedPullRequestSurface !== null,
187 + rightPanelPresenceValue,
188 + panelAnimationsActive,
189 + rightPanelRef?.threadId ?? null,
190 + panelAnimationDurationMs,
191 + );
192 + const rightPanelPresent = rightPanelPresence.present;
193 + const renderedPullRequestSurface = rightPanelPresence.value?.activeSurface ?? null;
194 + const renderedRightPanelSurfaces = rightPanelPresence.value?.surfaces ?? [];
195 + const panelEnvironmentId =
196 + (renderedPullRequestSurface?.environmentId as EnvironmentId | undefined) ??
197 + selectedProject?.environmentId ??
198 + null;
199 + const updateSearch = (patch: {
200 + [Key in keyof PullRequestsSearch]?: PullRequestsSearch[Key] | undefined;
201 + }) =>
202 + void navigate({
203 + search: (previous: PullRequestsSearch): PullRequestsSearch => {
204 + const next = { ...previous, ...patch };
205 + return {
206 + involvement: next.involvement ?? previous.involvement,
207 + state: next.state ?? previous.state,
208 + ...(next.sort && next.sort !== "ready" ? { sort: next.sort } : {}),
209 + ...(next.repository ? { repository: next.repository } : {}),
210 + ...(next.number ? { number: next.number } : {}),
211 + ...(next.projectId ? { projectId: next.projectId } : {}),
212 + ...(next.environmentId ? { environmentId: next.environmentId } : {}),
213 + ...(next.host ? { host: next.host } : {}),
214 + ...(next.selectedHost ? { selectedHost: next.selectedHost } : {}),
215 + ...(next.selectedProjectId ? { selectedProjectId: next.selectedProjectId } : {}),
216 + ...(next.selectedEnvironmentId
217 + ? { selectedEnvironmentId: next.selectedEnvironmentId }
218 + : {}),
219 + ...(next.q ? { q: next.q } : {}),
220 + ...(next.draft ? { draft: next.draft } : {}),
221 + ...(next.review ? { review: next.review } : {}),
222 + ...(next.checks ? { checks: next.checks } : {}),
223 + ...(next.author ? { author: next.author } : {}),
224 + ...(next.labels && next.labels.length > 0 ? { labels: next.labels } : {}),
225 + };
226 + },
227 + replace: true,
228 + });
229 +
230 + const clearedSelection = {
231 + repository: undefined,
232 + number: undefined,
233 + selectedProjectId: undefined,
234 + selectedEnvironmentId: undefined,
235 + selectedHost: undefined,
236 + };
237 + const updateListScope = (patch: PullRequestListPreferencePatch) => {
238 + const currentPreferences = pullRequestListPreferences({
239 + ...search,
240 + ...patch,
241 + involvement: patch.involvement ?? search.involvement,
242 + state: patch.state ?? search.state,
243 + });
244 + writePullRequestListPreferences(currentPreferences);
245 + updateSearch(patch);
246 + };
247 +
248 + const typedQuery = (search.q ?? "").trim();
249 + const [filtersOpen, setFiltersOpen] = useState(false);
250 + const {
251 + sentQuery,
252 + querySettled,
253 + typedParsed,
254 + sentParsed,
255 + menuFilters,
256 + menuFiltered,
257 + filters,
258 + hasFilters,
259 + localFilters,
260 + hasLocalFilters,
261 + } = usePullRequestQueryFilters(search, typedQuery);
262 + const turnRefreshes = usePullRequestTurnRefreshes(
263 + environmentQueries.map(({ environmentId }) => environmentId),
264 + );
265 + const turnRefreshToken = turnRefreshes
266 + .map(([environmentId, revision]) => `${environmentId}:${revision}`)
267 + .join("|");
268 + const scopeKey = `${environmentKey}:${assignmentKey}:${search.state}:${search.involvement}:${scopedProjectId ?? ""}:${search.host ?? ""}:${search.draft ?? ""}:${search.review ?? ""}:${search.checks ?? ""}:${search.author ?? ""}:${search.labels?.join("\u0000") ?? ""}`;
269 + const filterKey = `${scopeKey}:${sentQuery}`;
270 + const statsScope: PullRequestStatsScope = { key: filterKey, policy: statsPolicy };
271 + const [page, setPage] = useState<{
272 + key: string;
273 + size: number;
274 + cursors: Readonly<Record<string, PullRequestListCursors>> | null;
275 + /**
276 + * An environment can say it has more without saying where to carry on from — its provider has
277 + * no cursor to give — and a continuation naming only the others would strand its rows on the
278 + * host forever.
279 + */
280 + regrown: ReadonlyArray<string>;
281 + }>({ key: filterKey, size: PAGE_SIZE, cursors: null, regrown: [] });
282 + const pageSize = page.key === filterKey ? page.size : PAGE_SIZE;
283 + const sentCursors = page.key === filterKey ? page.cursors : null;
284 + const sentRegrown = page.key === filterKey ? page.regrown : [];
285 +
286 + if (page.key !== filterKey) {
287 + setPage({ key: filterKey, size: PAGE_SIZE, cursors: null, regrown: [] });
288 + }
289 +
290 + const listTargets = environmentQueries.flatMap(({ environmentId, projectIds }) => {
291 + const cursors = sentCursors?.[environmentId];
292 + if (sentCursors !== null && cursors === undefined && !sentRegrown.includes(environmentId)) {
293 + return [];
294 + }
295 + return [
296 + {
297 + environmentId,
298 + input: {
299 + state: search.state,
300 + involvement: search.involvement,
301 + limit: pageSize,
302 + ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
303 + ...(projectIds ? { projectIds } : {}),
304 + ...(search.host ? { host: search.host } : {}),
305 + ...(hasFilters ? { filters } : {}),
306 + ...(sentParsed.text ? { query: sentParsed.text } : {}),
307 + ...(cursors === undefined ? {} : { cursors }),
308 + } satisfies PullRequestListInput,
309 + },
310 + ];
311 + });
312 + const listQuery = usePullRequestList(listTargets);
313 +
314 + /**
315 + * Kept as its own read rather than remembered from an earlier answer because an answer cannot
316 + * say which question it belongs to: mid-switch the text has already changed and the data has
317 + * not, and a search's answer would file itself under the workspace.
318 + */
319 + const baselineTargets = environmentQueries.map(({ environmentId, projectIds }) => ({
320 + environmentId,
321 + input: {
322 + state: search.state,
323 + involvement: search.involvement,
324 + limit: PAGE_SIZE,
325 + ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
326 + ...(projectIds ? { projectIds } : {}),
327 + ...(search.host ? { host: search.host } : {}),
328 + ...(menuFiltered ? { filters: menuFilters } : {}),
329 + } satisfies PullRequestListInput,
330 + }));
331 + const baselineQuery = usePullRequestList(baselineTargets);
332 + const baselineEmpty =
333 + baselineQuery.data?.entries.length === 0 &&
334 + baselineQuery.data.errors.length === 0 &&
335 + !baselineQuery.isPending &&
336 + baselineQuery.error === null;
337 + const facetTargets = (() => {
338 + if (!filtersOpen) return NO_LIST_TARGETS;
339 + return environmentQueries.map(({ environmentId, projectIds }) => ({
340 + environmentId,
341 + input: {
342 + state: "all",
343 + involvement: search.involvement,
344 + limit: PAGE_SIZE,
345 + ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
346 + ...(projectIds ? { projectIds } : {}),
347 + ...(search.host ? { host: search.host } : {}),
348 + } satisfies PullRequestListInput,
349 + }));
350 + })();
351 + const facetQuery = usePullRequestList(facetTargets);
352 + const partitionsWanted = search.involvement === "all" && typedQuery.length === 0;
353 + const partitionTargets = (() => {
354 + // The main list goes first. Besides putting the visible rows on screen sooner, it proves
355 + // which repositories the host search indexes, so an empty partition does not trigger the
356 + // expensive per-repository fallback.
357 + if (
358 + !partitionsWanted ||
359 + baselineQuery.data === null ||
360 + baselineQuery.data.entries.length === 0
361 + ) {
362 + return { authored: NO_LIST_TARGETS, reviewing: NO_LIST_TARGETS };
363 + }
364 + const targetsFor = (involvement: PullRequestInvolvement) =>
365 + environmentQueries.map(({ environmentId, projectIds }) => ({
366 + environmentId,
367 + input: {
368 + state: search.state,
369 + involvement,
370 + limit: PAGE_SIZE,
371 + ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
372 + ...(projectIds ? { projectIds } : {}),
373 + ...(search.host ? { host: search.host } : {}),
374 + ...(menuFiltered ? { filters: menuFilters } : {}),
375 + } satisfies PullRequestListInput,
376 + }));
377 + return { authored: targetsFor("authored"), reviewing: targetsFor("reviewing") };
378 + })();
379 + const authoredQuery = usePullRequestList(partitionTargets.authored);
380 + const reviewingQuery = usePullRequestList(partitionTargets.reviewing);
381 + const invalidate = useAtomCommand(pullRequestEnvironment.invalidate, { reportFailure: false });
382 + const [detailRefreshToken, setDetailRefreshToken] = useState(0);
383 + const [invalidating, setInvalidating] = useState(false);
384 + const refreshing = invalidating || listQuery.isPending;
385 +
386 + const [loaded, setLoaded] = useState<{
387 + environmentKey: string;
388 + scope: string;
389 + query: string;
390 + /** The answer this was built from, so a re-render with the same answer leaves it alone. */
391 + source: MergedPullRequestList | null;
392 + data: MergedPullRequestList;
393 + partitions?: PullRequestPartitionsSnapshot;
394 + } | null>(null);
395 + const [ordered, setOrdered] = useState<{
396 + key: string;
397 + source: MergedPullRequestList;
398 + entries: ReadonlyArray<EnvironmentPullRequestEntry>;
399 + } | null>(null);
400 + const [overrides, setOverrides] = useState<ReadonlyMap<string, PullRequestListOverride>>(
401 + () => new Map(),
402 + );
403 + const overrideToken = useRef(0);
404 + const overrideEntry = (
405 + entry: EnvironmentPullRequestEntry,
406 + action: PullRequestAction,
407 + ): number | null => {
408 + const token = ++overrideToken.current;
409 + const override = pullRequestOverrideAfterAction(entry, action, new Date(), token);
410 + if (override === null) return null;
411 + setOverrides((current) => new Map(current).set(pullRequestEntryKey(entry), override));
412 + return token;
413 + };
414 + const revertOverride = (key: string, token: number | null) => {
415 + if (token === null) return;
416 + setOverrides((current) => {
417 + if (current.get(key)?.token !== token) return current;
418 + const next = new Map(current);
419 + next.delete(key);
420 + return next;
421 + });
422 + };
423 + const detailOverrideTokens = useRef(new Map<string, number | null>());
424 + const onSpeedAction = useStableCallback(({ entry, action }: PullRequestSpeedActionResult) => {
425 + // Some hosts accept a merge before it completes. Let the next host read declare it merged.
426 + if (action !== "merge") overrideEntry(entry, action);
427 + });
428 + const onBatchClosed = useStableCallback((entry: EnvironmentPullRequestEntry) => {
429 + onSpeedAction({ entry, action: "close" });
430 + });
431 + const { close: closeBatch, closingKeys } = usePullRequestCloseBatch(onBatchClosed);
432 + const [snapshotEnvironmentKey, setSnapshotEnvironmentKey] = useState("");
433 + if (environmentKey.length > 0 && snapshotEnvironmentKey !== environmentKey) {
434 + setSnapshotEnvironmentKey(environmentKey);
435 + if (loaded?.environmentKey !== environmentKey) {
436 + const snapshot = readPullRequestListSnapshot(
437 + typeof window === "undefined" ? undefined : window.localStorage,
438 + environmentKey,
439 + );
440 + setLoaded(
441 + snapshot === null
442 + ? null
443 + : {
444 + environmentKey,
445 + scope: snapshot.scope,
446 + query: "",
447 + source: null,
448 + data: snapshot.data,
449 + ...(snapshot.partitions === undefined ? {} : { partitions: snapshot.partitions }),
450 + },
451 + );
452 + }
453 + }
454 + const settledList = listQuery.data !== null && !listQuery.isPending ? listQuery.data : null;
455 + const answeredPartitions =
456 + partitionsWanted && baselineEmpty
457 + ? EMPTY_PARTITIONS
458 + : partitionsWanted && authoredQuery.data !== null && reviewingQuery.data !== null
459 + ? { authored: authoredQuery.data.entries, reviewing: reviewingQuery.data.entries }
460 + : null;
461 + const heldPartitions =
462 + loaded !== null && loaded.environmentKey === environmentKey && loaded.scope === scopeKey
463 + ? loaded.partitions
464 + : undefined;
465 + const nextPartitions = answeredPartitions ?? heldPartitions;
466 + const loadedEntries =
467 + settledList === null
468 + ? null
469 + : ordered?.key === filterKey
470 + ? ordered.entries
471 + : settledList.entries;
472 + if (
473 + settledList !== null &&
474 + loadedEntries !== null &&
475 + (loaded === null ||
476 + loaded.source !== settledList ||
477 + loaded.environmentKey !== environmentKey ||
478 + loaded.scope !== scopeKey ||
479 + loaded.query !== sentQuery ||
480 + loaded.data.entries !== loadedEntries ||
481 + loaded.partitions?.authored !== nextPartitions?.authored ||
482 + loaded.partitions?.reviewing !== nextPartitions?.reviewing)
483 + ) {
484 + setLoaded({
485 + environmentKey,
486 + scope: scopeKey,
487 + query: sentQuery,
488 + source: settledList,
489 + data: { ...settledList, entries: loadedEntries },
490 + ...(nextPartitions === undefined ? {} : { partitions: nextPartitions }),
491 + });
492 + }
493 + const snapshotToWrite =
494 + loaded !== null &&
495 + loaded.source !== null &&
496 + loaded.environmentKey.length > 0 &&
497 + loaded.query.length === 0
498 + ? loaded
499 + : null;
500 + const snapshotViewers = baselineQuery.data?.viewers;
501 + const snapshotProviders = baselineQuery.data?.providers;
502 + useEffect(() => {
503 + if (snapshotToWrite === null) return;
504 + writePullRequestListSnapshot(
505 + typeof window === "undefined" ? undefined : window.localStorage,
506 + snapshotToWrite.environmentKey,
507 + {
508 + scope: snapshotToWrite.scope,
509 + data: {
510 + ...snapshotToWrite.data,
511 + viewers: snapshotViewers ?? snapshotToWrite.data.viewers,
512 + providers: snapshotProviders ?? snapshotToWrite.data.providers,
513 + },
514 + ...(snapshotToWrite.partitions === undefined
515 + ? {}
516 + : { partitions: snapshotToWrite.partitions }),
517 + },
518 + );
519 + }, [snapshotToWrite, snapshotViewers, snapshotProviders]);
520 + const narrowed = (() => {
521 + if (loaded === null || loaded.environmentKey !== environmentKey || loaded.scope === scopeKey) {
522 + return null;
523 + }
524 + const entries = narrowPullRequestsToFilters(loaded.data.entries, {
525 + state: search.state,
526 + projectId: scopedProjectId,
527 + host: search.host,
528 + });
529 + return entries.length === 0 ? null : { ...loaded.data, entries };
530 + })();
531 + // A grown page is read by the list and nothing else: the baseline always asks for one page, so
532 + // a host with no cursor to continue from — where "more" means asking for a longer page — would
533 + // have its extra rows thrown away for the ninety-nine the baseline keeps answering with.
534 + const answered =
535 + (sentQuery.length === 0 && sentCursors === null && pageSize === PAGE_SIZE
536 + ? baselineQuery.data
537 + : listQuery.data) ??
538 + (loaded?.scope === scopeKey && loaded.query === sentQuery ? loaded.data : null);
539 + const carried =
540 + (sentQuery.length === 0 ? baselineQuery.data : undefined) ??
541 + (loaded?.scope === scopeKey ? loaded.data : null) ??
542 + narrowed;
543 + const listData = answered ?? carried;
544 + const showingCarried = answered === null && carried !== null;
545 + const loadingMore = listQuery.isPending && listData !== null;
546 + const firstLoad = listQuery.isPending && listData === null;
547 +
548 + if (
549 + answered !== null &&
550 + !listQuery.isPending &&
551 + !(listQuery.error && listQuery.data === null) &&
552 + (ordered === null || ordered.key !== filterKey || ordered.source !== answered)
553 + ) {
554 + if (ordered === null || ordered.key !== filterKey) {
555 + setOrdered({
556 + key: filterKey,
557 + source: answered,
558 + entries: rankPullRequestMatches(answered.entries, sentParsed.text),
559 + });
560 + } else if (sentCursors !== null) {
561 + const held = new Set(ordered.entries.map(pullRequestEntryKey));
562 + const arrived = answered.entries.filter((entry) => !held.has(pullRequestEntryKey(entry)));
563 + const appended = rankPullRequestMatches(
564 + arrived.toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
565 + sentParsed.text,
566 + );
567 + setOrdered({ key: filterKey, source: answered, entries: [...ordered.entries, ...appended] });
568 + } else {
569 + setOrdered({
570 + key: filterKey,
571 + source: answered,
572 + entries: reusePullRequestEntries(
573 + ordered.entries,
574 + rankPullRequestMatches(answered.entries, sentParsed.text),
575 + pullRequestEntryKey,
576 + ),
577 + });
578 + }
579 + const answeredEntries = answered.entries;
580 + setOverrides((current) =>
581 + settlePullRequestOverrides(current, answeredEntries, pullRequestEntryKey, Date.now()),
582 + );
583 + }
584 +
585 + // From this question's own answer, never from the rows being held while it travels: a
586 + // continuation is a boundary in one listing, and carrying one across a search would ask the new
587 + // question to start where the old one stopped — skipping its newest matches entirely.
588 + const nextCursors = answered?.nextCursors ?? {};
589 + const regrown = (answered?.truncatedEnvironments ?? []).filter(
590 + (environmentId) => nextCursors[environmentId] === undefined,
591 + );
592 + const canContinue = !showingCarried && Object.keys(nextCursors).length > 0;
593 + const loadMore = () => {
594 + if (canContinue) {
595 + setPage({
596 + key: filterKey,
597 + size: regrown.length === 0 ? pageSize : Math.min(pageSize + PAGE_SIZE, MAX_PAGE_SIZE),
598 + cursors: nextCursors,
599 + regrown,
600 + });
601 + return;
602 + }
603 + setPage({
604 + key: filterKey,
605 + size: Math.min(pageSize + PAGE_SIZE, MAX_PAGE_SIZE),
606 + cursors: null,
607 + regrown: [],
608 + });
609 + };
610 +
611 + const refreshList = (includeRelated = false, actedEnvironmentId?: EnvironmentId) => {
612 + const related = (
613 + includeRelated
614 + ? [
615 + ...baselineTargets,
616 + ...facetTargets,
617 + ...partitionTargets.authored,
618 + ...partitionTargets.reviewing,
619 + ]
620 + : []
621 + ).filter(
622 + ({ environmentId }) =>
623 + actedEnvironmentId === undefined || environmentId === actedEnvironmentId,
624 + );
625 + if (sentCursors === null) {
626 + listQuery.refresh([
627 + ...listTargets.filter(
628 + ({ environmentId }) =>
629 + actedEnvironmentId === undefined || environmentId === actedEnvironmentId,
630 + ),
631 + ...related,
632 + ]);
633 + return;
634 + }
635 + if (related.length > 0) listQuery.refresh(related);
636 + const loadedCount =
637 + ordered?.key === filterKey ? largestPullRequestReadCount(ordered.entries) : pageSize;
638 + setPage({
639 + key: filterKey,
640 + regrown: [],
641 + size: Math.min(
642 + Math.max(pageSize, Math.ceil(loadedCount / PAGE_SIZE) * PAGE_SIZE),
643 + MAX_PAGE_SIZE,
644 + ),
645 + cursors: null,
646 + });
647 + };
648 +
649 + const appliedTurnRefreshToken = useRef("");
650 + const refreshAfterTurn = useEffectEvent(() => {
651 + if (sentCursors !== null) refreshList();
652 + });
653 + useEffect(() => {
654 + if (turnRefreshToken.length === 0 || appliedTurnRefreshToken.current === turnRefreshToken) {
655 + return;
656 + }
657 + appliedTurnRefreshToken.current = turnRefreshToken;
658 + refreshAfterTurn();
659 + }, [turnRefreshToken]);
660 +
661 + useLiveRefresh(
662 + () => {
663 + refreshList(true);
664 + },
665 + { enabled: pullRequestsSupported },
666 + );
667 +
668 + const viewers = baselineQuery.data?.viewers ?? listData?.viewers ?? EMPTY_VIEWERS;
669 + const listErrors = baselineQuery.data?.errors ?? listData?.errors ?? [];
670 + const facets = collectPullRequestListFacets(
671 + [
672 + ...(facetQuery.data?.entries ?? []),
673 + ...(baselineQuery.data?.entries ?? listData?.entries ?? []),
674 + ],
675 + search.state,
676 + );
677 +
678 + const scrollRef = useRef<HTMLDivElement>(null);
679 + const {
680 + entries,
681 + listedPullRequestTabStatuses,
682 + groups,
683 + entriesByStatsKey,
684 + heldPullRequestsBySurface,
685 + } = pullRequestGroups({
686 + known: ordered?.key === filterKey ? ordered.entries : (listData?.entries ?? []),
687 + providers: baselineQuery.data?.providers ?? listData?.providers ?? [],
688 + viewers,
689 + involvement: search.involvement,
690 + localFilters,
691 + hasLocalFilters,
692 + text: typedParsed.text,
693 + answeredLocally: querySettled && !showingCarried,
694 + baselineEmpty,
695 + held:
696 + loaded !== null && loaded.environmentKey === environmentKey && loaded.scope === scopeKey
697 + ? loaded.partitions
698 + : undefined,
699 + authored: partitionsWanted ? authoredQuery.data?.entries : undefined,
700 + reviewing: partitionsWanted ? reviewingQuery.data?.entries : undefined,
701 + partitionsWanted,
702 + });
703 +
704 + const visibleStatsKeys = useRef({ key: filterKey, values: new Set<string>() });
705 + const [statsByRow, setStatsByRow] = useState<PullRequestDiffStats>(() => new Map());
706 + const [statsTargetState, setStatsTargetState] = useState<{
707 + readonly key: string;
708 + readonly batches: ReadonlyArray<PullRequestStatsBatch>;
709 + }>({ key: filterKey, batches: [] });
710 + const statsBatches = statsTargetState.key === filterKey ? statsTargetState.batches : [];
711 + const statsTargets = statsBatches.map(({ environmentId, input }) => ({
712 + environmentId,
713 + input,
714 + }));
715 + const statsQuery = usePullRequestListStats(statsTargets);
716 + const statsObserver = useRef<IntersectionObserver | null>(null);
717 + const statsRows = useRef(new Set<HTMLDivElement>());
718 + // Called from a row's ref cleanup, which keeps the render it attached in; this reads the latest.
719 + const releaseStatsRow = useStableCallback((key: string | undefined) => {
720 + const visible = visibleStatsKeys.current;
721 + if (
722 + statsPolicy !== "visible" ||
723 + key === undefined ||
724 + !visible.values.delete(key) ||
725 + statsQuery.isPending
726 + ) {
727 + return;
728 + }
729 + setStatsTargetState((current) => {
730 + if (current.key !== visible.key) return current;
731 + const batches = retainVisiblePullRequestStatsBatches(current.batches, visible.values);
732 + return batches.length === current.batches.length ? current : { key: current.key, batches };
733 + });
734 + });
735 + // Every row takes this as its ref, so a new identity would detach and reattach them all.
736 + const registerStatsRow = useStableCallback((node: HTMLDivElement | null) => {
737 + if (node === null || typeof IntersectionObserver === "undefined") return;
738 + statsRows.current.add(node);
739 + statsObserver.current?.observe(node);
740 + return () => {
741 + statsRows.current.delete(node);
742 + statsObserver.current?.unobserve(node);
743 + releaseStatsRow(node.dataset.pullRequestStatsKey);
744 + };
745 + });
746 + // Arriving stats must not re-run the effects that ask for them.
747 + const readStatsProgress = useEffectEvent(() => ({
748 + statsByRow,
749 + pending: statsQuery.isPending,
750 + }));
751 + useEffect(() => {
752 + if (statsPolicy !== "eager") return;
753 + const { statsByRow: known } = readStatsProgress();
754 + const candidateKeys = visibleStatsKeys.current.values;
755 + setStatsTargetState((current) => {
756 + const batches = current.key === filterKey ? current.batches : [];
757 + const added = pullRequestStatsRequestBatches({
758 + entriesByKey: entriesByStatsKey,
759 + candidateKeys,
760 + policy: statsPolicy,
761 + activeBatches: batches,
762 + statsByRow: known,
763 + });
764 + if (added.length === 0 && current.key === filterKey) return current;
765 + return { key: filterKey, batches: [...batches, ...added] };
766 + });
767 + }, [filterKey, entriesByStatsKey, statsPolicy]);
768 + // The observer outlives the rows it watches, so it reads the rows held at the time it fires.
769 + const readStatsRows = useEffectEvent(() => entriesByStatsKey);
770 + useEffect(() => {
771 + if (statsPolicy !== "visible" || typeof IntersectionObserver === "undefined") return;
772 + visibleStatsKeys.current = { key: filterKey, values: new Set() };
773 + const observer = new IntersectionObserver(
774 + (observed) => {
775 + const visible = visibleStatsKeys.current;
776 + if (visible.key !== filterKey) return;
777 + let changed = false;
778 + const entered = new Set<string>();
779 + const entriesByKey = readStatsRows();
780 + for (const item of observed) {
781 + const key = (item.target as HTMLElement).dataset.pullRequestStatsKey;
782 + if (key === undefined) continue;
783 + const wasVisible = visible.values.has(key);
784 + if (item.isIntersecting && entriesByKey.has(key)) {
785 + visible.values.add(key);
786 + if (!wasVisible) entered.add(key);
787 + } else {
788 + visible.values.delete(key);
789 + }
790 + if (wasVisible !== visible.values.has(key)) changed = true;
791 + }
792 + if (!changed) return;
793 + const progress = readStatsProgress();
794 + setStatsTargetState((current) => {
795 + const batches = current.key === filterKey ? current.batches : [];
796 + const retained = progress.pending
797 + ? batches
798 + : retainVisiblePullRequestStatsBatches(batches, visible.values);
799 + const added = pullRequestStatsRequestBatches({
800 + entriesByKey,
801 + candidateKeys: entered,
802 + policy: statsPolicy,
803 + activeBatches: batches,
804 + statsByRow: progress.statsByRow,
805 + });
806 + if (added.length === 0 && retained.length === batches.length) return current;
807 + return { key: filterKey, batches: [...retained, ...added] };
808 + });
809 + },
810 + { root: scrollRef.current, rootMargin: "480px" },
811 + );
812 + statsObserver.current = observer;
813 + for (const row of statsRows.current) observer.observe(row);
814 + return () => {
815 + observer.disconnect();
816 + if (statsObserver.current === observer) statsObserver.current = null;
817 + };
818 + }, [filterKey, statsPolicy]);
819 + useEffect(() => {
820 + if (statsPolicy !== "visible" || statsQuery.isPending) return;
821 + const visible = visibleStatsKeys.current;
822 + setStatsTargetState((current) => {
823 + if (current.key !== filterKey || visible.key !== filterKey) return current;
824 + const batches = retainVisiblePullRequestStatsBatches(current.batches, visible.values);
825 + return batches.length === current.batches.length ? current : { key: current.key, batches };
826 + });
827 + }, [filterKey, statsPolicy, statsQuery.isPending]);
828 + const [mergedStats, setMergedStats] = useState<typeof statsQuery.stats>(null);
829 + if (statsQuery.stats !== null && statsQuery.stats !== mergedStats) {
830 + const stats = statsQuery.stats;
831 + setMergedStats(stats);
832 + setStatsByRow((previous) => mergePullRequestDiffStats(previous, stats));
833 + }
834 + // Stable so a refresh that resumes after awaiting the host compares against the scope on screen
835 + // by then, not the one it started from.
836 + const refreshListAndStats = useStableCallback(
837 + (
838 + requestedStatsScope: PullRequestStatsScope = statsScope,
839 + actedEnvironmentId?: EnvironmentId,
840 + ) => {
841 + refreshList(true, actedEnvironmentId);
842 + const visible = visibleStatsKeys.current;
843 + const batches = pullRequestStatsRefreshBatches({
844 + requestedScope: requestedStatsScope,
845 + currentScope: statsScope,
846 + entriesByKey: entriesByStatsKey,
847 + candidateKeys: visible.key === requestedStatsScope.key ? visible.values : new Set(),
848 + statsByRow,
849 + });
850 + if (batches !== null) {
851 + setStatsTargetState({ key: requestedStatsScope.key, batches });
852 + statsQuery.refresh(
853 + batches
854 + .filter(({ environmentId }) =>
855 + actedEnvironmentId === undefined ? true : environmentId === actedEnvironmentId,
856 + )
857 + .map(({ environmentId, input }) => ({ environmentId, input })),
858 + );
859 + }
860 + },
861 + );
862 + const refreshFromHost = async () => {
863 + const requestedStatsScope = statsScope;
864 + setInvalidating(true);
865 + // Atom commands settle into results rather than throwing.
866 + await Promise.all(
867 + queryEnvironmentIds.map((environmentId) => invalidate({ environmentId, input: {} })),
868 + );
869 + setInvalidating(false);
870 + refreshListAndStats(requestedStatsScope);
871 + setDetailRefreshToken((token) => token + 1);
872 + };
873 + const {
874 + hosts,
875 + displayGroups,
876 + shownCount,
877 + hostActionsOf,
878 + closeSweepRows,
879 + listedPullRequestsBySurface,
880 + } = usePullRequestDisplayGroups({
881 + answered,
882 + host: search.host,
883 + groups,
884 + statsByRow,
885 + overrides,
886 + state: search.state,
887 + localFilters,
888 + hasLocalFilters,
889 + viewers,
890 + sort,
891 + text: typedParsed.text,
892 + involvement: search.involvement,
893 + });
894 + const showProvider = hosts.length > 1;
895 + const [closeSweepKeys, setCloseSweepKeys] = useState<ReadonlySet<string>>(() => new Set());
896 + const closeSensorRef = useRef<SidebarPointerSensor | null>(null);
897 + // A sweep spans many renders; each step reads the rows on screen at that moment.
898 + const readCloseSweep = useStableCallback(() => ({
899 + displayGroups,
900 + closeSweepRows,
901 + closingKeys,
902 + closeBatch,
903 + hostActionsOf,
904 + }));
905 + useEffect(
906 + () => () => closeSensorRef.current?.cancel(),
907 + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- The pointer sensor lives outside React; a new list under a sweep in progress must end it.
908 + [filterKey, search.q, sort],
909 + );
910 + useEffect(() => {
911 + const onKeyDown = (event: KeyboardEvent) => {
912 + if (event.key !== "Escape" || closeSensorRef.current === null) return;
913 + event.preventDefault();
914 + closeSensorRef.current.cancel();
915 + };
916 + document.addEventListener("keydown", onKeyDown, true);
917 + return () => document.removeEventListener("keydown", onKeyDown, true);
918 + }, []);
919 + const startCloseSweep = useStableCallback(
920 + (entry: EnvironmentPullRequestEntry, event: PointerEvent) => {
921 + closeSensorRef.current?.cancel();
922 + const originKey = pullRequestEntryKey(entry);
923 + const group = readCloseSweep().displayGroups.find((candidate) =>
924 + candidate.entries.some((row) => pullRequestEntryKey(row) === originKey),
925 + );
926 + if (!group || readCloseSweep().closingKeys.has(originKey)) return;
927 + const orderedKeys = readCloseSweep().displayGroups.flatMap((candidate) =>
928 + candidate.entries.map(pullRequestEntryKey),
929 + );
930 + const canClose = (key: string) => {
931 + const row = readCloseSweep().closeSweepRows.get(key);
932 + return (
933 + row?.groupKey === group.key &&
934 + row.entry.state === "open" &&
935 + readCloseSweep().hostActionsOf(row.entry).has("close") &&
936 + !readCloseSweep().closingKeys.has(key) &&
937 + !scrollRef.current?.querySelector(
938 + `[data-pull-request-key="${CSS.escape(key)}"] [data-pull-request-action-pending="true"]`,
939 + )
940 + );
941 + };
942 + let sweptKeys: string[] = [];
943 + let targetKey: string | null = null;
944 + const sweepTo = (key: string) => {
945 + if (key === targetKey) return;
946 + targetKey = key;
947 + sweptKeys = resolveSidebarSweepKeys(orderedKeys, originKey, key, canClose);
948 + setCloseSweepKeys(new Set(sweptKeys));
949 + };
950 + closeSensorRef.current = new SidebarPointerSensor({
951 + active: originKey,
952 + event,
953 + options: {
954 + distance: 6,
955 + onAttach: () => {},
956 + onFinish: () => {
957 + closeSensorRef.current = null;
958 + setCloseSweepKeys(new Set());
959 + },
960 + },
961 + onPending: () => {},
962 + onStart: () => sweepTo(originKey),
963 + onMove: ({ y }) => {
964 + const viewport = scrollRef.current;
965 + if (!viewport) return;
966 + const bounds = viewport.getBoundingClientRect();
967 + const visibleY = Math.min(Math.max(y, bounds.top), bounds.bottom - 1);
968 + let key: string | null = null;
969 + for (const row of viewport.querySelectorAll<HTMLElement>("[data-pull-request-key]")) {
970 + if (key !== null && row.getBoundingClientRect().top > visibleY) break;
971 + key = row.dataset.pullRequestKey ?? null;
972 + }
973 + if (key !== null) sweepTo(key);
974 + },
975 + onEnd: () => {
976 + const batch = sweptKeys.filter(canClose).flatMap((key) => {
977 + const row = readCloseSweep().closeSweepRows.get(key);
978 + return row ? [row.entry] : [];
979 + });
980 + void readCloseSweep().closeBatch(batch);
981 + },
982 + onCancel: () => {},
983 + onAbort: () => {},
984 + });
985 + },
986 + );
987 + const rightPanelAvailable = selectedPullRequestSurface !== null;
988 + const [maximized, setMaximized] = useState(false);
989 + const rightPanelMaximized = rightPanelState.isOpen && maximized;
990 + if (!rightPanelState.isOpen && maximized) setMaximized(false);
991 + const toggleRightPanelMaximized = () => {
992 + if (rightPanelState.isOpen) setMaximized((value) => !value);
993 + };
994 + const onGuideShown = () => setMaximized(true);
995 + useEffect(() => {
996 + if (!pullRequestsSupported || rightPanelRef === null || linkedSelection === null) return;
997 + useRightPanelStore.getState().openPullRequest(rightPanelRef, linkedSelection);
998 + }, [linkedSelection, pullRequestsSupported, rightPanelRef]);
999 +
1000 + const selected =
1001 + rightPanelState.isOpen && activePullRequestSurface !== null
1002 + ? {
1003 + environmentId: activePullRequestSurface.environmentId,
1004 + repository: activePullRequestSurface.repository,
1005 + number: activePullRequestSurface.number,
1006 + projectId: activePullRequestSurface.projectId as ProjectId,
1007 + host:
1008 + activePullRequestSurface.host ??
1009 + (selectedProject?.repositoryIdentity
1010 + ? pullRequestHostOf(
1011 + selectedProject.repositoryIdentity,
1012 + selectedProject.repositoryIdentity.provider as SourceControlProviderKind,
1013 + )
1014 + : undefined),
1015 + }
1016 + : null;
1017 +
1018 + const selectSurfaceInUrl = (surface: PullRequestSurface | null) =>
1019 + updateSearch(
1020 + surface === null
1021 + ? clearedSelection
1022 + : {
1023 + repository: surface.repository,
1024 + number: surface.number,
1025 + selectedProjectId: surface.projectId as ProjectId,
1026 + selectedHost: surface.host,
1027 + ...(surface.environmentId === undefined
1028 + ? {}
1029 + : { selectedEnvironmentId: surface.environmentId as EnvironmentId }),
1030 + },
1031 + );
1032 +
1033 + const toggleRightPanel = () => {
1034 + if (rightPanelRef === null) return;
1035 + if (rightPanelState.isOpen) {
1036 + useRightPanelStore.getState().close(rightPanelRef);
1037 + updateSearch(clearedSelection);
1038 + return;
1039 + }
1040 + if (selectedPullRequestSurface === null) return;
1041 + useRightPanelStore.getState().show(rightPanelRef);
1042 + selectSurfaceInUrl(selectedPullRequestSurface);
1043 + };
1044 +
1045 + const unavailableProjects = new Map(
1046 + listErrors.map(
1047 + (error) =>
1048 + [
1049 + pullRequestProjectKey({ id: error.projectId, environmentId: error.environmentId }),
1050 + error.message,
1051 + ] as const,
1052 + ),
1053 + );
1054 +
1055 + const selectEntry = (entry: PullRequestRowTarget) => {
1056 + if (rightPanelRef === null) return;
1057 + useRightPanelStore.getState().openPullRequest(rightPanelRef, entry);
1058 + updateSearch({
1059 + repository: entry.repository,
1060 + number: entry.number,
1061 + selectedProjectId: entry.projectId,
1062 + selectedEnvironmentId: entry.environmentId,
1063 + selectedHost: entry.host,
1064 + });
1065 + };
1066 +
1067 + const searchInput = (
1068 + <PullRequestSearchInput
1069 + value={search.q ?? ""}
1070 + busy={typedQuery.length > 0 && (!querySettled || showingCarried)}
1071 + onChange={(query) => updateListScope({ q: query || undefined })}
1072 + />
1073 + );
1074 + const panelToggleControls = (
1075 + <PanelLayoutControls
1076 + showTerminalControl={false}
1077 + showThreadPanelControl={false}
1078 + terminalAvailable={false}
1079 + terminalOpen={false}
1080 + terminalShortcutLabel={null}
1081 + threadPanelOpen={false}
1082 + threadPanelPresentation="inline"
1083 + threadPanelShortcutLabel={null}
1084 + onToggleThreadPanel={() => undefined}
1085 + rightPanelAvailable={rightPanelAvailable}
1086 + rightPanelOpen={rightPanelState.isOpen}
1087 + rightPanelShortcutLabel={shortcutLabelForCommand(keybindings, "rightPanel.toggle")}
1088 + rightPanelUnavailableLabel="Select a pull request first"
1089 + onToggleTerminal={() => undefined}
1090 + onToggleRightPanel={toggleRightPanel}
1091 + />
1092 + );
1093 + const openPanelControls = (
1094 + <div
1095 + className="absolute top-[var(--workspace-controls-top)] right-[var(--workspace-controls-right)] z-50 mr-px flex h-[var(--workspace-topbar-height)] items-center gap-1 [-webkit-app-region:no-drag]"
1096 + data-workspace-titlebar-controls
1097 + >
1098 + {rightPanelState.isOpen ? (
1099 + <RightPanelMaximizeControl
1100 + maximized={rightPanelMaximized}
1101 + onToggle={toggleRightPanelMaximized}
1102 + />
1103 + ) : null}
1104 + {panelToggleControls}
1105 + </div>
1106 + );
1107 + const carriedToNothing =
1108 + shownCount === 0 &&
1109 + typedQuery.length === 0 &&
1110 + (!querySettled || (showingCarried && listQuery.isPending));
1111 + const listBody = (
1112 + <>
1113 + {!capabilityKnown ? (
1114 + <PullRequestListGhost rows={7} />
1115 + ) : !pullRequestsSupported ? (
1116 + <PullRequestsUnavailableState
1117 + title="Pull requests unavailable"
1118 + error="Update your T3 Code servers to browse pull requests."
1119 + />
1120 + ) : firstLoad ? (
1121 + <PullRequestListGhost rows={7} />
1122 + ) : listQuery.error && shownCount === 0 ? (
1123 + <PullRequestsUnavailableState
1124 + error={listQuery.error}
1125 + refreshing={listQuery.isPending}
1126 + onRetry={() => listQuery.refresh()}
1127 + />
1128 + ) : carriedToNothing ? (
1129 + <PullRequestListGhost rows={7} />
1130 + ) : shownCount === 0 ? (
1131 + <PullRequestListEmptyState
1132 + hasProjects={!projectsKnown || projects.length > 0}
1133 + refreshing={refreshing}
1134 + onRefresh={() => void refreshFromHost()}
1135 + query={typedQuery}
1136 + filtered={
1137 + menuFiltered ||
1138 + search.state !== "open" ||
1139 + search.involvement !== "all" ||
1140 + scopedProjectId !== undefined ||
1141 + search.host !== undefined
1142 + }
1143 + searching={typedQuery.length > 0 && (!querySettled || showingCarried)}
1144 + canLoadMore={listData?.truncated === true && (canContinue || pageSize < MAX_PAGE_SIZE)}
1145 + loadingMore={loadingMore}
1146 + onClearQuery={() => updateListScope({ q: undefined })}
1147 + onLoadMore={loadMore}
1148 + />
1149 + ) : (
1150 + <PullRequestListGroups
1151 + groups={displayGroups}
1152 + environmentLabels={capableEnvironments.length > 1 ? environmentLabels : null}
1153 + query={typedParsed.text}
1154 + selected={selected}
1155 + showProvider={showProvider}
1156 + statsRef={registerStatsRow}
1157 + onSelect={selectEntry}
1158 + hostActionsOf={hostActionsOf}
1159 + onActed={onSpeedAction}
1160 + closingKeys={closingKeys}
1161 + sweepingKeys={closeSweepKeys}
1162 + onCloseSweepStart={startCloseSweep}
1163 + />
1164 + )}
1165 +
1166 + {listQuery.error && shownCount > 0 ? (
1167 + <div className="flex items-center justify-between gap-3 rounded-lg border border-warning/30 bg-warning-surface px-3 py-2 text-xs">
1168 + <span>{listQuery.error} Showing the last pull requests loaded.</span>
1169 + <Button size="xs" variant="outline" onClick={() => listQuery.refresh()}>
1170 + Retry
1171 + </Button>
1172 + </div>
1173 + ) : null}
1174 + {listData?.truncated && entries.length > 0 ? (
1175 + <div className="flex justify-center py-3 text-xs text-muted-foreground">
1176 + {loadingMore ? (
1177 + <span className="flex items-center gap-2">
1178 + <Spinner aria-hidden size="sm" />
1179 + {sentCursors === null ? "Updating pull requests" : "Loading more"}
1180 + </span>
1181 + ) : canContinue || pageSize < MAX_PAGE_SIZE ? (
1182 + <Button
1183 + size="sm"
1184 + variant="outline"
1185 + onClick={loadMore}
1186 + disabled={listQuery.isPending || showingCarried}
1187 + >
1188 + Load more pull requests
1189 + </Button>
1190 + ) : (
1191 + <span>Narrow your search to find more pull requests.</span>
1192 + )}
1193 + </div>
1194 + ) : null}
1195 + </>
1196 + );
1197 + const hostEntries = hosts.length > 0 ? hosts : expectedHosts;
1198 + const hostMenuOptions: ReadonlyArray<PullRequestFilterOption<string>> = [
1199 + { value: "", label: "All", Icon: Plug2Icon },
1200 + ...hostEntries.map((entry) => {
1201 + const summary = hosts.find((host) => host.host === entry.host);
1202 + return {
1203 + value: entry.host,
1204 + label: pullRequestHostLabel(hostEntries, entry),
1205 + Icon: getSourceControlPresentationForKind(entry.kind).Icon,
1206 + ...(summary === undefined || summary.configured
1207 + ? {}
1208 + : { unavailable: summary.detail ?? "This host could not be read." }),
1209 + };
1210 + }),
1211 + ];
1212 + const serverMenuOptions: ReadonlyArray<PullRequestFilterOption<string>> = [
1213 + { value: "", label: "All servers", Icon: LayersIcon },
1214 + ...capableEnvironments.map((environment) => ({
1215 + value: environment.environmentId,
1216 + label: environment.label,
1217 + Icon: environmentMachineIcon(resolveEnvironmentMachineKind(environment.serverConfig)),
1218 + })),
1219 + ];
1220 + const sortMenu = (
1221 + <PullRequestCompactFilterMenu
1222 + label="Sort pull requests"
1223 + triggerIcon={<ArrowDownUpIcon aria-hidden className="size-4" />}
1224 + triggerLabel="Sort"
1225 + outlined
1226 + value={sort}
1227 + options={SORT_OPTIONS}
1228 + onChange={(next) => updateListScope({ sort: next })}
1229 + />
1230 + );
1231 + const filtersMenu = (
1232 + <PullRequestFiltersMenuInSidebarOrder
1233 + onOpenChange={setFiltersOpen}
1234 + state={search.state}
1235 + stateOptions={STATE_TABS}
1236 + onState={(state) => updateListScope({ state })}
1237 + involvement={search.involvement}
1238 + involvementOptions={INVOLVEMENT_TABS}
1239 + onInvolvement={(involvement) => updateListScope({ involvement })}
1240 + filters={
1241 + typedParsed.filters.draft
1242 + ? { ...menuFilters, draft: typedParsed.filters.draft }
1243 + : menuFilters
1244 + }
1245 + onFilters={(value) => {
1246 + const { query, filters: next } = applyPullRequestDraftFilterChange(
1247 + typedQuery,
1248 + menuFilters,
1249 + value,
1250 + );
1251 + updateListScope({
1252 + ...(query === typedQuery ? {} : { q: query || undefined }),
1253 + draft: next.draft,
1254 + review: next.review,
1255 + checks: next.checks,
1256 + author: next.author,
1257 + labels: next.labels?.flatMap((group) => group),
1258 + });
1259 + }}
1260 + authorOptions={facets.authors}
1261 + labelOptions={facets.labels}
1262 + host={search.host}
1263 + hostOptions={hostMenuOptions}
1264 + onHost={(host) => updateListScope({ host })}
1265 + server={scopedEnvironmentId ?? undefined}
1266 + serverOptions={serverMenuOptions}
1267 + onServer={(server) => updateListScope({ environmentId: server, projectId: undefined })}
1268 + projects={scopedProjects}
1269 + projectId={scopedProjectId}
1270 + projectEnvironmentId={scopedProject?.environmentId}
1271 + unavailable={unavailableProjects}
1272 + onProject={(projectId, environmentId) =>
1273 + updateListScope(environmentId === undefined ? { projectId } : { projectId, environmentId })
1274 + }
1275 + />
1276 + );
1277 + const columnProps = {
1278 + refreshing,
1279 + onRefresh: () => void refreshFromHost(),
1280 + searchValue: search.q ?? "",
1281 + involvement: search.involvement,
1282 + state: search.state,
1283 + host: search.host,
1284 + hostMenuOptions,
1285 + onInvolvement: (involvement: PullRequestInvolvement) => updateListScope({ involvement }),
1286 + onState: (state: PullRequestListState) => updateListScope({ state }),
1287 + onHost: (host: string | undefined) => updateListScope({ host }),
1288 + searchInput,
1289 + sortMenu,
1290 + filtersMenu,
1291 + rightPanelControl: !pullRequestsSupported ? null : (
1292 + <span
1293 + aria-hidden
1294 + className={cn(
1295 + "shrink-0",
1296 + rightPanelState.isOpen ? "-ml-3 w-0" : "w-7 sm:w-5",
1297 + panelAnimationsActive && "transition-[width,margin] ease-out",
1298 + )}
1299 + style={
1300 + panelAnimationsActive
1301 + ? { transitionDuration: `${panelAnimationDurationMs}ms` }
1302 + : undefined
1303 + }
1304 + />
1305 + ),
1306 + titlebarControls:
1307 + // While the panel is closed the strip lives inside the header: a no-drag
1308 + // descendant beats the header's desktop drag-region, where a floating
1309 + // sibling loses (app-region hit-testing ignores z-index).
1310 + pullRequestsSupported ? (
1311 + rightPanelPresent ? (
1312 + <span
1313 + aria-hidden
1314 + className="pointer-events-none absolute inset-y-0 left-full w-7 [-webkit-app-region:no-drag]"
1315 + />
1316 + ) : (
1317 + openPanelControls
1318 + )
1319 + ) : null,
1320 + rightPanelOpen: rightPanelState.isOpen,
1321 + maximizedAway: rightPanelMaximized,
1322 + listBody,
1323 + scrollRef,
1324 + };
1325 +
1326 + const activateSurface = (surface: PullRequestSurface) => {
1327 + if (rightPanelRef === null) return;
1328 + useRightPanelStore.getState().activateSurface(rightPanelRef, surface.id);
1329 + selectSurfaceInUrl(surface);
1330 + };
1331 + const closeSurface = (surface: PullRequestSurface) => {
1332 + if (rightPanelRef === null) return;
1333 + useRightPanelStore.getState().closeSurface(rightPanelRef, surface.id);
1334 + const next = selectActiveRightPanelSurface(
1335 + useRightPanelStore.getState().byThreadKey,
1336 + rightPanelRef,
1337 + );
1338 + selectSurfaceInUrl(next?.kind === "pull-request" ? next : null);
1339 + };
1340 + const closeOtherSurfaces = (surface: PullRequestSurface) => {
1341 + if (rightPanelRef === null) return;
1342 + useRightPanelStore.getState().closeOtherSurfaces(rightPanelRef, surface.id);
1343 + selectSurfaceInUrl(surface);
1344 + };
1345 + const closeSurfacesToRight = (surface: PullRequestSurface) => {
1346 + if (rightPanelRef === null) return;
1347 + useRightPanelStore.getState().closeSurfacesToRight(rightPanelRef, surface.id);
1348 + const next = selectActiveRightPanelSurface(
1349 + useRightPanelStore.getState().byThreadKey,
1350 + rightPanelRef,
1351 + );
1352 + selectSurfaceInUrl(next?.kind === "pull-request" ? next : null);
1353 + };
1354 + const closeAllSurfaces = () => {
1355 + if (rightPanelRef === null) return;
1356 + useRightPanelStore.getState().closeAllSurfaces(rightPanelRef);
1357 + selectSurfaceInUrl(null);
1358 + };
1359 +
1360 + const copyPullRequestFromShortcut = useEffectEvent((event: KeyboardEvent) => {
1361 + if (!openPanelPullRequestUrl) return;
1362 + event.preventDefault();
1363 + event.stopPropagation();
1364 + if (event.repeat) return;
1365 + const url = openPanelPullRequestUrl;
1366 + void writeTextToClipboard(url, "pull request link").then(
1367 + (didCopy) => {
1368 + if (didCopy)
1369 + toastManager.add({ type: "success", title: "PR link copied", description: url });
1370 + },
1371 + (error) => {
1372 + toastManager.add({
1373 + type: "error",
1374 + title: "Failed to copy PR link",
1375 + description: error instanceof Error ? error.message : "An error occurred.",
1376 + });
1377 + },
1378 + );
1379 + });
1380 + const closeActiveSurfaceFromShortcut = useEffectEvent((event: KeyboardEvent) => {
1381 + if (activePullRequestSurface === null) return;
1382 + event.preventDefault();
1383 + event.stopPropagation();
1384 + if (!event.repeat) closeSurface(activePullRequestSurface);
1385 + });
1386 + const toggleRightPanelFromShortcut = useEffectEvent((event: KeyboardEvent) => {
1387 + if (!rightPanelAvailable) return;
1388 + event.preventDefault();
1389 + event.stopPropagation();
1390 + if (!event.repeat) toggleRightPanel();
1391 + });
1392 + const toggleRightPanelMaximizedFromShortcut = useEffectEvent((event: KeyboardEvent) => {
1393 + if (!rightPanelState.isOpen) return;
1394 + event.preventDefault();
1395 + event.stopPropagation();
1396 + if (!event.repeat) toggleRightPanelMaximized();
1397 + });
1398 + useEffect(() => {
1399 + const onKeyDown = (event: KeyboardEvent) => {
1400 + if (event.defaultPrevented || isCommandPaletteOpen()) return;
1401 + const command = resolveShortcutCommand(event, keybindings, {
1402 + context: getShortcutContext(),
1403 + });
1404 + if (command === "rightPanel.close") closeActiveSurfaceFromShortcut(event);
1405 + if (command === "rightPanel.toggle") toggleRightPanelFromShortcut(event);
1406 + if (command === "rightPanel.toggleMaximized") toggleRightPanelMaximizedFromShortcut(event);
1407 + if (command === "thread.copyReference") copyPullRequestFromShortcut(event);
1408 + };
1409 + document.addEventListener("keydown", onKeyDown);
1410 + return () => document.removeEventListener("keydown", onKeyDown);
1411 + }, [keybindings]);
1412 +
1413 + return (
1414 + <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none">
1415 + <div className="relative flex min-h-0 flex-1">
1416 + {pullRequestsSupported && rightPanelPresent ? openPanelControls : null}
1417 + <PullRequestsColumn {...columnProps} />
1418 +
1419 + {rightPanelPresent && renderedPullRequestSurface && panelEnvironmentId !== null ? (
1420 + <RightPanelTabs
1421 + mode="inline"
1422 + open={rightPanelState.isOpen}
1423 + maximized={rightPanelMaximized}
1424 + keybindings={keybindings}
1425 + getShortcutContext={getShortcutContext}
1426 + widthStorageKey="t3code:pull-request-panel-width"
1427 + defaultWidth={typeof window === "undefined" ? 640 : Math.floor(window.innerWidth / 2)}
1428 + surfaces={renderedRightPanelSurfaces}
1429 + environmentId={panelEnvironmentId}
1430 + activeSurfaceId={renderedPullRequestSurface.id}
1431 + pendingSurfaceIds={EMPTY_PENDING_SURFACES}
1432 + previewSessions={EMPTY_PREVIEW_SESSIONS}
1433 + desktopByTabId={EMPTY_PREVIEW_DESKTOP_STATE}
1434 + terminalLabelsById={EMPTY_TERMINAL_LABELS}
1435 + onActivate={(surface) => {
1436 + if (surface.kind === "pull-request") activateSurface(surface);
1437 + }}
1438 + onCloseSurface={(surface) => {
1439 + if (surface.kind === "pull-request") closeSurface(surface);
1440 + }}
1441 + onCloseOtherSurfaces={(surface) => {
1442 + if (surface.kind === "pull-request") closeOtherSurfaces(surface);
1443 + }}
1444 + onCloseSurfacesToRight={(surface) => {
1445 + if (surface.kind === "pull-request") closeSurfacesToRight(surface);
1446 + }}
1447 + onCloseAllSurfaces={closeAllSurfaces}
1448 + onMoveSurface={(surfaceId, toIndex) => {
1449 + if (rightPanelRef !== null)
1450 + useRightPanelStore.getState().moveSurface(rightPanelRef, surfaceId, toIndex);
1451 + }}
1452 + onCopyFilePath={() => undefined}
1453 + onAddBrowser={() => undefined}
1454 + onAddBrowserInProfile={() => undefined}
1455 + onAddTerminal={() => undefined}
1456 + onAddDiff={() => undefined}
1457 + onAddFiles={() => undefined}
1458 + onAddPullRequest={() => undefined}
1459 + onAddPullRequests={() => undefined}
1460 + onAddDevice={() => undefined}
1461 + browserAvailable={false}
1462 + terminalAvailable={false}
1463 + diffAvailable={false}
1464 + filesAvailable={false}
1465 + pullRequestAvailable={false}
1466 + pullRequestsAvailable={false}
1467 + deviceAvailable={false}
1468 + pullRequestStatusSeeds={listedPullRequestTabStatuses}
1469 + >
1470 + <PullRequestDetailPanel
1471 + getShortcutContext={getShortcutContext}
1472 + shortcutsEnabled={activePullRequestSurface?.id === renderedPullRequestSurface.id}
1473 + key={renderedPullRequestSurface.id}
1474 + environmentId={panelEnvironmentId}
1475 + onGuideShown={onGuideShown}
1476 + onSelectPullRequest={(reference) => {
1477 + if (rightPanelRef === null) return;
1478 + useRightPanelStore.getState().openPullRequest(rightPanelRef, {
1479 + projectId: reference.projectId,
1480 + repository: reference.repository,
1481 + number: reference.number,
1482 + ...(reference.host ? { host: reference.host } : {}),
1483 + environmentId: panelEnvironmentId,
1484 + });
1485 + updateSearch({
1486 + repository: reference.repository,
1487 + number: reference.number,
1488 + selectedHost: reference.host,
1489 + selectedProjectId: reference.projectId,
1490 + selectedEnvironmentId: panelEnvironmentId,
1491 + });
1492 + }}
1493 + reference={{
1494 + projectId: renderedPullRequestSurface.projectId as ProjectId,
1495 + repository: renderedPullRequestSurface.repository,
1496 + number: renderedPullRequestSurface.number,
1497 + ...(renderedPullRequestSurface.host
1498 + ? { host: renderedPullRequestSurface.host }
1499 + : {}),
1500 + }}
1501 + listEntry={
1502 + listedPullRequestsBySurface.get(
1503 + pullRequestListEntryId(renderedPullRequestSurface),
1504 + ) ?? null
1505 + }
1506 + refreshToken={detailRefreshToken}
1507 + onActed={(action, phase = "done") => {
1508 + // From every row held, not the ones on screen: a pull request closed from an open
1509 + // list has left the screen, and reopening it has to find it anyway.
1510 + const acted = heldPullRequestsBySurface.get(
1511 + pullRequestListEntryId(renderedPullRequestSurface),
1512 + );
1513 + const stateOnly =
1514 + action !== undefined &&
1515 + acted !== undefined &&
1516 + pullRequestOverrideAfterAction(acted, action, new Date(), 0) !== null;
1517 + if (stateOnly) {
1518 + const key = pullRequestEntryKey(acted);
1519 + if (phase === "sent" && action !== "merge") {
1520 + detailOverrideTokens.current.set(key, overrideEntry(acted, action));
1521 + }
1522 + if (phase === "failed" && action !== "merge") {
1523 + revertOverride(key, detailOverrideTokens.current.get(key) ?? null);
1524 + }
1525 + if (phase !== "sent") detailOverrideTokens.current.delete(key);
1526 + if (phase === "done" && action === "merge") {
1527 + overrideEntry(acted, action);
1528 + refreshListAndStats(undefined, panelEnvironmentId);
1529 + }
1530 + return;
1531 + }
1532 + if (phase === "done") refreshListAndStats(undefined, panelEnvironmentId);
1533 + }}
1534 + />
1535 + </RightPanelTabs>
1536 + ) : null}
1537 + </div>
1538 + </SidebarInset>
1539 + );
1540 +}
1541 +
1542 +function PullRequestFiltersMenuInSidebarOrder(
1543 + props: ComponentProps<typeof PullRequestFiltersMenu>,
1544 +) {
1545 + const sidebarProjectGroups = useSidebarProjectGroups();
1546 + const projects = sortProjectsByGroupOrder(props.projects, sidebarProjectGroups);
1547 + return <PullRequestFiltersMenu {...props} projects={projects} />;
1548 +}
apps/web/src/routes/_chat.pull-requests.tsx
+7 -1556
@@ -1,151 +1,11 @@
1 -import { applyPullRequestDraftFilterChange } from "@t3tools/client-runtime/pull-request-query";
2 -import { Spinner } from "~/components/ui/spinner";
3 -import type { PullRequestSpeedActionResult } from "~/components/pullRequest/PullRequestSpeedActions";
4 -import { usePullRequestCloseBatch } from "~/components/pullRequest/usePullRequestActions";
5 -import { SidebarPointerSensor } from "~/components/Sidebar.pointer";
6 -import { resolveSidebarSweepKeys } from "~/components/Sidebar.logic";
7 -import { sortProjectsByGroupOrder } from "@t3tools/client-runtime/state/project-grouping";
8 -import { pullRequestHostOf, resolveEnvironmentMachineKind } from "@t3tools/contracts";
9 -import type {
10 - EnvironmentId,
11 - ProjectId,
12 - PullRequestAction,
13 - PullRequestInvolvement,
14 - PullRequestListCursors,
15 - PullRequestListInput,
16 - PullRequestListResult,
17 - PullRequestListState,
18 - SourceControlProviderKind,
19 -} from "@t3tools/contracts";
20 -import { useAtomValue } from "@effect/atom-react";
21 -import { createFileRoute, useNavigate } from "@tanstack/react-router";
22 -import { ArrowDownUpIcon, LayersIcon, Plug2Icon } from "lucide-react";
23 -import { useEffect, useEffectEvent, useRef, useState, type ComponentProps } from "react";
1 +import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
2 +import { createFileRoute } from "@tanstack/react-router";
3
25 -import {
26 - collectPullRequestListFacets,
27 - narrowPullRequestsToFilters,
28 - mergePullRequestDiffStats,
29 - pullRequestEntryKey,
30 - rankPullRequestMatches,
31 - readPullRequestListSnapshot,
32 - writePullRequestListSnapshot,
33 - pullRequestStatsRefreshBatches,
34 - pullRequestStatsRequestBatches,
35 - retainVisiblePullRequestStatsBatches,
36 - type EnvironmentPullRequestEntry,
37 - type MergedPullRequestList,
38 - type PullRequestDiffStats,
39 - type PullRequestStatsBatch,
40 - type PullRequestStatsPolicy,
41 - type PullRequestStatsScope,
42 - type PullRequestPartitionsSnapshot,
43 - type PullRequestListOverride,
44 - pullRequestOverrideAfterAction,
45 - reusePullRequestEntries,
46 - settlePullRequestOverrides,
47 - largestPullRequestReadCount,
48 -} from "../components/pullRequest/pullRequestList.logic";
49 -import {
50 - pullRequestListPreferences,
51 - type PullRequestListPreferencePatch,
52 - type PullRequestListSort,
53 - writePullRequestListPreferences,
54 -} from "../components/pullRequest/pullRequestListPreferences";
55 -import { environmentMachineIcon } from "../components/EnvironmentMachineIcon";
56 -import { PullRequestDetailPanel } from "../components/pullRequest/PullRequestDetailPanel";
57 -import {
58 - PullRequestFiltersMenu,
59 - PullRequestSearchInput,
60 - pullRequestHostLabel,
61 - pullRequestProjectKey,
62 - type PullRequestFilterOption,
63 -} from "../components/pullRequest/PullRequestListFilters";
64 -import { PullRequestCompactFilterMenu } from "../components/pullRequest/PullRequestCompactFilterMenu";
65 -import {
66 - INVOLVEMENT_TABS,
67 - SORT_OPTIONS,
68 - STATE_TABS,
69 -} from "../components/pullRequest/pullRequestListOptions";
70 -import { PullRequestsColumn } from "../components/pullRequest/PullRequestsColumn";
71 -import { PullRequestListGroups } from "../components/pullRequest/PullRequestListGroups";
72 -import {
73 - pullRequestGroups,
74 - pullRequestListEntryId,
75 - usePullRequestDisplayGroups,
76 - usePullRequestQueryFilters,
77 - usePullRequestScope,
78 - type PullRequestsSearch,
79 -} from "../components/pullRequest/usePullRequestListView";
80 -import { PullRequestListEmptyState } from "../components/pullRequest/PullRequestListEmptyState";
81 -import { PullRequestListGhost } from "../components/pullRequest/PullRequestGhosts";
82 -import { type PullRequestRowTarget } from "../components/pullRequest/PullRequestRow";
83 -import { PullRequestsUnavailableState } from "../components/pullRequest/PullRequestsUnavailableState";
84 -import { RightPanelTabs } from "../components/RightPanelTabs";
85 -import { isCommandPaletteOpen } from "../commandPaletteBus";
86 -import { isElectron } from "../env";
87 -import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
88 -import { isTerminalFocused } from "../lib/terminalFocus";
89 -import {
90 - PanelLayoutControls,
91 - RightPanelMaximizeControl,
92 -} from "../components/chat/PanelLayoutControls";
93 -import { Button } from "../components/ui/button";
94 -import { SidebarInset } from "../components/ui/sidebar";
95 -import { useLiveRefresh } from "../hooks/useLiveRefresh";
96 -import { useStableCallback } from "../hooks/useStableCallback";
97 -import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl";
98 -import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
99 -import { toastManager } from "../components/ui/toast";
100 -import { useEscapeToGoBack } from "../hooks/useNavigateBack";
101 -import { usePanelAnimationSettings, usePanelPresence } from "../panelAnimations";
102 -import {
103 - PULL_REQUESTS_PANEL_REF,
104 - selectActiveRightPanelSurface,
105 - selectSelectedRightPanelSurface,
106 - selectThreadRightPanelState,
107 - useRightPanelStore,
108 - type PullRequestSurface,
109 -} from "../rightPanelStore";
110 -import { useSidebarProjectGroups } from "../hooks/useSidebarProjectGroups";
111 -import {
112 - pullRequestEnvironment,
113 - usePullRequestList,
114 - usePullRequestListStats,
115 - usePullRequestTurnRefreshes,
116 - type EnvironmentQueryTarget,
117 -} from "../state/pullRequests";
118 -import { useAtomCommand } from "../state/use-atom-command";
119 -import { cn } from "~/lib/utils";
120 -import { primaryServerKeybindingsAtom } from "~/state/server";
121 -import { getSourceControlPresentationForKind } from "~/sourceControlPresentation";
4 +import { type PullRequestListSort } from "../components/pullRequest/pullRequestListPreferences";
5 +import { SORT_OPTIONS } from "../components/pullRequest/pullRequestListOptions";
6 +import { type PullRequestsSearch } from "../components/pullRequest/usePullRequestListView";
7 +import { PullRequestsPage } from "../components/pullRequest/PullRequestsPage";
8
123 -function getShortcutContext() {
124 - return {
125 - terminalFocus: isTerminalFocused(),
126 - terminalOpen: false,
127 - previewFocus: false,
128 - previewOpen: false,
129 - modelPickerOpen: false,
130 - isWeb: !isElectron,
131 - isDesktop: isElectron,
132 - };
133 -}
134 -
135 -/**
136 - * One whole page from the host and no more: every provider asks for one row beyond the page as
137 - * its "is there more" probe, and GitHub serves a hundred per request — so asking for ninety-nine
138 - * costs one round trip where a hundred costs two.
139 - */
140 -const PAGE_SIZE = 99;
141 -const MAX_PAGE_SIZE = 500;
142 -const EMPTY_VIEWERS: PullRequestListResult["viewers"] = {};
143 -const EMPTY_PARTITIONS: PullRequestPartitionsSnapshot = { authored: [], reviewing: [] };
144 -const NO_LIST_TARGETS: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>> = [];
145 -const EMPTY_PREVIEW_SESSIONS = {};
146 -const EMPTY_PREVIEW_DESKTOP_STATE = {};
147 -const EMPTY_TERMINAL_LABELS = new Map<string, string>();
148 -const EMPTY_PENDING_SURFACES = new Set<string>();
9 const MAX_SEARCH_LABEL_CANDIDATES = 100;
10
11 function pullRequestSearchLabels(raw: unknown): Partial<Pick<PullRequestsSearch, "labels">> {
@@ -214,1414 +74,5 @@ export const Route = createFileRoute("/_chat/pull-requests")({
74 : {}),
75 ...pullRequestSearchLabels(raw.labels),
76 }),
217 - component: PullRequestsRouteView,
77 + component: PullRequestsPage,
78 });
219 -
220 -function PullRequestsRouteView() {
221 - useEscapeToGoBack();
222 - const search = Route.useSearch();
223 - const sort = search.sort ?? "ready";
224 - const statsPolicy: PullRequestStatsPolicy =
225 - sort === "ready" || sort === "largest" || sort === "smallest" ? "eager" : "visible";
226 - const navigate = useNavigate({ from: Route.fullPath });
227 - const keybindings = useAtomValue(primaryServerKeybindingsAtom);
228 - const {
229 - capableEnvironments,
230 - scopedEnvironmentId,
231 - environmentKey,
232 - capabilityKnown,
233 - pullRequestsSupported,
234 - projects,
235 - environmentLabels,
236 - scopedProjectId,
237 - scopedProject,
238 - scopedProjects,
239 - selectedProject,
240 - queryEnvironmentIds,
241 - environmentQueries,
242 - assignmentKey,
243 - linkedSelection,
244 - expectedHosts,
245 - projectsKnown,
246 - } = usePullRequestScope(search);
247 - const rightPanelRef = capableEnvironments.length === 0 ? null : PULL_REQUESTS_PANEL_REF;
248 - const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(rightPanelRef);
249 - const rightPanelState = useRightPanelStore((state) =>
250 - selectThreadRightPanelState(state.byThreadKey, rightPanelRef),
251 - );
252 - const selectedRightPanelSurface = useRightPanelStore((state) =>
253 - selectSelectedRightPanelSurface(state.byThreadKey, rightPanelRef),
254 - );
255 - const selectedPullRequestSurface =
256 - selectedRightPanelSurface?.kind === "pull-request" ? selectedRightPanelSurface : null;
257 - const activePullRequestSurface = rightPanelState.isOpen ? selectedPullRequestSurface : null;
258 - const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
259 - usePanelAnimationSettings();
260 - const rightPanelPresenceValue = {
261 - activeSurface: selectedPullRequestSurface,
262 - surfaces: rightPanelState.surfaces,
263 - };
264 - const rightPanelPresence = usePanelPresence(
265 - rightPanelState.isOpen && selectedPullRequestSurface !== null,
266 - rightPanelPresenceValue,
267 - panelAnimationsActive,
268 - rightPanelRef?.threadId ?? null,
269 - panelAnimationDurationMs,
270 - );
271 - const rightPanelPresent = rightPanelPresence.present;
272 - const renderedPullRequestSurface = rightPanelPresence.value?.activeSurface ?? null;
273 - const renderedRightPanelSurfaces = rightPanelPresence.value?.surfaces ?? [];
274 - const panelEnvironmentId =
275 - (renderedPullRequestSurface?.environmentId as EnvironmentId | undefined) ??
276 - selectedProject?.environmentId ??
277 - null;
278 - const updateSearch = (patch: {
279 - [Key in keyof PullRequestsSearch]?: PullRequestsSearch[Key] | undefined;
280 - }) =>
281 - void navigate({
282 - search: (previous: PullRequestsSearch): PullRequestsSearch => {
283 - const next = { ...previous, ...patch };
284 - return {
285 - involvement: next.involvement ?? previous.involvement,
286 - state: next.state ?? previous.state,
287 - ...(next.sort && next.sort !== "ready" ? { sort: next.sort } : {}),
288 - ...(next.repository ? { repository: next.repository } : {}),
289 - ...(next.number ? { number: next.number } : {}),
290 - ...(next.projectId ? { projectId: next.projectId } : {}),
291 - ...(next.environmentId ? { environmentId: next.environmentId } : {}),
292 - ...(next.host ? { host: next.host } : {}),
293 - ...(next.selectedHost ? { selectedHost: next.selectedHost } : {}),
294 - ...(next.selectedProjectId ? { selectedProjectId: next.selectedProjectId } : {}),
295 - ...(next.selectedEnvironmentId
296 - ? { selectedEnvironmentId: next.selectedEnvironmentId }
297 - : {}),
298 - ...(next.q ? { q: next.q } : {}),
299 - ...(next.draft ? { draft: next.draft } : {}),
300 - ...(next.review ? { review: next.review } : {}),
301 - ...(next.checks ? { checks: next.checks } : {}),
302 - ...(next.author ? { author: next.author } : {}),
303 - ...(next.labels && next.labels.length > 0 ? { labels: next.labels } : {}),
304 - };
305 - },
306 - replace: true,
307 - });
308 -
309 - const clearedSelection = {
310 - repository: undefined,
311 - number: undefined,
312 - selectedProjectId: undefined,
313 - selectedEnvironmentId: undefined,
314 - selectedHost: undefined,
315 - };
316 - const updateListScope = (patch: PullRequestListPreferencePatch) => {
317 - const currentPreferences = pullRequestListPreferences({
318 - ...search,
319 - ...patch,
320 - involvement: patch.involvement ?? search.involvement,
321 - state: patch.state ?? search.state,
322 - });
323 - writePullRequestListPreferences(currentPreferences);
324 - updateSearch(patch);
325 - };
326 -
327 - const typedQuery = (search.q ?? "").trim();
328 - const [filtersOpen, setFiltersOpen] = useState(false);
329 - const {
330 - sentQuery,
331 - querySettled,
332 - typedParsed,
333 - sentParsed,
334 - menuFilters,
335 - menuFiltered,
336 - filters,
337 - hasFilters,
338 - localFilters,
339 - hasLocalFilters,
340 - } = usePullRequestQueryFilters(search, typedQuery);
341 - const turnRefreshes = usePullRequestTurnRefreshes(
342 - environmentQueries.map(({ environmentId }) => environmentId),
343 - );
344 - const turnRefreshToken = turnRefreshes
345 - .map(([environmentId, revision]) => `${environmentId}:${revision}`)
346 - .join("|");
347 - const scopeKey = `${environmentKey}:${assignmentKey}:${search.state}:${search.involvement}:${scopedProjectId ?? ""}:${search.host ?? ""}:${search.draft ?? ""}:${search.review ?? ""}:${search.checks ?? ""}:${search.author ?? ""}:${search.labels?.join("\u0000") ?? ""}`;
348 - const filterKey = `${scopeKey}:${sentQuery}`;
349 - const statsScope: PullRequestStatsScope = { key: filterKey, policy: statsPolicy };
350 - const [page, setPage] = useState<{
351 - key: string;
352 - size: number;
353 - cursors: Readonly<Record<string, PullRequestListCursors>> | null;
354 - /**
355 - * An environment can say it has more without saying where to carry on from — its provider has
356 - * no cursor to give — and a continuation naming only the others would strand its rows on the
357 - * host forever.
358 - */
359 - regrown: ReadonlyArray<string>;
360 - }>({ key: filterKey, size: PAGE_SIZE, cursors: null, regrown: [] });
361 - const pageSize = page.key === filterKey ? page.size : PAGE_SIZE;
362 - const sentCursors = page.key === filterKey ? page.cursors : null;
363 - const sentRegrown = page.key === filterKey ? page.regrown : [];
364 -
365 - if (page.key !== filterKey) {
366 - setPage({ key: filterKey, size: PAGE_SIZE, cursors: null, regrown: [] });
367 - }
368 -
369 - const listTargets = environmentQueries.flatMap(({ environmentId, projectIds }) => {
370 - const cursors = sentCursors?.[environmentId];
371 - if (sentCursors !== null && cursors === undefined && !sentRegrown.includes(environmentId)) {
372 - return [];
373 - }
374 - return [
375 - {
376 - environmentId,
377 - input: {
378 - state: search.state,
379 - involvement: search.involvement,
380 - limit: pageSize,
381 - ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
382 - ...(projectIds ? { projectIds } : {}),
383 - ...(search.host ? { host: search.host } : {}),
384 - ...(hasFilters ? { filters } : {}),
385 - ...(sentParsed.text ? { query: sentParsed.text } : {}),
386 - ...(cursors === undefined ? {} : { cursors }),
387 - } satisfies PullRequestListInput,
388 - },
389 - ];
390 - });
391 - const listQuery = usePullRequestList(listTargets);
392 -
393 - /**
394 - * Kept as its own read rather than remembered from an earlier answer because an answer cannot
395 - * say which question it belongs to: mid-switch the text has already changed and the data has
396 - * not, and a search's answer would file itself under the workspace.
397 - */
398 - const baselineTargets = environmentQueries.map(({ environmentId, projectIds }) => ({
399 - environmentId,
400 - input: {
401 - state: search.state,
402 - involvement: search.involvement,
403 - limit: PAGE_SIZE,
404 - ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
405 - ...(projectIds ? { projectIds } : {}),
406 - ...(search.host ? { host: search.host } : {}),
407 - ...(menuFiltered ? { filters: menuFilters } : {}),
408 - } satisfies PullRequestListInput,
409 - }));
410 - const baselineQuery = usePullRequestList(baselineTargets);
411 - const baselineEmpty =
412 - baselineQuery.data?.entries.length === 0 &&
413 - baselineQuery.data.errors.length === 0 &&
414 - !baselineQuery.isPending &&
415 - baselineQuery.error === null;
416 - const facetTargets = (() => {
417 - if (!filtersOpen) return NO_LIST_TARGETS;
418 - return environmentQueries.map(({ environmentId, projectIds }) => ({
419 - environmentId,
420 - input: {
421 - state: "all",
422 - involvement: search.involvement,
423 - limit: PAGE_SIZE,
424 - ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
425 - ...(projectIds ? { projectIds } : {}),
426 - ...(search.host ? { host: search.host } : {}),
427 - } satisfies PullRequestListInput,
428 - }));
429 - })();
430 - const facetQuery = usePullRequestList(facetTargets);
431 - const partitionsWanted = search.involvement === "all" && typedQuery.length === 0;
432 - const partitionTargets = (() => {
433 - // The main list goes first. Besides putting the visible rows on screen sooner, it proves
434 - // which repositories the host search indexes, so an empty partition does not trigger the
435 - // expensive per-repository fallback.
436 - if (
437 - !partitionsWanted ||
438 - baselineQuery.data === null ||
439 - baselineQuery.data.entries.length === 0
440 - ) {
441 - return { authored: NO_LIST_TARGETS, reviewing: NO_LIST_TARGETS };
442 - }
443 - const targetsFor = (involvement: PullRequestInvolvement) =>
444 - environmentQueries.map(({ environmentId, projectIds }) => ({
445 - environmentId,
446 - input: {
447 - state: search.state,
448 - involvement,
449 - limit: PAGE_SIZE,
450 - ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
451 - ...(projectIds ? { projectIds } : {}),
452 - ...(search.host ? { host: search.host } : {}),
453 - ...(menuFiltered ? { filters: menuFilters } : {}),
454 - } satisfies PullRequestListInput,
455 - }));
456 - return { authored: targetsFor("authored"), reviewing: targetsFor("reviewing") };
457 - })();
458 - const authoredQuery = usePullRequestList(partitionTargets.authored);
459 - const reviewingQuery = usePullRequestList(partitionTargets.reviewing);
460 - const invalidate = useAtomCommand(pullRequestEnvironment.invalidate, { reportFailure: false });
461 - const [detailRefreshToken, setDetailRefreshToken] = useState(0);
462 - const [invalidating, setInvalidating] = useState(false);
463 - const refreshing = invalidating || listQuery.isPending;
464 -
465 - const [loaded, setLoaded] = useState<{
466 - environmentKey: string;
467 - scope: string;
468 - query: string;
469 - /** The answer this was built from, so a re-render with the same answer leaves it alone. */
470 - source: MergedPullRequestList | null;
471 - data: MergedPullRequestList;
472 - partitions?: PullRequestPartitionsSnapshot;
473 - } | null>(null);
474 - const [ordered, setOrdered] = useState<{
475 - key: string;
476 - source: MergedPullRequestList;
477 - entries: ReadonlyArray<EnvironmentPullRequestEntry>;
478 - } | null>(null);
479 - const [overrides, setOverrides] = useState<ReadonlyMap<string, PullRequestListOverride>>(
480 - () => new Map(),
481 - );
482 - const overrideToken = useRef(0);
483 - const overrideEntry = (
484 - entry: EnvironmentPullRequestEntry,
485 - action: PullRequestAction,
486 - ): number | null => {
487 - const token = ++overrideToken.current;
488 - const override = pullRequestOverrideAfterAction(entry, action, new Date(), token);
489 - if (override === null) return null;
490 - setOverrides((current) => new Map(current).set(pullRequestEntryKey(entry), override));
491 - return token;
492 - };
493 - const revertOverride = (key: string, token: number | null) => {
494 - if (token === null) return;
495 - setOverrides((current) => {
496 - if (current.get(key)?.token !== token) return current;
497 - const next = new Map(current);
498 - next.delete(key);
499 - return next;
500 - });
501 - };
502 - const detailOverrideTokens = useRef(new Map<string, number | null>());
503 - const onSpeedAction = useStableCallback(({ entry, action }: PullRequestSpeedActionResult) => {
504 - // Some hosts accept a merge before it completes. Let the next host read declare it merged.
505 - if (action !== "merge") overrideEntry(entry, action);
506 - });
507 - const onBatchClosed = useStableCallback((entry: EnvironmentPullRequestEntry) => {
508 - onSpeedAction({ entry, action: "close" });
509 - });
510 - const { close: closeBatch, closingKeys } = usePullRequestCloseBatch(onBatchClosed);
511 - const [snapshotEnvironmentKey, setSnapshotEnvironmentKey] = useState("");
512 - if (environmentKey.length > 0 && snapshotEnvironmentKey !== environmentKey) {
513 - setSnapshotEnvironmentKey(environmentKey);
514 - if (loaded?.environmentKey !== environmentKey) {
515 - const snapshot = readPullRequestListSnapshot(
516 - typeof window === "undefined" ? undefined : window.localStorage,
517 - environmentKey,
518 - );
519 - setLoaded(
520 - snapshot === null
521 - ? null
522 - : {
523 - environmentKey,
524 - scope: snapshot.scope,
525 - query: "",
526 - source: null,
527 - data: snapshot.data,
528 - ...(snapshot.partitions === undefined ? {} : { partitions: snapshot.partitions }),
529 - },
530 - );
531 - }
532 - }
533 - const settledList = listQuery.data !== null && !listQuery.isPending ? listQuery.data : null;
534 - const answeredPartitions =
535 - partitionsWanted && baselineEmpty
536 - ? EMPTY_PARTITIONS
537 - : partitionsWanted && authoredQuery.data !== null && reviewingQuery.data !== null
538 - ? { authored: authoredQuery.data.entries, reviewing: reviewingQuery.data.entries }
539 - : null;
540 - const heldPartitions =
541 - loaded !== null && loaded.environmentKey === environmentKey && loaded.scope === scopeKey
542 - ? loaded.partitions
543 - : undefined;
544 - const nextPartitions = answeredPartitions ?? heldPartitions;
545 - const loadedEntries =
546 - settledList === null
547 - ? null
548 - : ordered?.key === filterKey
549 - ? ordered.entries
550 - : settledList.entries;
551 - if (
552 - settledList !== null &&
553 - loadedEntries !== null &&
554 - (loaded === null ||
555 - loaded.source !== settledList ||
556 - loaded.environmentKey !== environmentKey ||
557 - loaded.scope !== scopeKey ||
558 - loaded.query !== sentQuery ||
559 - loaded.data.entries !== loadedEntries ||
560 - loaded.partitions?.authored !== nextPartitions?.authored ||
561 - loaded.partitions?.reviewing !== nextPartitions?.reviewing)
562 - ) {
563 - setLoaded({
564 - environmentKey,
565 - scope: scopeKey,
566 - query: sentQuery,
567 - source: settledList,
568 - data: { ...settledList, entries: loadedEntries },
569 - ...(nextPartitions === undefined ? {} : { partitions: nextPartitions }),
570 - });
571 - }
572 - const snapshotToWrite =
573 - loaded !== null &&
574 - loaded.source !== null &&
575 - loaded.environmentKey.length > 0 &&
576 - loaded.query.length === 0
577 - ? loaded
578 - : null;
579 - const snapshotViewers = baselineQuery.data?.viewers;
580 - const snapshotProviders = baselineQuery.data?.providers;
581 - useEffect(() => {
582 - if (snapshotToWrite === null) return;
583 - writePullRequestListSnapshot(
584 - typeof window === "undefined" ? undefined : window.localStorage,
585 - snapshotToWrite.environmentKey,
586 - {
587 - scope: snapshotToWrite.scope,
588 - data: {
589 - ...snapshotToWrite.data,
590 - viewers: snapshotViewers ?? snapshotToWrite.data.viewers,
591 - providers: snapshotProviders ?? snapshotToWrite.data.providers,
592 - },
593 - ...(snapshotToWrite.partitions === undefined
594 - ? {}
595 - : { partitions: snapshotToWrite.partitions }),
596 - },
597 - );
598 - }, [snapshotToWrite, snapshotViewers, snapshotProviders]);
599 - const narrowed = (() => {
600 - if (loaded === null || loaded.environmentKey !== environmentKey || loaded.scope === scopeKey) {
601 - return null;
602 - }
603 - const entries = narrowPullRequestsToFilters(loaded.data.entries, {
604 - state: search.state,
605 - projectId: scopedProjectId,
606 - host: search.host,
607 - });
608 - return entries.length === 0 ? null : { ...loaded.data, entries };
609 - })();
610 - // A grown page is read by the list and nothing else: the baseline always asks for one page, so
611 - // a host with no cursor to continue from — where "more" means asking for a longer page — would
612 - // have its extra rows thrown away for the ninety-nine the baseline keeps answering with.
613 - const answered =
614 - (sentQuery.length === 0 && sentCursors === null && pageSize === PAGE_SIZE
615 - ? baselineQuery.data
616 - : listQuery.data) ??
617 - (loaded?.scope === scopeKey && loaded.query === sentQuery ? loaded.data : null);
618 - const carried =
619 - (sentQuery.length === 0 ? baselineQuery.data : undefined) ??
620 - (loaded?.scope === scopeKey ? loaded.data : null) ??
621 - narrowed;
622 - const listData = answered ?? carried;
623 - const showingCarried = answered === null && carried !== null;
624 - const loadingMore = listQuery.isPending && listData !== null;
625 - const firstLoad = listQuery.isPending && listData === null;
626 -
627 - if (
628 - answered !== null &&
629 - !listQuery.isPending &&
630 - !(listQuery.error && listQuery.data === null) &&
631 - (ordered === null || ordered.key !== filterKey || ordered.source !== answered)
632 - ) {
633 - if (ordered === null || ordered.key !== filterKey) {
634 - setOrdered({
635 - key: filterKey,
636 - source: answered,
637 - entries: rankPullRequestMatches(answered.entries, sentParsed.text),
638 - });
639 - } else if (sentCursors !== null) {
640 - const held = new Set(ordered.entries.map(pullRequestEntryKey));
641 - const arrived = answered.entries.filter((entry) => !held.has(pullRequestEntryKey(entry)));
642 - const appended = rankPullRequestMatches(
643 - arrived.toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
644 - sentParsed.text,
645 - );
646 - setOrdered({ key: filterKey, source: answered, entries: [...ordered.entries, ...appended] });
647 - } else {
648 - setOrdered({
649 - key: filterKey,
650 - source: answered,
651 - entries: reusePullRequestEntries(
652 - ordered.entries,
653 - rankPullRequestMatches(answered.entries, sentParsed.text),
654 - pullRequestEntryKey,
655 - ),
656 - });
657 - }
658 - const answeredEntries = answered.entries;
659 - setOverrides((current) =>
660 - settlePullRequestOverrides(current, answeredEntries, pullRequestEntryKey, Date.now()),
661 - );
662 - }
663 -
664 - // From this question's own answer, never from the rows being held while it travels: a
665 - // continuation is a boundary in one listing, and carrying one across a search would ask the new
666 - // question to start where the old one stopped — skipping its newest matches entirely.
667 - const nextCursors = answered?.nextCursors ?? {};
668 - const regrown = (answered?.truncatedEnvironments ?? []).filter(
669 - (environmentId) => nextCursors[environmentId] === undefined,
670 - );
671 - const canContinue = !showingCarried && Object.keys(nextCursors).length > 0;
672 - const loadMore = () => {
673 - if (canContinue) {
674 - setPage({
675 - key: filterKey,
676 - size: regrown.length === 0 ? pageSize : Math.min(pageSize + PAGE_SIZE, MAX_PAGE_SIZE),
677 - cursors: nextCursors,
678 - regrown,
679 - });
680 - return;
681 - }
682 - setPage({
683 - key: filterKey,
684 - size: Math.min(pageSize + PAGE_SIZE, MAX_PAGE_SIZE),
685 - cursors: null,
686 - regrown: [],
687 - });
688 - };
689 -
690 - const refreshList = (includeRelated = false, actedEnvironmentId?: EnvironmentId) => {
691 - const related = (
692 - includeRelated
693 - ? [
694 - ...baselineTargets,
695 - ...facetTargets,
696 - ...partitionTargets.authored,
697 - ...partitionTargets.reviewing,
698 - ]
699 - : []
700 - ).filter(
701 - ({ environmentId }) =>
702 - actedEnvironmentId === undefined || environmentId === actedEnvironmentId,
703 - );
704 - if (sentCursors === null) {
705 - listQuery.refresh([
706 - ...listTargets.filter(
707 - ({ environmentId }) =>
708 - actedEnvironmentId === undefined || environmentId === actedEnvironmentId,
709 - ),
710 - ...related,
711 - ]);
712 - return;
713 - }
714 - if (related.length > 0) listQuery.refresh(related);
715 - const loadedCount =
716 - ordered?.key === filterKey ? largestPullRequestReadCount(ordered.entries) : pageSize;
717 - setPage({
718 - key: filterKey,
719 - regrown: [],
720 - size: Math.min(
721 - Math.max(pageSize, Math.ceil(loadedCount / PAGE_SIZE) * PAGE_SIZE),
722 - MAX_PAGE_SIZE,
723 - ),
724 - cursors: null,
725 - });
726 - };
727 -
728 - const appliedTurnRefreshToken = useRef("");
729 - const refreshAfterTurn = useEffectEvent(() => {
730 - if (sentCursors !== null) refreshList();
731 - });
732 - useEffect(() => {
733 - if (turnRefreshToken.length === 0 || appliedTurnRefreshToken.current === turnRefreshToken) {
734 - return;
735 - }
736 - appliedTurnRefreshToken.current = turnRefreshToken;
737 - refreshAfterTurn();
738 - }, [turnRefreshToken]);
739 -
740 - useLiveRefresh(
741 - () => {
742 - refreshList(true);
743 - },
744 - { enabled: pullRequestsSupported },
745 - );
746 -
747 - const viewers = baselineQuery.data?.viewers ?? listData?.viewers ?? EMPTY_VIEWERS;
748 - const listErrors = baselineQuery.data?.errors ?? listData?.errors ?? [];
749 - const facets = collectPullRequestListFacets(
750 - [
751 - ...(facetQuery.data?.entries ?? []),
752 - ...(baselineQuery.data?.entries ?? listData?.entries ?? []),
753 - ],
754 - search.state,
755 - );
756 -
757 - const scrollRef = useRef<HTMLDivElement>(null);
758 - const {
759 - entries,
760 - listedPullRequestTabStatuses,
761 - groups,
762 - entriesByStatsKey,
763 - heldPullRequestsBySurface,
764 - } = pullRequestGroups({
765 - known: ordered?.key === filterKey ? ordered.entries : (listData?.entries ?? []),
766 - providers: baselineQuery.data?.providers ?? listData?.providers ?? [],
767 - viewers,
768 - involvement: search.involvement,
769 - localFilters,
770 - hasLocalFilters,
771 - text: typedParsed.text,
772 - answeredLocally: querySettled && !showingCarried,
773 - baselineEmpty,
774 - held:
775 - loaded !== null && loaded.environmentKey === environmentKey && loaded.scope === scopeKey
776 - ? loaded.partitions
777 - : undefined,
778 - authored: partitionsWanted ? authoredQuery.data?.entries : undefined,
779 - reviewing: partitionsWanted ? reviewingQuery.data?.entries : undefined,
780 - partitionsWanted,
781 - });
782 -
783 - const visibleStatsKeys = useRef({ key: filterKey, values: new Set<string>() });
784 - const [statsByRow, setStatsByRow] = useState<PullRequestDiffStats>(() => new Map());
785 - const [statsTargetState, setStatsTargetState] = useState<{
786 - readonly key: string;
787 - readonly batches: ReadonlyArray<PullRequestStatsBatch>;
788 - }>({ key: filterKey, batches: [] });
789 - const statsBatches = statsTargetState.key === filterKey ? statsTargetState.batches : [];
790 - const statsTargets = statsBatches.map(({ environmentId, input }) => ({
791 - environmentId,
792 - input,
793 - }));
794 - const statsQuery = usePullRequestListStats(statsTargets);
795 - const statsObserver = useRef<IntersectionObserver | null>(null);
796 - const statsRows = useRef(new Set<HTMLDivElement>());
797 - // Called from a row's ref cleanup, which keeps the render it attached in; this reads the latest.
798 - const releaseStatsRow = useStableCallback((key: string | undefined) => {
799 - const visible = visibleStatsKeys.current;
800 - if (
801 - statsPolicy !== "visible" ||
802 - key === undefined ||
803 - !visible.values.delete(key) ||
804 - statsQuery.isPending
805 - ) {
806 - return;
807 - }
808 - setStatsTargetState((current) => {
809 - if (current.key !== visible.key) return current;
810 - const batches = retainVisiblePullRequestStatsBatches(current.batches, visible.values);
811 - return batches.length === current.batches.length ? current : { key: current.key, batches };
812 - });
813 - });
814 - // Every row takes this as its ref, so a new identity would detach and reattach them all.
815 - const registerStatsRow = useStableCallback((node: HTMLDivElement | null) => {
816 - if (node === null || typeof IntersectionObserver === "undefined") return;
817 - statsRows.current.add(node);
818 - statsObserver.current?.observe(node);
819 - return () => {
820 - statsRows.current.delete(node);
821 - statsObserver.current?.unobserve(node);
822 - releaseStatsRow(node.dataset.pullRequestStatsKey);
823 - };
824 - });
825 - // Arriving stats must not re-run the effects that ask for them.
826 - const readStatsProgress = useEffectEvent(() => ({
827 - statsByRow,
828 - pending: statsQuery.isPending,
829 - }));
830 - useEffect(() => {
831 - if (statsPolicy !== "eager") return;
832 - const { statsByRow: known } = readStatsProgress();
833 - const candidateKeys = visibleStatsKeys.current.values;
834 - setStatsTargetState((current) => {
835 - const batches = current.key === filterKey ? current.batches : [];
836 - const added = pullRequestStatsRequestBatches({
837 - entriesByKey: entriesByStatsKey,
838 - candidateKeys,
839 - policy: statsPolicy,
840 - activeBatches: batches,
841 - statsByRow: known,
842 - });
843 - if (added.length === 0 && current.key === filterKey) return current;
844 - return { key: filterKey, batches: [...batches, ...added] };
845 - });
846 - }, [filterKey, entriesByStatsKey, statsPolicy]);
847 - // The observer outlives the rows it watches, so it reads the rows held at the time it fires.
848 - const readStatsRows = useEffectEvent(() => entriesByStatsKey);
849 - useEffect(() => {
850 - if (statsPolicy !== "visible" || typeof IntersectionObserver === "undefined") return;
851 - visibleStatsKeys.current = { key: filterKey, values: new Set() };
852 - const observer = new IntersectionObserver(
853 - (observed) => {
854 - const visible = visibleStatsKeys.current;
855 - if (visible.key !== filterKey) return;
856 - let changed = false;
857 - const entered = new Set<string>();
858 - const entriesByKey = readStatsRows();
859 - for (const item of observed) {
860 - const key = (item.target as HTMLElement).dataset.pullRequestStatsKey;
861 - if (key === undefined) continue;
862 - const wasVisible = visible.values.has(key);
863 - if (item.isIntersecting && entriesByKey.has(key)) {
864 - visible.values.add(key);
865 - if (!wasVisible) entered.add(key);
866 - } else {
867 - visible.values.delete(key);
868 - }
869 - if (wasVisible !== visible.values.has(key)) changed = true;
870 - }
871 - if (!changed) return;
872 - const progress = readStatsProgress();
873 - setStatsTargetState((current) => {
874 - const batches = current.key === filterKey ? current.batches : [];
875 - const retained = progress.pending
876 - ? batches
877 - : retainVisiblePullRequestStatsBatches(batches, visible.values);
878 - const added = pullRequestStatsRequestBatches({
879 - entriesByKey,
880 - candidateKeys: entered,
881 - policy: statsPolicy,
882 - activeBatches: batches,
883 - statsByRow: progress.statsByRow,
884 - });
885 - if (added.length === 0 && retained.length === batches.length) return current;
886 - return { key: filterKey, batches: [...retained, ...added] };
887 - });
888 - },
889 - { root: scrollRef.current, rootMargin: "480px" },
890 - );
891 - statsObserver.current = observer;
892 - for (const row of statsRows.current) observer.observe(row);
893 - return () => {
894 - observer.disconnect();
895 - if (statsObserver.current === observer) statsObserver.current = null;
896 - };
897 - }, [filterKey, statsPolicy]);
898 - useEffect(() => {
899 - if (statsPolicy !== "visible" || statsQuery.isPending) return;
900 - const visible = visibleStatsKeys.current;
901 - setStatsTargetState((current) => {
902 - if (current.key !== filterKey || visible.key !== filterKey) return current;
903 - const batches = retainVisiblePullRequestStatsBatches(current.batches, visible.values);
904 - return batches.length === current.batches.length ? current : { key: current.key, batches };
905 - });
906 - }, [filterKey, statsPolicy, statsQuery.isPending]);
907 - const [mergedStats, setMergedStats] = useState<typeof statsQuery.stats>(null);
908 - if (statsQuery.stats !== null && statsQuery.stats !== mergedStats) {
909 - const stats = statsQuery.stats;
910 - setMergedStats(stats);
911 - setStatsByRow((previous) => mergePullRequestDiffStats(previous, stats));
912 - }
913 - // Stable so a refresh that resumes after awaiting the host compares against the scope on screen
914 - // by then, not the one it started from.
915 - const refreshListAndStats = useStableCallback(
916 - (
917 - requestedStatsScope: PullRequestStatsScope = statsScope,
918 - actedEnvironmentId?: EnvironmentId,
919 - ) => {
920 - refreshList(true, actedEnvironmentId);
921 - const visible = visibleStatsKeys.current;
922 - const batches = pullRequestStatsRefreshBatches({
923 - requestedScope: requestedStatsScope,
924 - currentScope: statsScope,
925 - entriesByKey: entriesByStatsKey,
926 - candidateKeys: visible.key === requestedStatsScope.key ? visible.values : new Set(),
927 - statsByRow,
928 - });
929 - if (batches !== null) {
930 - setStatsTargetState({ key: requestedStatsScope.key, batches });
931 - statsQuery.refresh(
932 - batches
933 - .filter(({ environmentId }) =>
934 - actedEnvironmentId === undefined ? true : environmentId === actedEnvironmentId,
935 - )
936 - .map(({ environmentId, input }) => ({ environmentId, input })),
937 - );
938 - }
939 - },
940 - );
941 - const refreshFromHost = async () => {
942 - const requestedStatsScope = statsScope;
943 - setInvalidating(true);
944 - // Atom commands settle into results rather than throwing.
945 - await Promise.all(
946 - queryEnvironmentIds.map((environmentId) => invalidate({ environmentId, input: {} })),
947 - );
948 - setInvalidating(false);
949 - refreshListAndStats(requestedStatsScope);
950 - setDetailRefreshToken((token) => token + 1);
951 - };
952 - const {
953 - hosts,
954 - displayGroups,
955 - shownCount,
956 - hostActionsOf,
957 - closeSweepRows,
958 - listedPullRequestsBySurface,
959 - } = usePullRequestDisplayGroups({
960 - answered,
961 - host: search.host,
962 - groups,
963 - statsByRow,
964 - overrides,
965 - state: search.state,
966 - localFilters,
967 - hasLocalFilters,
968 - viewers,
969 - sort,
970 - text: typedParsed.text,
971 - involvement: search.involvement,
972 - });
973 - const showProvider = hosts.length > 1;
974 - const [closeSweepKeys, setCloseSweepKeys] = useState<ReadonlySet<string>>(() => new Set());
975 - const closeSensorRef = useRef<SidebarPointerSensor | null>(null);
976 - // A sweep spans many renders; each step reads the rows on screen at that moment.
977 - const readCloseSweep = useStableCallback(() => ({
978 - displayGroups,
979 - closeSweepRows,
980 - closingKeys,
981 - closeBatch,
982 - hostActionsOf,
983 - }));
984 - useEffect(
985 - () => () => closeSensorRef.current?.cancel(),
986 - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- The pointer sensor lives outside React; a new list under a sweep in progress must end it.
987 - [filterKey, search.q, sort],
988 - );
989 - useEffect(() => {
990 - const onKeyDown = (event: KeyboardEvent) => {
991 - if (event.key !== "Escape" || closeSensorRef.current === null) return;
992 - event.preventDefault();
993 - closeSensorRef.current.cancel();
994 - };
995 - document.addEventListener("keydown", onKeyDown, true);
996 - return () => document.removeEventListener("keydown", onKeyDown, true);
997 - }, []);
998 - const startCloseSweep = useStableCallback(
999 - (entry: EnvironmentPullRequestEntry, event: PointerEvent) => {
1000 - closeSensorRef.current?.cancel();
1001 - const originKey = pullRequestEntryKey(entry);
1002 - const group = readCloseSweep().displayGroups.find((candidate) =>
1003 - candidate.entries.some((row) => pullRequestEntryKey(row) === originKey),
1004 - );
1005 - if (!group || readCloseSweep().closingKeys.has(originKey)) return;
1006 - const orderedKeys = readCloseSweep().displayGroups.flatMap((candidate) =>
1007 - candidate.entries.map(pullRequestEntryKey),
1008 - );
1009 - const canClose = (key: string) => {
1010 - const row = readCloseSweep().closeSweepRows.get(key);
1011 - return (
1012 - row?.groupKey === group.key &&
1013 - row.entry.state === "open" &&
1014 - readCloseSweep().hostActionsOf(row.entry).has("close") &&
1015 - !readCloseSweep().closingKeys.has(key) &&
1016 - !scrollRef.current?.querySelector(
1017 - `[data-pull-request-key="${CSS.escape(key)}"] [data-pull-request-action-pending="true"]`,
1018 - )
1019 - );
1020 - };
1021 - let sweptKeys: string[] = [];
1022 - let targetKey: string | null = null;
1023 - const sweepTo = (key: string) => {
1024 - if (key === targetKey) return;
1025 - targetKey = key;
1026 - sweptKeys = resolveSidebarSweepKeys(orderedKeys, originKey, key, canClose);
1027 - setCloseSweepKeys(new Set(sweptKeys));
1028 - };
1029 - closeSensorRef.current = new SidebarPointerSensor({
1030 - active: originKey,
1031 - event,
1032 - options: {
1033 - distance: 6,
1034 - onAttach: () => {},
1035 - onFinish: () => {
1036 - closeSensorRef.current = null;
1037 - setCloseSweepKeys(new Set());
1038 - },
1039 - },
1040 - onPending: () => {},
1041 - onStart: () => sweepTo(originKey),
1042 - onMove: ({ y }) => {
1043 - const viewport = scrollRef.current;
1044 - if (!viewport) return;
1045 - const bounds = viewport.getBoundingClientRect();
1046 - const visibleY = Math.min(Math.max(y, bounds.top), bounds.bottom - 1);
1047 - let key: string | null = null;
1048 - for (const row of viewport.querySelectorAll<HTMLElement>("[data-pull-request-key]")) {
1049 - if (key !== null && row.getBoundingClientRect().top > visibleY) break;
1050 - key = row.dataset.pullRequestKey ?? null;
1051 - }
1052 - if (key !== null) sweepTo(key);
1053 - },
1054 - onEnd: () => {
1055 - const batch = sweptKeys.filter(canClose).flatMap((key) => {
1056 - const row = readCloseSweep().closeSweepRows.get(key);
1057 - return row ? [row.entry] : [];
1058 - });
1059 - void readCloseSweep().closeBatch(batch);
1060 - },
1061 - onCancel: () => {},
1062 - onAbort: () => {},
1063 - });
1064 - },
1065 - );
1066 - const rightPanelAvailable = selectedPullRequestSurface !== null;
1067 - const [maximized, setMaximized] = useState(false);
1068 - const rightPanelMaximized = rightPanelState.isOpen && maximized;
1069 - if (!rightPanelState.isOpen && maximized) setMaximized(false);
1070 - const toggleRightPanelMaximized = () => {
1071 - if (rightPanelState.isOpen) setMaximized((value) => !value);
1072 - };
1073 - const onGuideShown = () => setMaximized(true);
1074 - useEffect(() => {
1075 - if (!pullRequestsSupported || rightPanelRef === null || linkedSelection === null) return;
1076 - useRightPanelStore.getState().openPullRequest(rightPanelRef, linkedSelection);
1077 - }, [linkedSelection, pullRequestsSupported, rightPanelRef]);
1078 -
1079 - const selected =
1080 - rightPanelState.isOpen && activePullRequestSurface !== null
1081 - ? {
1082 - environmentId: activePullRequestSurface.environmentId,
1083 - repository: activePullRequestSurface.repository,
1084 - number: activePullRequestSurface.number,
1085 - projectId: activePullRequestSurface.projectId as ProjectId,
1086 - host:
1087 - activePullRequestSurface.host ??
1088 - (selectedProject?.repositoryIdentity
1089 - ? pullRequestHostOf(
1090 - selectedProject.repositoryIdentity,
1091 - selectedProject.repositoryIdentity.provider as SourceControlProviderKind,
1092 - )
1093 - : undefined),
1094 - }
1095 - : null;
1096 -
1097 - const selectSurfaceInUrl = (surface: PullRequestSurface | null) =>
1098 - updateSearch(
1099 - surface === null
1100 - ? clearedSelection
1101 - : {
1102 - repository: surface.repository,
1103 - number: surface.number,
1104 - selectedProjectId: surface.projectId as ProjectId,
1105 - selectedHost: surface.host,
1106 - ...(surface.environmentId === undefined
1107 - ? {}
1108 - : { selectedEnvironmentId: surface.environmentId as EnvironmentId }),
1109 - },
1110 - );
1111 -
1112 - const toggleRightPanel = () => {
1113 - if (rightPanelRef === null) return;
1114 - if (rightPanelState.isOpen) {
1115 - useRightPanelStore.getState().close(rightPanelRef);
1116 - updateSearch(clearedSelection);
1117 - return;
1118 - }
1119 - if (selectedPullRequestSurface === null) return;
1120 - useRightPanelStore.getState().show(rightPanelRef);
1121 - selectSurfaceInUrl(selectedPullRequestSurface);
1122 - };
1123 -
1124 - const unavailableProjects = new Map(
1125 - listErrors.map(
1126 - (error) =>
1127 - [
1128 - pullRequestProjectKey({ id: error.projectId, environmentId: error.environmentId }),
1129 - error.message,
1130 - ] as const,
1131 - ),
1132 - );
1133 -
1134 - const selectEntry = (entry: PullRequestRowTarget) => {
1135 - if (rightPanelRef === null) return;
1136 - useRightPanelStore.getState().openPullRequest(rightPanelRef, entry);
1137 - updateSearch({
1138 - repository: entry.repository,
1139 - number: entry.number,
1140 - selectedProjectId: entry.projectId,
1141 - selectedEnvironmentId: entry.environmentId,
1142 - selectedHost: entry.host,
1143 - });
1144 - };
1145 -
1146 - const searchInput = (
1147 - <PullRequestSearchInput
1148 - value={search.q ?? ""}
1149 - busy={typedQuery.length > 0 && (!querySettled || showingCarried)}
1150 - onChange={(query) => updateListScope({ q: query || undefined })}
1151 - />
1152 - );
1153 - const panelToggleControls = (
1154 - <PanelLayoutControls
1155 - showTerminalControl={false}
1156 - showThreadPanelControl={false}
1157 - terminalAvailable={false}
1158 - terminalOpen={false}
1159 - terminalShortcutLabel={null}
1160 - threadPanelOpen={false}
1161 - threadPanelPresentation="inline"
1162 - threadPanelShortcutLabel={null}
1163 - onToggleThreadPanel={() => undefined}
1164 - rightPanelAvailable={rightPanelAvailable}
1165 - rightPanelOpen={rightPanelState.isOpen}
1166 - rightPanelShortcutLabel={shortcutLabelForCommand(keybindings, "rightPanel.toggle")}
1167 - rightPanelUnavailableLabel="Select a pull request first"
1168 - onToggleTerminal={() => undefined}
1169 - onToggleRightPanel={toggleRightPanel}
1170 - />
1171 - );
1172 - const openPanelControls = (
1173 - <div
1174 - className="absolute top-[var(--workspace-controls-top)] right-[var(--workspace-controls-right)] z-50 mr-px flex h-[var(--workspace-topbar-height)] items-center gap-1 [-webkit-app-region:no-drag]"
1175 - data-workspace-titlebar-controls
1176 - >
1177 - {rightPanelState.isOpen ? (
1178 - <RightPanelMaximizeControl
1179 - maximized={rightPanelMaximized}
1180 - onToggle={toggleRightPanelMaximized}
1181 - />
1182 - ) : null}
1183 - {panelToggleControls}
1184 - </div>
1185 - );
1186 - const carriedToNothing =
1187 - shownCount === 0 &&
1188 - typedQuery.length === 0 &&
1189 - (!querySettled || (showingCarried && listQuery.isPending));
1190 - const listBody = (
1191 - <>
1192 - {!capabilityKnown ? (
1193 - <PullRequestListGhost rows={7} />
1194 - ) : !pullRequestsSupported ? (
1195 - <PullRequestsUnavailableState
1196 - title="Pull requests unavailable"
1197 - error="Update your T3 Code servers to browse pull requests."
1198 - />
1199 - ) : firstLoad ? (
1200 - <PullRequestListGhost rows={7} />
1201 - ) : listQuery.error && shownCount === 0 ? (
1202 - <PullRequestsUnavailableState
1203 - error={listQuery.error}
1204 - refreshing={listQuery.isPending}
1205 - onRetry={() => listQuery.refresh()}
1206 - />
1207 - ) : carriedToNothing ? (
1208 - <PullRequestListGhost rows={7} />
1209 - ) : shownCount === 0 ? (
1210 - <PullRequestListEmptyState
1211 - hasProjects={!projectsKnown || projects.length > 0}
1212 - refreshing={refreshing}
1213 - onRefresh={() => void refreshFromHost()}
1214 - query={typedQuery}
1215 - filtered={
1216 - menuFiltered ||
1217 - search.state !== "open" ||
1218 - search.involvement !== "all" ||
1219 - scopedProjectId !== undefined ||
1220 - search.host !== undefined
1221 - }
1222 - searching={typedQuery.length > 0 && (!querySettled || showingCarried)}
1223 - canLoadMore={listData?.truncated === true && (canContinue || pageSize < MAX_PAGE_SIZE)}
1224 - loadingMore={loadingMore}
1225 - onClearQuery={() => updateListScope({ q: undefined })}
1226 - onLoadMore={loadMore}
1227 - />
1228 - ) : (
1229 - <PullRequestListGroups
1230 - groups={displayGroups}
1231 - environmentLabels={capableEnvironments.length > 1 ? environmentLabels : null}
1232 - query={typedParsed.text}
1233 - selected={selected}
1234 - showProvider={showProvider}
1235 - statsRef={registerStatsRow}
1236 - onSelect={selectEntry}
1237 - hostActionsOf={hostActionsOf}
1238 - onActed={onSpeedAction}
1239 - closingKeys={closingKeys}
1240 - sweepingKeys={closeSweepKeys}
1241 - onCloseSweepStart={startCloseSweep}
1242 - />
1243 - )}
1244 -
1245 - {listQuery.error && shownCount > 0 ? (
1246 - <div className="flex items-center justify-between gap-3 rounded-lg border border-warning/30 bg-warning-surface px-3 py-2 text-xs">
1247 - <span>{listQuery.error} Showing the last pull requests loaded.</span>
1248 - <Button size="xs" variant="outline" onClick={() => listQuery.refresh()}>
1249 - Retry
1250 - </Button>
1251 - </div>
1252 - ) : null}
1253 - {listData?.truncated && entries.length > 0 ? (
1254 - <div className="flex justify-center py-3 text-xs text-muted-foreground">
1255 - {loadingMore ? (
1256 - <span className="flex items-center gap-2">
1257 - <Spinner aria-hidden size="sm" />
1258 - {sentCursors === null ? "Updating pull requests" : "Loading more"}
1259 - </span>
1260 - ) : canContinue || pageSize < MAX_PAGE_SIZE ? (
1261 - <Button
1262 - size="sm"
1263 - variant="outline"
1264 - onClick={loadMore}
1265 - disabled={listQuery.isPending || showingCarried}
1266 - >
1267 - Load more pull requests
1268 - </Button>
1269 - ) : (
1270 - <span>Narrow your search to find more pull requests.</span>
1271 - )}
1272 - </div>
1273 - ) : null}
1274 - </>
1275 - );
1276 - const hostEntries = hosts.length > 0 ? hosts : expectedHosts;
1277 - const hostMenuOptions: ReadonlyArray<PullRequestFilterOption<string>> = [
1278 - { value: "", label: "All", Icon: Plug2Icon },
1279 - ...hostEntries.map((entry) => {
1280 - const summary = hosts.find((host) => host.host === entry.host);
1281 - return {
1282 - value: entry.host,
1283 - label: pullRequestHostLabel(hostEntries, entry),
1284 - Icon: getSourceControlPresentationForKind(entry.kind).Icon,
1285 - ...(summary === undefined || summary.configured
1286 - ? {}
1287 - : { unavailable: summary.detail ?? "This host could not be read." }),
1288 - };
1289 - }),
1290 - ];
1291 - const serverMenuOptions: ReadonlyArray<PullRequestFilterOption<string>> = [
1292 - { value: "", label: "All servers", Icon: LayersIcon },
1293 - ...capableEnvironments.map((environment) => ({
1294 - value: environment.environmentId,
1295 - label: environment.label,
1296 - Icon: environmentMachineIcon(resolveEnvironmentMachineKind(environment.serverConfig)),
1297 - })),
1298 - ];
1299 - const sortMenu = (
1300 - <PullRequestCompactFilterMenu
1301 - label="Sort pull requests"
1302 - triggerIcon={<ArrowDownUpIcon aria-hidden className="size-4" />}
1303 - triggerLabel="Sort"
1304 - outlined
1305 - value={sort}
1306 - options={SORT_OPTIONS}
1307 - onChange={(next) => updateListScope({ sort: next })}
1308 - />
1309 - );
1310 - const filtersMenu = (
1311 - <PullRequestFiltersMenuInSidebarOrder
1312 - onOpenChange={setFiltersOpen}
1313 - state={search.state}
1314 - stateOptions={STATE_TABS}
1315 - onState={(state) => updateListScope({ state })}
1316 - involvement={search.involvement}
1317 - involvementOptions={INVOLVEMENT_TABS}
1318 - onInvolvement={(involvement) => updateListScope({ involvement })}
1319 - filters={
1320 - typedParsed.filters.draft
1321 - ? { ...menuFilters, draft: typedParsed.filters.draft }
1322 - : menuFilters
1323 - }
1324 - onFilters={(value) => {
1325 - const { query, filters: next } = applyPullRequestDraftFilterChange(
1326 - typedQuery,
1327 - menuFilters,
1328 - value,
1329 - );
1330 - updateListScope({
1331 - ...(query === typedQuery ? {} : { q: query || undefined }),
1332 - draft: next.draft,
1333 - review: next.review,
1334 - checks: next.checks,
1335 - author: next.author,
1336 - labels: next.labels?.flatMap((group) => group),
1337 - });
1338 - }}
1339 - authorOptions={facets.authors}
1340 - labelOptions={facets.labels}
1341 - host={search.host}
1342 - hostOptions={hostMenuOptions}
1343 - onHost={(host) => updateListScope({ host })}
1344 - server={scopedEnvironmentId ?? undefined}
1345 - serverOptions={serverMenuOptions}
1346 - onServer={(server) => updateListScope({ environmentId: server, projectId: undefined })}
1347 - projects={scopedProjects}
1348 - projectId={scopedProjectId}
1349 - projectEnvironmentId={scopedProject?.environmentId}
1350 - unavailable={unavailableProjects}
1351 - onProject={(projectId, environmentId) =>
1352 - updateListScope(environmentId === undefined ? { projectId } : { projectId, environmentId })
1353 - }
1354 - />
1355 - );
1356 - const columnProps = {
1357 - refreshing,
1358 - onRefresh: () => void refreshFromHost(),
1359 - searchValue: search.q ?? "",
1360 - involvement: search.involvement,
1361 - state: search.state,
1362 - host: search.host,
1363 - hostMenuOptions,
1364 - onInvolvement: (involvement: PullRequestInvolvement) => updateListScope({ involvement }),
1365 - onState: (state: PullRequestListState) => updateListScope({ state }),
1366 - onHost: (host: string | undefined) => updateListScope({ host }),
1367 - searchInput,
1368 - sortMenu,
1369 - filtersMenu,
1370 - rightPanelControl: !pullRequestsSupported ? null : (
1371 - <span
1372 - aria-hidden
1373 - className={cn(
1374 - "shrink-0",
1375 - rightPanelState.isOpen ? "-ml-3 w-0" : "w-7 sm:w-5",
1376 - panelAnimationsActive && "transition-[width,margin] ease-out",
1377 - )}
1378 - style={
1379 - panelAnimationsActive
1380 - ? { transitionDuration: `${panelAnimationDurationMs}ms` }
1381 - : undefined
1382 - }
1383 - />
1384 - ),
1385 - titlebarControls:
1386 - // While the panel is closed the strip lives inside the header: a no-drag
1387 - // descendant beats the header's desktop drag-region, where a floating
1388 - // sibling loses (app-region hit-testing ignores z-index).
1389 - pullRequestsSupported ? (
1390 - rightPanelPresent ? (
1391 - <span
1392 - aria-hidden
1393 - className="pointer-events-none absolute inset-y-0 left-full w-7 [-webkit-app-region:no-drag]"
1394 - />
1395 - ) : (
1396 - openPanelControls
1397 - )
1398 - ) : null,
1399 - rightPanelOpen: rightPanelState.isOpen,
1400 - maximizedAway: rightPanelMaximized,
1401 - listBody,
1402 - scrollRef,
1403 - };
1404 -
1405 - const activateSurface = (surface: PullRequestSurface) => {
1406 - if (rightPanelRef === null) return;
1407 - useRightPanelStore.getState().activateSurface(rightPanelRef, surface.id);
1408 - selectSurfaceInUrl(surface);
1409 - };
1410 - const closeSurface = (surface: PullRequestSurface) => {
1411 - if (rightPanelRef === null) return;
1412 - useRightPanelStore.getState().closeSurface(rightPanelRef, surface.id);
1413 - const next = selectActiveRightPanelSurface(
1414 - useRightPanelStore.getState().byThreadKey,
1415 - rightPanelRef,
1416 - );
1417 - selectSurfaceInUrl(next?.kind === "pull-request" ? next : null);
1418 - };
1419 - const closeOtherSurfaces = (surface: PullRequestSurface) => {
1420 - if (rightPanelRef === null) return;
1421 - useRightPanelStore.getState().closeOtherSurfaces(rightPanelRef, surface.id);
1422 - selectSurfaceInUrl(surface);
1423 - };
1424 - const closeSurfacesToRight = (surface: PullRequestSurface) => {
1425 - if (rightPanelRef === null) return;
1426 - useRightPanelStore.getState().closeSurfacesToRight(rightPanelRef, surface.id);
1427 - const next = selectActiveRightPanelSurface(
1428 - useRightPanelStore.getState().byThreadKey,
1429 - rightPanelRef,
1430 - );
1431 - selectSurfaceInUrl(next?.kind === "pull-request" ? next : null);
1432 - };
1433 - const closeAllSurfaces = () => {
1434 - if (rightPanelRef === null) return;
1435 - useRightPanelStore.getState().closeAllSurfaces(rightPanelRef);
1436 - selectSurfaceInUrl(null);
1437 - };
1438 -
1439 - const copyPullRequestFromShortcut = useEffectEvent((event: KeyboardEvent) => {
1440 - if (!openPanelPullRequestUrl) return;
1441 - event.preventDefault();
1442 - event.stopPropagation();
1443 - if (event.repeat) return;
1444 - const url = openPanelPullRequestUrl;
1445 - void writeTextToClipboard(url, "pull request link").then(
1446 - (didCopy) => {
1447 - if (didCopy)
1448 - toastManager.add({ type: "success", title: "PR link copied", description: url });
1449 - },
1450 - (error) => {
1451 - toastManager.add({
1452 - type: "error",
1453 - title: "Failed to copy PR link",
1454 - description: error instanceof Error ? error.message : "An error occurred.",
1455 - });
1456 - },
1457 - );
1458 - });
1459 - const closeActiveSurfaceFromShortcut = useEffectEvent((event: KeyboardEvent) => {
1460 - if (activePullRequestSurface === null) return;
1461 - event.preventDefault();
1462 - event.stopPropagation();
1463 - if (!event.repeat) closeSurface(activePullRequestSurface);
1464 - });
1465 - const toggleRightPanelFromShortcut = useEffectEvent((event: KeyboardEvent) => {
1466 - if (!rightPanelAvailable) return;
1467 - event.preventDefault();
1468 - event.stopPropagation();
1469 - if (!event.repeat) toggleRightPanel();
1470 - });
1471 - const toggleRightPanelMaximizedFromShortcut = useEffectEvent((event: KeyboardEvent) => {
1472 - if (!rightPanelState.isOpen) return;
1473 - event.preventDefault();
1474 - event.stopPropagation();
1475 - if (!event.repeat) toggleRightPanelMaximized();
1476 - });
1477 - useEffect(() => {
1478 - const onKeyDown = (event: KeyboardEvent) => {
1479 - if (event.defaultPrevented || isCommandPaletteOpen()) return;
1480 - const command = resolveShortcutCommand(event, keybindings, {
1481 - context: getShortcutContext(),
1482 - });
1483 - if (command === "rightPanel.close") closeActiveSurfaceFromShortcut(event);
1484 - if (command === "rightPanel.toggle") toggleRightPanelFromShortcut(event);
1485 - if (command === "rightPanel.toggleMaximized") toggleRightPanelMaximizedFromShortcut(event);
1486 - if (command === "thread.copyReference") copyPullRequestFromShortcut(event);
1487 - };
1488 - document.addEventListener("keydown", onKeyDown);
1489 - return () => document.removeEventListener("keydown", onKeyDown);
1490 - }, [keybindings]);
1491 -
1492 - return (
1493 - <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none">
1494 - <div className="relative flex min-h-0 flex-1">
1495 - {pullRequestsSupported && rightPanelPresent ? openPanelControls : null}
1496 - <PullRequestsColumn {...columnProps} />
1497 -
1498 - {rightPanelPresent && renderedPullRequestSurface && panelEnvironmentId !== null ? (
1499 - <RightPanelTabs
1500 - mode="inline"
1501 - open={rightPanelState.isOpen}
1502 - maximized={rightPanelMaximized}
1503 - keybindings={keybindings}
1504 - getShortcutContext={getShortcutContext}
1505 - widthStorageKey="t3code:pull-request-panel-width"
1506 - defaultWidth={typeof window === "undefined" ? 640 : Math.floor(window.innerWidth / 2)}
1507 - surfaces={renderedRightPanelSurfaces}
1508 - environmentId={panelEnvironmentId}
1509 - activeSurfaceId={renderedPullRequestSurface.id}
1510 - pendingSurfaceIds={EMPTY_PENDING_SURFACES}
1511 - previewSessions={EMPTY_PREVIEW_SESSIONS}
1512 - desktopByTabId={EMPTY_PREVIEW_DESKTOP_STATE}
1513 - terminalLabelsById={EMPTY_TERMINAL_LABELS}
1514 - onActivate={(surface) => {
1515 - if (surface.kind === "pull-request") activateSurface(surface);
1516 - }}
1517 - onCloseSurface={(surface) => {
1518 - if (surface.kind === "pull-request") closeSurface(surface);
1519 - }}
1520 - onCloseOtherSurfaces={(surface) => {
1521 - if (surface.kind === "pull-request") closeOtherSurfaces(surface);
1522 - }}
1523 - onCloseSurfacesToRight={(surface) => {
1524 - if (surface.kind === "pull-request") closeSurfacesToRight(surface);
1525 - }}
1526 - onCloseAllSurfaces={closeAllSurfaces}
1527 - onMoveSurface={(surfaceId, toIndex) => {
1528 - if (rightPanelRef !== null)
1529 - useRightPanelStore.getState().moveSurface(rightPanelRef, surfaceId, toIndex);
1530 - }}
1531 - onCopyFilePath={() => undefined}
1532 - onAddBrowser={() => undefined}
1533 - onAddBrowserInProfile={() => undefined}
1534 - onAddTerminal={() => undefined}
1535 - onAddDiff={() => undefined}
1536 - onAddFiles={() => undefined}
1537 - onAddPullRequest={() => undefined}
1538 - onAddPullRequests={() => undefined}
1539 - onAddDevice={() => undefined}
1540 - browserAvailable={false}
1541 - terminalAvailable={false}
1542 - diffAvailable={false}
1543 - filesAvailable={false}
1544 - pullRequestAvailable={false}
1545 - pullRequestsAvailable={false}
1546 - deviceAvailable={false}
1547 - pullRequestStatusSeeds={listedPullRequestTabStatuses}
1548 - >
1549 - <PullRequestDetailPanel
1550 - getShortcutContext={getShortcutContext}
1551 - shortcutsEnabled={activePullRequestSurface?.id === renderedPullRequestSurface.id}
1552 - key={renderedPullRequestSurface.id}
1553 - environmentId={panelEnvironmentId}
1554 - onGuideShown={onGuideShown}
1555 - onSelectPullRequest={(reference) => {
1556 - if (rightPanelRef === null) return;
1557 - useRightPanelStore.getState().openPullRequest(rightPanelRef, {
1558 - projectId: reference.projectId,
1559 - repository: reference.repository,
1560 - number: reference.number,
1561 - ...(reference.host ? { host: reference.host } : {}),
1562 - environmentId: panelEnvironmentId,
1563 - });
1564 - updateSearch({
1565 - repository: reference.repository,
1566 - number: reference.number,
1567 - selectedHost: reference.host,
1568 - selectedProjectId: reference.projectId,
1569 - selectedEnvironmentId: panelEnvironmentId,
1570 - });
1571 - }}
1572 - reference={{
1573 - projectId: renderedPullRequestSurface.projectId as ProjectId,
1574 - repository: renderedPullRequestSurface.repository,
1575 - number: renderedPullRequestSurface.number,
1576 - ...(renderedPullRequestSurface.host
1577 - ? { host: renderedPullRequestSurface.host }
1578 - : {}),
1579 - }}
1580 - listEntry={
1581 - listedPullRequestsBySurface.get(
1582 - pullRequestListEntryId(renderedPullRequestSurface),
1583 - ) ?? null
1584 - }
1585 - refreshToken={detailRefreshToken}
1586 - onActed={(action, phase = "done") => {
1587 - // From every row held, not the ones on screen: a pull request closed from an open
1588 - // list has left the screen, and reopening it has to find it anyway.
1589 - const acted = heldPullRequestsBySurface.get(
1590 - pullRequestListEntryId(renderedPullRequestSurface),
1591 - );
1592 - const stateOnly =
1593 - action !== undefined &&
1594 - acted !== undefined &&
1595 - pullRequestOverrideAfterAction(acted, action, new Date(), 0) !== null;
1596 - if (stateOnly) {
1597 - const key = pullRequestEntryKey(acted);
1598 - if (phase === "sent" && action !== "merge") {
1599 - detailOverrideTokens.current.set(key, overrideEntry(acted, action));
1600 - }
1601 - if (phase === "failed" && action !== "merge") {
1602 - revertOverride(key, detailOverrideTokens.current.get(key) ?? null);
1603 - }
1604 - if (phase !== "sent") detailOverrideTokens.current.delete(key);
1605 - if (phase === "done" && action === "merge") {
1606 - overrideEntry(acted, action);
1607 - refreshListAndStats(undefined, panelEnvironmentId);
1608 - }
1609 - return;
1610 - }
1611 - if (phase === "done") refreshListAndStats(undefined, panelEnvironmentId);
1612 - }}
1613 - />
1614 - </RightPanelTabs>
1615 - ) : null}
1616 - </div>
1617 - </SidebarInset>
1618 - );
1619 -}
1620 -
1621 -function PullRequestFiltersMenuInSidebarOrder(
1622 - props: ComponentProps<typeof PullRequestFiltersMenu>,
1623 -) {
1624 - const sidebarProjectGroups = useSidebarProjectGroups();
1625 - const projects = sortProjectsByGroupOrder(props.projects, sidebarProjectGroups);
1626 - return <PullRequestFiltersMenu {...props} projects={projects} />;
1627 -}