Skip to content

Commit b2b6463

Browse files
refactor(web): pull request views record answers and refresh by revision
Pull request pages and panels record shared summaries, snapshots and guide watches from query answers, refetch when a host revision changes, and keep files-viewed writes in a scope-keyed store instead of chaining effects on tokens and counters. Effect categories removed: - shared summary, list, detail snapshot and running-guide mirrors moved into query answer handlers - window and document key listeners moved to dispatcher scopes (detail, page, guide tour, list search, close-sweep Escape) - sentinels, overflow, condense and stats visibility observers moved to ref callbacks - values reported back to parents derived in render (selected commit, stats batches, tab fallback) - refresh-token and revalidation-counter effects replaced by reads keyed on the pull request's host revision - per-watch guide run components replaced by an app-lifetime poller - files-viewed mirror and scope-leave effects moved into a scoped store - code tab file reveals became requests that pend until the file loads Bugs fixed: - A review guide seen as Running reported the previous run's failure as a toast or desktop notification. - A selected commit missing from a still-loading list was reset to "all commits" permanently. - Comment overflow was measured after paint, so the fade and button popped in. - A guide open request with review guides disabled looped between tabs. - A files-viewed answer for a scope that was left and re-entered was applied to the new visit. Kept effects: - Linked-selection panel open: the URL changes through reload and back/forward and resolves against late project data. - Guide tab maximize on show: needs the page's maximized state in a store. - Close-sweep sensor cancel. Temporary compat shims (removed in a later layer of this stack): - components/pullRequest/guide/PullRequestGuideRunCoordinator.tsx: final startGuideRunNotifications plus a compat PullRequestGuideRunCoordinator component that the base __root mounts until appInit starts it in the web-chat-view layer; guideRunStore's final shape removes the state the base coordinator used (removed in layer 10) - hooks/useSettings.ts: starts model-preference migration at module load until appInit starts it in the app-bootstrap layer (the final module drops useMigrateModelPreferences) (removed in layer 10) - components/diffs/useCodeViewFileReveal.ts: final hook plus a retry effect for the base DiffPanel's (viewer, scope, readyFileKeys) call, so DiffPanel's reveal still waits for the file to render until DiffPanel lands in the web-files layer; the PR code tab needs the final hook (removed in layer 07) Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent f7e4f66 commit b2b6463

36 files changed

Lines changed: 2593 additions & 1230 deletions

‎apps/web/src/components/RightPanelTabs.tsx‎

