Open History to see the last commit
1import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2import { pullRequestHostOf, ThreadId } from "@t3tools/contracts";
3import type {
4 EnvironmentId,
5 ProjectId,
6 PullRequestInvolvement,
7 PullRequestListEntry,
8 PullRequestListResult,
9 PullRequestListState,
10 SourceControlProviderKind,
11} from "@t3tools/contracts";
12import { createFileRoute, useNavigate } from "@tanstack/react-router";
13import {
14 ChevronDownIcon,
15 EyeIcon,
16 GitMergeIcon,
17 GitPullRequestClosedIcon,
18 GitPullRequestIcon,
19 LayersIcon,
20 PenLineIcon,
21 LoaderIcon,
22 RefreshCwIcon,
23 SearchIcon,
24} from "lucide-react";
25import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
26
27import {
28 filterPullRequestsByInvolvement,
29 groupPullRequestsByInvolvement,
30 matchesPullRequestQuery,
31 narrowPullRequestsToFilters,
32 mergePullRequestDiffStats,
33 partitionPullRequestsWithPriority,
34 pullRequestEntryKey,
35 rankPullRequestMatches,
36 readPullRequestListSnapshot,
37 resolveProjectScope,
38 withDiffStat,
39 writePullRequestListSnapshot,
40 scorePullRequestMatch,
41 type PullRequestDiffStats,
42 type PullRequestPartitionsSnapshot,
43} from "../components/pullRequest/pullRequestList.logic";
44import { PullRequestDetailPanel } from "../components/pullRequest/PullRequestDetailPanel";
45import {
46 PullRequestFiltersMenu,
47 PullRequestSearchInput,
48 pullRequestHostLabel,
49 type PullRequestExpectedHost,
50 type PullRequestFilterOption,
51} from "../components/pullRequest/PullRequestListFilters";
52import { PullRequestListEmptyState } from "../components/pullRequest/PullRequestListEmptyState";
53import { PullRequestListGhost } from "../components/pullRequest/PullRequestGhosts";
54import { PullRequestRow } from "../components/pullRequest/PullRequestRow";
55import { PullRequestsUnavailableState } from "../components/pullRequest/PullRequestsUnavailableState";
56import { RightPanelTabs, type PullRequestTabStatus } from "../components/RightPanelTabs";
57import {
58 WorkspaceBreadcrumb,
59 WorkspaceBreadcrumbItem,
60 WorkspaceBreadcrumbSeparator,
61} from "../components/WorkspaceBreadcrumb";
62import { PanelLayoutControls } from "../components/chat/PanelLayoutControls";
63import { Button } from "../components/ui/button";
64import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "../components/ui/menu";
65import { SidebarInset } from "../components/ui/sidebar";
66import { useLiveRefresh } from "../hooks/useLiveRefresh";
67import {
68 pullRequestSurfaceId,
69 selectActiveRightPanelSurface,
70 selectSelectedRightPanelSurface,
71 selectThreadRightPanelState,
72 useRightPanelStore,
73 type PullRequestSurface,
74} from "../rightPanelStore";
75import { useDebouncedValue } from "../state/queries";
76import { useAllEnvironmentShellsBootstrapped, useProjects } from "../state/entities";
77import { usePrimaryEnvironment } from "../state/environments";
78import { pullRequestEnvironment } from "../state/pullRequests";
79import { useEnvironmentQuery } from "../state/query";
80import { useAtomCommand } from "../state/use-atom-command";
81import { cn } from "~/lib/utils";
82import { getSourceControlPresentationForKind } from "~/sourceControlPresentation";
83import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
84
85export interface PullRequestsSearch {
86 readonly involvement: PullRequestInvolvement;
87 readonly state: PullRequestListState;
88 /** Scopes the list. Separate from the selection so one cannot silently change the other. */
89 readonly projectId?: ProjectId;
90 /**
91 * Narrows the list to one host, named as the host itself: two GitHub installs are two
92 * accounts, and their shared provider kind cannot tell them apart. Absent means every host.
93 */
94 readonly host?: string;
95 readonly repository?: string;
96 readonly number?: number;
97 readonly selectedProjectId?: ProjectId;
98 readonly q?: string;
99}
100
101// The state filters wear the same glyphs the rows do, so the two read as one vocabulary.
102const INVOLVEMENT_TABS = [
103 { value: "all", label: "All", Icon: LayersIcon },
104 { value: "reviewing", label: "Reviewing", Icon: EyeIcon },
105 { value: "authored", label: "Authored", Icon: PenLineIcon },
106] as const satisfies ReadonlyArray<PullRequestFilterOption<PullRequestInvolvement>>;
107
108const STATE_TABS = [
109 { value: "all", label: "All", Icon: LayersIcon },
110 { value: "open", label: "Open", Icon: GitPullRequestIcon },
111 { value: "closed", label: "Closed", Icon: GitPullRequestClosedIcon },
112 { value: "merged", label: "Merged", Icon: GitMergeIcon },
113] as const satisfies ReadonlyArray<PullRequestFilterOption<PullRequestListState>>;
114
115/** Long enough that a keystroke does not become a request, short enough to feel answered. */
116const SEARCH_DEBOUNCE_MS = 250;
117/** What `scorePullRequestMatch` gives a row none of whose own fields carry the search text. */
118const MATCHED_ELSEWHERE_SCORE = 10;
119/**
120 * One whole page from the host and no more: every provider asks for one row beyond the page as
121 * its "is there more" probe, and GitHub serves a hundred per request — so asking for ninety-nine
122 * costs one round trip where a hundred costs two.
123 */
124const PAGE_SIZE = 99;
125/** The largest page the listing accepts; past it the request is refused outright. */
126const MAX_PAGE_SIZE = 500;
127/** Stable empty map so the memos below do not see a new object on every render. */
128const EMPTY_VIEWERS: PullRequestListResult["viewers"] = {};
129/** The list owns one environment-scoped right panel rather than borrowing a real thread's. */
130const PULL_REQUESTS_PANEL_ID = ThreadId.make("pull-requests-panel");
131const EMPTY_PREVIEW_SESSIONS = {};
132const EMPTY_TERMINAL_LABELS = new Map<string, string>();
133const EMPTY_PENDING_SURFACES = new Set<string>();
134
135export const Route = createFileRoute("/_chat/pull-requests")({
136 validateSearch: (raw: Record<string, unknown>): PullRequestsSearch => ({
137 involvement:
138 raw.involvement === "reviewing" || raw.involvement === "authored" ? raw.involvement : "all",
139 state:
140 raw.state === "closed" || raw.state === "merged" || raw.state === "all" ? raw.state : "open",
141 ...(typeof raw.repository === "string" && raw.repository
142 ? { repository: raw.repository.slice(0, 200) }
143 : {}),
144 ...(typeof raw.number === "number" && Number.isInteger(raw.number) && raw.number > 0
145 ? { number: raw.number }
146 : {}),
147 ...(typeof raw.projectId === "string" && raw.projectId
148 ? { projectId: raw.projectId as ProjectId }
149 : {}),
150 ...(typeof raw.host === "string" && raw.host ? { host: raw.host.slice(0, 200) } : {}),
151 ...(typeof raw.selectedProjectId === "string" && raw.selectedProjectId
152 ? { selectedProjectId: raw.selectedProjectId as ProjectId }
153 : {}),
154 ...(typeof raw.q === "string" && raw.q ? { q: raw.q.slice(0, 200) } : {}),
155 }),
156 component: PullRequestsRouteView,
157});
158
159function PullRequestsRouteView() {
160 const search = Route.useSearch();
161 const navigate = useNavigate({ from: Route.fullPath });
162 const primaryEnvironment = usePrimaryEnvironment();
163 const environmentId = primaryEnvironment?.environmentId ?? null;
164 const capabilityKnown = primaryEnvironment !== null && primaryEnvironment.serverConfig !== null;
165 const pullRequestsSupported =
166 primaryEnvironment?.serverConfig?.environment.capabilities.pullRequests === true;
167 // The primary environment may still be connecting, or may predate this feature. In either
168 // case every query remains idle until the server has explicitly advertised these APIs.
169 const pullRequestEnvironmentId = pullRequestsSupported ? environmentId : null;
170 const allProjects = useProjects();
171 // Whether the workspace has said what it holds yet. Until it has, an empty project list is
172 // "not loaded" rather than "none", and telling a reader to add a project they already have is
173 // the one wrong answer the empty state can give.
174 const projectsKnown = useAllEnvironmentShellsBootstrapped();
175 // The page reads one environment, so a project from another one could neither be listed
176 // nor acted on: scoping here keeps the filter and the selection honest.
177 const projects = useMemo(
178 () => allProjects.filter((project) => project.environmentId === environmentId),
179 [allProjects, environmentId],
180 );
181 const scopedProjects = useMemo(
182 () =>
183 projects
184 .map((project) => ({
185 id: project.id,
186 title: project.title,
187 workspaceRoot: project.workspaceRoot,
188 }))
189 .toSorted((left, right) => left.title.localeCompare(right.title)),
190 [projects],
191 );
192 // The scope the URL asks for, once the environment has had its say about whether it exists.
193 const scopedProjectId = useMemo(
194 () => resolveProjectScope(search.projectId, projects, projectsKnown),
195 [projects, projectsKnown, search.projectId],
196 );
197 const rightPanelRef = useMemo(
198 () => (environmentId === null ? null : scopeThreadRef(environmentId, PULL_REQUESTS_PANEL_ID)),
199 [environmentId],
200 );
201 const rightPanelState = useRightPanelStore((state) =>
202 selectThreadRightPanelState(state.byThreadKey, rightPanelRef),
203 );
204 const selectedRightPanelSurface = useRightPanelStore((state) =>
205 selectSelectedRightPanelSurface(state.byThreadKey, rightPanelRef),
206 );
207 const selectedPullRequestSurface =
208 selectedRightPanelSurface?.kind === "pull-request" ? selectedRightPanelSurface : null;
209 const activePullRequestSurface = rightPanelState.isOpen ? selectedPullRequestSurface : null;
210 const [pullRequestTabStatuses, setPullRequestTabStatuses] = useState<
211 Record<string, PullRequestTabStatus>
212 >({});
213 const handlePullRequestTabStatusChange = useCallback((status: PullRequestTabStatus) => {
214 const id = pullRequestSurfaceId(status);
215 setPullRequestTabStatuses((current) =>
216 current[id]?.state === status.state && current[id]?.isDraft === status.isDraft
217 ? current
218 : { ...current, [id]: status },
219 );
220 }, []);
221
222 const updateSearch = useCallback(
223 (patch: {
224 [Key in keyof PullRequestsSearch]?: PullRequestsSearch[Key] | undefined;
225 }) =>
226 void navigate({
227 // Rebuilt rather than spread so a cleared field leaves the URL instead of
228 // lingering as an explicit `undefined`.
229 search: (previous: PullRequestsSearch): PullRequestsSearch => {
230 const next = { ...previous, ...patch };
231 return {
232 involvement: next.involvement ?? previous.involvement,
233 state: next.state ?? previous.state,
234 ...(next.repository ? { repository: next.repository } : {}),
235 ...(next.number ? { number: next.number } : {}),
236 ...(next.projectId ? { projectId: next.projectId } : {}),
237 ...(next.host ? { host: next.host } : {}),
238 ...(next.selectedProjectId ? { selectedProjectId: next.selectedProjectId } : {}),
239 ...(next.q ? { q: next.q } : {}),
240 };
241 },
242 replace: true,
243 }),
244 [navigate],
245 );
246
247 // Changing what the list contains must not leave a selection from the previous view open.
248 // The project filter is untouched: it is the user's scope, not part of the selection.
249 const clearedSelection = {
250 repository: undefined,
251 number: undefined,
252 selectedProjectId: undefined,
253 };
254 const updateListScope = (patch: {
255 [Key in keyof PullRequestsSearch]?: PullRequestsSearch[Key] | undefined;
256 }) => {
257 if (rightPanelRef !== null) {
258 // Hide the old selection while retaining peer PR tabs for parallel reviews.
259 useRightPanelStore.getState().close(rightPanelRef);
260 }
261 updateSearch({ ...patch, ...clearedSelection });
262 };
263
264 // Searching asks the hosts, which takes a round trip, so the text is held for a moment before
265 // it is sent. Until it lands, the rows already on screen are narrowed locally: the answer is
266 // late but the page is not.
267 const typedQuery = (search.q ?? "").trim();
268 const sentQuery = useDebouncedValue(typedQuery, SEARCH_DEBOUNCE_MS);
269 const querySettled = typedQuery === sentQuery;
270
271 // Page size is view state, not a URL concern: a shared link should open the first page.
272 const scopeKey = `${environmentId ?? ""}:${search.state}:${search.involvement}:${scopedProjectId ?? ""}:${search.host ?? ""}`;
273 const filterKey = `${scopeKey}:${sentQuery}`;
274 // Where the next slice carries on from, per repository, as the server handed it back. Sending
275 // it is what makes a second page cost a second page rather than the whole list again — and a
276 // repository it does not name has run out and is not read a second time.
277 const [page, setPage] = useState<{
278 key: string;
279 size: number;
280 cursors: Record<string, string> | null;
281 }>({ key: filterKey, size: PAGE_SIZE, cursors: null });
282 const pageSize = page.key === filterKey ? page.size : PAGE_SIZE;
283 const sentCursors = page.key === filterKey ? page.cursors : null;
284
285 // Typing a search, or clearing one, starts the list again at its first page. Without this the
286 // paging state from before the search is still filed under these filters and comes back with
287 // it, so clearing would return to the slice that had been scrolled to rather than to the list.
288 useEffect(() => {
289 setPage({ key: filterKey, size: PAGE_SIZE, cursors: null });
290 }, [filterKey]);
291
292 const listQuery = useEnvironmentQuery(
293 pullRequestEnvironmentId === null
294 ? null
295 : pullRequestEnvironment.list({
296 environmentId: pullRequestEnvironmentId,
297 input: {
298 state: search.state,
299 // The hosts narrow by involvement themselves — GitHub by author and review request,
300 // and so on — so asking them is the difference between a page of results and a page
301 // of everything with the answer somewhere further down it.
302 involvement: search.involvement,
303 limit: pageSize,
304 ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
305 ...(search.host ? { host: search.host } : {}),
306 ...(sentQuery ? { query: sentQuery } : {}),
307 ...(sentCursors ? { cursors: sentCursors } : {}),
308 },
309 }),
310 );
311
312 /**
313 * The same filters with nothing typed, read whether or not anything is. It is the same atom the
314 * list itself uses while no search is on, so it costs nothing then; while one is, it is what the
315 * page knows about the workspace — who is signed in, which hosts there are, which repositories
316 * could not be read — and what it shows the moment the search is cleared.
317 *
318 * Kept as its own read rather than remembered from an earlier answer because an answer cannot
319 * say which question it belongs to: mid-switch the text has already changed and the data has
320 * not, and a search's answer would file itself under the workspace.
321 */
322 const baselineQuery = useEnvironmentQuery(
323 pullRequestEnvironmentId === null
324 ? null
325 : pullRequestEnvironment.list({
326 environmentId: pullRequestEnvironmentId,
327 input: {
328 state: search.state,
329 involvement: search.involvement,
330 limit: PAGE_SIZE,
331 ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
332 ...(search.host ? { host: search.host } : {}),
333 },
334 }),
335 );
336 // The priority groups' own reads. The feed below is paginated by recency, so an older authored
337 // or review-requested row can be missing from its first page; partitioned from these
338 // server-filtered reads instead, the priority view is complete up front and a continuation can
339 // only ever append below what is already on screen. A search re-ranks the whole list by match,
340 // so no partitions are read for one. These are the same atoms the Authored and Reviewing tabs
341 // ask for, so switching to either is answered from cache.
342 const partitionsWanted = search.involvement === "all" && typedQuery.length === 0;
343 const authoredQuery = useEnvironmentQuery(
344 pullRequestEnvironmentId === null || !partitionsWanted
345 ? null
346 : pullRequestEnvironment.list({
347 environmentId: pullRequestEnvironmentId,
348 input: {
349 state: search.state,
350 involvement: "authored",
351 limit: PAGE_SIZE,
352 ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
353 ...(search.host ? { host: search.host } : {}),
354 },
355 }),
356 );
357 const reviewingQuery = useEnvironmentQuery(
358 pullRequestEnvironmentId === null || !partitionsWanted
359 ? null
360 : pullRequestEnvironment.list({
361 environmentId: pullRequestEnvironmentId,
362 input: {
363 state: search.state,
364 involvement: "reviewing",
365 limit: PAGE_SIZE,
366 ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
367 ...(search.host ? { host: search.host } : {}),
368 },
369 }),
370 );
371 // The header's refresh punches through the server's cache before re-reading; the error and
372 // empty states retry plainly, because a failure is never cached.
373 const invalidate = useAtomCommand(pullRequestEnvironment.invalidate, { reportFailure: false });
374 // What the reader pressed refresh for is everything they can see, not the one query that
375 // happens to be theirs: the list, the counts beside its rows, and whatever the panel is
376 // showing. The panel owns its own reads, so it is told to redo them rather than reached into.
377 const [detailRefreshToken, setDetailRefreshToken] = useState(0);
378 // The queries only go pending once the invalidation has come back, so refreshing is tracked
379 // from the first moment rather than the second: a button that stays live through the slow half
380 // of its own work is a button that gets pressed again, and buys the whole cascade twice.
381 const [invalidating, setInvalidating] = useState(false);
382 const refreshFromHost = async () => {
383 setInvalidating(true);
384 try {
385 if (pullRequestEnvironmentId !== null) {
386 await invalidate({ environmentId: pullRequestEnvironmentId, input: {} });
387 }
388 } finally {
389 setInvalidating(false);
390 }
391 refreshList();
392 baselineQuery.refresh();
393 authoredQuery.refresh();
394 reviewingQuery.refresh();
395 statsQuery.refresh();
396 setDetailRefreshToken((token) => token + 1);
397 };
398 const refreshing = invalidating || listQuery.isPending;
399
400 // Every page size and every search is its own query, and a new one starts empty. The last
401 // answer for these filters is held so the page grows and narrows in place rather than blanking
402 // out: a longer page reads as growth, and a search shows the rows it already has, narrowed
403 // here, until the hosts answer for themselves.
404 const [loaded, setLoaded] = useState<{
405 environmentId: EnvironmentId | null;
406 scope: string;
407 query: string;
408 data: PullRequestListResult;
409 /** The priority groups' own answers, carried so a cold start has whole groups too. */
410 partitions?: PullRequestPartitionsSnapshot;
411 } | null>(null);
412 // A reload recreates the registry the queries live in, so with nothing held the page would
413 // cold-start into skeletons even though almost every row is unchanged. The last answer for
414 // this environment is kept across reloads and hydrated here as the carried rows: they render
415 // at once — narrowed to the current filters like any carried answer — and the live read
416 // reconciles them in place by key rather than replacing them with ghosts.
417 useEffect(() => {
418 if (environmentId === null) return;
419 setLoaded((current) => {
420 // Another environment's rows could not even be narrowed — nothing on a row says which
421 // environment read it — so its snapshot beats holding them.
422 if (current !== null && current.environmentId === environmentId) return current;
423 const snapshot = readPullRequestListSnapshot(
424 typeof window === "undefined" ? undefined : window.localStorage,
425 environmentId,
426 );
427 if (snapshot === null) return null;
428 return {
429 environmentId,
430 scope: snapshot.scope,
431 query: "",
432 data: snapshot.data,
433 ...(snapshot.partitions === undefined ? {} : { partitions: snapshot.partitions }),
434 };
435 });
436 }, [environmentId]);
437 useEffect(() => {
438 // Only once this query has settled. While a search is being swapped in or out the text has
439 // already changed and the data has not, so recording them together would file the previous
440 // answer under the new question — which is how a search's answer came to speak for the
441 // workspace after the search was cleared.
442 if (!listQuery.data || listQuery.isPending) return;
443 const data = listQuery.data;
444 setLoaded((current) => {
445 // The partitions arrive on their own clock, so this records whichever have landed by
446 // now and runs again when the rest do. Until then the ones already held for this scope
447 // stay — hydrated or previously answered — rather than being dropped for a feed that
448 // merely settled first.
449 const partitions =
450 partitionsWanted && authoredQuery.data !== null && reviewingQuery.data !== null
451 ? { authored: authoredQuery.data.entries, reviewing: reviewingQuery.data.entries }
452 : current !== null &&
453 current.environmentId === environmentId &&
454 current.scope === scopeKey
455 ? current.partitions
456 : undefined;
457 // A search's answer is the search's, not the workspace's, so only unsearched lists
458 // persist. Written here where the held partitions are in reach, so a feed settling
459 // ahead of them cannot overwrite a stored snapshot that already had both groups.
460 if (environmentId !== null && sentQuery.length === 0) {
461 writePullRequestListSnapshot(
462 typeof window === "undefined" ? undefined : window.localStorage,
463 environmentId,
464 { scope: scopeKey, data, ...(partitions === undefined ? {} : { partitions }) },
465 );
466 }
467 return {
468 environmentId,
469 scope: scopeKey,
470 query: sentQuery,
471 data,
472 ...(partitions === undefined ? {} : { partitions }),
473 };
474 });
475 }, [
476 environmentId,
477 scopeKey,
478 sentQuery,
479 listQuery.data,
480 listQuery.isPending,
481 partitionsWanted,
482 authoredQuery.data,
483 reviewingQuery.data,
484 ]);
485 // Changing a filter asks a question nothing has answered yet, and the page is already holding
486 // perfectly good rows for the last one. Rather than blank out for the round trip, those rows
487 // are narrowed to the new filters and stay until the answer lands — a subset of it, never a
488 // row it excludes. Narrowed to nothing there is nothing to carry, and the skeletons below are
489 // right after all. Another environment's rows are dropped rather than narrowed: nothing on a
490 // row says which environment read it.
491 const narrowed = useMemo(() => {
492 if (loaded === null || loaded.environmentId !== environmentId || loaded.scope === scopeKey) {
493 return null;
494 }
495 const entries = narrowPullRequestsToFilters(loaded.data.entries, {
496 state: search.state,
497 projectId: scopedProjectId,
498 host: search.host,
499 });
500 return entries.length === 0 ? null : { ...loaded.data, entries };
501 }, [environmentId, loaded, scopeKey, scopedProjectId, search.host, search.state]);
502 // With nothing typed and nothing to carry on from, the answer is taken from the read that is
503 // keyed to exactly that question. Otherwise a search's answer lingers for a render after the
504 // text has gone — the data cannot say which question it belongs to, but the read it came from
505 // can, and that is what stops a cleared search from keeping its own rows.
506 // A grown page is read by the list and nothing else: the baseline always asks for one page, so
507 // a host with no cursor to continue from — where "more" means asking for a longer page — would
508 // have its extra rows thrown away for the ninety-nine the baseline keeps answering with.
509 const answered =
510 (sentQuery.length === 0 && sentCursors === null && pageSize === PAGE_SIZE
511 ? baselineQuery.data
512 : listQuery.data) ??
513 (loaded?.scope === scopeKey && loaded.query === sentQuery ? loaded.data : null);
514 // Clearing a search returns to a list that has already been read, so it comes back at once
515 // rather than after another round trip: the search was the temporary state, not the list.
516 const carried =
517 (sentQuery.length === 0 ? baselineQuery.data : undefined) ??
518 (loaded?.scope === scopeKey ? loaded.data : null) ??
519 narrowed;
520 const listData = answered ?? carried;
521 /** The rows on screen answer the previous question, held while this one is on its way. */
522 const showingCarried = answered === null && carried !== null;
523 const loadingMore = listQuery.isPending && listData !== null;
524 /** Nothing read and nothing to carry, which is the one thing skeletons are for. */
525 const firstLoad = listQuery.isPending && listData === null;
526
527 // A longer page is the same list with more on the end, so the rows already read stay where
528 // they were read: each answer is merged onto the last rather than replacing it, and anything
529 // new lands at the bottom. Only a different question — other filters, another search — starts
530 // the order again.
531 const [ordered, setOrdered] = useState<{
532 key: string;
533 entries: ReadonlyArray<PullRequestListEntry>;
534 } | null>(null);
535 useEffect(() => {
536 if (!answered) return;
537 setOrdered((previous) => {
538 if (previous === null || previous.key !== filterKey) {
539 return { key: filterKey, entries: rankPullRequestMatches(answered.entries, sentQuery) };
540 }
541 if (sentCursors !== null) {
542 // A continuation is a slice, not the list: it carries only what comes after the rows
543 // already held, and says nothing about a repository that has run out. Everything on
544 // screen therefore stays, and the slice — ordered among itself, since one repository's
545 // next rows can be newer than another's last — lands under it.
546 const held = new Set(previous.entries.map(pullRequestEntryKey));
547 const arrived = answered.entries.filter((entry) => !held.has(pullRequestEntryKey(entry)));
548 const appended = rankPullRequestMatches(
549 arrived.toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
550 sentQuery,
551 );
552 return { key: filterKey, entries: [...previous.entries, ...appended] };
553 }
554 // A whole-page answer replaces the order outright. Positions used to be inherited so the
555 // list would not shift under a reader, but inheriting them filed a pull request opened
556 // since the last read at the bottom of the page — below rows a week older — where "the
557 // latest" is exactly what a refresh was for. The host answers in the order the page
558 // reads, so its order stands; a row that moved was updated, and moving is the news.
559 return { key: filterKey, entries: rankPullRequestMatches(answered.entries, sentQuery) };
560 });
561 }, [answered, filterKey, sentCursors, sentQuery]);
562
563 // Carrying on where the last answer stopped, and only raising the page size for the hosts that
564 // could not say where that was.
565 // From this question's own answer, never from the rows being held while it travels: a
566 // continuation is a boundary in one listing, and carrying one across a search would ask the
567 // new question to start where the old one stopped — skipping its newest matches entirely.
568 const nextCursors = answered?.nextCursors ?? {};
569 const canContinue = !showingCarried && Object.keys(nextCursors).length > 0;
570 const loadMore = () => {
571 if (canContinue) {
572 setPage({ key: filterKey, size: pageSize, cursors: nextCursors });
573 return;
574 }
575 setPage({
576 key: filterKey,
577 size: Math.min(pageSize + PAGE_SIZE, MAX_PAGE_SIZE),
578 cursors: null,
579 });
580 };
581
582 // A refresh means the whole visible list again, and a cursored query cannot answer that: it
583 // re-reads only its own slice, so the rows loaded before it would never see a merge, a close,
584 // or a retitle. Going back to a single page long enough to cover everything on screen lets the
585 // merge above bring every row up to date in place.
586 const refreshList = () => {
587 if (sentCursors === null) {
588 listQuery.refresh();
589 return;
590 }
591 const loadedCount = ordered?.key === filterKey ? ordered.entries.length : pageSize;
592 setPage({
593 key: filterKey,
594 size: Math.min(
595 Math.max(pageSize, Math.ceil(loadedCount / PAGE_SIZE) * PAGE_SIZE),
596 MAX_PAGE_SIZE,
597 ),
598 cursors: null,
599 });
600 };
601
602 // The list goes stale the same way the detail does: somebody opens a pull request, a check
603 // finishes, a branch is merged. So it reads again on the way back to the window, and once a
604 // minute while somebody is reading it. Those reads go through the server's cache and stop
605 // when the reader stops, which is what keeps a page left open from spending a night of the
606 // host's rate limit.
607 useLiveRefresh(
608 () => {
609 refreshList();
610 baselineQuery.refresh();
611 authoredQuery.refresh();
612 reviewingQuery.refresh();
613 },
614 { enabled: pullRequestEnvironmentId !== null },
615 );
616
617 const viewers = baselineQuery.data?.viewers ?? listData?.viewers ?? EMPTY_VIEWERS;
618 const listErrors = baselineQuery.data?.errors ?? listData?.errors ?? [];
619
620 /** The hosts that narrowed the listing themselves, so their answer is not narrowed again. */
621 const searchingHosts = useMemo(
622 () =>
623 new Set(
624 (baselineQuery.data?.providers ?? listData?.providers ?? []).flatMap((provider) =>
625 provider.searchesOnHost ? [provider.host] : [],
626 ),
627 ),
628 [baselineQuery.data?.providers, listData?.providers],
629 );
630
631 const entries = useMemo(() => {
632 const known = ordered?.key === filterKey ? ordered.entries : (listData?.entries ?? []);
633 const involvementEntries = filterPullRequestsByInvolvement(known, viewers, search.involvement);
634 // The hosts search more than the row shows — a body, a review, a commit message — so once
635 // their answer is in, narrowing it again here would throw away matches the reader asked for.
636 // The local pass stands in for the answer that has not arrived yet, and for the hosts that
637 // answered without searching at all: Azure DevOps has no text filter, so its rows arrive
638 // whole and would otherwise sit under a search that never touched them.
639 if (typedQuery.length === 0) return involvementEntries;
640 const answeredLocally = querySettled && !showingCarried;
641 return involvementEntries.filter(
642 (entry) =>
643 (answeredLocally && searchingHosts.has(entry.host)) ||
644 matchesPullRequestQuery(entry, typedQuery),
645 );
646 }, [
647 filterKey,
648 listData,
649 ordered,
650 querySettled,
651 search.involvement,
652 searchingHosts,
653 showingCarried,
654 typedQuery,
655 viewers,
656 ]);
657
658 const sentinelRef = useRef<HTMLDivElement>(null);
659 useEffect(() => {
660 const sentinel = sentinelRef.current;
661 // A failed page must stop the observer. Retained rows keep the sentinel on screen, so
662 // re-arming it after a failure would ask for the next page again, forever.
663 //
664 // Rows on screen are also what makes reaching the sentinel mean anything: with none, it
665 // sits directly below the empty state and is always in view, so a search that matches
666 // nothing would page through the whole host on its own — one listing of every repository
667 // per step — while the reader looks at an empty page. With nothing to scroll past, the
668 // next page is asked for rather than assumed.
669 if (
670 !sentinel ||
671 entries.length === 0 ||
672 listData?.truncated !== true ||
673 listQuery.isPending ||
674 listQuery.error !== null ||
675 // The rows on screen belong to the previous question, so nothing about them says where
676 // this one carries on from. Growing the page under them would answer neither.
677 showingCarried ||
678 // Asking past the cap is refused, which would strand the list on an error the retry
679 // could never clear, so growth stops here and the rest stays on the host. A continuation
680 // does not grow the page at all, so the cap does not apply to it.
681 (!canContinue && pageSize >= MAX_PAGE_SIZE)
682 ) {
683 return;
684 }
685 const observer = new IntersectionObserver(
686 (observed) => {
687 if (observed.some((entry) => entry.isIntersecting)) {
688 loadMore();
689 }
690 },
691 // Start the next page slightly before the sentinel is on screen.
692 { rootMargin: "240px" },
693 );
694 observer.observe(sentinel);
695 return () => observer.disconnect();
696 }, [
697 entries.length,
698 filterKey,
699 canContinue,
700 listData?.truncated,
701 listQuery.error,
702 listQuery.isPending,
703 pageSize,
704 showingCarried,
705 ]);
706
707 /**
708 * The line counts, asked for once the rows are on screen. On GitHub they are forty per cent of
709 * the read that answers the whole page, for two small numbers at the end of a row — so the
710 * listing leaves them out and they arrive a moment later, into rows that already draw without
711 * them. Keyed by the rows being shown, so scrolling further asks only about what is new.
712 */
713 const groups = useMemo(() => {
714 if (search.involvement !== "all") return [{ key: "others" as const, label: "", entries }];
715 // Until both partitions have answered, the snapshot's stand in — they are yesterday's
716 // groups, but whole ones, where grouping the feed's first page locally loses every
717 // authored row older than it. Once the live reads land they take over; with neither,
718 // the local grouping is still better than nothing.
719 const held =
720 loaded !== null && loaded.environmentId === environmentId && loaded.scope === scopeKey
721 ? loaded.partitions
722 : undefined;
723 const authored = partitionsWanted ? (authoredQuery.data?.entries ?? held?.authored) : undefined;
724 const reviewing = partitionsWanted
725 ? (reviewingQuery.data?.entries ?? held?.reviewing)
726 : undefined;
727 if (authored === undefined || reviewing === undefined) {
728 return groupPullRequestsByInvolvement(entries, viewers);
729 }
730 return partitionPullRequestsWithPriority(entries, authored, reviewing);
731 }, [
732 authoredQuery.data?.entries,
733 entries,
734 environmentId,
735 loaded,
736 partitionsWanted,
737 reviewingQuery.data?.entries,
738 scopeKey,
739 search.involvement,
740 viewers,
741 ]);
742
743 // Keyed by every row being shown — the partitions can hold rows the feed has not paged to —
744 // so scrolling further asks only about what is new.
745 const statsInput = useMemo(
746 () => ({
747 refs: groups
748 .flatMap((group) => group.entries)
749 .map((entry) => ({
750 projectId: entry.projectId,
751 repository: entry.repository,
752 number: entry.number,
753 })),
754 }),
755 [groups],
756 );
757 const statsQuery = useEnvironmentQuery(
758 pullRequestEnvironmentId === null || statsInput.refs.length === 0
759 ? null
760 : pullRequestEnvironment.listStats({
761 environmentId: pullRequestEnvironmentId,
762 input: statsInput,
763 }),
764 );
765 // Adding or removing one row keys a fresh stats query with nothing in it yet, so the counts
766 // are merged into what is already held rather than rebuilt: every count on screen stays until
767 // its replacement arrives.
768 const [statsByRow, setStatsByRow] = useState<PullRequestDiffStats>(() => new Map());
769 useEffect(() => {
770 const stats = statsQuery.data?.stats;
771 if (stats === undefined) return;
772 setStatsByRow((previous) => mergePullRequestDiffStats(previous, stats));
773 }, [statsQuery.data]);
774
775 // A link from a thread or the sidebar only knows the repository, so the owning project is
776 // resolved here; an explicit `projectId` in the URL still wins.
777 const projectIdForRepository = useMemo(() => {
778 const repository = search.repository?.toLowerCase();
779 if (repository === undefined) return undefined;
780 const identity = projects.find(
781 (project) =>
782 project.repositoryIdentity?.owner &&
783 project.repositoryIdentity.name &&
784 `${project.repositoryIdentity.owner}/${project.repositoryIdentity.name}`.toLowerCase() ===
785 repository &&
786 // The same `owner/name` can exist on two hosts. Without this the first match wins, and
787 // a link that named its host opens the pull request from the other one.
788 (search.host === undefined ||
789 pullRequestHostOf(
790 project.repositoryIdentity,
791 project.repositoryIdentity.provider as SourceControlProviderKind,
792 ) === search.host.toLowerCase()),
793 );
794 return identity?.id;
795 }, [projects, search.host, search.repository]);
796
797 // The selection is resolved the same way the scope is: an id from another environment can
798 // never be read here, and one that arrived before the projects did is not yet wrong.
799 const linkedProjectId = useMemo(
800 () => resolveProjectScope(search.selectedProjectId, projects, projectsKnown),
801 [projects, projectsKnown, search.selectedProjectId],
802 );
803 // The scope filter stands in as a last resort: a link can carry `projectId` with a repository
804 // whose identity the inference above cannot match, and refusing to open it because of the
805 // weaker signal would ignore the stronger one the URL spelled out.
806 const selectedProjectId = linkedProjectId ?? projectIdForRepository ?? scopedProjectId;
807 const linkedSelection = useMemo(
808 () =>
809 search.repository && search.number && selectedProjectId
810 ? { repository: search.repository, number: search.number, projectId: selectedProjectId }
811 : null,
812 [search.number, search.repository, selectedProjectId],
813 );
814 useEffect(() => {
815 if (!pullRequestsSupported || rightPanelRef === null || linkedSelection === null) return;
816 useRightPanelStore.getState().openPullRequest(rightPanelRef, linkedSelection);
817 }, [linkedSelection, pullRequestsSupported, rightPanelRef]);
818
819 const selected =
820 rightPanelState.isOpen && activePullRequestSurface !== null
821 ? {
822 repository: activePullRequestSurface.repository,
823 number: activePullRequestSurface.number,
824 projectId: activePullRequestSurface.projectId as ProjectId,
825 }
826 : null;
827
828 const selectSurfaceInUrl = (surface: PullRequestSurface | null) =>
829 updateSearch(
830 surface === null
831 ? clearedSelection
832 : {
833 repository: surface.repository,
834 number: surface.number,
835 selectedProjectId: surface.projectId as ProjectId,
836 },
837 );
838
839 const toggleRightPanel = () => {
840 if (rightPanelRef === null) return;
841 if (rightPanelState.isOpen) {
842 useRightPanelStore.getState().close(rightPanelRef);
843 updateSearch(clearedSelection);
844 return;
845 }
846 if (selectedPullRequestSurface === null) return;
847 useRightPanelStore.getState().show(rightPanelRef);
848 selectSurfaceInUrl(selectedPullRequestSurface);
849 };
850
851 // The provider list is the workspace's hosts, not the filtered ones, so switching to a host
852 // cannot make the switcher that got you there disappear.
853 const [hosts, setHosts] = useState<PullRequestListResult["providers"]>([]);
854 useEffect(() => {
855 // Only from an answer to these filters. Rows carried over from the previous ones bring the
856 // host summaries of the question they answered, and coming back from one host to all of them
857 // would take the switcher's other hosts out of it on the strength of the narrowed answer.
858 if (answered === null) return;
859 // An unfiltered response is the full set of hosts. A filtered one only seeds the switcher
860 // when there is nothing to seed it with, which is a link that arrived already scoped.
861 setHosts((previous) =>
862 search.host === undefined || previous.length === 0 ? answered.providers : previous,
863 );
864 }, [answered, search.host]);
865 const showProvider = hosts.length > 1;
866 // The workspace's own projects already name their hosts, so the row's shape is known before
867 // the list is. Only its shape: which hosts can actually be read still comes from the server.
868 const expectedHosts = useMemo(() => {
869 const byHost = new Map<string, PullRequestExpectedHost>();
870 for (const project of projects) {
871 const kind = project.repositoryIdentity?.provider as SourceControlProviderKind | undefined;
872 if (kind === undefined) continue;
873 const host = pullRequestHostOf(project.repositoryIdentity, kind);
874 if (!byHost.has(host)) byHost.set(host, { host, kind });
875 }
876 return [...byHost.values()];
877 }, [projects]);
878
879 /** Reported per project rather than as a count, so the reader can see which one it was. */
880 const unavailableProjects = useMemo(
881 () => new Map(listErrors.map((error) => [error.projectId, error.message] as const)),
882 [listErrors],
883 );
884
885 // Stable so the memoized rows can skip re-rendering when the list around them changes.
886 const selectEntry = useCallback(
887 (entry: PullRequestListEntry) => {
888 if (rightPanelRef === null) return;
889 useRightPanelStore.getState().openPullRequest(rightPanelRef, entry);
890 updateSearch({
891 repository: entry.repository,
892 number: entry.number,
893 selectedProjectId: entry.projectId,
894 });
895 },
896 [rightPanelRef, updateSearch],
897 );
898
899 const searchInput = (
900 <PullRequestSearchInput
901 value={search.q ?? ""}
902 busy={typedQuery.length > 0 && (!querySettled || showingCarried)}
903 onChange={(query) => updateSearch({ q: query || undefined })}
904 />
905 );
906 const panelToggleControls = (
907 <PanelLayoutControls
908 showTerminalControl={false}
909 terminalAvailable={false}
910 terminalOpen={false}
911 terminalShortcutLabel={null}
912 rightPanelAvailable={rightPanelState.surfaces.length > 0}
913 rightPanelOpen={rightPanelState.isOpen}
914 rightPanelShortcutLabel={null}
915 liveAgentCount={0}
916 onToggleTerminal={() => undefined}
917 onToggleRightPanel={toggleRightPanel}
918 />
919 );
920 const openPanelControls = (
921 <div className="workspace-titlebar-controls right-2 z-50 gap-1 [-webkit-app-region:no-drag] wco:right-[var(--workspace-controls-right)]">
922 {panelToggleControls}
923 </div>
924 );
925 // The rows carried over from the last filters can also narrow to nothing one step further on,
926 // where involvement is applied against the viewers of the answer they came from. "Nothing under
927 // these filters" is a claim, and it is the wrong one to make about a question still in flight,
928 // so that case waits with the skeletons rather than answering for the hosts. A search says so
929 // in its own words and is left to.
930 const carriedToNothing =
931 showingCarried && listQuery.isPending && entries.length === 0 && typedQuery.length === 0;
932 const listBody = (
933 <>
934 {!capabilityKnown ? (
935 <PullRequestListGhost rows={7} />
936 ) : !pullRequestsSupported ? (
937 <PullRequestsUnavailableState
938 title="Pull requests unavailable"
939 error="Update this environment's T3 Code server to browse pull requests."
940 />
941 ) : firstLoad ? (
942 <PullRequestListGhost rows={7} />
943 ) : listQuery.error && listData === null ? (
944 <PullRequestsUnavailableState error={listQuery.error} onRetry={() => listQuery.refresh()} />
945 ) : carriedToNothing ? (
946 <PullRequestListGhost rows={7} />
947 ) : entries.length === 0 ? (
948 <PullRequestListEmptyState
949 hasProjects={!projectsKnown || projects.length > 0}
950 refreshing={refreshing}
951 onRefresh={() => void refreshFromHost()}
952 query={typedQuery}
953 filtered={
954 search.state !== "open" ||
955 search.involvement !== "all" ||
956 scopedProjectId !== undefined ||
957 search.host !== undefined
958 }
959 searching={typedQuery.length > 0 && (!querySettled || showingCarried)}
960 canLoadMore={listData?.truncated === true && (canContinue || pageSize < MAX_PAGE_SIZE)}
961 loadingMore={loadingMore}
962 onClearQuery={() => updateSearch({ q: undefined })}
963 onLoadMore={loadMore}
964 />
965 ) : (
966 <div className="space-y-3">
967 {groups.map((group) => (
968 <div key={group.key} className="space-y-0.5">
969 {group.label ? (
970 <h2 className="px-3 pb-0.5 text-xs font-medium text-muted-foreground/70">
971 {group.label}
972 </h2>
973 ) : null}
974 {group.entries.map((entry) => (
975 <PullRequestRow
976 key={pullRequestEntryKey(entry)}
977 // A row whose host reported its line counts keeps them; one whose host left
978 // them for later takes whatever has arrived since, and draws without them
979 // until it does.
980 entry={withDiffStat(entry, statsByRow)}
981 showProjectTitle
982 showProvider={showProvider}
983 // Ten is the floor the ranking gives a row whose own fields say nothing
984 // about the search: the host matched something this row cannot show.
985 matchedElsewhere={
986 typedQuery.length > 0 &&
987 scorePullRequestMatch(entry, typedQuery) <= MATCHED_ELSEWHERE_SCORE
988 }
989 selected={
990 selected?.repository === entry.repository && selected.number === entry.number
991 }
992 onSelect={selectEntry}
993 />
994 ))}
995 </div>
996 ))}
997 </div>
998 )}
999
1000 {listQuery.error && listData !== null ? (
1001 <div className="flex items-center justify-between gap-3 rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs">
1002 <span>The latest request failed. Showing the last pull requests loaded.</span>
1003 <Button size="xs" variant="outline" onClick={() => listQuery.refresh()}>
1004 Retry
1005 </Button>
1006 </div>
1007 ) : null}
1008 {listData?.truncated && entries.length > 0 ? (
1009 <div ref={sentinelRef} className="flex justify-center py-2 text-xs text-muted-foreground">
1010 {loadingMore ? (
1011 <span className="flex items-center gap-2">
1012 <LoaderIcon aria-hidden className="size-3.5 animate-spin" />
1013 Loading more
1014 </span>
1015 ) : null}
1016 </div>
1017 ) : null}
1018 </>
1019 );
1020 // The same names and glyphs the host pills wear, so the compact menu and the pills read as
1021 // one control: "GitHub" with its mark, never the bare hostname — unless two installs of one
1022 // kind force the hostname to tell them apart.
1023 const hostEntries = hosts.length > 0 ? hosts : expectedHosts;
1024 const hostMenuOptions: ReadonlyArray<PullRequestFilterOption<string>> = [
1025 { value: "", label: "All hosts", Icon: LayersIcon },
1026 ...hostEntries.map((entry) => {
1027 // `expectedHosts` stands in before the server has answered, and nothing is known to be
1028 // unreadable yet; once the summaries arrive they carry whether each one could be read.
1029 const summary = hosts.find((host) => host.host === entry.host);
1030 return {
1031 value: entry.host,
1032 label: pullRequestHostLabel(hostEntries, entry),
1033 Icon: getSourceControlPresentationForKind(entry.kind).Icon,
1034 ...(summary === undefined || summary.configured
1035 ? {}
1036 : { unavailable: summary.detail ?? "This host could not be read." }),
1037 };
1038 }),
1039 ];
1040 const filtersMenu = (
1041 <PullRequestFiltersMenu
1042 state={search.state}
1043 stateOptions={STATE_TABS}
1044 onState={(state) => updateListScope({ state })}
1045 involvement={search.involvement}
1046 involvementOptions={INVOLVEMENT_TABS}
1047 onInvolvement={(involvement) => updateListScope({ involvement })}
1048 host={search.host}
1049 hostOptions={hostMenuOptions}
1050 onHost={(host) => updateListScope({ host })}
1051 environmentId={environmentId}
1052 projects={scopedProjects}
1053 projectId={scopedProjectId}
1054 unavailable={unavailableProjects}
1055 onProject={(projectId) => updateListScope({ projectId })}
1056 />
1057 );
1058 const columnProps = {
1059 refreshing,
1060 onRefresh: () => void refreshFromHost(),
1061 searchValue: search.q ?? "",
1062 involvement: search.involvement,
1063 state: search.state,
1064 host: search.host,
1065 hostMenuOptions,
1066 onInvolvement: (involvement: PullRequestInvolvement) => updateListScope({ involvement }),
1067 onState: (state: PullRequestListState) => updateListScope({ state }),
1068 onHost: (host: string | undefined) => updateListScope({ host }),
1069 searchInput,
1070 filtersMenu,
1071 rightPanelControl:
1072 !pullRequestsSupported || rightPanelState.isOpen ? null : panelToggleControls,
1073 rightPanelOpen: rightPanelState.isOpen,
1074 listBody,
1075 };
1076
1077 const activateSurface = (surface: PullRequestSurface) => {
1078 if (rightPanelRef === null) return;
1079 useRightPanelStore.getState().activateSurface(rightPanelRef, surface.id);
1080 selectSurfaceInUrl(surface);
1081 };
1082 const closeSurface = (surface: PullRequestSurface) => {
1083 if (rightPanelRef === null) return;
1084 useRightPanelStore.getState().closeSurface(rightPanelRef, surface.id);
1085 const next = selectActiveRightPanelSurface(
1086 useRightPanelStore.getState().byThreadKey,
1087 rightPanelRef,
1088 );
1089 selectSurfaceInUrl(next?.kind === "pull-request" ? next : null);
1090 };
1091 const closeOtherSurfaces = (surface: PullRequestSurface) => {
1092 if (rightPanelRef === null) return;
1093 useRightPanelStore.getState().closeOtherSurfaces(rightPanelRef, surface.id);
1094 selectSurfaceInUrl(surface);
1095 };
1096 const closeSurfacesToRight = (surface: PullRequestSurface) => {
1097 if (rightPanelRef === null) return;
1098 useRightPanelStore.getState().closeSurfacesToRight(rightPanelRef, surface.id);
1099 const next = selectActiveRightPanelSurface(
1100 useRightPanelStore.getState().byThreadKey,
1101 rightPanelRef,
1102 );
1103 selectSurfaceInUrl(next?.kind === "pull-request" ? next : null);
1104 };
1105 const closeAllSurfaces = () => {
1106 if (rightPanelRef === null) return;
1107 useRightPanelStore.getState().closeAllSurfaces(rightPanelRef);
1108 selectSurfaceInUrl(null);
1109 };
1110
1111 return (
1112 <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
1113 <div className="relative flex min-h-0 flex-1">
1114 {pullRequestsSupported && rightPanelState.isOpen ? openPanelControls : null}
1115 <PullRequestsColumn {...columnProps} />
1116
1117 {rightPanelState.isOpen && activePullRequestSurface && pullRequestEnvironmentId !== null ? (
1118 <RightPanelTabs
1119 mode="inline"
1120 widthStorageKey="t3code:pull-request-panel-width"
1121 // Default to roughly half the viewport: the PR list needs more
1122 // room than a chat, so the 540px chat-preview default squashes
1123 // it. SSR has no window, so fall back to a reasonable width.
1124 defaultWidth={typeof window === "undefined" ? 640 : Math.floor(window.innerWidth / 2)}
1125 surfaces={rightPanelState.surfaces}
1126 activeSurfaceId={activePullRequestSurface.id}
1127 pendingSurfaceIds={EMPTY_PENDING_SURFACES}
1128 previewSessions={EMPTY_PREVIEW_SESSIONS}
1129 terminalLabelsById={EMPTY_TERMINAL_LABELS}
1130 onActivate={(surface) => {
1131 if (surface.kind === "pull-request") activateSurface(surface);
1132 }}
1133 onCloseSurface={(surface) => {
1134 if (surface.kind === "pull-request") closeSurface(surface);
1135 }}
1136 onCloseOtherSurfaces={(surface) => {
1137 if (surface.kind === "pull-request") closeOtherSurfaces(surface);
1138 }}
1139 onCloseSurfacesToRight={(surface) => {
1140 if (surface.kind === "pull-request") closeSurfacesToRight(surface);
1141 }}
1142 onCloseAllSurfaces={closeAllSurfaces}
1143 onCopyFilePath={() => undefined}
1144 onAddBrowser={() => undefined}
1145 onAddTerminal={() => undefined}
1146 onAddDiff={() => undefined}
1147 onAddFiles={() => undefined}
1148 onAddPullRequest={() => undefined}
1149 onAddAgents={() => undefined}
1150 browserAvailable={false}
1151 terminalAvailable={false}
1152 diffAvailable={false}
1153 filesAvailable={false}
1154 pullRequestAvailable={false}
1155 agentsAvailable={false}
1156 liveAgentCount={0}
1157 pullRequestStatuses={pullRequestTabStatuses}
1158 >
1159 <PullRequestDetailPanel
1160 key={activePullRequestSurface.id}
1161 environmentId={pullRequestEnvironmentId}
1162 reference={{
1163 projectId: activePullRequestSurface.projectId as ProjectId,
1164 repository: activePullRequestSurface.repository,
1165 number: activePullRequestSurface.number,
1166 }}
1167 refreshToken={detailRefreshToken}
1168 // Merging, closing or reopening changes the row this panel was opened from, so
1169 // the list behind it is out of date the moment the host takes the action.
1170 onActed={() => {
1171 refreshList();
1172 baselineQuery.refresh();
1173 authoredQuery.refresh();
1174 reviewingQuery.refresh();
1175 }}
1176 onStateChange={handlePullRequestTabStatusChange}
1177 chromeVariant="collapse"
1178 />
1179 </RightPanelTabs>
1180 ) : null}
1181 </div>
1182 </SidebarInset>
1183 );
1184}
1185
1186/**
1187 * A compact stand-in for one pill group: the trigger wears the current choice, the choices
1188 * live in a menu. Same options, same handler — only the footprint changes.
1189 */
1190function CompactFilterMenu<Value extends string>({
1191 label,
1192 value,
1193 options,
1194 onChange,
1195}: {
1196 label: string;
1197 value: Value;
1198 options: ReadonlyArray<PullRequestFilterOption<Value>>;
1199 onChange: (value: Value) => void;
1200}) {
1201 const current = options.find((option) => option.value === value) ?? options[0]!;
1202 return (
1203 <Menu>
1204 <MenuTrigger
1205 aria-label={label}
1206 className="inline-flex h-7 shrink-0 items-center gap-1 rounded-md px-1.5 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-foreground"
1207 >
1208 {current.label}
1209 <ChevronDownIcon aria-hidden className="size-3 text-muted-foreground/70" />
1210 </MenuTrigger>
1211 <MenuPopup align="start" side="bottom" className="min-w-40">
1212 <MenuRadioGroup value={value} onValueChange={(next) => onChange(next as Value)}>
1213 {options.map((option) => (
1214 <MenuRadioItem
1215 key={option.value}
1216 value={option.value}
1217 // A host the server has already said it cannot read is not a choice here either.
1218 // The pills disable it; a menu that offers it would answer the press by replacing
1219 // a working list with the same failure the pill row exists to explain.
1220 disabled={option.unavailable !== undefined}
1221 title={option.unavailable}
1222 >
1223 <span className="flex min-w-0 items-center gap-2">
1224 <option.Icon aria-hidden className="size-3.5" />
1225 {option.label}
1226 </span>
1227 </MenuRadioItem>
1228 ))}
1229 </MenuRadioGroup>
1230 </MenuPopup>
1231 </Menu>
1232 );
1233}
1234
1235/**
1236 * The search, folded to an icon until asked for. Opening moves focus into the input — the
1237 * whole point of pressing it is to type. It stays open while it holds a query, so an active
1238 * search is never invisible; empty and blurred, it folds back.
1239 */
1240function ExpandableSearch({
1241 searchInput,
1242 searchValue,
1243 open,
1244 onOpenChange,
1245 focusToken,
1246 onFocusWithin,
1247}: {
1248 searchInput: ReactNode;
1249 searchValue: string;
1250 open: boolean;
1251 onOpenChange: (open: boolean) => void;
1252 /** Bumped to pull focus into the input while it is already showing — the Mod+F path. */
1253 focusToken: number;
1254 /**
1255 * Focus entering and leaving the expanded input. An unmount fires no blur, which is the
1256 * point: whoever unmounted this can still see the reader was mid-typing and move the
1257 * focus somewhere that continues the sentence.
1258 */
1259 onFocusWithin?: (focused: boolean) => void;
1260}) {
1261 const containerRef = useRef<HTMLDivElement | null>(null);
1262 useEffect(() => {
1263 if (!open) return;
1264 containerRef.current?.querySelector("input")?.focus();
1265 }, [open]);
1266 const appliedFocusToken = useRef(focusToken);
1267 useEffect(() => {
1268 if (appliedFocusToken.current === focusToken) return;
1269 appliedFocusToken.current = focusToken;
1270 const input = containerRef.current?.querySelector("input");
1271 input?.focus();
1272 input?.select();
1273 }, [focusToken]);
1274 if (open || searchValue.length > 0) {
1275 return (
1276 <div
1277 ref={containerRef}
1278 className="w-56 shrink-0"
1279 onFocus={() => onFocusWithin?.(true)}
1280 onBlur={() => {
1281 onFocusWithin?.(false);
1282 if (searchValue.length === 0) onOpenChange(false);
1283 }}
1284 >
1285 {searchInput}
1286 </div>
1287 );
1288 }
1289 return (
1290 <Button
1291 size="icon-sm"
1292 variant="ghost"
1293 aria-label="Search pull requests"
1294 onClick={() => onOpenChange(true)}
1295 >
1296 <SearchIcon className="size-4" />
1297 </Button>
1298 );
1299}
1300
1301/**
1302 * The pull request list column. The full controls live at the top of the scroll flow; once
1303 * they scroll away, the title transforms into the scope itself — "Pull Requests / Open ▾
1304 * Authored ▾" — where each segment is the menu for that filter, and a folded search sits on
1305 * the right. Scrolled back up, the topbar returns to the plain title. The topbar is the
1306 * window drag region throughout; its interactive children opt out through the `.drag-region`
1307 * descendant rules.
1308 */
1309function PullRequestsColumn({
1310 refreshing,
1311 onRefresh,
1312 searchValue,
1313 involvement,
1314 state,
1315 host,
1316 hostMenuOptions,
1317 onInvolvement,
1318 onState,
1319 onHost,
1320 searchInput,
1321 filtersMenu,
1322 rightPanelControl,
1323 rightPanelOpen,
1324 listBody,
1325}: {
1326 refreshing: boolean;
1327 onRefresh: () => void;
1328 searchValue: string;
1329 involvement: PullRequestInvolvement;
1330 state: PullRequestListState;
1331 host: string | undefined;
1332 hostMenuOptions: ReadonlyArray<PullRequestFilterOption<string>>;
1333 onInvolvement: (involvement: PullRequestInvolvement) => void;
1334 onState: (state: PullRequestListState) => void;
1335 onHost: (host: string | undefined) => void;
1336 searchInput: ReactNode;
1337 filtersMenu: ReactNode;
1338 rightPanelControl: ReactNode;
1339 rightPanelOpen: boolean;
1340 listBody: ReactNode;
1341}) {
1342 const scrollRef = useRef<HTMLDivElement | null>(null);
1343 const markerRef = useRef<HTMLDivElement | null>(null);
1344 const [condensed, setCondensed] = useState(false);
1345 useEffect(() => {
1346 const marker = markerRef.current;
1347 if (!marker) return;
1348 const observer = new IntersectionObserver(
1349 ([entry]) => setCondensed(entry ? !entry.isIntersecting : false),
1350 { root: scrollRef.current },
1351 );
1352 observer.observe(marker);
1353 return () => observer.disconnect();
1354 }, []);
1355 // Typing into the topbar search narrows the list, and a short enough list un-scrolls the
1356 // page — which dissolves the condensed topbar and unmounts the very input being typed in.
1357 // The two inputs are one search to the reader, so the focus follows the value into the
1358 // in-flow bar, caret at the end, and the sentence continues.
1359 const topbarSearchFocusedRef = useRef(false);
1360 const inFlowSearchRef = useRef<HTMLDivElement | null>(null);
1361 const [searchOpen, setSearchOpen] = useState(false);
1362 const [searchFocusToken, setSearchFocusToken] = useState(0);
1363 // Mod+F belongs to this page's own search: the desktop shell binds no find-in-page, so the
1364 // shortcut would otherwise do nothing. Condensed, it unfolds the topbar search; at the top,
1365 // it focuses the in-flow bar and selects the query the way a find field would.
1366 useEffect(() => {
1367 const onKeyDown = (event: KeyboardEvent) => {
1368 if (event.defaultPrevented) return;
1369 if (event.key.toLowerCase() !== "f" || !(event.metaKey || event.ctrlKey)) return;
1370 if (event.altKey || event.shiftKey) return;
1371 event.preventDefault();
1372 if (condensed) {
1373 setSearchOpen(true);
1374 setSearchFocusToken((token) => token + 1);
1375 return;
1376 }
1377 const input = inFlowSearchRef.current?.querySelector("input");
1378 input?.focus();
1379 input?.select();
1380 };
1381 window.addEventListener("keydown", onKeyDown);
1382 return () => window.removeEventListener("keydown", onKeyDown);
1383 }, [condensed]);
1384 useEffect(() => {
1385 if (condensed) return;
1386 // The fold-out is gone from the chrome; forgetting it open keeps the next condensing
1387 // from starting with an empty expanded search nobody asked for.
1388 setSearchOpen(false);
1389 if (!topbarSearchFocusedRef.current) return;
1390 topbarSearchFocusedRef.current = false;
1391 const input = inFlowSearchRef.current?.querySelector("input");
1392 if (!input) return;
1393 input.focus();
1394 input.setSelectionRange(input.value.length, input.value.length);
1395 }, [condensed]);
1396
1397 return (
1398 // Painted flat like the chat column: the inset underneath carries the chrome grain, and a
1399 // content surface that lets it show reads as a different background than every thread.
1400 <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">
1401 <header
1402 className={cn(
1403 "workspace-topbar drag-region gap-1.5 px-3 sm:px-5",
1404 // A closed right panel leaves this column full-width, so its header runs
1405 // underneath the native window controls on Windows; reserve the inset the
1406 // way Settings and the chat view do. While the panel is open the column
1407 // ends at the panel's left edge and the absolute controls strip (already
1408 // WCO-aware) owns the top-right corner.
1409 !rightPanelOpen && "wco:pr-[var(--workspace-native-controls-inset)]",
1410 COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
1411 )}
1412 >
1413 {condensed ? (
1414 <WorkspaceBreadcrumb ariaLabel="Pull request scope">
1415 {/* The page name remains the foreground anchor in both states; the live filters are
1416 its compact scope, grouped as the second crumb rather than pretending each menu
1417 is a separate page in the hierarchy. */}
1418 <WorkspaceBreadcrumbItem current>
1419 <h1 className="truncate">Pull Requests</h1>
1420 </WorkspaceBreadcrumbItem>
1421 <WorkspaceBreadcrumbSeparator />
1422 <WorkspaceBreadcrumbItem className="gap-1.5 overflow-hidden">
1423 <CompactFilterMenu
1424 label="Filter by state"
1425 value={state}
1426 options={STATE_TABS}
1427 onChange={onState}
1428 />
1429 <CompactFilterMenu
1430 label="Filter by involvement"
1431 value={involvement}
1432 options={INVOLVEMENT_TABS}
1433 onChange={onInvolvement}
1434 />
1435 {hostMenuOptions.length > 2 ? (
1436 <CompactFilterMenu
1437 label="Filter by host"
1438 value={host ?? ""}
1439 options={hostMenuOptions}
1440 onChange={(next) => onHost(next === "" ? undefined : next)}
1441 />
1442 ) : null}
1443 </WorkspaceBreadcrumbItem>
1444 </WorkspaceBreadcrumb>
1445 ) : (
1446 <WorkspaceBreadcrumb ariaLabel="Pull requests breadcrumb">
1447 <WorkspaceBreadcrumbItem current>
1448 <h1 className="truncate">Pull Requests</h1>
1449 </WorkspaceBreadcrumbItem>
1450 </WorkspaceBreadcrumb>
1451 )}
1452 <div className="min-w-0 flex-1" />
1453 {condensed ? (
1454 <ExpandableSearch
1455 searchInput={searchInput}
1456 searchValue={searchValue}
1457 open={searchOpen}
1458 onOpenChange={setSearchOpen}
1459 focusToken={searchFocusToken}
1460 onFocusWithin={(focused) => {
1461 topbarSearchFocusedRef.current = focused;
1462 }}
1463 />
1464 ) : null}
1465 <Button
1466 size="icon-sm"
1467 variant="ghost"
1468 aria-label="Refresh pull requests"
1469 onClick={onRefresh}
1470 >
1471 <RefreshCwIcon className={cn("size-4", refreshing && "animate-spin")} />
1472 </Button>
1473 {rightPanelControl}
1474 </header>
1475
1476 <div
1477 ref={scrollRef}
1478 className="pull-requests-scroll-fade scrollbar-gutter-both min-h-0 flex-1 overflow-y-auto"
1479 >
1480 {/* The top padding is the fade band's own height (1.5rem here), the same pairing the
1481 settings page makes: at rest the controls sit fully below the mask, and only
1482 content actually passing under the chrome fades. */}
1483 <div className="mx-auto flex w-full max-w-4xl flex-col gap-4 px-5 pt-6 pb-12">
1484 <div className="flex flex-col gap-3">
1485 <div ref={inFlowSearchRef} className="flex items-center gap-2">
1486 {searchInput}
1487 {filtersMenu}
1488 </div>
1489 {/* Scrolled past this marker, the controls are gone and the title takes over. */}
1490 <div ref={markerRef} aria-hidden className="-mt-3 h-px w-full" />
1491 </div>
1492
1493 {listBody}
1494 </div>
1495 </div>
1496 </div>
1497 );
1498}