Skip to content

Commit 0c78cc4

Browse files
fix(web): citations open at mount survive StrictMode effect replay
Retire a replaced citation activation when it is replaced, not in an effect cleanup that StrictMode replays on mount. Escape and pointerdown dismiss a pending citation before the viewport mounts, and the fold lookup stops once the cited entry is found. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 8db5133 commit 0c78cc4

3 files changed

Lines changed: 92 additions & 54 deletions

File tree

‎apps/web/src/components/chat/MessagesTimeline.browser.test.tsx‎

Lines changed: 43 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { onTestFinished } from "vite-plus/test";
33
import { stubGlobal } from "../../../test/render";
44
import { EnvironmentId, MessageId, RunId, ScheduledTaskId, ThreadId } from "@t3tools/contracts";
55
import type { LegendListRef } from "@legendapp/list/react";
6-
import { createRef, Profiler, type ComponentProps, type ReactElement } from "react";
6+
import { createRef, Profiler, StrictMode, type ComponentProps, type ReactElement } from "react";
77
import { describe, expect, it, vi } from "vite-plus/test";
88

99
import "~/index.css";
@@ -110,10 +110,10 @@ function message(
110110
};
111111
}
112112

113-
async function renderElement(element: ReactElement) {
113+
async function renderElement(element: ReactElement, options: { router?: false } = {}) {
114114
const container = document.createElement("div");
115115
container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
116-
const screen = await render(element, { container });
116+
const screen = await render(element, { container, ...options });
117117
const buttons = (name: string | RegExp) =>
118118
[...container.querySelectorAll<HTMLElement>("button, [role=button]")].filter((button) => {
119119
const label = button.getAttribute("aria-label") ?? button.textContent ?? "";
@@ -239,24 +239,50 @@ describe("MessagesTimeline messages", () => {
239239
});
240240
});
241241

242+
const CITATION_REQUEST = {
243+
key: "activation-1",
244+
citation: {
245+
version: 1,
246+
environmentId: ENVIRONMENT_ID,
247+
threadId: ThreadId.make("thread-cited"),
248+
messageId: MessageId.make("cited"),
249+
text: "the cited answer",
250+
start: 0,
251+
end: 16,
252+
prefix: "",
253+
suffix: "",
254+
},
255+
} satisfies NonNullable<TimelineProps["citationRequest"]>;
256+
242257
describe("MessagesTimeline citations", () => {
258+
it("lands a citation present at mount under StrictMode", async () => {
259+
await using _screen = await renderElement(
260+
<StrictMode>
261+
<MessagesTimeline
262+
{...baseProps()}
263+
timelineEntries={[
264+
message("A question", {}, "question"),
265+
message("the cited answer", { role: "assistant" }, "cited"),
266+
]}
267+
citationRequest={CITATION_REQUEST}
268+
citationHistory={{ _tag: "found" }}
269+
/>
270+
</StrictMode>,
271+
// The test router mounts route content without StrictMode's effect replay.
272+
{ router: false },
273+
);
274+
// StrictMode replays effect cleanups on mount; the activation must survive them.
275+
await vi.waitFor(() =>
276+
expect(document.querySelector("[data-citation-highlighted]")?.textContent).toContain(
277+
"the cited answer",
278+
),
279+
);
280+
});
281+
243282
it("waits for cited history to load before giving up on a response outside the window", async () => {
244283
using toast = vi.spyOn(toastManager, "add");
245284
const props = baseProps();
246-
const citationRequest = {
247-
key: "activation-1",
248-
citation: {
249-
version: 1,
250-
environmentId: ENVIRONMENT_ID,
251-
threadId: ThreadId.make("thread-cited"),
252-
messageId: MessageId.make("cited"),
253-
text: "the cited answer",
254-
start: 0,
255-
end: 16,
256-
prefix: "",
257-
suffix: "",
258-
},
259-
} satisfies NonNullable<TimelineProps["citationRequest"]>;
285+
const citationRequest = CITATION_REQUEST;
260286
const recent = message("A recent question", {}, "recent");
261287
const timeline = (entries: Entry[], citationHistory: CitedHistory) => (
262288
<MessagesTimeline

‎apps/web/src/components/chat/MessagesTimeline.tsx‎

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -574,37 +574,41 @@ const ConversationTimeline = memo(function ConversationTimeline({
574574
}
575575
}
576576
// A cited response folded inside a turn opens its fold once per activation;
577-
// the user can fold it again afterwards. Only a citation that can still land
578-
// (an assistant message, history not failed) opens anything.
577+
// the user can fold it again. Only a citation that can still land opens one.
578+
// The marker stops the O(entries) fold lookup once the entry is found, since
579+
// the href stays in the URL after the citation settles.
580+
const [citationExpandedFor, setCitationExpandedFor] = useState<string | null>(null);
581+
// Back/Forward can restore an earlier activation key, so the marker clears
582+
// between activations and a revisit opens the fold again.
583+
if (!citationRequest && citationExpandedFor !== null) setCitationExpandedFor(null);
579584
const citedEntry =
580-
citationRequest && citationHistory._tag !== "failed"
585+
citationRequest &&
586+
citationExpandedFor !== citationRequest.key &&
587+
citationHistory._tag !== "failed"
581588
? timelineEntries.find(
582589
(entry) =>
583590
entry.kind === "message" &&
584591
entry.message.role === "assistant" &&
585592
entry.message.id === citationRequest.citation.messageId,
586593
)
587594
: undefined;
588-
const citationFoldRunIds = citedEntry
589-
? (findFoldRunIds ??
595+
if (citationRequest && citedEntry) {
596+
const citedRunId = (
597+
findFoldRunIds ??
590598
timelineTurnFoldRunIdsByEntryId({
591599
timelineEntries,
592600
latestRun,
593601
runningRunId,
594602
isWorking,
595603
runlessWorkActive,
596-
}))
597-
: null;
598-
const citedRunId = citedEntry ? citationFoldRunIds?.get(citedEntry.id) : undefined;
599-
// Back/Forward can restore an earlier activation key, so the marker clears
600-
// between activations and a revisit opens the fold again.
601-
const [citationExpandedFor, setCitationExpandedFor] = useState<string | null>(null);
602-
if (!citationRequest && citationExpandedFor !== null) setCitationExpandedFor(null);
603-
if (citedRunId && citationRequest && citationExpandedFor !== citationRequest.key) {
604+
})
605+
).get(citedEntry.id);
604606
setCitationExpandedFor(citationRequest.key);
605-
setExpandedRunIds((previous) =>
606-
previous.has(citedRunId) ? previous : new Set(previous).add(citedRunId),
607-
);
607+
if (citedRunId) {
608+
setExpandedRunIds((previous) =>
609+
previous.has(citedRunId) ? previous : new Set(previous).add(citedRunId),
610+
);
611+
}
608612
}
609613
const visibleExpandedRunIds =
610614
!activeFindRunId || paintedExpandedRunIds.has(activeFindRunId)

‎apps/web/src/components/chat/useAssistantCitationTarget.ts‎

Lines changed: 29 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect, useState } from "react";
1+
import { useEffect, useRef, useState } from "react";
22
import type { AssistantCitationRequest, AssistantCitationTarget } from "./AssistantCitationSource";
33
import type { CitationPhase } from "./citationProcedure";
44

@@ -15,10 +15,12 @@ const CITATION_SCROLL_KEYS = new Set([
1515
/** One activation of a citation; virtual row remounts and listeners share it. */
1616
interface CitationNavigation {
1717
readonly target: AssistantCitationTarget;
18-
/** Takes over from the live follow for this activation; the cleanup retires it. */
19-
readonly activate: () => () => void;
18+
/** Takes over from the live follow for this activation. */
19+
readonly activate: () => void;
20+
/** Stops this activation for good once another one (or none) replaces it. */
21+
readonly retire: () => void;
2022
/** Listens for user navigation that stops this activation's pending scroll. */
21-
readonly attachDismissal: (viewport: HTMLElement) => () => void;
23+
readonly attachDismissal: (viewport: HTMLElement | null) => () => void;
2224
}
2325

2426
interface CitationSettlement {
@@ -70,12 +72,12 @@ export function useAssistantCitationTarget({
7072
const activate = () => {
7173
// The follow must yield before the citation row starts scrolling.
7274
if (!done) onManualNavigation();
73-
return () => {
74-
activationRef.current.dismissed = true;
75-
activationRef.current.cancelScroll?.();
76-
};
7775
};
78-
const attachDismissal = (citationViewport: HTMLElement) => {
76+
const retire = () => {
77+
activationRef.current.dismissed = true;
78+
activationRef.current.cancelScroll?.();
79+
};
80+
const attachDismissal = (citationViewport: HTMLElement | null) => {
7981
// User navigation stops a pending citation scroll; Escape dismisses it outright.
8082
const dismiss = (onlyPending: boolean) => {
8183
const activation = activationRef.current;
@@ -92,7 +94,7 @@ export function useAssistantCitationTarget({
9294
} else if (
9395
CITATION_SCROLL_KEYS.has(event.key) &&
9496
event.target instanceof Node &&
95-
citationViewport.contains(event.target)
97+
citationViewport?.contains(event.target)
9698
) {
9799
dismiss(true);
98100
}
@@ -103,25 +105,31 @@ export function useAssistantCitationTarget({
103105
const onNavigation = () => dismiss(true);
104106
document.addEventListener("keydown", onKeyDown);
105107
document.addEventListener("pointerdown", onNavigation, true);
106-
citationViewport.addEventListener("wheel", onWheel, { passive: true });
107-
citationViewport.addEventListener("touchmove", onNavigation, { passive: true });
108+
citationViewport?.addEventListener("wheel", onWheel, { passive: true });
109+
citationViewport?.addEventListener("touchmove", onNavigation, { passive: true });
108110
return () => {
109111
document.removeEventListener("keydown", onKeyDown);
110112
document.removeEventListener("pointerdown", onNavigation, true);
111-
citationViewport.removeEventListener("wheel", onWheel);
112-
citationViewport.removeEventListener("touchmove", onNavigation);
113+
citationViewport?.removeEventListener("wheel", onWheel);
114+
citationViewport?.removeEventListener("touchmove", onNavigation);
113115
};
114116
};
115-
return { target, activate, attachDismissal };
117+
return { target, activate, retire, attachDismissal };
116118
}
117119

118-
useEffect(() => current?.activate(), [current]);
119-
// The viewport mounts after the first render and the activation changes with
120-
// the route, so the listeners follow both.
120+
// Retiring is one-way, so it runs when the activation is replaced rather than
121+
// in a cleanup: StrictMode and <Activity> replay cleanups on a live activation.
122+
// Unmounting needs no retire; the rows observing it unmount with the list.
123+
const activatedRef = useRef<CitationNavigation | null>(null);
121124
useEffect(() => {
122-
if (!current || !viewport) return;
123-
return current.attachDismissal(viewport);
124-
}, [current, viewport]);
125+
if (activatedRef.current === current) return;
126+
activatedRef.current?.retire();
127+
activatedRef.current = current;
128+
current?.activate();
129+
}, [current]);
130+
// Escape and pointerdown dismiss before the viewport mounts; the viewport
131+
// listeners join once it exists.
132+
useEffect(() => current?.attachDismissal(viewport), [current, viewport]);
125133

126134
const settled = current !== null && settlement?.target === current.target ? settlement : null;
127135
const target =

0 commit comments

Comments
 (0)