Lines changed: 44 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ import type { DesktopPreviewOverlay } from "~/previewStateStore";
5353
import type { RightPanelSurface } from "~/rightPanelStore";
5454
import { cn } from "~/lib/utils";
5555
import { resolveShortcutCommand, type ShortcutMatchContext } from "~/keybindings";
56+
import { registerCommands } from "~/shortcuts/dispatcher";
5657
import { readLocalApi } from "~/localApi";
5758
import { useStableCallback } from "~/hooks/useStableCallback";
5859
import { Button } from "~/components/ui/button";
@@ -379,21 +380,23 @@ function RightPanelEmptyState(props: {
379380
const highlightIndex =
380381
availableActions.length === 0 ? -1 : Math.min(highlight, availableActions.length - 1);
381382

382-
const handleShortcut = useEffectEvent((event: KeyboardEvent) => {
383+
const handleLetterShortcut = useEffectEvent((event: KeyboardEvent) => {
383384
const action = surfaceShortcutActionForKey(availableActions, event);
384-
if (!action) return;
385-
if (document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return;
385+
if (!action) return false;
386+
if (document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return false;
386387
const target = event.composedPath()[0] ?? event.target;
387-
if (target instanceof Element && surfaceShortcutTargetsTypingContext(target)) return;
388+
if (target instanceof Element && surfaceShortcutTargetsTypingContext(target)) return false;
388389
event.preventDefault();
389390
event.stopPropagation();
390391
action.onClick();
392+
return true;
391393
});
392-
useEffect(() => {
393-
const handler = (event: KeyboardEvent) => handleShortcut(event);
394-
window.addEventListener("keydown", handler, true);
395-
return () => window.removeEventListener("keydown", handler, true);
396-
}, []);
394+
// Capture phase, so a launcher letter wins over the chat's type-to-focus.
395+
useEffect(
396+
() =>
397+
registerCommands({}, { capture: true, onKeyDown: (event) => handleLetterShortcut(event) }),
398+
[],
399+
);
397400

398401
const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
399402
if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
@@ -734,7 +737,7 @@ function PullRequestSurfaceIcon({
734737
repository: surface.repository,
735738
number: surface.number,
736739
};
737-
const sharedSummary = useSharedPullRequestSummary(resolvedEnvironmentId, reference, null);
740+
const sharedSummary = useSharedPullRequestSummary(resolvedEnvironmentId, reference);
738741
const status = linkedSnapshot ?? newestPullRequestSummary(detail, sharedSummary) ?? seed ?? null;
739742
if (status === null) {
740743
return <PullRequestGlyph.pullRequest className="size-3 shrink-0 text-muted-foreground" />;
@@ -958,32 +961,34 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
958961

959962
if (props.open === false && addSurfaceMenuOpen) setAddSurfaceMenuOpen(false);
960963

961-
const onNewSurfaceKeyDown = useEffectEvent((event: KeyboardEvent) => {
962-
if (event.defaultPrevented || event.isComposing) return;
964+
const handleNewSurfaceShortcut = useEffectEvent((event: KeyboardEvent) => {
965+
if (event.isComposing) return false;
963966
if (
964967
resolveShortcutCommand(event, props.keybindings, {
965968
context: { ...props.getShortcutContext(), rightPanelOpen: true },
966969
}) !== "rightPanel.new"
967970
)
968-
return;
969-
if (!addSurfaceMenuOpen && document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return;
971+
return false;
972+
if (!addSurfaceMenuOpen && document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS))
973+
return false;
970974
event.preventDefault();
971975
event.stopPropagation();
972976
if (!event.repeat) {
973977
addSurfaceTriggerRef.current?.focus();
974978
setAddSurfaceMenuOpen(true);
975979
}
980+
return true;
976981
});
982+
// Capture phase, ahead of focused widgets (the terminal) that consume the chord themselves.
977983
useEffect(() => {
978984
if (props.open === false) return;
979-
document.addEventListener("keydown", onNewSurfaceKeyDown, true);
980-
return () => document.removeEventListener("keydown", onNewSurfaceKeyDown, true);
985+
return registerCommands(
986+
{},
987+
{ capture: true, onKeyDown: (event) => handleNewSurfaceShortcut(event) },
988+
);
981989
}, [props.open]);
982990

983-
const updateTabScrollState = () => {
984-
const viewport = tabScrollViewport(tabListRef.current);
985-
if (!viewport) return;
986-
991+
const updateTabScrollState = (viewport: HTMLDivElement) => {
987992
const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE;
988993
const canScrollLeft = hasOverflow && viewport.scrollLeft > TAB_SCROLL_EDGE_TOLERANCE;
989994
const canScrollRight =
@@ -1182,34 +1187,19 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
11821187
setRenamingDevice(null);
11831188
});
11841189

1190+
// A newly active tab, or tabs that start overflowing, can sit outside the scrolled strip.
11851191
useEffect(() => {
11861192
if (!props.activeSurfaceId || !tabScrollState.hasOverflow) return;
11871193
const activeTab = tabListRef.current?.querySelector<HTMLElement>("[data-active-tab='true']");
11881194
activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" });
11891195
}, [props.activeSurfaceId, tabScrollState.hasOverflow]);
11901196

1191-
useEffect(() => {
1192-
const viewport = tabScrollViewport(tabListRef.current);
1193-
if (!viewport) return;
1194-
1195-
const content = viewport.firstElementChild;
1196-
const stopObserving = observeResize(
1197-
content ? [viewport, content] : viewport,
1198-
updateTabScrollState,
1199-
);
1200-
viewport.addEventListener("scroll", updateTabScrollState, { passive: true });
1201-
updateTabScrollState();
1202-
1203-
return () => {
1204-
stopObserving();
1205-
viewport.removeEventListener("scroll", updateTabScrollState);
1206-
};
1207-
}, [updateTabScrollState]);
1208-
1209-
useEffect(() => {
1210-
const viewport = tabScrollViewport(tabListRef.current);
1197+
const attachTabList = (root: HTMLDivElement | null) => {
1198+
tabListRef.current = root;
1199+
const viewport = tabScrollViewport(root);
12111200
if (!viewport) return;
12121201

1202+
const update = () => updateTabScrollState(viewport);
12131203
const handleWheel = (event: WheelEvent) => {
12141204
if (event.ctrlKey) return;
12151205
let delta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY;
@@ -1221,12 +1211,22 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
12211211
viewport.scrollLeft += delta;
12221212
if (viewport.scrollLeft === previousScrollLeft) return;
12231213
event.preventDefault();
1224-
updateTabScrollState();
1214+
update();
12251215
};
12261216

1217+
const content = viewport.firstElementChild;
1218+
const stopObserving = observeResize(content ? [viewport, content] : viewport, update);
1219+
viewport.addEventListener("scroll", update, { passive: true });
12271220
viewport.addEventListener("wheel", handleWheel, { passive: false });
1228-
return () => viewport.removeEventListener("wheel", handleWheel);
1229-
}, [updateTabScrollState]);
1221+
update();
1222+
1223+
return () => {
1224+
tabListRef.current = null;
1225+
stopObserving();
1226+
viewport.removeEventListener("scroll", update);
1227+
viewport.removeEventListener("wheel", handleWheel);
1228+
};
1229+
};
12301230

12311231
return (
12321232
<PreviewPanelShell
@@ -1249,7 +1249,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
12491249
>
12501250
<ScrollArea
12511251
radius="none"
1252-
ref={tabListRef}
1252+
ref={attachTabList}
12531253
hideScrollbars
12541254
scrollFade
12551255
className="min-w-0 flex-1"

‎apps/web/src/components/ThreadStatusIndicators.tsx‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -93,19 +93,14 @@ export function useLinkedThreadPullRequest(
9393
const currentStatus = current === null ? null : linkedPullRequestSnapshotStatus(current);
9494
const fallback =
9595
current === null ? ((!supportsLinks ? linkedPullRequest : null) ?? branchPullRequest) : null;
96-
// Preserve reference identity so sidebar renders do not touch the summary cache.
9796
const reference = fallback == null ? null : linkedPullRequestReference(fallback);
98-
const queried = useEnvironmentQuery(
97+
// Mounted for its answers, which land in the shared summary read below.
98+
useEnvironmentQuery(
9999
!enabled || environmentId === null || reference === null
100100
? null
101101
: linkedPullRequestDetailAtom({ environmentId, input: reference }),
102102
);
103-
const detail = useSharedPullRequestSummary(
104-
environmentId,
105-
reference,
106-
queried.data,
107-
queried.dataUpdatedAt,
108-
);
103+
const detail = useSharedPullRequestSummary(environmentId, reference);
109104

110105
if (current !== null) return currentStatus;
111106
return detail === null
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import type { CodeViewScrollTarget } from "@pierre/diffs";
2+
import { describe, expect, it } from "vite-plus/test";
3+
4+
import { createCodeViewFileReveal } from "./useCodeViewFileReveal";
5+
6+
function viewer(initialItems: ReadonlyArray<string>) {
7+
const items = new Set(initialItems);
8+
const scrolls: CodeViewScrollTarget[] = [];
9+
return {
10+
items,
11+
scrolls,
12+
getInstance: () => ({}),
13+
getItem: (id: string) => (items.has(id) ? {} : undefined),
14+
scrollTo: (target: CodeViewScrollTarget) => scrolls.push(target),
15+
};
16+
}
17+
18+
describe("createCodeViewFileReveal", () => {
19+
it("scrolls at once to a file the viewer holds", () => {
20+
const reveal = createCodeViewFileReveal();
21+
const view = viewer(["a"]);
22+
23+
reveal.request(view, "a");
24+
25+
expect(view.scrolls).toEqual([{ type: "item", id: "a", align: "start" }]);
26+
});
27+
28+
it("keeps a missing file pending until a flush finds it, then drops it", () => {
29+
const reveal = createCodeViewFileReveal();
30+
const view = viewer([]);
31+
32+
reveal.request(view, "a");
33+
reveal.flush(view);
34+
expect(view.scrolls).toEqual([]);
35+
36+
view.items.add("a");
37+
reveal.flush(view);
38+
reveal.flush(view);
39+
expect(view.scrolls).toHaveLength(1);
40+
});
41+
42+
it("drops a pending reveal when another viewer replaces the one it was asked of", () => {
43+
const reveal = createCodeViewFileReveal();
44+
const first = viewer([]);
45+
const second = viewer(["a"]);
46+
47+
reveal.request(first, "a");
48+
reveal.flush(second);
49+
50+
expect(second.scrolls).toEqual([]);
51+
});
52+
});
Lines changed: 36 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,48 @@
11
import type { CodeViewScrollTarget } from "@pierre/diffs";
2-
import { useEffect, useRef, useState } from "react";
2+
import { useEffect, useState } from "react";
33

44
interface FileRevealHandle {
55
getInstance(): object | undefined;
6+
getItem(id: string): object | undefined;
67
scrollTo(target: CodeViewScrollTarget): void;
78
}
89

10+
/**
11+
* Scrolls a code view to a file. A file the viewer does not hold yet stays
12+
* pending until `flush` (from the viewer's post-render) finds it. A pending
13+
* reveal belongs to the viewer it was asked of, so a remounted viewer, such as
14+
* one for another diff scope, drops it.
15+
*/
16+
export function createCodeViewFileReveal() {
17+
let pending: { readonly viewer: FileRevealHandle; readonly fileKey: string } | null = null;
18+
const apply = (viewer: FileRevealHandle, fileKey: string) => {
19+
if (!viewer.getInstance() || viewer.getItem(fileKey) === undefined) return false;
20+
viewer.scrollTo({ type: "item", id: fileKey, align: "start" });
21+
return true;
22+
};
23+
return {
24+
request(viewer: FileRevealHandle | null, fileKey: string) {
25+
pending = viewer === null || apply(viewer, fileKey) ? null : { viewer, fileKey };
26+
},
27+
flush(viewer: FileRevealHandle | null) {
28+
if (pending === null || pending.viewer !== viewer) return;
29+
if (apply(pending.viewer, pending.fileKey)) pending = null;
30+
},
31+
};
32+
}
33+
34+
// Compat shim until the web-files layer: the base DiffPanel passes
35+
// (viewer, scope, readyFileKeys) and never calls `flush`, so a pending reveal
36+
// is retried here whenever the viewer, scope or rendered files change.
937
export function useCodeViewFileReveal<TScope>(
1038
viewer: FileRevealHandle | null,
11-
scope: TScope,
12-
readyFileKeys?: ReadonlyArray<string>,
39+
legacyScope?: TScope,
40+
legacyReadyFileKeys?: ReadonlyArray<string>,
1341
) {
14-
const [request, setRequest] = useState<{ fileKey: string; scope: TScope } | null>(null);
15-
const handledRequest = useRef<typeof request>(null);
16-
42+
const [reveal] = useState(createCodeViewFileReveal);
1743
useEffect(() => {
18-
if (request === null || handledRequest.current === request) return;
19-
if (request.scope !== scope) {
20-
handledRequest.current = request;
21-
return;
22-
}
23-
if (!viewer?.getInstance() || (readyFileKeys && !readyFileKeys.includes(request.fileKey)))
24-
return;
25-
26-
viewer.scrollTo({ type: "item", id: request.fileKey, align: "start" });
27-
handledRequest.current = request;
28-
}, [request, scope, viewer, readyFileKeys]);
29-
30-
return (fileKey: string) => setRequest({ fileKey, scope });
44+
if (legacyScope === undefined && legacyReadyFileKeys === undefined) return;
45+
reveal.flush(viewer);
46+
}, [reveal, viewer, legacyScope, legacyReadyFileKeys]);
47+
return (fileKey: string) => reveal.request(viewer, fileKey);
3148
}

‎apps/web/src/components/pullRequest/LinkPullRequestDialog.tsx‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
} from "@t3tools/client-runtime/pull-request-link-input";
66
import { useAtomValue } from "@effect/atom-react";
77
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
8-
import { useEffect, useRef, useState } from "react";
8+
import { useRef, useState } from "react";
99

1010
import { useProjects, useThreadShell } from "~/state/entities";
1111
import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
@@ -85,11 +85,6 @@ function LinkPullRequestDialog({
8585
setSubmitError(null);
8686
}
8787
}
88-
useEffect(() => {
89-
if (!open) return;
90-
const frame = window.requestAnimationFrame(() => inputRef.current?.focus());
91-
return () => window.cancelAnimationFrame(frame);
92-
}, [open]);
9388

9489
const resolved = resolveLinkPullRequestInput({
9590
reference,
@@ -126,7 +121,7 @@ function LinkPullRequestDialog({
126121

127122
return (
128123
<Dialog open={open} onOpenChange={(next) => (pending ? undefined : onOpenChange(next))}>
129-
<DialogPopup className="max-w-xl">
124+
<DialogPopup className="max-w-xl" initialFocus={inputRef}>
130125
<DialogHeader>
131126
<DialogTitle>Link pull request</DialogTitle>
132127
<DialogDescription>

0 commit comments

Comments
 (0)