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 21, 23:30 UTC
fix(web): PR links jump to the comment, diff line, checks or commits they name (#33989)
Co-authored-by: Md.Sadiq <mohammadsadiq4950@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Yash Singh committed
Nov 10, 2026 at 21:12 UTC
b3fdf2b10fb92e5dbc71a83381c602a8a464bbca
40 files changed
+1871
-84
apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
+48
-3
@@ -1,3 +1,8 @@
1
+import {
2
+ parsePullRequestAnchor,
3
+ pullRequestAnchorMatchesUrl,
4
+ resolvePullRequestReviewAnchor,
5
+} from "@t3tools/shared/pullRequestAnchor";
6
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
7
import { useAtomRefresh } from "@effect/atom-react";
8
import { useFocusEffect, useNavigation, type StaticScreenProps } from "@react-navigation/native";
@@ -8,7 +13,7 @@ import {
13
import { AsyncResult } from "effect/reactivity";
14
import type { PullRequestThreadComment } from "@t3tools/contracts";
15
import { useRef, useState } from "react";
11
-import { ScrollView, View } from "react-native";
16
+import { ScrollView, View, type ScrollViewInstance } from "react-native";
17
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
18
import { NativeScrollViewMarker as ScrollViewMarker } from "../../native/NativeScrollViewMarker";
19
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -138,11 +143,27 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss
143
[...extra, ...(thread?.comments ?? [])].map((comment) => [comment.id, comment]),
144
).values(),
145
].sort((left, right) => left.createdAt.localeCompare(right.createdAt));
146
+ const scrollRef = useRef<ScrollViewInstance>(null);
147
+ const pendingTop = useRef<number | null>(null);
148
+ const positionedComment = useRef<string | null>(null);
149
+ const location = parsePullRequestAnchor(params.navigationUrl);
150
+ const anchor =
151
+ location?.kind === "timeline"
152
+ ? resolvePullRequestReviewAnchor(location.anchor, [], [{ comments }])
153
+ : null;
154
const canReply = permissions.canReply && Boolean(thread);
155
const resolveLabel = thread?.isResolved ? "Unresolve" : "Resolve";
156
return (
157
<PullRequestMarkdownRepository params={params} changeRequest={detail.data}>
145
- <KeyboardAvoidingView automaticOffset behavior="height" className="flex-1 bg-screen">
158
+ <KeyboardAvoidingView
159
+ automaticOffset
160
+ behavior="height"
161
+ className="flex-1 bg-screen"
162
+ // Any touch, such as replying or loading replies, ends the wait to reposition the link.
163
+ onTouchStart={() => {
164
+ pendingTop.current = null;
165
+ }}
166
+ >
167
<AppBar
168
title="Discussion"
169
subtitle={`#${params.number}`}
@@ -162,6 +183,12 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss
183
/>
184
<ScrollViewMarker style={{ flex: 1 }}>
185
<ScrollView
186
+ ref={scrollRef}
187
+ onContentSizeChange={() => {
188
+ if (pendingTop.current === null) return;
189
+ scrollRef.current?.scrollTo({ y: pendingTop.current, animated: false });
190
+ pendingTop.current = null;
191
+ }}
192
className="flex-1"
193
contentInsetAdjustmentBehavior="automatic"
194
keyboardShouldPersistTaps="handled"
@@ -192,7 +219,25 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss
219
<Text>This discussion is no longer available.</Text>
220
) : null}
221
{comments.map((comment) => (
195
- <View key={comment.id} className="gap-3 border-b border-border-subtle py-4">
222
+ <View
223
+ key={comment.id}
224
+ onLayout={(event) => {
225
+ if (
226
+ anchor === null ||
227
+ !pullRequestAnchorMatchesUrl(anchor, comment.url) ||
228
+ positionedComment.current === comment.id
229
+ )
230
+ return;
231
+ positionedComment.current = comment.id;
232
+ pendingTop.current = event.nativeEvent.layout.y;
233
+ scrollRef.current?.scrollTo({ y: pendingTop.current, animated: false });
234
+ }}
235
+ className={
236
+ anchor !== null && pullRequestAnchorMatchesUrl(anchor, comment.url)
237
+ ? "-mx-3 gap-3 rounded-2xl border border-primary bg-primary/10 px-3 py-4"
238
+ : "gap-3 border-b border-border-subtle py-4"
239
+ }
240
+ >
241
<View className="flex-row items-center gap-2">
242
<PullRequestAvatar actor={comment.author} size={28} />
243
<Text className="min-w-0 flex-1 text-sm font-t3-medium">
apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+158
-7
@@ -1,3 +1,10 @@
1
+import {
2
+ parsePullRequestAnchor,
3
+ pullRequestAnchorMatchesUrl,
4
+ pullRequestDiffPathMatches,
5
+ pullRequestLinkCommit,
6
+ resolvePullRequestReviewAnchor,
7
+} from "@t3tools/shared/pullRequestAnchor";
8
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
9
import { Chip } from "../../components/ui/Chip";
10
import { pullRequestTabOffset } from "./pullRequestTabScroll";
@@ -154,8 +161,34 @@ function usePullRequestActivityRows(params: PullRequestParams, filter: ActivityF
161
});
162
return rows;
163
})();
164
+ const location = parsePullRequestAnchor(params.navigationUrl);
165
+ const anchor =
166
+ location?.kind !== "timeline"
167
+ ? null
168
+ : result.data
169
+ ? resolvePullRequestReviewAnchor(
170
+ location.anchor,
171
+ result.data.comments,
172
+ result.data.reviewThreads,
173
+ )
174
+ : location.anchor;
175
+ const targetComment = anchor
176
+ ? result.data?.comments.find((comment) => pullRequestAnchorMatchesUrl(anchor, comment.url))
177
+ : null;
178
+ const targetThread = anchor
179
+ ? result.data?.reviewThreads.find((thread) =>
180
+ thread.comments.some((comment) => pullRequestAnchorMatchesUrl(anchor, comment.url)),
181
+ )
182
+ : null;
183
+ const targetKey = targetThread
184
+ ? `discussion:${targetThread.id}`
185
+ : targetComment
186
+ ? `comment:${targetComment.id}`
187
+ : null;
188
return {
189
rows,
190
+ targetKey,
191
+ targetThread,
192
hiddenCount: filtered?.hiddenCount ?? 0,
193
pending: result.isPending && !result.data,
194
error: result.error,
@@ -334,7 +367,10 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
367
const params = route.params;
368
usePullRequestEnvironmentFallback(params);
369
const connected = usePullRequestConnected(params.environmentId);
337
- const [chosenSection, setSection] = useState<"overview" | "activity" | "guide">("overview");
370
+ const [chosenSection, setSection] = useState<"overview" | "activity" | "guide">(() => {
371
+ const kind = parsePullRequestAnchor(params.navigationUrl)?.kind;
372
+ return kind === "timeline" || kind === "commits" ? "activity" : "overview";
373
+ });
374
const requestedSection = useRef(chosenSection);
375
const [listAnimationsReady, setListAnimationsReady] = useState(false);
376
const [descriptionExpanded, setDescriptionExpanded] = useState(false);
@@ -345,7 +381,14 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
381
const shown = (tab: typeof chosenSection) =>
382
!guidesEnabled && tab === "guide" ? "overview" : tab;
383
const section = shown(chosenSection);
348
- const [activityFilter, setActivityFilter] = useState<ActivityFilter>(DEFAULT_ACTIVITY_FILTER);
384
+ const [activityFilter, setActivityFilter] = useState<ActivityFilter>(() => {
385
+ const kind = parsePullRequestAnchor(params.navigationUrl)?.kind;
386
+ return kind === "timeline"
387
+ ? { ...DEFAULT_ACTIVITY_FILTER, bots: true, resolved: true }
388
+ : kind === "commits"
389
+ ? { ...DEFAULT_ACTIVITY_FILTER, kind: "commits" }
390
+ : DEFAULT_ACTIVITY_FILTER;
391
+ });
392
const activityContent = usePullRequestActivityRows(params, activityFilter);
393
const scrollOffsets = useRef<Record<string, number>>({});
394
// The offset of the tab last shown, and which tab that was: a tab standing in for a hidden guide
@@ -386,6 +429,74 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
429
scrollViews.current[next]?.scrollToOffset({ offset, animated: false });
430
setSection(next);
431
};
432
+ const followLink = useEffectEvent(() => {
433
+ const target = parsePullRequestAnchor(params.navigationUrl);
434
+ if (target?.kind === "diff" || target?.kind === "code") {
435
+ const commit = pullRequestLinkCommit(params.navigationUrl);
436
+ navigation.navigate("PullRequestFile", {
437
+ ...params,
438
+ path: "",
439
+ ...(commit ? { commit } : {}),
440
+ });
441
+ } else if (target?.kind === "timeline") {
442
+ selectSection("activity");
443
+ setActivityFilter((filter) => ({ ...filter, kind: "all", bots: true, resolved: true }));
444
+ } else if (target?.kind === "commits") {
445
+ selectSection("activity");
446
+ setActivityFilter((filter) => ({ ...filter, kind: "commits" }));
447
+ } else if (target?.kind === "checks") {
448
+ selectSection("overview");
449
+ // Checks head Overview, which a reused screen may have scrolled past.
450
+ scrollViews.current.overview?.scrollToOffset({ offset: -contentTopInset, animated: false });
451
+ } else if (target?.kind === "summary") {
452
+ selectSection("overview");
453
+ }
454
+ });
455
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a link selects its native PR section or diff even when the route is reused
456
+ useEffect(() => {
457
+ // oxlint-disable-next-line react/set-state-in-effect -- URL navigation selects the PR section and makes its target visible
458
+ followLink();
459
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- each clicked URL is a fresh navigation request
460
+ }, [params.navigationUrl, params.navigationId]);
461
+
462
+ const activityTargetIndex = activityContent.rows.findIndex(
463
+ (row) => row.key === activityContent.targetKey,
464
+ );
465
+ const openedDiscussion = useRef<string | null>(null);
466
+ const positionedActivity = useRef<string | null>(null);
467
+ // Rows above the target measure in after the first jump, so it is held until the user scrolls.
468
+ const heldActivityRow = useRef<number | null>(null);
469
+ const positionActivityRow = (index: number) =>
470
+ void scrollViews.current.activity?.scrollToIndex({
471
+ index,
472
+ viewPosition: 0,
473
+ viewOffset: contentTopInset + 12,
474
+ animated: false,
475
+ });
476
+ const revealActivity = useEffectEvent(() => {
477
+ const key = `${params.navigationUrl}:${params.navigationId ?? 0}`;
478
+ if (activityContent.targetThread && openedDiscussion.current !== key) {
479
+ openedDiscussion.current = key;
480
+ navigation.navigate("PullRequestDiscussion", {
481
+ ...params,
482
+ discussionId: activityContent.targetThread.id,
483
+ });
484
+ return;
485
+ }
486
+ // Later filter or refresh changes move the row; they must not pull the user back to it.
487
+ if (activityTargetIndex >= 0 && positionedActivity.current !== key) {
488
+ positionedActivity.current = key;
489
+ // Its top sits under the app bar; centering a long comment pushed its start off screen.
490
+ heldActivityRow.current = activityTargetIndex + 1;
491
+ positionActivityRow(activityTargetIndex + 1);
492
+ }
493
+ });
494
+ const targetThreadId = activityContent.targetThread?.id;
495
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reveals the requested activity once its asynchronous rows arrive
496
+ useEffect(() => {
497
+ revealActivity();
498
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- reruns when activity resolves the URL target, even a thread the filter hides
499
+ }, [params.navigationUrl, params.navigationId, activityTargetIndex, targetThreadId]);
500
const tabContent = activityContent;
501
const filesY = useRef(0);
502
const descriptionY = useRef(0);
@@ -596,6 +707,13 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
707
// The scroll view owns its resting offset. LegendList keeps the first
708
// initialScrollOffset it gets, and the first render has the window's top
709
// inset (0 on the folded iPhone Duo), not the header's.
710
+ onScrollBeginDrag={
711
+ tab === "activity"
712
+ ? () => {
713
+ heldActivityRow.current = null;
714
+ }
715
+ : undefined
716
+ }
717
onScroll={(event) => {
718
const offset = event.nativeEvent.contentOffset.y;
719
scrollOffsets.current[tab] = offset;
@@ -619,6 +737,13 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
737
alwaysBounceVertical
738
scrollsToTop={section === tab}
739
onItemSizeChanged={({ itemKey }) => {
740
+ const held = heldActivityRow.current;
741
+ if (tab === "activity" && held !== null) {
742
+ // A filter or refresh that moved the row ends the hold.
743
+ if (held !== activityTargetIndex + 1) heldActivityRow.current = null;
744
+ else positionActivityRow(held);
745
+ return;
746
+ }
747
if (
748
tab !== "overview" ||
749
section !== "overview" ||
@@ -848,9 +973,20 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) {
973
(detail.data ?? route.params.initialSummary)?.provider,
974
).changeRequest;
975
const result = usePullRequestDiff(route.params, terminology);
976
+ // Other screens open files with the link's params spread in; only the link's own entry follows it.
977
+ const linkAnchor =
978
+ route.params.path === "" &&
979
+ (route.params.commit ?? null) === pullRequestLinkCommit(route.params.navigationUrl)
980
+ ? parsePullRequestAnchor(route.params.navigationUrl)
981
+ : null;
982
+ const linkPath =
983
+ linkAnchor?.kind === "diff" && result.parsed.kind === "files"
984
+ ? result.parsed.files.find((file) => pullRequestDiffPathMatches(linkAnchor.digest, file.path))
985
+ ?.path
986
+ : undefined;
987
const filter = usePullRequestFileFilter(
988
result.parsed,
853
- route.params.focus ? route.params.path : undefined,
989
+ linkPath ?? (route.params.focus ? route.params.path : undefined),
990
);
991
const { refresh: refreshDetail } = detail;
992
useFocusEffect(refreshDetail);
@@ -922,15 +1058,30 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) {
1058
code: row.content ?? "",
1059
});
1060
};
925
- const [jumpPath, setJumpPath] = useState(route.params.path);
1061
+ const [pickedPath, setJumpPath] = useState<string | null>(null);
1062
+ const jumpPath = pickedPath ?? linkPath ?? route.params.path;
1063
const requestedFile =
1064
result.parsed.kind === "files"
1065
? result.parsed.files.find((file) => file.path === jumpPath)
1066
: undefined;
1067
const targetFile =
1068
data.files.find((file) => file.path === jumpPath) ??
932
- (!jumpPath || requestedFile ? data.files[0] : undefined);
933
- const focus = route.params.focus;
1069
+ (linkAnchor?.kind === "diff" && !linkPath
1070
+ ? undefined
1071
+ : !jumpPath || requestedFile
1072
+ ? data.files[0]
1073
+ : undefined);
1074
+ const range = pickedPath === null && linkAnchor?.kind === "diff" ? linkAnchor.range : null;
1075
+ const focus =
1076
+ route.params.focus ??
1077
+ (range
1078
+ ? {
1079
+ side: range.side === "left" ? ("old" as const) : ("new" as const),
1080
+ start: range.start,
1081
+ end: range.end,
1082
+ endSide: range.endSide === "left" ? ("old" as const) : ("new" as const),
1083
+ }
1084
+ : undefined);
1085
const focusedRows = guideFocusedRows(data.rows, targetFile?.id, focus);
1086
const focusIndex = focusedRows.length
1087
? data.rows.findIndex((row) => row.id === focusedRows[0]?.id)
@@ -941,7 +1092,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) {
1092
// The filter the current jump was made under. Hiding or showing test files replaces the rows,
1093
// so a jump made under the other filter has to run again. Native applies the entry
1094
// destination before its first viewport, so the first one counts as made.
944
- const jumpedUnder = useRef<boolean | null>(filter.hideTestFiles);
1095
+ const jumpedUnder = useRef<boolean | null>(targetFile ? filter.hideTestFiles : null);
1096
const hasTestFiles =
1097
result.parsed.kind === "files" &&
1098
result.parsed.files.some((file) => isTestChangedFile(file.path));
apps/mobile/src/features/pull-requests/PullRequestStatusRows.tsx
+8
-1
@@ -1,3 +1,4 @@
1
+import { parsePullRequestAnchor } from "@t3tools/shared/pullRequestAnchor";
2
import { usePullRequestConnected } from "./usePullRequestConnected";
3
import { useAtomValue } from "@effect/atom-react";
4
import { useNavigation } from "@react-navigation/native";
@@ -102,7 +103,13 @@ export function PullRequestStatusMenu(props: RowProps) {
103
}
104
105
export function PullRequestChecksRow(props: RowProps) {
105
- const [expanded, setExpanded] = useState(false);
106
+ const linked = parsePullRequestAnchor(props.params.navigationUrl)?.kind === "checks";
107
+ const [expanded, setExpanded] = useState(linked);
108
+ const [seenNavigation, setSeenNavigation] = useState(props.params.navigationId);
109
+ if (props.params.navigationId !== seenNavigation) {
110
+ setSeenNavigation(props.params.navigationId);
111
+ if (linked) setExpanded(true);
112
+ }
113
const checks = pullRequestChecksSummary(props.pr);
114
const action = usePullRequestAction(props.params, props.pr);
115
const definition = sourceControlClients.get(props.pr.provider);
apps/mobile/src/features/pull-requests/PullRequestTimeline.tsx
+29
-3
@@ -1,3 +1,7 @@
1
+import {
2
+ parsePullRequestAnchor,
3
+ pullRequestAnchorMatchesUrl,
4
+} from "@t3tools/shared/pullRequestAnchor";
5
import { PullRequestEntryRow } from "./PullRequestEntryRow";
6
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
7
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
@@ -74,7 +78,10 @@ function TimelineComment({
78
params: PullRequestParams;
79
actions: CommentActions;
80
}) {
77
- const [expanded, setExpanded] = useState(false);
81
+ const target = parsePullRequestAnchor(params.navigationUrl);
82
+ const linked =
83
+ target?.kind === "timeline" && pullRequestAnchorMatchesUrl(target.anchor, comment.url);
84
+ const [expanded, setExpanded] = useState(linked);
85
const { themeVariables: colors } = useAppearancePreferences();
86
const long = comment.body.length > 450 || comment.body.split("\n").length > 8;
87
const content = useMemo(
@@ -108,7 +115,13 @@ function TimelineComment({
115
</Text>
116
) : null}
117
{preview.trim() || content.attachments.length ? (
111
- <View className="gap-2 overflow-hidden rounded-2xl bg-grouped-card p-3">
118
+ <View
119
+ className={
120
+ linked
121
+ ? "gap-2 overflow-hidden rounded-2xl border border-primary bg-primary/10 p-3"
122
+ : "gap-2 overflow-hidden rounded-2xl bg-grouped-card p-3"
123
+ }
124
+ >
125
<View style={long && !expanded ? { maxHeight: 240, overflow: "hidden" } : undefined}>
126
<PullRequestMarkdown
127
markdown={long && !expanded ? comment.body.slice(0, 1200) : comment.body}
@@ -202,6 +215,7 @@ export function pullRequestTimelineRows(
215
navigation: Pick<NavigationProp<ReactNavigation.RootParamList>, "navigate" | "dispatch">,
216
actions: CommentActions,
217
) {
218
+ const linkTarget = parsePullRequestAnchor(params.navigationUrl);
219
const discussionIds = new Set(
220
activity.reviewThreads.flatMap((thread) => thread.comments.map((comment) => comment.id)),
221
);
@@ -211,7 +225,19 @@ export function pullRequestTimelineRows(
225
.map((comment) => ({
226
key: `comment:${comment.id}`,
227
date: comment.createdAt,
214
- content: <TimelineComment comment={comment} params={params} actions={actions} />,
228
+ content: (
229
+ <TimelineComment
230
+ key={
231
+ linkTarget?.kind === "timeline" &&
232
+ pullRequestAnchorMatchesUrl(linkTarget.anchor, comment.url)
233
+ ? `${comment.id}:${params.navigationId ?? params.navigationUrl}`
234
+ : comment.id
235
+ }
236
+ comment={comment}
237
+ params={params}
238
+ actions={actions}
239
+ />
240
+ ),
241
})),
242
...activity.reviewThreads.map((thread) => ({
243
key: `discussion:${thread.id}`,
apps/mobile/src/features/pull-requests/guide/guideDiffFocus.test.ts
new
+30
@@ -0,0 +1,30 @@
1
+import { expect, it } from "vite-plus/test";
2
+import type { NativeReviewDiffRow } from "../../diffs/nativeReviewDiffSurface";
3
+import { guideFocusedRows } from "./guideDiffFocus";
4
+
5
+it("focuses a range that crosses diff sides in either direction", () => {
6
+ const rows: NativeReviewDiffRow[] = [
7
+ { kind: "file", id: "file", fileId: "f" },
8
+ { kind: "line", id: "a", fileId: "f", oldLineNumber: 12 },
9
+ { kind: "line", id: "b", fileId: "f", oldLineNumber: 13 },
10
+ { kind: "line", id: "c", fileId: "f", newLineNumber: 12 },
11
+ { kind: "line", id: "d", fileId: "f", newLineNumber: 13 },
12
+ { kind: "line", id: "other", fileId: "other", newLineNumber: 13 },
13
+ ];
14
+ expect(
15
+ guideFocusedRows(rows, "f", { side: "old", start: 12, endSide: "new", end: 13 }).map(
16
+ (row) => row.id,
17
+ ),
18
+ ).toEqual(["a", "b", "c", "d"]);
19
+ expect(
20
+ guideFocusedRows(rows, "f", { side: "new", start: 13, endSide: "old", end: 12 }).map(
21
+ (row) => row.id,
22
+ ),
23
+ ).toEqual(["a", "b", "c", "d"]);
24
+ expect(
25
+ guideFocusedRows(rows, "f", { side: "old", start: 12, end: 13 }).map((row) => row.id),
26
+ ).toEqual(["a", "b"]);
27
+ expect(guideFocusedRows(rows, "f", { side: "old", start: 99, endSide: "new", end: 13 })).toEqual(
28
+ [],
29
+ );
30
+});
apps/mobile/src/features/pull-requests/guide/guideDiffFocus.ts
+18
@@ -2,6 +2,7 @@ import type { NativeReviewDiffRow } from "../../diffs/nativeReviewDiffSurface";
2
3
export type GuideDiffFocus = {
4
readonly side: "old" | "new";
5
+ readonly endSide?: "old" | "new";
6
readonly start: number;
7
readonly end: number;
8
};
@@ -12,6 +13,23 @@ export function guideFocusedRows(
13
focus: GuideDiffFocus | undefined,
14
) {
15
if (!fileId || !focus) return [];
16
+ if (focus.endSide && focus.endSide !== focus.side) {
17
+ const start = rows.findIndex(
18
+ (row) =>
19
+ row.fileId === fileId &&
20
+ (focus.side === "old" ? row.oldLineNumber : row.newLineNumber) === focus.start,
21
+ );
22
+ const end = rows.findIndex(
23
+ (row) =>
24
+ row.fileId === fileId &&
25
+ (focus.endSide === "old" ? row.oldLineNumber : row.newLineNumber) === focus.end,
26
+ );
27
+ return start < 0 || end < 0
28
+ ? []
29
+ : rows
30
+ .slice(Math.min(start, end), Math.max(start, end) + 1)
31
+ .filter((row) => row.fileId === fileId && row.kind === "line");
32
+ }
33
return rows.filter((row) => {
34
const line = focus.side === "old" ? row.oldLineNumber : row.newLineNumber;
35
return (
apps/mobile/src/features/pull-requests/pullRequestNavigation.test.ts
+7
-1
@@ -34,7 +34,13 @@ describe("native PR entry points", () => {
34
context,
35
projects,
36
),
37
- ).toEqual({ ...context, host: "github.com", repository: "org/repo", number: 12 });
37
+ ).toEqual({
38
+ ...context,
39
+ host: "github.com",
40
+ repository: "org/repo",
41
+ number: 12,
42
+ navigationUrl: "https://github.com/org/repo/pull/12/files#diff",
43
+ });
44
expect(
45
nativePullRequestDestination(
46
"https://git.example/group/sub/repo/-/merge_requests/9",
apps/mobile/src/features/pull-requests/usePullRequestDiff.ts
+2
@@ -23,6 +23,8 @@ export type PullRequestParams = {
23
readonly repository: string;
24
readonly number: number;
25
readonly host?: string;
26
+ readonly navigationUrl?: string;
27
+ readonly navigationId?: number;
28
readonly initialSummary?: PullRequestListEntry | PullRequestSummary;
29
};
30
apps/mobile/src/lib/pullRequestNavigation.ts
+2
@@ -1,3 +1,4 @@
1
+import { parsePullRequestAnchor } from "@t3tools/shared/pullRequestAnchor";
2
import { resolveChangeRequestLinkTarget } from "@t3tools/client-runtime/change-request-links";
3
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
4
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
@@ -24,6 +25,7 @@ export function nativePullRequestDestination(
25
projectId: String(target.project.id),
26
repository: target.repository,
27
number: target.number,
28
+ ...(parsePullRequestAnchor(url) ? { navigationUrl: url } : {}),
29
...(target.host === undefined ? {} : { host: target.host }),
30
};
31
}
apps/mobile/src/native/useOpenPullRequest.ts
+7
-1
@@ -9,6 +9,9 @@ import { appAtomRegistry } from "../state/atom-registry";
9
import { environmentServerConfigsAtom } from "../state/server";
10
import { withKnownPullRequestSummary } from "../state/use-thread-pr";
11
12
+let linkNavigationId = 0;
13
+const nextLinkNavigationId = () => ++linkNavigationId;
14
+
15
type PullRequestContext = { readonly environmentId: string; readonly projectId: string };
16
17
// Avoid useRoute so layouts without route context can open any thread's pull requests.
@@ -24,7 +27,10 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean
27
serverConfigs.has(environmentId),
28
);
29
if (!destination) return tryOpenExternalUrl(url, "pull-request");
27
- const params = withKnownPullRequestSummary(destination);
30
+ const params = withKnownPullRequestSummary({
31
+ ...destination,
32
+ ...(destination.navigationUrl ? { navigationId: nextLinkNavigationId() } : {}),
33
+ });
34
// Android shows one page at a time; iOS opens it over the current page, so Back returns.
35
if (Platform.OS === "android") selectDetail({ name: "PullRequest", params });
36
else if (replace) navigation.dispatch(StackActions.replace("PullRequest", params));
apps/web/src/components/chat/RightPanelSurfaceContent.tsx
+4
@@ -150,6 +150,10 @@ export function RightPanelSurfaceContent(props: {
150
number: surface.number,
151
}}
152
initialTab={surface.detailTab ?? "summary"}
153
+ revealUrl={surface.revealUrl}
154
+ onRevealSettled={(revealUrl) => {
155
+ useRightPanelStore.getState().settlePullRequestReveal(threadRef, surface.id, revealUrl);
156
+ }}
157
onTabChange={(tab) => {
158
useRightPanelStore.getState().setPullRequestDetailTab(threadRef, surface.id, tab);
159
}}
apps/web/src/components/diffs/useCodeViewFileReveal.test.ts
+119
-3
@@ -6,11 +6,13 @@ import { createCodeViewFileReveal } from "./useCodeViewFileReveal";
6
function viewer(initialItems: ReadonlyArray<string>) {
7
const items = new Set(initialItems);
8
const scrolls: CodeViewScrollTarget[] = [];
9
+ const collapsed = new Set<string>();
10
return {
11
items,
12
+ collapsed,
13
scrolls,
14
getInstance: () => ({}),
13
- getItem: (id: string) => (items.has(id) ? {} : undefined),
15
+ getItem: (id: string) => (items.has(id) ? { collapsed: collapsed.has(id) } : undefined),
16
scrollTo: (target: CodeViewScrollTarget) => scrolls.push(target),
17
};
18
}
@@ -24,6 +26,13 @@ describe("createCodeViewFileReveal", () => {
26
reveal.request("a");
27
28
expect(view.scrolls).toEqual([{ type: "item", id: "a", align: "start" }]);
29
+ const range = { start: 12, side: "deletions", end: 15, endSide: "additions" } as const;
30
+ view.collapsed.add("a");
31
+ reveal.request("a", range);
32
+ expect(view.scrolls).toHaveLength(1);
33
+ view.collapsed.delete("a");
34
+ reveal.flush();
35
+ expect(view.scrolls.at(-1)).toEqual({ type: "range", id: "a", range, align: "center" });
36
});
37
38
it("keeps a missing file pending until a flush finds it, then drops it", () => {
@@ -54,19 +63,126 @@ describe("createCodeViewFileReveal", () => {
63
expect(view.scrolls).toEqual([{ type: "item", id: "a", align: "start" }]);
64
});
65
57
- it("drops a pending reveal when its viewer detaches, and positions the next viewer on request", () => {
66
+ it("renders the destination file and expands context before positioning its range", () => {
67
+ const reveal = createCodeViewFileReveal();
68
+ const view = viewer(["a"]);
69
+ let rendered = false;
70
+ let expanded = false;
71
+ const instance = {
72
+ revealLine: () => {
73
+ if (expanded) return false;
74
+ expanded = true;
75
+ return true;
76
+ },
77
+ getLinePosition: () => (expanded ? { top: 100, height: 20 } : undefined),
78
+ };
79
+ reveal.attach({
80
+ ...view,
81
+ getInstance: () => ({ getRenderedItems: () => (rendered ? [{ id: "a", instance }] : []) }),
82
+ });
83
+ const range = { start: 12, end: 15, side: "additions" } as const;
84
+ reveal.request("a", range);
85
+ expect(view.scrolls).toEqual([{ type: "item", id: "a", align: "start" }]);
86
+ rendered = true;
87
+ reveal.flush();
88
+ expect(expanded).toBe(true);
89
+ expect(view.scrolls).toHaveLength(1);
90
+ reveal.flush();
91
+ expect(view.scrolls.at(-1)).toEqual({ type: "range", id: "a", range, align: "center" });
92
+ });
93
+
94
+ it("expands a patch-only file to an unchanged line before positioning it", () => {
95
+ const reveal = createCodeViewFileReveal();
96
+ const view = viewer(["a"]);
97
+ let partial = true;
98
+ const expanded: unknown[] = [];
99
+ const instance = {
100
+ getDiffForSearch: () =>
101
+ ({
102
+ isPartial: partial,
103
+ hunks: [{ additionStart: 10, additionCount: 5, deletionStart: 10, deletionCount: 5 }],
104
+ }) as never,
105
+ expandHunk: (...args: unknown[]) => expanded.push(args),
106
+ revealLine: () => false,
107
+ getLinePosition: () => ({ top: 100, height: 20 }),
108
+ };
109
+ reveal.attach({
110
+ ...view,
111
+ getInstance: () => ({ getRenderedItems: () => [{ id: "a", instance }] }),
112
+ });
113
+ const range = { start: 30, end: 30, side: "additions" } as const;
114
+ reveal.request("a", range);
115
+ expect(expanded).toEqual([[1, "up", 26]]);
116
+ reveal.flush();
117
+ expect(view.scrolls).toEqual([]);
118
+ // The expander loads the file; the next render holds the line.
119
+ partial = false;
120
+ reveal.flush();
121
+ expect(view.scrolls).toEqual([{ type: "range", id: "a", range, align: "center" }]);
122
+
123
+ // Removed lines always sit in a hunk, and a deleted file has no contents to load.
124
+ const deleted = viewer(["d"]);
125
+ const removedRange = { start: 3, end: 4, side: "deletions" } as const;
126
+ reveal.attach({
127
+ ...deleted,
128
+ getInstance: () => ({
129
+ getRenderedItems: () => [
130
+ {
131
+ id: "d",
132
+ instance: {
133
+ ...instance,
134
+ getDiffForSearch: () =>
135
+ ({
136
+ isPartial: true,
137
+ hunks: [
138
+ { additionStart: 0, additionCount: 0, deletionStart: 1, deletionCount: 8 },
139
+ ],
140
+ }) as never,
141
+ },
142
+ },
143
+ ],
144
+ }),
145
+ });
146
+ reveal.request("d", removedRange);
147
+ expect(expanded).toHaveLength(1);
148
+ expect(deleted.scrolls).toEqual([
149
+ { type: "range", id: "d", range: removedRange, align: "center" },
150
+ ]);
151
+ });
152
+
153
+ it("drops a pending reveal when another diff's viewer replaces it, but repositions a range a remount loses", () => {
154
const reveal = createCodeViewFileReveal();
155
const first = viewer([]);
60
- const second = viewer(["a"]);
156
+ // Item ids carry the diff's scope, so another diff's viewer holds other ids.
157
+ const second = viewer(["b"]);
158
reveal.attach(first);
159
160
reveal.request("a");
161
reveal.attach(null);
162
reveal.attach(second);
163
+ second.items.add("a");
164
reveal.flush();
165
expect(second.scrolls).toEqual([]);
166
167
reveal.request("a");
168
expect(second.scrolls).toHaveLength(1);
169
+
170
+ // The first diff load remounts the viewer right after a range scroll, so it is repeated once.
171
+ const range = { start: 3, end: 4, side: "additions" } as const;
172
+ const remounted = viewer(["a"]);
173
+ reveal.request("a", range);
174
+ reveal.attach(null);
175
+ reveal.attach(remounted);
176
+ reveal.flush();
177
+ expect(remounted.scrolls).toEqual([{ type: "range", id: "a", range, align: "center" }]);
178
+
179
+ // Scrolling away before that second pass keeps the user where they went.
180
+ const scrolledAway = viewer(["a"]);
181
+ reveal.request("a", range);
182
+ reveal.cancel();
183
+ reveal.attach(null);
184
+ reveal.attach(scrolledAway);
185
+ reveal.flush();
186
+ expect(scrolledAway.scrolls).toEqual([]);
187
});
188
});
apps/web/src/components/diffs/useCodeViewFileReveal.ts
+151
-12
@@ -1,37 +1,176 @@
1
-import type { CodeViewScrollTarget } from "@pierre/diffs";
1
+import type {
2
+ CodeViewScrollTarget,
3
+ SelectedLineRange,
4
+ FileDiffMetadata,
5
+ SelectionSide,
6
+} from "@pierre/diffs";
7
import { useState } from "react";
8
9
interface FileRevealHandle {
5
- getInstance(): object | undefined;
6
- getItem(id: string): object | undefined;
10
+ getInstance():
11
+ | {
12
+ getRenderedItems?(): readonly {
13
+ id: string;
14
+ instance: {
15
+ getDiffForSearch?(): FileDiffMetadata | undefined;
16
+ revealLine?(line: number): boolean;
17
+ expandHunk?(hunkIndex: number, direction: "up" | "down", lineCount: number): void;
18
+ getLinePosition(
19
+ line: number,
20
+ side?: SelectionSide,
21
+ ): { top: number; height: number } | undefined;
22
+ };
23
+ }[];
24
+ }
25
+ | undefined;
26
+ getItem(id: string): { collapsed?: boolean } | undefined;
27
scrollTo(target: CodeViewScrollTarget): void;
28
}
29
30
+// Mirrors the viewer's `revealLine`, which reads distances from the edges of the collapsed gap.
31
+function expandPartialDiffToLine(
32
+ diff: FileDiffMetadata,
33
+ line: number,
34
+ expandHunk: (hunkIndex: number, direction: "up" | "down", lineCount: number) => void,
35
+): boolean {
36
+ const { hunks } = diff;
37
+ if (
38
+ hunks.some(
39
+ (hunk) => line >= hunk.additionStart && line < hunk.additionStart + hunk.additionCount,
40
+ )
41
+ ) {
42
+ return false;
43
+ }
44
+ const next = hunks.findIndex((hunk) => line < hunk.additionStart);
45
+ const previous = next === -1 ? hunks.at(-1) : hunks[next - 1];
46
+ const fromStart = line - (previous ? previous.additionStart + previous.additionCount : 1) + 1;
47
+ const after = next === -1 ? undefined : hunks[next];
48
+ if (after === undefined) expandHunk(hunks.length, "up", fromStart + REVEAL_CONTEXT_LINES);
49
+ else if (fromStart <= after.additionStart - line) {
50
+ expandHunk(next, "up", fromStart + REVEAL_CONTEXT_LINES);
51
+ } else expandHunk(next, "down", after.additionStart - line + REVEAL_CONTEXT_LINES);
52
+ return true;
53
+}
54
+
55
+const REVEAL_CONTEXT_LINES = 10;
56
+
57
/**
58
* Scrolls a code view to a file. `attach` is the viewer's ref and `flush` its post-render
59
* handler, so a reveal asked before the viewer mounts, or for a file it does not hold yet, is
13
- * positioned once it does. A reveal belongs to the diff it was asked of, so detaching the viewer,
14
- * such as remounting it for another diff scope, drops it.
60
+ * positioned once it does. A reveal belongs to the diff it was asked of, so a viewer remounted for
61
+ * another diff scope, which no longer holds the file, drops it.
62
*/
63
export function createCodeViewFileReveal() {
64
let viewer: FileRevealHandle | null = null;
18
- let pending: string | null = null;
65
+ let detachedInstance: object | undefined;
66
+ let pending: {
67
+ id: string;
68
+ range?: SelectedLineRange;
69
+ positionedFile?: boolean;
70
+ loadingFile?: boolean;
71
+ settling?: boolean;
72
+ } | null = null;
73
const flush = () => {
74
if (pending === null || viewer === null) return;
21
- if (!viewer.getInstance() || viewer.getItem(pending) === undefined) return;
22
- viewer.scrollTo({ type: "item", id: pending, align: "start" });
23
- pending = null;
75
+ const item = viewer.getItem(pending.id);
76
+ if (!viewer.getInstance() || item === undefined || item.collapsed === true) return;
77
+ const renderedItems = viewer.getInstance()?.getRenderedItems?.();
78
+ if (pending.range && renderedItems) {
79
+ const rendered = renderedItems.find((entry) => entry.id === pending?.id);
80
+ if (!rendered) {
81
+ if (!pending.positionedFile) {
82
+ pending.positionedFile = true;
83
+ viewer.scrollTo({ type: "item", id: pending.id, align: "start" });
84
+ }
85
+ return;
86
+ }
87
+ const diff = rendered.instance.getDiffForSearch?.();
88
+ const additionLine = (line: number, side: SelectionSide | undefined) => {
89
+ if (side !== "deletions" || !diff) return line;
90
+ const next = diff.hunks.find((hunk) => line < hunk.deletionStart + hunk.deletionCount);
91
+ const last = diff.hunks.at(-1);
92
+ return next
93
+ ? line + next.additionStart - next.deletionStart
94
+ : last
95
+ ? line +
96
+ last.additionStart +
97
+ last.additionCount -
98
+ last.deletionStart -
99
+ last.deletionCount
100
+ : line;
101
+ };
102
+ const { range } = pending;
103
+ const startLine = additionLine(range.start, range.side);
104
+ const endLine = additionLine(range.end, range.endSide ?? range.side);
105
+ // A patch-only diff holds no unchanged lines, and `revealLine` declines to expand it. The
106
+ // viewer's own expander loads the file first, so a line outside every hunk is opened with it.
107
+ if (diff?.isPartial && rendered.instance.expandHunk) {
108
+ // Wait for the file contents the expander asked for.
109
+ if (pending.loadingFile) return;
110
+ const { expandHunk } = rendered.instance;
111
+ // A removed line is always in a hunk, and a deleted file has no contents to load.
112
+ const removed = (line: number, side: SelectionSide | undefined) =>
113
+ side === "deletions" &&
114
+ diff.hunks.some(
115
+ (hunk) => line >= hunk.deletionStart && line < hunk.deletionStart + hunk.deletionCount,
116
+ );
117
+ const outside = [
118
+ ...new Set([
119
+ ...(removed(range.start, range.side) ? [] : [startLine]),
120
+ ...(removed(range.end, range.endSide ?? range.side) ? [] : [endLine]),
121
+ ]),
122
+ ];
123
+ const opened = outside.map((line) => expandPartialDiffToLine(diff, line, expandHunk));
124
+ if (opened.some(Boolean)) {
125
+ pending.loadingFile = true;
126
+ return;
127
+ }
128
+ }
129
+ const startExpanded = rendered.instance.revealLine?.(startLine);
130
+ const endExpanded = rendered.instance.revealLine?.(endLine);
131
+ if (startExpanded || endExpanded) return;
132
+ if (
133
+ !rendered.instance.getLinePosition(range.start, range.side) ||
134
+ !rendered.instance.getLinePosition(range.end, range.endSide ?? range.side)
135
+ )
136
+ return;
137
+ }
138
+ const target = pending;
139
+ // The diff's first load can remount the viewer or re-render it right after this scroll, which
140
+ // loses it; the range is positioned once more on the next render that can hold it.
141
+ pending = target.range && !target.settling ? { ...target, settling: true } : null;
142
+ viewer.scrollTo(
143
+ target.range
144
+ ? { type: "range", id: target.id, range: target.range, align: "center" }
145
+ : { type: "item", id: target.id, align: "start" },
146
+ );
147
};
148
return {
149
attach(next: FileRevealHandle | null) {
27
- if (viewer !== null && next !== viewer) pending = null;
150
+ // The viewer rebuilds its handle on every render and can remount during the diff's first
151
+ // load. Item ids carry the diff's scope, so only a viewer without the item drops the reveal.
152
+ const previous = viewer?.getInstance() ?? detachedInstance;
153
+ if (next === null) detachedInstance = previous;
154
+ else {
155
+ const instance = next.getInstance();
156
+ if (pending !== null && previous !== undefined && instance !== previous) {
157
+ if (instance === undefined || next.getItem(pending.id) === undefined) pending = null;
158
+ // A new instance starts from the patch again, so it must expand the line itself.
159
+ else pending.loadingFile = false;
160
+ }
161
+ detachedInstance = undefined;
162
+ }
163
viewer = next;
164
flush();
165
},
31
- request(fileKey: string) {
32
- pending = fileKey;
166
+ request(fileKey: string, range?: SelectedLineRange) {
167
+ pending = { id: fileKey, ...(range ? { range } : {}) };
168
flush();
169
},
170
+ /** The user scrolled; a reveal still being positioned must not pull them back. */
171
+ cancel() {
172
+ pending = null;
173
+ },
174
flush,
175
};
176
}
apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx
+67
-4
@@ -1,3 +1,5 @@
1
+import { sha256 } from "@noble/hashes/sha2";
2
+import { bytesToHex } from "@noble/hashes/utils";
3
import {
4
EnvironmentId,
5
ProjectId,
@@ -8,6 +10,8 @@ import {
10
import { expect, it, vi } from "vite-plus/test";
11
12
import "~/index.css";
13
+import { __setClientSettingsForTests } from "../../hooks/useSettings";
14
+import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
15
16
const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => {
17
const { AsyncResult, Atom } = await import("effect/reactivity");
@@ -34,11 +38,13 @@ const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => {
38
};
39
const pages: Record<string, PullRequestDiffResult> = {
40
first: {
37
- patch: Array.from({ length: 40 }, (_, index) => filePatch(`early-${index}.ts`)).join(""),
41
+ patch: Array.from({ length: 40 }, (_, index) =>
42
+ filePatch(index === 1 ? "early-1.test.ts" : `early-${index}.ts`),
43
+ ).join(""),
44
truncated: true,
45
nextCursor: "page-2",
46
},
41
- "page-2": { patch: filePatch("late.ts"), truncated: false, nextCursor: null },
47
+ "page-2": { patch: filePatch("late.test.ts"), truncated: false, nextCursor: null },
48
};
49
return {
50
// An environment query whose refetch returns equal content hands back the previous value
@@ -126,6 +132,8 @@ const detail: PullRequestDetailView = {
132
};
133
134
function setup({ paged }: { paged: boolean }) {
135
+ window.localStorage.removeItem("t3code.diffHideTestFiles");
136
+ __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
137
mocks.paged = paged;
138
mocks.diffCommits = [];
139
}
@@ -133,6 +141,8 @@ function setup({ paged }: { paged: boolean }) {
141
const tab = (
142
refreshToken: number,
143
revealRequest: { readonly path: string; readonly nonce: number } | null = null,
144
+ revealUrl?: string,
145
+ onRevealSettled?: (url: string) => void,
146
) => (
147
<PullRequestCodeTab
148
scrollerRef={() => {}}
@@ -144,6 +154,8 @@ const tab = (
154
onRefresh={() => {}}
155
refreshToken={refreshToken}
156
revealRequest={revealRequest}
157
+ revealUrl={revealUrl}
158
+ onRevealSettled={onRevealSettled}
159
/>
160
);
161
@@ -193,13 +205,30 @@ it("scrolls to a file asked for as the tab opens", async () => {
205
206
it("pages forward to a file asked for that is not loaded yet, then scrolls to it", async () => {
207
setup({ paged: true });
208
+ __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: true });
209
+ using _preferences = {
210
+ [Symbol.dispose]() {
211
+ window.localStorage.removeItem("t3code.diffHideTestFiles");
212
+ __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
213
+ },
214
+ };
215
const container = pagedContainer();
216
await using screen = await render(tab(0), { container });
217
await expect.element(screen.getByText("early-0.ts", { exact: true }).first()).toBeVisible();
218
+ await screen.getByRole("button", { name: "Hide test files" }).click();
219
200
- await screen.rerender(tab(0, { path: "late.ts", nonce: 1 }));
220
+ const url = `${detail.url}/files#diff-${bytesToHex(sha256(new TextEncoder().encode("late.test.ts")))}R4-R5`;
221
+ const settled = vi.fn();
222
+ await screen.rerender(tab(0, null, url, settled));
223
202
- await expectFileHeaderShown(screen, container, "late.ts");
224
+ await expectFileHeaderShown(screen, container, "late.test.ts");
225
+ await expect.element(screen.getByText("three()", { exact: true })).toBeVisible();
226
+ await vi.waitFor(() => expect(settled).toHaveBeenCalledWith(url));
227
+ // A settled link keeps its test file past the filter, and a later click reveals it again.
228
+ await screen.rerender(tab(0, { path: "early-0.ts", nonce: 1 }));
229
+ await expectFileHeaderShown(screen, container, "early-0.ts");
230
+ await screen.rerender(tab(0, { path: "early-0.ts", nonce: 1 }, url, settled));
231
+ await expectFileHeaderShown(screen, container, "late.test.ts");
232
});
233
234
it("never requests the diff of a selected commit the pull request no longer has", async () => {
@@ -235,3 +264,37 @@ it("never requests the diff of a selected commit the pull request no longer has"
264
.toBeVisible();
265
expect(mocks.diffCommits).not.toContain("gone");
266
});
267
+
268
+it("answers a commit's diff link only once that commit's diff is shown", async () => {
269
+ setup({ paged: false });
270
+ const container = document.createElement("div");
271
+ container.className = "flex h-[700px] w-[900px]";
272
+ const oid = "c".repeat(40);
273
+ const withCommit = {
274
+ ...detail,
275
+ commits: [{ oid, messageHeadline: "Linked commit", committedDate: "2026-09-01T00:00:00Z" }],
276
+ };
277
+ const url = `${detail.url}/commits/${oid}#diff-${bytesToHex(sha256(new TextEncoder().encode("a.ts")))}R2`;
278
+ const settled = vi.fn();
279
+ const scoped = (selectedCommitOid: string | null, revealUrl?: string) => (
280
+ <PullRequestCodeTab
281
+ scrollerRef={() => {}}
282
+ environmentId={EnvironmentId.make("environment")}
283
+ reference={detail}
284
+ detail={withCommit}
285
+ selectedCommitOid={selectedCommitOid}
286
+ onSelectedCommitChange={() => {}}
287
+ onRefresh={() => {}}
288
+ revealUrl={revealUrl}
289
+ onRevealSettled={settled}
290
+ />
291
+ );
292
+ await using screen = await render(scoped(null), { container });
293
+ await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();
294
+
295
+ // The panel selects the link's commit after this tab has already seen the link.
296
+ await screen.rerender(scoped(null, url));
297
+ expect(settled).not.toHaveBeenCalled();
298
+ await screen.rerender(scoped(oid, url));
299
+ await vi.waitFor(() => expect(settled).toHaveBeenCalledWith(url));
300
+});
apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
+79
-3
@@ -1,3 +1,8 @@
1
+import {
2
+ parsePullRequestAnchor,
3
+ pullRequestDiffPathMatches,
4
+ pullRequestLinkCommit,
5
+} from "@t3tools/shared/pullRequestAnchor";
6
import {
7
capitalizeTerm,
8
sourceControlClients,
@@ -348,6 +353,8 @@ function PullRequestCodeTab({
353
refreshToken = 0,
354
backgroundRefreshToken = 0,
355
revealRequest = null,
356
+ revealUrl,
357
+ onRevealSettled,
358
}: {
359
scrollerRef: (node: HTMLDivElement | null) => void;
360
environmentId: EnvironmentId;
@@ -364,6 +371,9 @@ function PullRequestCodeTab({
371
onRefresh: () => void;
372
refreshToken?: number;
373
backgroundRefreshToken?: number;
374
+ /** A clicked link to a file or line range, until onRevealSettled reports it shown. */
375
+ revealUrl?: string | undefined;
376
+ onRevealSettled?: ((revealUrl: string) => void) | undefined;
377
revealRequest?: { readonly path: string; readonly nonce: number } | null;
378
}) {
379
const resolvedTheme = useRenderedAppearance();
@@ -575,6 +585,20 @@ function PullRequestCodeTab({
585
`pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}`,
586
ignoreWhitespace,
587
);
588
+ const linkAnchor = parsePullRequestAnchor(revealUrl);
589
+ const linkFile =
590
+ linkAnchor?.kind === "diff"
591
+ ? loadedFiles.find((file) =>
592
+ pullRequestDiffPathMatches(linkAnchor.digest, resolveFileDiffPath(file)),
593
+ )
594
+ : undefined;
595
+ const pendingLinkPath = linkFile ? resolveFileDiffPath(linkFile) : null;
596
+ // The linked file stays shown past the test-file filter after the link settles.
597
+ const [revealedLink, setRevealedLink] = useState<{
598
+ readonly scope: string;
599
+ readonly path: string;
600
+ } | null>(null);
601
+ const linkPath = pendingLinkPath ?? (revealedLink?.scope === scopeKey ? revealedLink.path : null);
602
const testFileCount = loadedFiles.filter((file) =>
603
isTestChangedFile(resolveFileDiffPath(file)),
604
).length;
@@ -582,7 +606,7 @@ function PullRequestCodeTab({
606
const files = hideTestFiles
607
? loadedFiles.filter((file) => {
608
const path = resolveFileDiffPath(file);
585
- return path === revealRequest?.path || !isTestChangedFile(path);
609
+ return path === revealRequest?.path || path === linkPath || !isTestChangedFile(path);
610
})
611
: loadedFiles;
612
const hiddenTestFileCount = loadedFiles.length - files.length;
@@ -790,7 +814,7 @@ function PullRequestCodeTab({
814
setFileViewed,
815
};
816
793
- const revealFile = (path: string) => {
817
+ const revealFile = (path: string, range?: SelectedLineRange) => {
818
const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);
819
if (item === undefined) return;
820
// Unfold only: a second reveal before the unfold renders must not fold the file again.
@@ -799,7 +823,8 @@ function PullRequestCodeTab({
823
toggleFileDiffFoldForViewed(item.id, false, effectiveFoldOverride, current),
824
);
825
}
802
- codeViewReveal.request(item.id);
826
+ if (range) setSelectedLines({ id: item.id, range });
827
+ codeViewReveal.request(item.id, range);
828
};
829
830
const toggleAllFiles = () => {
@@ -1430,6 +1455,53 @@ function PullRequestCodeTab({
1455
answerReveal();
1456
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load until the requested file arrives.
1457
}, [canLoadNextSlice, items, revealRequest]);
1458
+ // The store clears a settled link after this render, so one link must not reveal twice.
1459
+ const answeredLink = useRef<string | null>(null);
1460
+ const revealLink = useEffectEvent(() => {
1461
+ if (revealUrl === undefined) answeredLink.current = null;
1462
+ if (revealUrl === undefined || linkAnchor?.kind !== "diff") return;
1463
+ // The panel selects the link's commit after this tab's effects run, so the files on screen
1464
+ // can still be another commit's.
1465
+ const linkCommit = pullRequestLinkCommit(revealUrl);
1466
+ if ((detail.commits.some((entry) => entry.oid === linkCommit) ? linkCommit : null) !== commit) {
1467
+ return;
1468
+ }
1469
+ const key = `${scopeKey}:${revealUrl}`;
1470
+ if (answeredLink.current === key) return;
1471
+ if (
1472
+ !pendingLinkPath ||
1473
+ !items.some((item) => resolveFileDiffPath(item.fileDiff) === pendingLinkPath)
1474
+ ) {
1475
+ if (canLoadNextSlice) loadNextSlice();
1476
+ // Every page is loaded and none has the file.
1477
+ else if (!pendingLinkPath && loadedSlices.length > 0 && nextCursor === null) {
1478
+ answeredLink.current = key;
1479
+ onRevealSettled?.(revealUrl);
1480
+ }
1481
+ return;
1482
+ }
1483
+ answeredLink.current = key;
1484
+ setRevealedLink({ scope: scopeKey, path: pendingLinkPath });
1485
+ onRevealSettled?.(revealUrl);
1486
+ const range = linkAnchor.range;
1487
+ revealFile(
1488
+ pendingLinkPath,
1489
+ range
1490
+ ? {
1491
+ start: range.start,
1492
+ end: range.end,
1493
+ side: toViewerSide(range.side),
1494
+ endSide: toViewerSide(range.endSide),
1495
+ }
1496
+ : undefined,
1497
+ );
1498
+ });
1499
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pages and scrolls the virtual diff to a clicked file or line range
1500
+ useEffect(() => {
1501
+ // oxlint-disable-next-line react/set-state-in-effect -- revealing unfolds the target and may request the next diff page
1502
+ revealLink();
1503
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- retries the reveal as diff pages and viewer items arrive
1504
+ }, [revealUrl, pendingLinkPath, canLoadNextSlice, items]);
1505
const withToolbar = (body: ReactNode) => (
1506
<div className="flex h-full min-h-0 flex-col">
1507
{toolbar}
@@ -1534,6 +1606,10 @@ function PullRequestCodeTab({
1606
<div className="flex min-h-0 flex-1 overflow-hidden">
1607
<div
1608
className="relative min-h-0 min-w-0 flex-1"
1609
+ onWheelCapture={codeViewReveal.cancel}
1610
+ onTouchStartCapture={codeViewReveal.cancel}
1611
+ onPointerDownCapture={codeViewReveal.cancel}
1612
+ onKeyDownCapture={codeViewReveal.cancel}
1613
// Headers live in shadow DOM; composedPath crosses that boundary.
1614
onClickCapture={(event) => {
1615
const composedPath = event.nativeEvent.composedPath?.() ?? [];
apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+128
-4
@@ -1,3 +1,9 @@
1
+import {
2
+ parsePullRequestAnchor,
3
+ pullRequestLinkCommit,
4
+ resolvePullRequestReviewAnchor,
5
+ type PullRequestAnchor,
6
+} from "@t3tools/shared/pullRequestAnchor";
7
import { projectChangeRequestUrl } from "@t3tools/client-runtime/change-request-links";
8
import { normalizeThreadPullRequestKey } from "@t3tools/client-runtime/thread-pull-requests";
9
import { useAtomValue } from "@effect/atom-react";
@@ -126,6 +132,8 @@ import {
132
isStackedPullRequestBase,
133
pullRequestActionNeedsHostRefresh,
134
pullRequestCheckoutCommand,
135
+ pullRequestTimelineEventMatches,
136
+ buildPullRequestTimeline,
137
pullRequestFindingKey,
138
pullRequestHandoffLabels,
139
PULL_REQUEST_MERGE_METHOD_LABELS,
@@ -255,6 +263,22 @@ function pullRequestStackReference(
263
};
264
}
265
266
+function linkedTab(anchor: PullRequestAnchor | null): PullRequestDetailTab | null {
267
+ switch (anchor?.kind) {
268
+ case "code":
269
+ case "diff":
270
+ return "code";
271
+ case "commits":
272
+ case "timeline":
273
+ return "timeline";
274
+ case "checks":
275
+ case "summary":
276
+ return "summary";
277
+ default:
278
+ return null;
279
+ }
280
+}
281
+
282
export function PullRequestDetailPanel({
283
environmentId,
284
shortcutsEnabled,
@@ -271,6 +295,8 @@ export function PullRequestDetailPanel({
295
onBack,
296
onSelectPullRequest,
297
onGuideShown,
298
+ revealUrl,
299
+ onRevealSettled,
300
initialTab = "summary",
301
onTabChange,
302
}: {
@@ -297,6 +323,10 @@ export function PullRequestDetailPanel({
323
composerDraftTarget?: ScopedThreadRef | DraftId;
324
onBack?: (() => void) | undefined;
325
onGuideShown?: (() => void) | undefined;
326
+ /** A clicked link into this pull request, waiting to be shown. */
327
+ revealUrl?: string | undefined;
328
+ /** Reports the link it was given shown or missing, so a newer link stays pending. */
329
+ onRevealSettled?: ((revealUrl: string) => void) | undefined;
330
initialTab?: PullRequestDetailTab;
331
onTabChange?: ((tab: PullRequestDetailTab) => void) | undefined;
332
}) {
@@ -355,7 +385,10 @@ export function PullRequestDetailPanel({
385
coreDetail,
386
detail,
387
} = usePullRequestDetail(environmentId, reference, matchingListEntry);
358
- const [selectedTab, setTab] = useState<PullRequestDetailTab>(initialTab);
388
+ const revealAnchor = parsePullRequestAnchor(revealUrl);
389
+ const [selectedTab, setTab] = useState<PullRequestDetailTab>(
390
+ () => linkedTab(revealAnchor) ?? initialTab,
391
+ );
392
const reviewGuidesEnabled = useEnvironmentSettings(
393
environmentId,
394
(settings) => settings.reviewGuidesEnabled,
@@ -379,7 +412,7 @@ export function PullRequestDetailPanel({
412
const [codeCommitScope, setCodeCommitScope] = useState<{
413
readonly pullRequestKey: string;
414
readonly oid: string | null;
382
- }>(() => ({ pullRequestKey, oid: null }));
415
+ }>(() => ({ pullRequestKey, oid: pullRequestLinkCommit(revealUrl) }));
416
const selectedCodeCommitOid =
417
codeCommitScope.pullRequestKey === pullRequestKey ? codeCommitScope.oid : null;
418
const selectCodeCommit = (oid: string | null) => {
@@ -399,6 +432,33 @@ export function PullRequestDetailPanel({
432
void loadCodeTab();
433
selectTab("code");
434
};
435
+ // Cached activity can predate a linked comment, so a miss waits for one host read. `after` is
436
+ // when that read's invalidation finished; null while it runs.
437
+ const revealHostRead = useRef<{ readonly url: string; readonly after: number | null } | null>(
438
+ null,
439
+ );
440
+ const settleReveal = (url: string) => {
441
+ revealHostRead.current = null;
442
+ onRevealSettled?.(url);
443
+ };
444
+ const followLink = useEffectEvent(() => {
445
+ if (revealUrl === undefined) return;
446
+ const next = linkedTab(revealAnchor);
447
+ if (next === null) return settleReveal(revealUrl);
448
+ if (next === "code") {
449
+ selectCodeCommit(pullRequestLinkCommit(revealUrl));
450
+ void loadCodeTab();
451
+ }
452
+ selectTab(next);
453
+ // These name a tab, not a place in it.
454
+ if (revealAnchor?.kind === "code" || revealAnchor?.kind === "commits") settleReveal(revealUrl);
455
+ });
456
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a clicked link lives in the panel store and selects its tab even when the panel is already mounted
457
+ useEffect(() => {
458
+ // oxlint-disable-next-line react/set-state-in-effect -- link navigation selects the PR tab and commit scope
459
+ followLink();
460
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- each clicked link is a navigation request
461
+ }, [revealUrl]);
462
const tabScopeKey = `${environmentId}:${pullRequestKey}`;
463
const [tabMountState, setTabMountState] = useState(() => ({
464
key: tabScopeKey,
@@ -601,14 +661,72 @@ export function PullRequestDetailPanel({
661
const invalidate = useAtomCommand(pullRequestEnvironment.invalidate, { reportFailure: false });
662
const [isInvalidating, setIsInvalidating] = useState(false);
663
const refreshing = isInvalidating || detailQuery.isPending;
604
- const refreshFromHost = async () => {
664
+ /** Resolves whether the host cache was invalidated before the refetch. */
665
+ const refetchFromHost = async () => {
666
setIsInvalidating(true);
667
// Atom commands settle without throwing, so reset always runs.
607
- await invalidate({ environmentId, input: { reference } });
668
+ const invalidated = await invalidate({ environmentId, input: { reference } });
669
refreshDetail();
670
setRefreshToken((token) => token + 1);
671
setIsInvalidating(false);
672
+ return invalidated._tag === "Success";
673
+ };
674
+ const refreshFromHost = async () => {
675
+ await refetchFromHost();
676
};
677
+ const timelineAnchor =
678
+ revealAnchor?.kind !== "timeline"
679
+ ? null
680
+ : detail === null
681
+ ? revealAnchor.anchor
682
+ : resolvePullRequestReviewAnchor(
683
+ revealAnchor.anchor,
684
+ detail.comments,
685
+ detail.reviewThreads,
686
+ );
687
+ // Loaded activity without the linked item, keyed by load so a refetch is checked again.
688
+ const revealMissedAt =
689
+ timelineAnchor !== null &&
690
+ detail !== null &&
691
+ !activityQuery.isPending &&
692
+ !buildPullRequestTimeline(detail).some((event) =>
693
+ pullRequestTimelineEventMatches(event, timelineAnchor),
694
+ )
695
+ ? activityQuery.dataUpdatedAt
696
+ : null;
697
+ const revealReadFailed = revealMissedAt !== null && activityQuery.error !== null;
698
+ const readHostForReveal = useEffectEvent(() => {
699
+ if (revealUrl === undefined || revealMissedAt === null) return;
700
+ const read = revealHostRead.current;
701
+ if (read?.url !== revealUrl) {
702
+ const request = { url: revealUrl, after: null };
703
+ revealHostRead.current = request;
704
+ void refetchFromHost().then((invalidated) => {
705
+ if (revealHostRead.current !== request) return;
706
+ // Without an invalidation the refetch could only repeat the cached read.
707
+ if (!invalidated) return settleReveal(request.url);
708
+ revealHostRead.current = { url: request.url, after: Date.now() };
709
+ });
710
+ return;
711
+ }
712
+ // A read that finished before the invalidation cannot show the item is missing. `after` is
713
+ // stamped once the refetch was requested, so a read in that same millisecond is the new one.
714
+ if (read.after !== null && (revealReadFailed || revealMissedAt >= read.after)) {
715
+ settleReveal(revealUrl);
716
+ }
717
+ });
718
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a linked comment missing from cached activity asks the host once before the link settles
719
+ useEffect(() => {
720
+ readHostForReveal();
721
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- each load that misses the linked item is checked against the host read
722
+ }, [revealMissedAt, revealReadFailed, revealUrl]);
723
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a host read outliving the panel must not settle a later link
724
+ useEffect(
725
+ () => () => {
726
+ revealHostRead.current = null;
727
+ },
728
+ [],
729
+ );
730
const refreshFromHostOnRequest = useEffectEvent(() => void refreshFromHost());
731
const appliedForcedToken = useRef(forcedRefreshToken);
732
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a new forced refresh token invalidates the host cache and refetches
@@ -1746,6 +1864,8 @@ export function PullRequestDetailPanel({
1864
<div className={cn("absolute inset-0", tab !== "summary" && "invisible")}>
1865
<PullRequestSummaryTab
1866
scrollerRef={scrollerRefs.summary}
1867
+ revealUrl={tab === "summary" ? revealUrl : undefined}
1868
+ onRevealSettled={settleReveal}
1869
environmentId={environmentId}
1870
threadRef={threadRef}
1871
reference={reference}
@@ -1809,6 +1929,8 @@ export function PullRequestDetailPanel({
1929
) : (
1930
<PullRequestTimelineTab
1931
scrollerRef={scrollerRefs.timeline}
1932
+ revealUrl={tab === "timeline" ? revealUrl : undefined}
1933
+ onRevealSettled={settleReveal}
1934
detail={detail}
1935
environmentId={environmentId}
1936
threadRef={threadRef}
@@ -1844,6 +1966,8 @@ export function PullRequestDetailPanel({
1966
refreshToken={refreshToken}
1967
backgroundRefreshToken={turnRefresh ?? 0}
1968
revealRequest={codeRevealRequest}
1969
+ revealUrl={tab === "code" ? revealUrl : undefined}
1970
+ onRevealSettled={settleReveal}
1971
/>
1972
</Suspense>
1973
</div>
apps/web/src/components/pullRequest/PullRequestLinkPreview.tsx
+96
-5
@@ -1,5 +1,6 @@
1
import type { PreviewCard as PreviewCardPrimitive } from "@base-ui/react/preview-card";
2
import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
3
+import { parsePullRequestAnchor, pullRequestLinkCommit } from "@t3tools/shared/pullRequestAnchor";
4
import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts";
5
import {
6
cloneElement,
@@ -18,7 +19,12 @@ import { useEnvironmentQuery } from "~/state/query";
19
20
import { PreviewCard, PreviewCardPopup, PreviewCardTrigger } from "../ui/preview-card";
21
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
21
-import { PullRequestActorAvatar, resolvePullRequestState } from "./pullRequestPresentation";
22
+import { pullRequestLinkSubject, pullRequestReviewOutcome } from "./pullRequestDetail.logic";
23
+import {
24
+ PullRequestActorAvatar,
25
+ PullRequestReviewOutcomeBadge,
26
+ resolvePullRequestState,
27
+} from "./pullRequestPresentation";
28
29
interface PullRequestLinkPreviewTarget {
30
readonly environmentId: EnvironmentId;
@@ -57,6 +63,20 @@ export function PullRequestLinkPreview({
63
})
64
: null,
65
);
66
+ // A link to a comment or commit shows that, read from the activity the panel shares.
67
+ const namesSubject =
68
+ parsePullRequestAnchor(originalUrl)?.kind === "timeline" ||
69
+ pullRequestLinkCommit(originalUrl) !== null;
70
+ const activityQuery = useEnvironmentQuery(
71
+ open && namesSubject
72
+ ? pullRequestEnvironment.activity({
73
+ environmentId: target.environmentId,
74
+ input: target.input,
75
+ })
76
+ : null,
77
+ );
78
+ const subject =
79
+ activityQuery.data === null ? null : pullRequestLinkSubject(originalUrl, activityQuery.data);
80
const summary = useSharedPullRequestSummary(
81
open ? target.environmentId : null,
82
open ? target.input : null,
@@ -136,10 +156,16 @@ export function PullRequestLinkPreview({
156
</span>
157
)}
158
</div>
139
- <p className="mt-1 text-sm font-medium leading-snug text-foreground text-pretty">
140
- {card.title}
141
- </p>
142
- {card.author === undefined ? null : (
159
+ {subject?.kind === "comment" ? (
160
+ <LinkedComment subject={subject} />
161
+ ) : subject?.kind === "commit" ? (
162
+ <LinkedCommit commit={subject.commit} />
163
+ ) : (
164
+ <p className="mt-1 text-sm font-medium leading-snug text-foreground text-pretty">
165
+ {card.title}
166
+ </p>
167
+ )}
168
+ {card.author === undefined || subject !== null ? null : (
169
<div className="mt-2 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
170
<PullRequestActorAvatar actor={card.author} className="size-4" />
171
<span className="min-w-0 truncate">{authorLabel}</span>
@@ -161,3 +187,68 @@ export function PullRequestLinkPreview({
187
</PreviewCard>
188
);
189
}
190
+
191
+function actorLabel(actor: { readonly login: string } | null | undefined) {
192
+ return actor?.login ?? "ghost";
193
+}
194
+
195
+function LinkedComment({
196
+ subject,
197
+}: {
198
+ subject: Extract<ReturnType<typeof pullRequestLinkSubject>, { kind: "comment" }>;
199
+}) {
200
+ const outcome = pullRequestReviewOutcome(subject.reviewState);
201
+ return (
202
+ <div className="mt-2 min-w-0">
203
+ <div className="flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
204
+ <PullRequestActorAvatar actor={subject.author} className="size-4" />
205
+ <span className="min-w-0 truncate font-medium text-foreground">
206
+ {actorLabel(subject.author)}
207
+ </span>
208
+ {outcome === null ? (
209
+ <span className="shrink-0">commented</span>
210
+ ) : (
211
+ <PullRequestReviewOutcomeBadge outcome={outcome} className="shrink-0" />
212
+ )}
213
+ <span aria-hidden>·</span>
214
+ <span className="shrink-0">
215
+ <RelativeTime timestamp={subject.createdAt} />
216
+ </span>
217
+ </div>
218
+ {subject.excerpt === null ? null : (
219
+ <p className="mt-1.5 line-clamp-4 text-xs leading-relaxed text-foreground text-pretty">
220
+ {subject.excerpt}
221
+ </p>
222
+ )}
223
+ </div>
224
+ );
225
+}
226
+
227
+function LinkedCommit({
228
+ commit,
229
+}: {
230
+ commit: Extract<ReturnType<typeof pullRequestLinkSubject>, { kind: "commit" }>["commit"];
231
+}) {
232
+ const author = commit.authors?.[0];
233
+ return (
234
+ <div className="mt-2 min-w-0">
235
+ <p className="text-sm font-medium leading-snug text-foreground text-pretty">
236
+ {commit.messageHeadline}
237
+ </p>
238
+ <div className="mt-1.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
239
+ <code className="shrink-0 font-mono">{commit.oid.slice(0, 7)}</code>
240
+ {author === undefined ? null : (
241
+ <>
242
+ <span aria-hidden>·</span>
243
+ <PullRequestActorAvatar actor={author} className="size-4" />
244
+ <span className="min-w-0 truncate">{actorLabel(author)}</span>
245
+ </>
246
+ )}
247
+ <span aria-hidden>·</span>
248
+ <span className="shrink-0">
249
+ <RelativeTime timestamp={commit.committedDate} />
250
+ </span>
251
+ </div>
252
+ </div>
253
+ );
254
+}
apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
+98
-9
@@ -1,3 +1,5 @@
1
+import { parsePullRequestAnchor } from "@t3tools/shared/pullRequestAnchor";
2
+import { holdLinkedNodeInView } from "./holdLinkedNodeInView";
3
import { useAtomValue } from "@effect/atom-react";
4
import {
5
capitalizeTerm,
@@ -23,7 +25,7 @@ import {
25
UsersIcon,
26
} from "lucide-react";
27
import * as Schema from "effect/Schema";
26
-import { useRef, useState, type ReactNode } from "react";
28
+import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react";
29
30
import { pullRequestEnvironment } from "~/state/pullRequests";
31
import { useLocalStorage } from "~/hooks/useLocalStorage";
@@ -356,16 +358,27 @@ function Section({
358
title,
359
defaultOpen = true,
360
keepMounted = false,
361
+ revealCount = 0,
362
actions,
363
children,
364
}: {
365
title: string;
366
defaultOpen?: boolean;
367
keepMounted?: boolean;
368
+ /** Reopens the section each time a link reveals it. */
369
+ revealCount?: number;
370
actions?: ReactNode;
371
children: ReactNode;
372
}) {
368
- const [open, setOpen] = useState(defaultOpen);
373
+ // A reveal opens at once: the opening animation would move what was just scrolled to.
374
+ const [open, setOpen] = useState<boolean | "revealed">(
375
+ revealCount > 0 ? "revealed" : defaultOpen,
376
+ );
377
+ const [seenRevealCount, setSeenRevealCount] = useState(revealCount);
378
+ if (revealCount !== seenRevealCount) {
379
+ setSeenRevealCount(revealCount);
380
+ setOpen("revealed");
381
+ }
382
const headingRef = useRef<HTMLDivElement>(null);
383
const setOpenWithScrollAnchor = (nextOpen: boolean) => {
384
if (!nextOpen) {
@@ -387,7 +400,7 @@ function Section({
400
};
401
return (
402
<Collapsible
390
- open={open}
403
+ open={open !== false}
404
onOpenChange={setOpenWithScrollAnchor}
405
render={<section aria-label={title} />}
406
data-pull-request-summary-section
@@ -408,7 +421,7 @@ function Section({
421
</CollapsibleTrigger>
422
{actions}
423
</div>
411
- <CollapsiblePanel keepMounted={keepMounted}>
424
+ <CollapsiblePanel keepMounted={keepMounted} animate={open !== "revealed"}>
425
<div className="px-4 pb-4">{children}</div>
426
</CollapsiblePanel>
427
</Collapsible>
@@ -422,6 +435,8 @@ const CommentFilterSchema = Schema.Struct({ bots: Schema.Boolean, resolved: Sche
435
const DEFAULT_COMMENT_FILTER: typeof CommentFilterSchema.Type = { bots: false, resolved: false };
436
437
export function PullRequestSummaryTab({
438
+ revealUrl,
439
+ onRevealSettled,
440
scrollerRef,
441
environmentId,
442
threadRef,
@@ -438,6 +453,9 @@ export function PullRequestSummaryTab({
453
onRefresh,
454
onRefreshChecks = onRefresh,
455
}: {
456
+ /** A clicked link to scroll to, until onRevealSettled reports it shown. */
457
+ revealUrl?: string | undefined;
458
+ onRevealSettled?: ((revealUrl: string) => void) | undefined;
459
scrollerRef: (node: HTMLDivElement | null) => void;
460
environmentId: EnvironmentId;
461
threadRef: ScopedThreadRef | null;
@@ -562,6 +580,60 @@ export function PullRequestSummaryTab({
580
const [commentSaving, setCommentSaving] = useState(false);
581
const editingCommentId = commentScope?.pullRequest === detail.url ? commentScope.commentId : null;
582
583
+ const scrollRef = useRef<HTMLDivElement | null>(null);
584
+ const location = parsePullRequestAnchor(revealUrl);
585
+ const [checksReveals, setChecksReveals] = useState(0);
586
+ const [descriptionReveals, setDescriptionReveals] = useState(0);
587
+ const [seenRevealUrl, setSeenRevealUrl] = useState<string | undefined>(undefined);
588
+ if (revealUrl !== seenRevealUrl) {
589
+ setSeenRevealUrl(revealUrl);
590
+ if (location?.kind === "checks") setChecksReveals((count) => count + 1);
591
+ if (location?.kind === "summary" && location.anchor !== "top") {
592
+ setDescriptionReveals((count) => count + 1);
593
+ }
594
+ }
595
+ const stopHolding = useRef<(() => void) | null>(null);
596
+ const revealSummary = useEffectEvent(() => {
597
+ const root = scrollRef.current;
598
+ if (revealUrl === undefined || !root) return;
599
+ let target: HTMLElement | null | undefined;
600
+ if (location?.kind === "checks") {
601
+ target = root.querySelector<HTMLElement>(
602
+ '[data-pull-request-summary-section][aria-label="Checks"]',
603
+ );
604
+ } else if (location?.kind === "summary") {
605
+ if (location.anchor === "top") {
606
+ stopHolding.current?.();
607
+ root.scrollTop = 0;
608
+ return onRevealSettled?.(revealUrl);
609
+ }
610
+ target = /^issue-\d+$/.test(location.anchor)
611
+ ? root.querySelector<HTMLElement>("[data-pr-description]")
612
+ : [...root.querySelectorAll<HTMLElement>("[id]")].find(
613
+ (node) => node.id === location.anchor || node.id === `user-content-${location.anchor}`,
614
+ );
615
+ }
616
+ // A heading may still be rendering; the link stays pending until it appears.
617
+ if (!target) return;
618
+ stopHolding.current?.();
619
+ const heading = target.hasAttribute("data-pull-request-summary-section")
620
+ ? null
621
+ : target.closest("[data-pull-request-summary-section]")?.firstElementChild;
622
+ stopHolding.current = holdLinkedNodeInView(
623
+ target,
624
+ root,
625
+ () => (heading?.getBoundingClientRect().height ?? 0) + (heading ? 8 : 0),
626
+ );
627
+ onRevealSettled?.(revealUrl);
628
+ });
629
+ const editingDescription = bodyScope?.url === detail.url;
630
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls to a linked section, description or heading once it renders
631
+ useEffect(() => {
632
+ revealSummary();
633
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- retries once the description markdown renders, including after its editor closes
634
+ }, [revealUrl, description, checksReveals, descriptionReveals, editingDescription]);
635
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the hold observes DOM outside React and must end with the tab
636
+ useEffect(() => () => stopHolding.current?.(), []);
637
// Checkbox ticks and the editor share one draft, so each starts from the other's latest body.
638
const saveDescription = async (body: string) => {
639
const key = detail.url;
@@ -733,7 +805,14 @@ export function PullRequestSummaryTab({
805
};
806
807
return (
736
- <div ref={scrollerRef} className="h-full overflow-y-auto" data-pull-request-summary-scroll>
808
+ <div
809
+ ref={(node) => {
810
+ scrollRef.current = node;
811
+ scrollerRef(node);
812
+ }}
813
+ className="h-full overflow-y-auto"
814
+ data-pull-request-summary-scroll
815
+ >
816
<section className="px-4 pt-2.5 pb-1">
817
<div className="space-y-2">
818
<MetaRow icon={<UsersIcon className="size-3.5" />} label="Reviewers">
@@ -838,9 +917,14 @@ export function PullRequestSummaryTab({
917
</div>
918
</section>
919
841
- <Section key={`description:${detail.url}`} title="Description" keepMounted>
920
+ <Section
921
+ key={`description:${detail.url}`}
922
+ title="Description"
923
+ keepMounted
924
+ revealCount={descriptionReveals}
925
+ >
926
<div className="group">
843
- {bodyScope?.url === detail.url ? (
927
+ {editingDescription ? (
928
<PullRequestMarkdownEditor
929
allowEmpty
930
value={bodyScope.body}
@@ -855,7 +939,7 @@ export function PullRequestSummaryTab({
939
onCancel={() => setBodyScope(null)}
940
/>
941
) : (
858
- <div className="flex items-start gap-1">
942
+ <div className="flex items-start gap-1" data-pr-description>
943
<PullRequestMarkdown
944
className="min-w-0 flex-1"
945
text={description.trim().length > 0 ? description : "_No description provided._"}
@@ -875,7 +959,12 @@ export function PullRequestSummaryTab({
959
</div>
960
</Section>
961
878
- <Section key={`checks:${detail.url}`} title="Checks" defaultOpen={false}>
962
+ <Section
963
+ key={`checks:${detail.url}`}
964
+ title="Checks"
965
+ defaultOpen={false}
966
+ revealCount={checksReveals}
967
+ >
968
{checksStale ? (
969
<div className="flex items-center gap-2 text-xs text-muted-foreground">
970
<span>Check details are out of date.</span>
apps/web/src/components/pullRequest/PullRequestTimelineTab.browser.test.tsx
+88
-1
@@ -4,7 +4,7 @@ import {
4
SourceControlProviderKind,
5
type PullRequestDetailView,
6
} from "@t3tools/contracts";
7
-import { expect, it } from "vite-plus/test";
7
+import { expect, it, vi } from "vite-plus/test";
8
9
import { render } from "../../../test/render";
10
import "../../index.css";
@@ -87,3 +87,90 @@ it("mounts only the timeline rows near the viewport of a huge pull request", asy
87
expect(mounted).toBeGreaterThan(0);
88
expect(mounted).toBeLessThan(COMMITS / 10);
89
});
90
+
91
+it.each(["review", "issue-comment", "resolved-reply"] as const)(
92
+ "reveals a linked %s below the virtual viewport",
93
+ async (kind) => {
94
+ const url = `${detail.url}#${kind === "review" ? "pullrequestreview-123" : kind === "issue-comment" ? "issuecomment-123" : "discussion_r123"}`;
95
+ const linkedDetail: PullRequestDetailView = {
96
+ ...detail,
97
+ comments:
98
+ kind === "resolved-reply"
99
+ ? []
100
+ : [
101
+ {
102
+ id: "linked",
103
+ kind,
104
+ author: detail.author,
105
+ body: "Linked reply",
106
+ createdAt: "2026-10-01T00:00:00Z",
107
+ url,
108
+ path: null,
109
+ reviewState: kind === "review" ? "CHANGES_REQUESTED" : null,
110
+ },
111
+ ],
112
+ reviewThreads:
113
+ kind !== "resolved-reply"
114
+ ? []
115
+ : [
116
+ {
117
+ id: "thread",
118
+ path: "src/test.ts",
119
+ line: 5,
120
+ side: "right",
121
+ isResolved: true,
122
+ isOutdated: false,
123
+ comments: [
124
+ {
125
+ id: "root",
126
+ author: detail.author,
127
+ body: "Root comment",
128
+ createdAt: "2026-10-01T00:00:00Z",
129
+ url: `${detail.url}#discussion_r122`,
130
+ },
131
+ {
132
+ id: "reply",
133
+ author: detail.author,
134
+ body: "Linked reply",
135
+ createdAt: "2026-10-01T00:01:00Z",
136
+ url,
137
+ },
138
+ ],
139
+ },
140
+ ],
141
+ };
142
+ const settled = vi.fn();
143
+ await using screen = await render(
144
+ <div style={{ height: 600 }}>
145
+ <PullRequestTimelineTab
146
+ scrollerRef={() => {}}
147
+ detail={linkedDetail}
148
+ environmentId={EnvironmentId.make("environment")}
149
+ reference={detail}
150
+ order="oldest"
151
+ onOpenCommit={() => {}}
152
+ onRefresh={() => {}}
153
+ revealUrl={url}
154
+ onRevealSettled={settled}
155
+ />
156
+ </div>,
157
+ );
158
+ await expect.element(screen.getByText("Linked reply", { exact: true })).toBeVisible();
159
+ await vi.waitFor(() => expect(settled).toHaveBeenCalledWith(url));
160
+ await screen.rerender(
161
+ <div style={{ height: 600 }}>
162
+ <PullRequestTimelineTab
163
+ scrollerRef={() => {}}
164
+ detail={linkedDetail}
165
+ environmentId={EnvironmentId.make("environment")}
166
+ reference={detail}
167
+ order="oldest"
168
+ onOpenCommit={() => {}}
169
+ onRefresh={() => {}}
170
+ onRevealSettled={settled}
171
+ />
172
+ </div>,
173
+ );
174
+ await expect.element(screen.getByText("Linked reply", { exact: true })).toBeVisible();
175
+ },
176
+);
apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
+103
-9
@@ -1,3 +1,9 @@
1
+import {
2
+ parsePullRequestAnchor,
3
+ pullRequestAnchorMatchesUrl,
4
+ resolvePullRequestReviewAnchor,
5
+} from "@t3tools/shared/pullRequestAnchor";
6
+import { holdLinkedNodeInView } from "./holdLinkedNodeInView";
7
import {
8
capitalizeTerm,
9
sourceControlClients,
@@ -20,7 +26,7 @@ import {
26
MessageSquareIcon,
27
MessageSquarePlusIcon,
28
} from "lucide-react";
23
-import { useState, type ReactNode } from "react";
29
+import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react";
30
31
import { cn } from "~/lib/utils";
32
import { readLocalApi } from "~/localApi";
@@ -35,6 +41,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
41
import {
42
buildPullRequestTimeline,
43
groupPullRequestTimelineConversations,
44
+ pullRequestTimelineEventMatches,
45
type PullRequestTimelineRow,
46
isPullRequestVerdictStale,
47
newestPullRequestCommitAt,
@@ -66,6 +73,7 @@ import {
73
import { LegendList, type LegendListRef } from "@legendapp/list/react";
74
75
interface ReactionSurface {
76
+ revealAnchor?: string | null;
77
readonly canReact: boolean;
78
/** Absent where there is no composer beside the panel to add a remark to. */
79
readonly onAddToChat?: ((comment: PullRequestComment) => void) | undefined;
@@ -259,7 +267,16 @@ function ConversationCard({
267
};
268
269
return (
262
- <article className="group py-2">
270
+ <article
271
+ {...(reactions.revealAnchor != null &&
272
+ pullRequestAnchorMatchesUrl(reactions.revealAnchor, event.url)
273
+ ? {
274
+ "data-pr-link-target": true,
275
+ tabIndex: -1,
276
+ className: "group rounded-lg py-2 ring-1 ring-primary/40 outline-none",
277
+ }
278
+ : { className: "group py-2" })}
279
+ >
280
<div className="px-2">
281
<div className="flex min-w-0 flex-wrap items-center gap-2">
282
<div className="min-w-0 flex-1">
@@ -339,19 +356,25 @@ function uniqueConversationActors(events: ReadonlyArray<PullRequestTimelineEvent
356
}
357
358
function ConversationGroup({
359
+ revealAnchor,
360
events,
361
editable,
362
cwd,
363
onOpen,
364
reactions,
365
}: {
366
+ revealAnchor?: string | null;
367
events: ReadonlyArray<PullRequestTimelineEvent>;
368
editable: ReadonlyMap<string, PullRequestComment>;
369
cwd: string;
370
onOpen: (url: string) => void;
371
reactions: ReactionSurface;
372
}) {
354
- const [open, setOpen] = useState(false);
373
+ const [open, setOpen] = useState(
374
+ () =>
375
+ revealAnchor != null &&
376
+ events.some((event) => pullRequestAnchorMatchesUrl(revealAnchor, event.url)),
377
+ );
378
const actors = uniqueConversationActors(events);
379
const first = events[0];
380
if (first === undefined) return null;
@@ -413,6 +436,7 @@ function ConversationGroup({
436
}
437
438
function ReviewThreadEvent({
439
+ revealAnchor,
440
event,
441
thread,
442
editable,
@@ -420,6 +444,7 @@ function ReviewThreadEvent({
444
onOpen,
445
reactions,
446
}: {
447
+ revealAnchor?: string | null;
448
event: PullRequestTimelineEvent;
449
thread: PullRequestTimelineThread;
450
editable: ReadonlyMap<string, PullRequestComment>;
@@ -428,7 +453,14 @@ function ReviewThreadEvent({
453
reactions: ReactionSurface;
454
}) {
455
const dismissed = pullRequestReviewOutcome(event.reviewState) === "dismissed";
431
- const [expanded, setExpanded] = useState(!thread.isResolved && !dismissed);
456
+ const [expanded, setExpanded] = useState(
457
+ () =>
458
+ (revealAnchor != null &&
459
+ [event, ...thread.replies].some((item) =>
460
+ pullRequestAnchorMatchesUrl(revealAnchor, item.url),
461
+ )) ||
462
+ (!thread.isResolved && !dismissed),
463
+ );
464
const replyCount = thread.replies.length + thread.moreReplies;
465
466
return (
@@ -675,6 +707,8 @@ function ReviewVerdictEvent({
707
}
708
709
export function PullRequestTimelineTab({
710
+ revealUrl,
711
+ onRevealSettled,
712
scrollerRef,
713
detail,
714
environmentId,
@@ -685,6 +719,9 @@ export function PullRequestTimelineTab({
719
onAddToChat,
720
onRefresh,
721
}: {
722
+ /** A clicked link to scroll to and mark, until onRevealSettled reports it shown. */
723
+ revealUrl?: string | undefined;
724
+ onRevealSettled?: ((revealUrl: string) => void) | undefined;
725
scrollerRef: (node: HTMLElement | null) => void;
726
detail: PullRequestDetailView;
727
environmentId: EnvironmentId;
@@ -696,9 +733,29 @@ export function PullRequestTimelineTab({
733
onRefresh: () => void;
734
}) {
735
const events = buildPullRequestTimeline(detail);
736
+ const location = parsePullRequestAnchor(revealUrl);
737
+ const revealAnchor = location?.kind === "timeline" ? location.anchor : null;
738
+ // The linked item stays marked and open after it is shown, until another link replaces it.
739
+ const [linked, setLinked] = useState<{ readonly anchor: string; readonly count: number } | null>(
740
+ () => (revealAnchor === null ? null : { anchor: revealAnchor, count: 1 }),
741
+ );
742
+ const [seenRevealUrl, setSeenRevealUrl] = useState(revealUrl);
743
+ if (revealUrl !== seenRevealUrl) {
744
+ setSeenRevealUrl(revealUrl);
745
+ // Each click remounts the linked row, so it opens again even after the user closed it.
746
+ if (revealAnchor !== null) setLinked({ anchor: revealAnchor, count: (linked?.count ?? 0) + 1 });
747
+ }
748
+ const anchor = linked
749
+ ? resolvePullRequestReviewAnchor(linked.anchor, detail.comments, detail.reviewThreads)
750
+ : null;
751
+ const listRef = useRef<LegendListRef | null>(null);
752
+ const matches = (event: PullRequestTimelineEvent) =>
753
+ anchor !== null && pullRequestTimelineEventMatches(event, anchor);
754
+
755
const term = sourceControlClients.get(detail.provider).changeRequest.singular;
756
const newestCommitAt = newestPullRequestCommitAt(detail.commits);
757
const reactions: ReactionSurface = {
758
+ revealAnchor: anchor,
759
canReact: detail.capabilities.reactions === true,
760
onAddToChat: onAddToChat && ((comment) => onAddToChat({ kind: "comment", comment })),
761
environmentId,
@@ -716,23 +773,48 @@ export function PullRequestTimelineTab({
773
);
774
const orderedEvents = order === "newest" ? events : events.toReversed();
775
const rows = groupPullRequestTimelineConversations(orderedEvents);
776
+ const targetIndex = rows.findIndex((row) =>
777
+ row.kind === "comments" ? row.events.some(matches) : matches(row.event),
778
+ );
779
+ const stopHolding = useRef<(() => void) | null>(null);
780
+ const reveal = useEffectEvent(() => {
781
+ const list = listRef.current;
782
+ const url = revealUrl;
783
+ if (url === undefined || revealAnchor === null || targetIndex < 0 || !list) return;
784
+ stopHolding.current?.();
785
+ void list.scrollToIndex({ index: targetIndex, viewPosition: 0, animated: false }).then(() => {
786
+ const scroller = list.getScrollableNode();
787
+ const node = scroller?.querySelector<HTMLElement>("[data-pr-link-target=true]");
788
+ if (scroller && node) stopHolding.current = holdLinkedNodeInView(node, scroller, () => 16);
789
+ onRevealSettled?.(url);
790
+ });
791
+ });
792
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reveals a link destination after activity loading and virtual list mounting
793
+ useEffect(() => {
794
+ reveal();
795
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- runs for each clicked link and again when activity resolves its row
796
+ }, [revealUrl, targetIndex]);
797
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the hold observes DOM outside React and must end with the tab
798
+ useEffect(() => () => stopHolding.current?.(), []);
799
const openOnHost = (url: string) => {
800
void readLocalApi()?.shell.openExternal(url);
801
};
802
803
const rowKey = (row: PullRequestTimelineRow) => {
724
- if (row.kind === "comments") return `comments:${row.events[0]?.id ?? "empty"}`;
804
+ if (row.kind === "comments")
805
+ return `comments:${row.events[0]?.id ?? "empty"}:${row.events.some(matches) ? (linked?.count ?? "") : ""}`;
806
const event = row.event;
807
// A thread's resolution or dismissal remounts it, so its disclosure starts in the new state.
808
return event.thread === undefined
728
- ? event.id
729
- : `thread:${event.id}:${event.thread.isResolved}:${pullRequestReviewOutcome(event.reviewState) === "dismissed"}`;
809
+ ? `${event.id}:${matches(event) ? (linked?.count ?? "") : ""}`
810
+ : `thread:${event.id}:${matches(event) ? (linked?.count ?? "") : ""}:${event.thread.isResolved}:${pullRequestReviewOutcome(event.reviewState) === "dismissed"}`;
811
};
812
const renderRow = ({ item: row }: { item: PullRequestTimelineRow }) => {
813
if (row.kind === "comments") {
814
return (
815
<ConversationGroup
816
events={row.events}
817
+ revealAnchor={anchor}
818
editable={editable}
819
cwd={detail.workspaceRoot}
820
onOpen={openOnHost}
@@ -746,6 +828,7 @@ export function PullRequestTimelineTab({
828
<ReviewThreadEvent
829
event={event}
830
thread={event.thread}
831
+ revealAnchor={anchor}
832
editable={editable}
833
cwd={detail.workspaceRoot}
834
onOpen={openOnHost}
@@ -785,7 +868,10 @@ export function PullRequestTimelineTab({
868
// the page. The connector line is drawn by the content container, behind the rows.
869
return (
870
<LegendList<PullRequestTimelineRow>
788
- ref={(list: LegendListRef | null) => scrollerRef(list?.getScrollableNode() ?? null)}
871
+ ref={(list: LegendListRef | null) => {
872
+ listRef.current = list;
873
+ scrollerRef(list?.getScrollableNode() ?? null);
874
+ }}
875
data={rows}
876
extraData={{ editable, reactions, newestCommitAt }}
877
keyExtractor={rowKey}
@@ -793,7 +879,15 @@ export function PullRequestTimelineTab({
879
estimatedItemSize={140}
880
className="scrollbar-gutter-both h-full px-4"
881
contentContainerClassName="relative mx-auto w-full max-w-3xl before:absolute before:bottom-10 before:left-[15px] before:top-6 before:w-px before:bg-border/45"
796
- ListHeaderComponent={<div className="h-5" />}
882
+ ListHeaderComponent={
883
+ anchor !== null && targetIndex < 0 && revealUrl === undefined ? (
884
+ <p role="status" className="py-4 text-xs text-muted-foreground">
885
+ The linked item is not in the loaded activity.
886
+ </p>
887
+ ) : (
888
+ <div className="h-5" />
889
+ )
890
+ }
891
ListFooterComponent={<div className="h-5" />}
892
/>
893
);
apps/web/src/components/pullRequest/PullRequestsPage.tsx
+10
@@ -1027,10 +1027,13 @@ export function PullRequestsPage() {
1027
if (rightPanelState.isOpen) setMaximized((value) => !value);
1028
};
1029
const onGuideShown = () => setMaximized(true);
1030
+ // updateSearch leaves selectedUrl out, so a reload does not reveal the link again.
1031
+ const consumeLinkedUrl = useEffectEvent(() => updateSearch({}));
1032
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens the URL-linked pull request in the right panel store
1033
useEffect(() => {
1034
if (!pullRequestsSupported || rightPanelRef === null || linkedSelection === null) return;
1035
useRightPanelStore.getState().openPullRequest(rightPanelRef, linkedSelection);
1036
+ if (linkedSelection.revealUrl !== undefined) consumeLinkedUrl();
1037
}, [linkedSelection, pullRequestsSupported, rightPanelRef]);
1038
1039
const selected =
@@ -1521,6 +1524,13 @@ export function PullRequestsPage() {
1524
getShortcutContext={getShortcutContext}
1525
shortcutsEnabled={activePullRequestSurface?.id === renderedPullRequestSurface.id}
1526
key={renderedPullRequestSurface.id}
1527
+ revealUrl={renderedPullRequestSurface.revealUrl}
1528
+ onRevealSettled={(revealUrl) => {
1529
+ if (rightPanelRef === null) return;
1530
+ useRightPanelStore
1531
+ .getState()
1532
+ .settlePullRequestReveal(rightPanelRef, renderedPullRequestSurface.id, revealUrl);
1533
+ }}
1534
environmentId={panelEnvironmentId}
1535
onGuideShown={onGuideShown}
1536
onSelectPullRequest={(reference) => {
apps/web/src/components/pullRequest/holdLinkedNodeInView.ts
new
+39
@@ -0,0 +1,39 @@
1
+import { observeResize } from "~/lib/observeResize";
2
+
3
+const USER_SCROLL_INTENT = ["wheel", "touchstart", "pointerdown", "keydown"] as const;
4
+
5
+/**
6
+ * Keeps a linked node `offset()` below the scroller's top while the content around it opens and
7
+ * its markdown loads, until the user scrolls, the node leaves, or the returned stop runs. Only the
8
+ * scroller moves; scrollIntoView would also scroll the panel's clipped ancestors.
9
+ */
10
+export function holdLinkedNodeInView(
11
+ node: HTMLElement,
12
+ scroller: HTMLElement,
13
+ offset: () => number,
14
+): () => void {
15
+ const controller = new AbortController();
16
+ const stop = () => {
17
+ unobserve();
18
+ controller.abort();
19
+ };
20
+ const align = () => {
21
+ if (!node.isConnected) return stop();
22
+ scroller.scrollTop +=
23
+ node.getBoundingClientRect().top - scroller.getBoundingClientRect().top - offset();
24
+ };
25
+ const unobserve = observeResize([...scroller.children], align);
26
+ for (const type of USER_SCROLL_INTENT) {
27
+ scroller.addEventListener(type, stop, { passive: true, signal: controller.signal });
28
+ }
29
+ align();
30
+ // Activity can load after the click; by then the user may be typing elsewhere.
31
+ const active = document.activeElement;
32
+ if (
33
+ !(active instanceof HTMLElement) ||
34
+ !(active.isContentEditable || active.matches("input, textarea, select"))
35
+ ) {
36
+ node.focus({ preventScroll: true });
37
+ }
38
+ return stop;
39
+}
apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts
+53
@@ -50,6 +50,7 @@ import {
50
shouldRefreshPullRequestActivity,
51
resolveBaseFreshness,
52
buildPullRequestTimeline,
53
+ pullRequestLinkSubject,
54
writePullRequestDetailSnapshot,
55
readableFailure,
56
} from "./pullRequestDetail.logic";
@@ -313,6 +314,58 @@ describe("review verdicts", () => {
314
});
315
316
describe("pull request timeline", () => {
317
+ it("names the comment or commit a link points at for its hover card", () => {
318
+ const pr = "https://github.com/o/r/pull/1";
319
+ const sha = "a".repeat(40);
320
+ const activity = {
321
+ comments: [
322
+ {
323
+ ...TIMELINE_SOURCE.comments[0]!,
324
+ url: `${pr}#issuecomment-5`,
325
+ body: "<!-- bot -->\n> [!NOTE]\n> **Looks** good, see `run()` ",
326
+ },
327
+ ],
328
+ reviewThreads: [
329
+ {
330
+ id: "t",
331
+ path: "a.ts",
332
+ line: 1,
333
+ side: "right" as const,
334
+ isResolved: false,
335
+ isOutdated: false,
336
+ comments: [
337
+ {
338
+ id: "r1",
339
+ author: { login: "reviewer", name: null, avatarUrl: null },
340
+ body: "nit",
341
+ createdAt: "2026-07-03T00:00:00Z",
342
+ url: `${pr}#discussion_r1`,
343
+ reviewUrl: `${pr}#pullrequestreview-9`,
344
+ },
345
+ ],
346
+ },
347
+ ],
348
+ commits: [{ oid: sha, messageHeadline: "fix it", committedDate: "2026-07-02T00:00:00Z" }],
349
+ };
350
+ expect(pullRequestLinkSubject(`${pr}#issuecomment-5`, activity)).toMatchObject({
351
+ kind: "comment",
352
+ excerpt: "Looks good, see run()",
353
+ });
354
+ // A review with no text of its own is shown through the comment it posted.
355
+ expect(pullRequestLinkSubject(`${pr}#pullrequestreview-9`, activity)).toMatchObject({
356
+ kind: "comment",
357
+ author: { login: "reviewer" },
358
+ excerpt: "nit",
359
+ });
360
+ expect(pullRequestLinkSubject(`${pr}/commits/${sha}`, activity)).toMatchObject({
361
+ kind: "commit",
362
+ commit: { messageHeadline: "fix it" },
363
+ });
364
+ for (const url of [pr, `${pr}/files`, `${pr}/checks`, `${pr}#issuecomment-6`]) {
365
+ expect(pullRequestLinkSubject(url, activity), url).toBeNull();
366
+ }
367
+ });
368
+
369
it("orders host timestamps by instant across offsets and fractional seconds", () => {
370
const events = buildPullRequestTimeline({
371
...TIMELINE_SOURCE,
apps/web/src/components/pullRequest/pullRequestDetail.logic.ts
+81
@@ -1,3 +1,9 @@
1
+import {
2
+ parsePullRequestAnchor,
3
+ pullRequestAnchorMatchesUrl,
4
+ pullRequestLinkCommit,
5
+ resolvePullRequestReviewAnchor,
6
+} from "@t3tools/shared/pullRequestAnchor";
7
import { stripInlineContextReferences } from "~/lib/composerContextReferences";
8
import type { Nodes as MdastNodes } from "mdast";
9
import { fromMarkdown } from "mdast-util-from-markdown";
@@ -17,6 +23,7 @@ import {
23
type PullRequestCheck,
24
type PullRequestChecksState as ContractPullRequestChecksState,
25
type PullRequestComment,
26
+ type PullRequestActivity,
27
type PullRequestCommit,
28
type PullRequestContextMetadata,
29
type PullRequestDetailView,
@@ -694,6 +701,80 @@ function readableBody(raw: string): string | null {
701
* Merged wins over closed: GitHub sets both timestamps on a merge, and reporting "closed" for a
702
* merged pull request would misstate what happened.
703
*/
704
+export type PullRequestLinkSubject =
705
+ | {
706
+ readonly kind: "comment";
707
+ readonly author: PullRequestActor | null;
708
+ readonly createdAt: string;
709
+ readonly reviewState: string | null;
710
+ readonly excerpt: string | null;
711
+ }
712
+ | { readonly kind: "commit"; readonly commit: PullRequestCommit };
713
+
714
+const LINK_EXCERPT_LENGTH = 280;
715
+
716
+/** The words of a markdown body, without markup, HTML or images, for a short preview. */
717
+function markdownExcerpt(body: string): string | null {
718
+ const words: string[] = [];
719
+ const visit = (node: MdastNodes) => {
720
+ if (node.type === "text" || node.type === "inlineCode") words.push(node.value);
721
+ if (node.type !== "code" && "children" in node) for (const child of node.children) visit(child);
722
+ };
723
+ visit(fromMarkdown(body));
724
+ // GitHub's alert marker (`> [!NOTE]`) parses as text but reads as markup.
725
+ const text = words
726
+ .join(" ")
727
+ .replace(/\[!(?:note|tip|important|warning|caution)\]/giu, "")
728
+ .replace(/\s+/gu, " ")
729
+ .trim();
730
+ if (text === "") return null;
731
+ return text.length > LINK_EXCERPT_LENGTH ? `${text.slice(0, LINK_EXCERPT_LENGTH - 1)}…` : text;
732
+}
733
+
734
+/** The comment or commit a pull request link names, for its hover card; null for the PR itself. */
735
+export function pullRequestLinkSubject(
736
+ url: string,
737
+ activity: Pick<PullRequestActivity, "comments" | "reviewThreads" | "commits">,
738
+): PullRequestLinkSubject | null {
739
+ const oid = pullRequestLinkCommit(url)?.toLowerCase();
740
+ if (oid !== undefined) {
741
+ const commit = activity.commits.find((candidate) => candidate.oid.toLowerCase() === oid);
742
+ return commit === undefined ? null : { kind: "commit", commit };
743
+ }
744
+ const location = parsePullRequestAnchor(url);
745
+ if (location?.kind !== "timeline") return null;
746
+ const anchor = resolvePullRequestReviewAnchor(
747
+ location.anchor,
748
+ activity.comments,
749
+ activity.reviewThreads,
750
+ );
751
+ const comment = activity.comments.find((candidate) =>
752
+ pullRequestAnchorMatchesUrl(anchor, candidate.url),
753
+ );
754
+ const threadComment = activity.reviewThreads
755
+ .flatMap((thread) => thread.comments)
756
+ .find((candidate) => pullRequestAnchorMatchesUrl(anchor, candidate.url));
757
+ const found = comment ?? threadComment;
758
+ if (found === undefined) return null;
759
+ return {
760
+ kind: "comment",
761
+ author: found.author,
762
+ createdAt: found.createdAt,
763
+ reviewState: comment?.reviewState ?? null,
764
+ excerpt: markdownExcerpt(found.body),
765
+ };
766
+}
767
+
768
+/** Whether a link anchor names this event or a reply in its review thread. */
769
+export function pullRequestTimelineEventMatches(
770
+ event: PullRequestTimelineEvent,
771
+ anchor: string,
772
+): boolean {
773
+ return [event, ...(event.thread?.replies ?? [])].some((item) =>
774
+ pullRequestAnchorMatchesUrl(anchor, item.url),
775
+ );
776
+}
777
+
778
export function buildPullRequestTimeline(
779
detail: Pick<
780
PullRequestDetailView,
apps/web/src/components/pullRequest/usePullRequestListView.ts
+12
@@ -40,6 +40,7 @@ import { pullRequestFilterProjects } from "@t3tools/client-runtime/pull-request-
40
import { pullRequestListEntryId } from "./pullRequestListGroups.logic";
41
42
export interface PullRequestsSearch extends PullRequestListPreferences {
43
+ readonly selectedUrl?: string;
44
readonly environmentId?: EnvironmentId;
45
readonly projectId?: ProjectId;
46
readonly host?: string;
@@ -139,6 +140,16 @@ export function usePullRequestScope(search: PullRequestsSearch) {
140
const assignmentKey = environmentQueries
141
.map(({ environmentId, projectIds }) => `${environmentId}#${projectIds?.join("+") ?? "*"}`)
142
.join("|");
143
+ // The URL is user-controlled and stands in for the PR link until detail loads.
144
+ const selectedLink = search.selectedUrl
145
+ ? sourceControlClients.parseChangeRequestUrl(search.selectedUrl)?.link
146
+ : undefined;
147
+ const selectedUrl =
148
+ selectedLink !== undefined &&
149
+ selectedLink.number === search.number &&
150
+ selectedLink.repository.toLowerCase() === search.repository?.toLowerCase()
151
+ ? search.selectedUrl
152
+ : undefined;
153
const linkedSelection =
154
search.repository && search.number && selectedProject
155
? {
@@ -146,6 +157,7 @@ export function usePullRequestScope(search: PullRequestsSearch) {
157
repository: search.repository,
158
number: search.number,
159
projectId: selectedProject.id,
160
+ ...(selectedUrl ? { url: selectedUrl, revealUrl: selectedUrl } : {}),
161
...(selectedHost ? { host: selectedHost } : {}),
162
}
163
: null;
apps/web/src/lib/openPullRequestLink.browser.test.tsx
+2
@@ -85,6 +85,8 @@ it.each([
85
["shiftKey", commitUrl],
86
["altKey", commitUrl],
87
["shiftKey", pullRequestCommitUrl],
88
+ ["shiftKey", `${pullRequestCommitUrl}#diff-abcR5`],
89
+ ["altKey", `${pullRequestCommitUrl}#diff-abcR5`],
90
] as const)("keeps %s clicks on %s native", async (modifier, url) => {
91
setup();
92
await using screen = await render(
apps/web/src/lib/openPullRequestLink.ts
+17
-1
@@ -1,3 +1,4 @@
1
+import { parsePullRequestAnchor } from "@t3tools/shared/pullRequestAnchor";
2
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
3
import { useAtomValue } from "@effect/atom-react";
4
import { useNavigate } from "@tanstack/react-router";
@@ -89,6 +90,7 @@ export function useOpenChangeRequestLink(
90
});
91
if (target === null) return false;
92
const { project, repository, number, host } = target;
93
+ const revealUrl = parsePullRequestAnchor(targetUrl) === null ? undefined : targetUrl;
94
const pullRequestsSearch = {
95
repository,
96
number,
@@ -106,6 +108,7 @@ export function useOpenChangeRequestLink(
108
...(host === undefined ? {} : { host }),
109
repository,
110
url: targetUrl,
111
+ ...(revealUrl === undefined ? {} : { revealUrl }),
112
number,
113
});
114
if (!resolvedThreadRef) {
@@ -124,7 +127,12 @@ export function useOpenChangeRequestLink(
127
}
128
void navigate({
129
to: "/pull-requests",
127
- search: { involvement: "all", state: "all", ...pullRequestsSearch },
130
+ search: {
131
+ involvement: "all",
132
+ state: "all",
133
+ ...pullRequestsSearch,
134
+ ...(revealUrl === undefined ? {} : { selectedUrl: revealUrl }),
135
+ },
136
});
137
return true;
138
};
@@ -140,6 +148,14 @@ export function useOpenChangeRequestLink(
148
const parsedCommit = sourceControlClients.parseCommitUrl(targetUrl, identity?.provider);
149
// Shift and Alt keep their browser meaning (new window, download) on commit links.
150
if (parsedCommit !== null && (event.shiftKey || event.altKey)) return false;
151
+ // A plain commit link stays a workspace commit; one naming a file or line opens the PR's diff.
152
+ const anchor = parsePullRequestAnchor(targetUrl);
153
+ if (anchor !== null && anchor.kind !== "code" && openPullRequest()) {
154
+ event.preventDefault();
155
+ event.stopPropagation();
156
+ return true;
157
+ }
158
+
159
if (
160
parsedCommit !== null &&
161
commitThread &&
apps/web/src/rightPanelStore.test.ts
+39
@@ -1009,6 +1009,45 @@ describe("rightPanelStore", () => {
1009
selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA),
1010
).toMatchObject({ url });
1011
expect(state.surfaces[1]).not.toHaveProperty("url");
1012
+ expect(state.surfaces[0]).not.toHaveProperty("revealUrl");
1013
+ });
1014
+
1015
+ it("holds a clicked link until the panel settles it, and a later link replaces it", async () => {
1016
+ const pr = { projectId: "project-a", repository: "pingdotgg/t3code", number: 4909 };
1017
+ const id = pullRequestSurfaceId(pr);
1018
+ const url = "https://github.com/pingdotgg/t3code/pull/4909";
1019
+ const surface = () =>
1020
+ selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA);
1021
+ const comment = (n: number) => `${url}#issuecomment-${n}`;
1022
+ const store = useRightPanelStore.getState();
1023
+ store.openPullRequest(refA, { ...pr, url: comment(1), revealUrl: comment(1) });
1024
+ expect(surface()).toMatchObject({ url: comment(1), revealUrl: comment(1) });
1025
+ store.openPullRequest(refA, { ...pr, url });
1026
+ expect(surface()).not.toHaveProperty("revealUrl");
1027
+ store.openPullRequest(refA, { ...pr, url: comment(2), revealUrl: comment(2) });
1028
+ // A host read started for an earlier link settles only that link.
1029
+ store.settlePullRequestReveal(refA, id, comment(1));
1030
+ expect(surface()).toMatchObject({ revealUrl: comment(2) });
1031
+ store.settlePullRequestReveal(refA, id, comment(2));
1032
+ expect(surface()).toMatchObject({ url: comment(2) });
1033
+ expect(surface()).not.toHaveProperty("revealUrl");
1034
+ // Reopening a closed tab hands back its surface, whose url still names the comment.
1035
+ store.openPullRequest(refA, { ...pr, url: comment(2) });
1036
+ expect(surface()).not.toHaveProperty("revealUrl");
1037
+ store.openPullRequest(refA, { ...pr, url: comment(3), revealUrl: comment(3) });
1038
+ await reloadRightPanelStore();
1039
+ expect(surface()).toMatchObject({ url: comment(3) });
1040
+ expect(surface()).not.toHaveProperty("revealUrl");
1041
+ store.openPullRequest(refA, { ...pr, url: comment(4), revealUrl: comment(4) });
1042
+ store.closeSurface(refA, id);
1043
+ await reopenClosedView(useClosedViewStore.getState().entries[0]!, {
1044
+ workspaceAvailable: true,
1045
+ openPreview: () => {
1046
+ throw new Error("A PR tab must not create a browser session");
1047
+ },
1048
+ });
1049
+ expect(surface()).toMatchObject({ url: comment(4) });
1050
+ expect(surface()).not.toHaveProperty("revealUrl");
1051
});
1052
1053
it("restores each environment, thread and PR surface's detail tab after reload and URL reopen", async () => {
apps/web/src/rightPanelStore.ts
+48
-13
@@ -73,6 +73,8 @@ export type RightPanelSurface =
73
repository: string;
74
number: number;
75
url?: string;
76
+ /** A clicked link waiting for the panel to show where it points; cleared once shown. */
77
+ revealUrl?: string;
78
detailTab?: PullRequestDetailTab;
79
}
80
| { id: "pull-requests"; kind: "pull-requests" }
@@ -148,6 +150,8 @@ interface RightPanelStoreState {
150
repository: string;
151
number: number;
152
url?: string;
153
+ /** A clicked link to reveal; reopening a surface passes only its `url`. */
154
+ revealUrl?: string;
155
detailTab?: PullRequestDetailTab;
156
},
157
) => void;
@@ -156,6 +160,8 @@ interface RightPanelStoreState {
160
surfaceId: string,
161
detailTab: PullRequestDetailTab,
162
) => void;
163
+ /** Clears the surface's pending link only while it is still `revealUrl`. */
164
+ settlePullRequestReveal: (ref: ScopedThreadRef, surfaceId: string, revealUrl: string) => void;
165
openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;
166
splitTerminal: (
167
ref: ScopedThreadRef,
@@ -293,6 +299,13 @@ export function pullRequestSurface(target: {
299
};
300
}
301
302
+/** A pending link belongs to the click that made it, not to a reload or a reopen. */
303
+const withoutReveal = (surface: RightPanelSurface): RightPanelSurface => {
304
+ if (surface.kind !== "pull-request" || surface.revealUrl === undefined) return surface;
305
+ const { revealUrl: _pending, ...rest } = surface;
306
+ return rest;
307
+};
308
+
309
const upsertSurface = (
310
current: ThreadRightPanelState,
311
surface: RightPanelSurface,
@@ -752,16 +765,17 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
765
userAction(state, scopedThreadKey(ref), (current) => {
766
const surface = pullRequestSurface(target);
767
const next = upsertSurface(current, surface);
755
- return target.url
756
- ? {
757
- ...next,
758
- surfaces: next.surfaces.map((entry) =>
759
- entry.id === surface.id && entry.kind === "pull-request"
760
- ? { ...entry, ...surface }
761
- : entry,
762
- ),
763
- }
764
- : next;
768
+ const { url, revealUrl } = target;
769
+ if (!url && !revealUrl) return next;
770
+ return {
771
+ ...next,
772
+ surfaces: next.surfaces.map((entry) => {
773
+ if (entry.id !== surface.id || entry.kind !== "pull-request") return entry;
774
+ // A later link replaces one not yet shown.
775
+ const { revealUrl: _previous, ...rest } = entry;
776
+ return { ...rest, ...surface, ...(revealUrl ? { revealUrl } : {}) };
777
+ }),
778
+ };
779
}),
780
),
781
setPullRequestDetailTab: (ref, surfaceId, detailTab) =>
@@ -781,6 +795,20 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
795
),
796
}));
797
}),
798
+ settlePullRequestReveal: (ref, surfaceId, revealUrl) =>
799
+ set((state) => {
800
+ const threadKey = scopedThreadKey(ref);
801
+ const existing = state.byThreadKey[threadKey]?.surfaces.find(
802
+ (surface) => surface.id === surfaceId,
803
+ );
804
+ if (existing?.kind !== "pull-request" || existing.revealUrl !== revealUrl) return state;
805
+ return automaticUpdate(state, threadKey, (current) => ({
806
+ ...current,
807
+ surfaces: current.surfaces.map((surface) =>
808
+ surface.id === surfaceId ? withoutReveal(surface) : surface,
809
+ ),
810
+ }));
811
+ }),
812
openFile: (ref, requestedPath, line) =>
813
set((state) =>
814
userAction(state, scopedThreadKey(ref), (current) => {
@@ -1164,8 +1192,15 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
1192
),
1193
partialize: (state) => ({
1194
byThreadKey: Object.fromEntries(
1167
- Object.entries(state.byThreadKey).filter(
1168
- ([threadKey]) => !isPullRequestsPanelKey(threadKey),
1195
+ Object.entries(state.byThreadKey).flatMap(([threadKey, threadState]) =>
1196
+ isPullRequestsPanelKey(threadKey)
1197
+ ? []
1198
+ : [
1199
+ [
1200
+ threadKey,
1201
+ { ...threadState, surfaces: threadState.surfaces.map(withoutReveal) },
1202
+ ],
1203
+ ],
1204
),
1205
),
1206
threadPanelVisibilityByThreadKey: Object.fromEntries(
@@ -1195,7 +1230,7 @@ useRightPanelStore.subscribe((next, previous) => {
1230
...removed.filter((surface) => surface.id !== before.activeSurfaceId),
1231
...removed.filter((surface) => surface.id === before.activeSurfaceId),
1232
];
1198
- for (const surface of closedInOrder) {
1233
+ for (const surface of closedInOrder.map(withoutReveal)) {
1234
if (
1235
surface.kind === "terminal" ||
1236
(surface.kind === "preview" && surface.resourceId !== null)
apps/web/src/routes/_chat.pull-requests.tsx
+1
@@ -29,6 +29,7 @@ function pullRequestSearchLabels(raw: unknown): Partial<Pick<PullRequestsSearch,
29
30
export const Route = createFileRoute("/_chat/pull-requests")({
31
validateSearch: (raw: Record<string, unknown>): PullRequestsSearch => ({
32
+ ...(typeof raw.selectedUrl === "string" ? { selectedUrl: raw.selectedUrl.slice(0, 4096) } : {}),
33
involvement:
34
raw.involvement === "reviewing" || raw.involvement === "authored" ? raw.involvement : "all",
35
state:
docs/user/source-control.md
+4
@@ -194,6 +194,10 @@ Where you can edit a description, you can also tick its checkboxes from the Summ
194
(the Overview tab on mobile).
195
GitLab calls these merge requests.
196
197
+A link to part of a pull request opens that part: a comment or review is marked in the activity, a
198
+changed-line link opens the file at those lines, a checks link opens the checks, and a commit link
199
+opens that commit's changes. On web and desktop, hovering a comment or commit link previews it.
200
+
201
On mobile, **Pull requests** lists reviews across your connected environments. Open a review
202
to read its description, activity, commits, and changed files. Line comments stay as drafts
203
until you submit the review. **Work on PR** opens a chat with the review attached; sending
packages/contracts/src/pullRequest.ts
+2
@@ -173,6 +173,8 @@ export const PullRequestThreadComment = Schema.Struct({
173
createdAt: IsoDateTime,
174
editedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
175
url: Schema.NullOr(Schema.String),
176
+ /** The review that posted the comment, so a link to a review with no text finds its comments. */
177
+ reviewUrl: Schema.optional(Schema.NullOr(Schema.String)),
178
reactions: Schema.optional(Schema.Array(PullRequestReaction)),
179
canEdit: Schema.optional(Schema.Boolean),
180
});
packages/shared/package.json
+4
@@ -3,6 +3,10 @@
3
"private": true,
4
"type": "module",
5
"exports": {
6
+ "./pullRequestAnchor": {
7
+ "types": "./src/pullRequestAnchor.ts",
8
+ "import": "./src/pullRequestAnchor.ts"
9
+ },
10
"./changedFileKind": {
11
"types": "./src/changedFileKind.ts",
12
"import": "./src/changedFileKind.ts"
packages/shared/src/pullRequestAnchor.test.ts
new
+135
@@ -0,0 +1,135 @@
1
+import { expect, it } from "vite-plus/test";
2
+import {
3
+ parsePullRequestAnchor,
4
+ pullRequestAnchorMatchesUrl,
5
+ pullRequestDiffPathMatches,
6
+ pullRequestLinkCommit,
7
+ resolvePullRequestReviewAnchor,
8
+} from "./pullRequestAnchor.ts";
9
+
10
+const url = "https://github.com/owner/repo/pull/7";
11
+it.each(["discussion_r123", "r123", "discussion-diff-123R5-L9", "discussion-diff-123"])(
12
+ "resolves review comment alias %s",
13
+ (hash) => {
14
+ expect(parsePullRequestAnchor(`${url}#${hash}`)).toEqual({
15
+ kind: "timeline",
16
+ anchor: "discussion_r123",
17
+ });
18
+ expect(pullRequestAnchorMatchesUrl("discussion_r123", `${url}#${hash}`)).toBe(true);
19
+ },
20
+);
21
+it.each([
22
+ "pullrequestreview-123",
23
+ "issuecomment-123",
24
+ "commitcomment-123",
25
+ "event-123",
26
+ "note_123",
27
+ "comment-123",
28
+])("preserves timeline anchor %s", (anchor) => {
29
+ expect(parsePullRequestAnchor(`${url}#${anchor}`)).toEqual({ kind: "timeline", anchor });
30
+});
31
+it.each(["a".repeat(32), "b".repeat(64)])(
32
+ "reads file and cross-side line ranges for %s",
33
+ (digest) => {
34
+ expect(parsePullRequestAnchor(`${url}/files#diff-${digest}`)).toEqual({
35
+ kind: "diff",
36
+ digest,
37
+ range: null,
38
+ });
39
+ expect(parsePullRequestAnchor(`${url}/changes#diff-${digest}L12-R15`)).toEqual({
40
+ kind: "diff",
41
+ digest,
42
+ range: { start: 12, side: "left", end: 15, endSide: "right" },
43
+ });
44
+ expect(parsePullRequestAnchor(`${url}#diff-${digest}R42`)).toEqual({
45
+ kind: "diff",
46
+ digest,
47
+ range: { start: 42, side: "right", end: 42, endSide: "right" },
48
+ });
49
+ },
50
+);
51
+it.each([
52
+ [
53
+ "src/hello world.ts",
54
+ "bcea8deb9d67b305e28c4a0b0d021615",
55
+ "066802cf2cf056706e4e4951cb7dff2717a2ae32fd9797c1f1b41062d57db929",
56
+ ],
57
+ [
58
+ "src/日本語.ts",
59
+ "5c66d5d565666e46924cf80d7bbfdab3",
60
+ "191b8ebf2241225db999eaf8b6ff44b07934d577f347d0ff684591eecad34944",
61
+ ],
62
+ [
63
+ "old/path.ts",
64
+ "f5d455478d496859b654884654393a61",
65
+ "aa38d67014e2c59d51ea456a155e039f4e32f636a4c450714c3b517bb8bde7e7",
66
+ ],
67
+])("matches GitHub path digests for %s", (path, legacy, current) => {
68
+ for (const digest of [legacy, current]) {
69
+ expect(pullRequestDiffPathMatches(digest, path)).toBe(true);
70
+ expect(pullRequestDiffPathMatches(digest, "other.ts")).toBe(false);
71
+ }
72
+});
73
+it("handles encoded hashes and rejects invalid line numbers and URLs", () => {
74
+ expect(parsePullRequestAnchor(`${url}#%64iscussion_r123`)).toEqual({
75
+ kind: "timeline",
76
+ anchor: "discussion_r123",
77
+ });
78
+ expect(parsePullRequestAnchor(`${url}#diff-abcR0`)).toBeNull();
79
+ expect(parsePullRequestAnchor(`${url}#diff-abcR9999999999999999999`)).toBeNull();
80
+ expect(parsePullRequestAnchor("invalid")).toBeNull();
81
+ expect(parsePullRequestAnchor(url)).toBeNull();
82
+ expect(parsePullRequestAnchor(`${url}#unknown`)).toEqual({ kind: "summary", anchor: "unknown" });
83
+ expect(parsePullRequestAnchor(`${url}/files-not-a-tab`)).toBeNull();
84
+ expect(parsePullRequestAnchor(`${url}/commits/main`)).toBeNull();
85
+ expect(parsePullRequestAnchor(`${url}/checks/extra`)).toBeNull();
86
+});
87
+
88
+it("keeps the commit scope of a PR diff permalink", () => {
89
+ const sha = "a".repeat(40);
90
+ expect(pullRequestLinkCommit(`${url}/commits/${sha}#diff-abcR5`)).toBe(sha);
91
+ expect(pullRequestLinkCommit(`${url}/files#diff-abcR5`)).toBeNull();
92
+});
93
+
94
+const gitlab = "https://gitlab.com/group/repo/-/merge_requests/7";
95
+it.each([
96
+ [`${url}/files`, "code"],
97
+ [`${url}/files/`, "code"],
98
+ [`${url}/changes`, "code"],
99
+ [`${url}/commits/${"a".repeat(40)}`, "code"],
100
+ [`${url}/commits`, "commits"],
101
+ [`${url}/checks?check_run_id=1`, "checks"],
102
+ [`${gitlab}/diffs`, "code"],
103
+ [`${gitlab}/commits`, "commits"],
104
+ [`${gitlab}/pipelines`, "checks"],
105
+] as const)("keeps unknown and missing hashes in the tab %s names", (path, kind) => {
106
+ for (const hash of ["", "#unknown", "#diff-abcR0", "#diff-abcR9999999999999999999", "#%ZZ"]) {
107
+ expect(parsePullRequestAnchor(`${path}${hash}`)).toEqual({ kind });
108
+ }
109
+ expect(parsePullRequestAnchor(`${path}#issuecomment-123`)).toEqual({
110
+ kind: "timeline",
111
+ anchor: "issuecomment-123",
112
+ });
113
+});
114
+
115
+it("finds a review with no text of its own through the earliest comment it posted", () => {
116
+ const review = `${url}#pullrequestreview-9`;
117
+ const threads = [
118
+ {
119
+ comments: [
120
+ { url: `${url}#discussion_r3`, createdAt: "2026-07-01T00:02:00Z", reviewUrl: review },
121
+ { url: `${url}#discussion_r2`, createdAt: "2026-07-01T00:01:00Z", reviewUrl: review },
122
+ { url: `${url}#discussion_r1`, createdAt: "2026-07-01T00:00:00Z" },
123
+ ],
124
+ },
125
+ ];
126
+ expect(resolvePullRequestReviewAnchor("pullrequestreview-9", [], threads)).toBe("discussion_r2");
127
+ // A review shown in its own right, an unknown review and other anchors are kept.
128
+ expect(resolvePullRequestReviewAnchor("pullrequestreview-9", [{ url: review }], threads)).toBe(
129
+ "pullrequestreview-9",
130
+ );
131
+ expect(resolvePullRequestReviewAnchor("pullrequestreview-8", [], threads)).toBe(
132
+ "pullrequestreview-8",
133
+ );
134
+ expect(resolvePullRequestReviewAnchor("issuecomment-9", [], threads)).toBe("issuecomment-9");
135
+});
packages/shared/src/pullRequestAnchor.ts
new
+149
@@ -0,0 +1,149 @@
1
+import { md5 } from "@noble/hashes/legacy";
2
+import { sha256 } from "@noble/hashes/sha2";
3
+import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils";
4
+
5
+export interface PullRequestAnchorRange {
6
+ readonly start: number;
7
+ readonly side: "left" | "right";
8
+ readonly end: number;
9
+ readonly endSide: "left" | "right";
10
+}
11
+
12
+export type PullRequestAnchor =
13
+ | { readonly kind: "code" }
14
+ | { readonly kind: "commits" }
15
+ | { readonly kind: "checks" }
16
+ | {
17
+ readonly kind: "diff";
18
+ readonly digest: string;
19
+ readonly range: PullRequestAnchorRange | null;
20
+ }
21
+ | { readonly kind: "timeline"; readonly anchor: string }
22
+ | { readonly kind: "summary"; readonly anchor: string };
23
+
24
+function pullRequestUrlHash(url: string | null | undefined): string {
25
+ if (!url) return "";
26
+ try {
27
+ return decodeURIComponent(new URL(url).hash.slice(1));
28
+ } catch {
29
+ return "";
30
+ }
31
+}
32
+
33
+function normalizePullRequestCommentAnchor(anchor: string): string {
34
+ return anchor.replace(
35
+ /^(?:r|discussion-diff-)(\d+)(?:[LR]\d+(?:-[LR]\d+)?)?$/i,
36
+ "discussion_r$1",
37
+ );
38
+}
39
+
40
+// GitHub pull request tabs and their GitLab merge request equivalents.
41
+function pullRequestPathTab(pathname: string): PullRequestAnchor | null {
42
+ const tab = /\/(?:pull|-\/merge_requests)\/\d+\/([a-z]+)(?:\/(.*))?$/i.exec(pathname);
43
+ const rest = tab?.[2] ?? "";
44
+ switch (tab?.[1]?.toLowerCase()) {
45
+ case "files":
46
+ case "changes":
47
+ case "diffs":
48
+ return { kind: "code" };
49
+ case "commits":
50
+ if (rest === "") return { kind: "commits" };
51
+ return /^[a-f0-9]{40}\/?$/i.test(rest) ? { kind: "code" } : null;
52
+ case "checks":
53
+ case "pipelines":
54
+ return rest === "" ? { kind: "checks" } : null;
55
+ default:
56
+ return null;
57
+ }
58
+}
59
+
60
+export function parsePullRequestAnchor(url: string | null | undefined): PullRequestAnchor | null {
61
+ let parsed: URL;
62
+ try {
63
+ parsed = new URL(url ?? "");
64
+ } catch {
65
+ return null;
66
+ }
67
+ const fallback = pullRequestPathTab(parsed.pathname);
68
+ const anchor = pullRequestUrlHash(url);
69
+ if (!anchor) return fallback;
70
+ // GitHub line ranges may cross diff sides; file digests were MD5 before SHA-256.
71
+ const diff = /^diff-([a-f0-9]+)(?:([LR])(\d+)(?:-([LR])(\d+))?)?$/i.exec(anchor);
72
+ if (diff) {
73
+ const start = Number(diff[3]);
74
+ const end = Number(diff[5] ?? diff[3]);
75
+ if (
76
+ diff[2] &&
77
+ (!Number.isSafeInteger(start) || start < 1 || !Number.isSafeInteger(end) || end < 1)
78
+ )
79
+ return fallback;
80
+ return {
81
+ kind: "diff",
82
+ digest: (diff[1] ?? "").toLowerCase(),
83
+ range: diff[2]
84
+ ? {
85
+ start,
86
+ side: diff[2].toUpperCase() === "L" ? "left" : "right",
87
+ end,
88
+ endSide: (diff[4] ?? diff[2]).toUpperCase() === "L" ? "left" : "right",
89
+ }
90
+ : null,
91
+ };
92
+ }
93
+ if (
94
+ /^(?:(?:issuecomment-|pullrequestreview-|discussion_r|r|commitcomment-|event-|note_|comment-)\d+|discussion-diff-\d+(?:[LR]\d+(?:-[LR]\d+)?)?)$/i.test(
95
+ anchor,
96
+ )
97
+ ) {
98
+ return { kind: "timeline", anchor: normalizePullRequestCommentAnchor(anchor) };
99
+ }
100
+ return fallback ?? { kind: "summary", anchor };
101
+}
102
+
103
+export function pullRequestAnchorMatchesUrl(
104
+ anchor: string,
105
+ url: string | null | undefined,
106
+): boolean {
107
+ return normalizePullRequestCommentAnchor(pullRequestUrlHash(url)) === anchor;
108
+}
109
+
110
+interface AnchoredComment {
111
+ readonly url: string | null;
112
+ readonly createdAt: string;
113
+ readonly reviewUrl?: string | null | undefined;
114
+}
115
+
116
+/**
117
+ * A review with no text of its own appears only through the line comments it posted, so its link
118
+ * resolves to the earliest of those. Any other anchor, or a review shown in its own right, is kept.
119
+ */
120
+export function resolvePullRequestReviewAnchor(
121
+ anchor: string,
122
+ comments: ReadonlyArray<Pick<AnchoredComment, "url">>,
123
+ reviewThreads: ReadonlyArray<{ readonly comments: ReadonlyArray<AnchoredComment> }>,
124
+): string {
125
+ if (!/^pullrequestreview-\d+$/i.test(anchor)) return anchor;
126
+ if (comments.some((comment) => pullRequestAnchorMatchesUrl(anchor, comment.url))) return anchor;
127
+ // The earliest comment the review posted; `toSorted` is missing from Hermes.
128
+ let posted: AnchoredComment | undefined;
129
+ for (const comment of reviewThreads.flatMap((thread) => thread.comments)) {
130
+ if (comment.url === null || !pullRequestAnchorMatchesUrl(anchor, comment.reviewUrl)) continue;
131
+ if (posted === undefined || comment.createdAt < posted.createdAt) posted = comment;
132
+ }
133
+ const own = posted ? normalizePullRequestCommentAnchor(pullRequestUrlHash(posted.url)) : "";
134
+ return own || anchor;
135
+}
136
+
137
+export function pullRequestDiffPathMatches(digest: string, path: string): boolean {
138
+ const bytes = utf8ToBytes(path);
139
+ return digest === bytesToHex(digest.length === 32 ? md5(bytes) : sha256(bytes));
140
+}
141
+
142
+export function pullRequestLinkCommit(url: string | null | undefined): string | null {
143
+ if (!url) return null;
144
+ try {
145
+ return /\/pull\/\d+\/commits\/([a-f0-9]{40})\/?$/i.exec(new URL(url).pathname)?.[1] ?? null;
146
+ } catch {
147
+ return null;
148
+ }
149
+}
packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
+1
@@ -351,6 +351,7 @@ function threadComments(
351
lastEditedAt: null,
352
url: `https://github.com/acme/web/pull/7#discussion_${id}`,
353
isMinimized: false,
354
+ pullRequestReview: null,
355
reactionGroups: [],
356
})),
357
};
packages/source-control-github/src/server/gitHubPullRequestJson.test.ts
+14
-1
@@ -110,6 +110,7 @@ const remark = ({ author, reactionGroups: groups, ...raw }: Json) => ({
110
lastEditedAt: null,
111
isMinimized: false,
112
url: "https://github.com/acme/web/pull/1#discussion",
113
+ pullRequestReview: null,
114
...raw,
115
author: actor(author),
116
reactionGroups: reactionGroups(groups),
@@ -893,7 +894,14 @@ describe("review thread decoding", () => {
894
comments: {
895
nodes: [
896
{ id: "t1", body: "fix this", createdAt: "2026-07-01T00:00:00Z" },
896
- { id: "t2", body: "fixed", createdAt: "2026-07-01T01:00:00Z" },
897
+ {
898
+ id: "t2",
899
+ body: "fixed",
900
+ createdAt: "2026-07-01T01:00:00Z",
901
+ pullRequestReview: {
902
+ url: "https://github.com/acme/web/pull/1#pullrequestreview-9",
903
+ },
904
+ },
905
],
906
},
907
},
@@ -902,6 +910,11 @@ describe("review thread decoding", () => {
910
);
911
const comments = reviewThreadConversation(result.threads.map((entry) => entry.thread));
912
expect(comments.map((comment) => comment.id)).toEqual(["t1", "t2"]);
913
+ // A reply-only review has no text of its own; its link finds it through the reply it posted.
914
+ expect(result.threads[0]?.thread.comments.map((comment) => comment.reviewUrl)).toEqual([
915
+ undefined,
916
+ "https://github.com/acme/web/pull/1#pullrequestreview-9",
917
+ ]);
918
});
919
920
it("leaves out hidden thread comments, and a thread with none left", () => {
packages/source-control-github/src/server/gitHubPullRequestJson.ts
+2
@@ -1314,6 +1314,7 @@ export function toReviewDismissalsPage(result: ReviewDismissals.Result): {
1314
}
1315
1316
function toThreadComment(comment: ThreadComment, viewer: string | null): PullRequestThreadComment {
1317
+ const reviewUrl = trimmed(comment.pullRequestReview?.url);
1318
return {
1319
id: comment.id,
1320
author: toActor(comment.author),
@@ -1321,6 +1322,7 @@ function toThreadComment(comment: ThreadComment, viewer: string | null): PullReq
1322
createdAt: comment.createdAt,
1323
editedAt: comment.lastEditedAt,
1324
url: trimmed(comment.url),
1325
+ ...(reviewUrl === null ? {} : { reviewUrl }),
1326
reactions: toReactions(comment.reactionGroups, viewer),
1327
};
1328
}
packages/source-control-github/src/server/pullRequestReviews.graphql
+4
@@ -38,6 +38,10 @@ fragment ThreadComment on PullRequestReviewComment {
38
lastEditedAt
39
url
40
isMinimized
41
+ # A review link names the review, not its comments; this lets it find the comments it posted.
42
+ pullRequestReview {
43
+ url
44
+ }
45
...Reactions
46
}
47
packages/source-control-github/src/server/pullRequestReviews.graphql.ts
+12
-3
@@ -89,6 +89,13 @@ export const Actor = Schema.Struct({
89
})
90
export interface Actor extends Schema.Struct.Type<typeof Actor.fields> {}
91
92
+/** A review object for a given pull request. */
93
+export const PullRequestReviewPullRequestReview = Schema.Struct({
94
+ /** The HTTP URL permalink for this PullRequestReview. */
95
+ url: Shared.URI
96
+})
97
+export interface PullRequestReviewPullRequestReview extends Schema.Struct.Type<typeof PullRequestReviewPullRequestReview.fields> {}
98
+
99
/**
100
* `fragment ThreadComment on PullRequestReviewComment`
101
*
@@ -109,6 +116,8 @@ export const ThreadComment = Schema.Struct({
116
url: Shared.URI,
117
/** Returns whether or not a comment has been minimized. */
118
isMinimized: Schema.Boolean,
119
+ /** The pull request review associated with this review comment. */
120
+ pullRequestReview: Schema.NullOr(PullRequestReviewPullRequestReview),
121
/** A list of reactions grouped by content left on the subject. */
122
reactionGroups: Schema.NullOr(Schema.Array(ReactionGroup))
123
})
@@ -425,7 +434,7 @@ export const ReviewThreads = GraphQL.query("ReviewThreads", {
434
fragments: [
435
{ name: "ReviewThreadPage", body: ["on PullRequestReviewThreadConnection{totalCount pageInfo{hasNextPage endCursor}nodes{id isResolved isOutdated path line diffSide comments(first:10){totalCount pageInfo{hasNextPage endCursor}nodes{...ThreadComment}}}}"] },
436
{ name: "Reactions", body: ["on Reactable{__typename reactionGroups{content viewerHasReacted reactors(first:10){totalCount nodes{__typename...on User{login}...on Bot{login}...on Organization{login}...on Mannequin{login}}}}}"] },
428
- { name: "ThreadComment", body: ["on PullRequestReviewComment{id author{__typename login avatarUrl}body createdAt lastEditedAt url isMinimized...Reactions}"] }
437
+ { name: "ThreadComment", body: ["on PullRequestReviewComment{id author{__typename login avatarUrl}body createdAt lastEditedAt url isMinimized pullRequestReview{url}...Reactions}"] }
438
]
439
},
440
variables: {
@@ -475,7 +484,7 @@ export const ReviewThreadPages = GraphQL.query("ReviewThreadPages", {
484
],
485
fragments: [
486
{ name: "ReviewThreadPage", body: ["on PullRequestReviewThreadConnection{totalCount pageInfo{hasNextPage endCursor}nodes{id isResolved isOutdated path line diffSide comments(first:10){totalCount pageInfo{hasNextPage endCursor}nodes{...ThreadComment}}}}"] },
478
- { name: "ThreadComment", body: ["on PullRequestReviewComment{id author{__typename login avatarUrl}body createdAt lastEditedAt url isMinimized...Reactions}"] },
487
+ { name: "ThreadComment", body: ["on PullRequestReviewComment{id author{__typename login avatarUrl}body createdAt lastEditedAt url isMinimized pullRequestReview{url}...Reactions}"] },
488
{ name: "Reactions", body: ["on Reactable{__typename reactionGroups{content viewerHasReacted reactors(first:10){totalCount nodes{__typename...on User{login}...on Bot{login}...on Organization{login}...on Mannequin{login}}}}}"] }
489
]
490
},
@@ -552,7 +561,7 @@ export const ReviewThreadComments = GraphQL.query("ReviewThreadComments", {
561
{ name: "node", body: ["(id:$", "threadId", "){__typename...on PullRequestReviewThread{pullRequest{id}comments(first:100 after:$", "after", "){pageInfo{hasNextPage endCursor}nodes{...ThreadComment}}}}"] }
562
],
563
fragments: [
555
- { name: "ThreadComment", body: ["on PullRequestReviewComment{id author{__typename login avatarUrl}body createdAt lastEditedAt url isMinimized...Reactions}"] },
564
+ { name: "ThreadComment", body: ["on PullRequestReviewComment{id author{__typename login avatarUrl}body createdAt lastEditedAt url isMinimized pullRequestReview{url}...Reactions}"] },
565
{ name: "Reactions", body: ["on Reactable{__typename reactionGroups{content viewerHasReacted reactors(first:10){totalCount nodes{__typename...on User{login}...on Bot{login}...on Organization{login}...on Mannequin{login}}}}}"] }
566
]
567
},