Skip to content

Commit a5ecca2

Browse files
fix(web): citations to older responses load their history instead of failing
Clicking a citation whose response sits outside the loaded thread window showed "The cited response is unavailable" right away. The timeline's citation hook could page history through a `loadEarlier` prop, but nothing has passed that prop since the V2 orchestrator merge, so it gave up on the first render. Paging now runs in citationProcedure: one atom per citation activation pages history toward the cited message with loadEarlierHistory (up to 20 pages), reports found or failed, and stops when the activation is left. The timeline derives a phase (loading, expanding, ready, failed) from that result and its own rows. The citation hook derives its target and positioning from the phase in render instead of setting state from an effect, and opening a folded turn for the cited response is a render-phase state adjustment like the find-match fold. Effects: useAssistantCitationTarget 2 -> 2 (the navigation state machine effect is gone; one effect owns the activation's follow takeover and retirement, one attaches the dismissal listeners to the viewport, since both synchronize with things outside React). MessagesTimeline 12 -> 12. ChatView unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 3ed0688 commit a5ecca2

6 files changed

Lines changed: 583 additions & 195 deletions

File tree

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,7 @@ import {
258258
RevertConfirmHost,
259259
} from "./chat/ChatOverlayHosts";
260260
import type { AssistantCitationRequest } from "./chat/AssistantCitationSource";
261+
import { useCitedHistory } from "./chat/citationProcedure";
261262
import type { MessagesTimelineHistoryControls } from "./chat/MessagesTimeline";
262263
import { ThreadTimeline } from "./chat/ThreadTimeline";
263264
import { ProviderSubagentBar } from "./chat/ProviderSubagentBar";
@@ -566,6 +567,7 @@ export default function ChatView(props: ChatViewProps) {
566567
? { citation, key: citationLocation.key ?? citationLocation.href }
567568
: null;
568569
})() as AssistantCitationRequest | null;
570+
const citationHistory = useCitedHistory(citationRequest);
569571
const { resolvedTheme } = useTheme();
570572
const composerRuntimeMode = useComposerDraftStore(
571573
(store) => store.getComposerDraft(composerDraftTarget)?.runtimeMode ?? null,
@@ -3217,7 +3219,7 @@ export default function ChatView(props: ChatViewProps) {
32173219
readyMarkdownCwd={gitCwd}
32183220
readyWorkspaceRoot={activeWorkspaceRoot ?? null}
32193221
citationRequest={paintOnlyDisplayedTimeline ? null : citationRequest}
3220-
citationHistoryLoading={threadDetailLoading}
3222+
citationHistory={citationHistory}
32213223
{...(!paintOnlyDisplayedTimeline
32223224
? {
32233225
onCiteAssistantText: citeAssistantTextStable,

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

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ import { deriveTimelineEntriesFromVisibleTurnItems } from "../../session-logic";
1515
import { remarkThoughtPreview } from "./TimelineWorkEntryRow.logic";
1616
import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
1717
import { collectThreadFindRanges } from "./threadFindHighlights";
18+
import { toastManager } from "../ui/toast";
19+
import type { CitedHistory } from "./citationProcedure";
1820

1921
const environmentQuery = vi.hoisted(() => ({
2022
error: "Pull request not found",
@@ -237,6 +239,46 @@ describe("MessagesTimeline messages", () => {
237239
});
238240
});
239241

242+
describe("MessagesTimeline citations", () => {
243+
it("waits for cited history to load before giving up on a response outside the window", async () => {
244+
using toast = vi.spyOn(toastManager, "add");
245+
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"]>;
260+
const recent = message("A recent question", {}, "recent");
261+
const timeline = (entries: Entry[], citationHistory: CitedHistory) => (
262+
<MessagesTimeline
263+
{...props}
264+
timelineEntries={entries}
265+
citationRequest={citationRequest}
266+
citationHistory={citationHistory}
267+
/>
268+
);
269+
await using screen = await renderElement(timeline([recent], { _tag: "loading" }));
270+
await expect.element(screen.getByText("A recent question")).toBeVisible();
271+
272+
await screen.rerender(
273+
timeline([message("the cited answer", { role: "assistant" }, "cited"), recent], {
274+
_tag: "found",
275+
}),
276+
);
277+
await expect.element(screen.getByText("the cited answer")).toBeVisible();
278+
expect(toast).not.toHaveBeenCalled();
279+
});
280+
});
281+
240282
describe("MessagesTimeline automation prompts", () => {
241283
it("folds an automation prompt into a bubble titled by its task", async () => {
242284
setup({ scheduledTasks: [{ id: TASK_ID, title: "Nightly triage" }] });

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

Lines changed: 47 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@ import {
5959
import { AssistantSelectionToolbar } from "./AssistantSelectionToolbar";
6060
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
6161
import { type AssistantCitationRequest } from "./AssistantCitationSource";
62-
import { useAssistantCitationTarget, type CitationHistoryPage } from "./useAssistantCitationTarget";
62+
import { useAssistantCitationTarget } from "./useAssistantCitationTarget";
63+
import { resolveCitationPhase, type CitedHistory } from "./citationProcedure";
6364
import {
6465
resolveTimelineIsAtEnd,
6566
resolveTimelineMinimapHasPersistentGutter,
@@ -168,6 +169,8 @@ const TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH = {
168169
animated: true,
169170
} as const satisfies MaintainScrollAtEndOptions;
170171

172+
const CITED_HISTORY_LOADING: CitedHistory = { _tag: "loading" };
173+
171174
export interface MessagesTimelineHistoryControls {
172175
readonly hasMoreHistory: boolean;
173176
readonly loading: boolean;
@@ -177,7 +180,7 @@ export interface MessagesTimelineHistoryControls {
177180

178181
interface MessagesTimelineProps {
179182
citationRequest?: AssistantCitationRequest | null;
180-
citationHistoryLoading?: boolean;
183+
citationHistory?: CitedHistory;
181184
onCiteAssistantText?: (
182185
citation: AssistantCitation,
183186
sourceAnchor: AssistantCitationSourceAnchor,
@@ -265,7 +268,6 @@ interface MessagesTimelineProps {
265268
emptyPlaceholderInset: number;
266269
topFadeEnabled?: boolean;
267270
historyControls?: MessagesTimelineHistoryControls | undefined;
268-
loadEarlier?: CitationHistoryPage | null;
269271
findExpanded?: boolean;
270272
findQuery?: string;
271273
activeFindMatch?: ThreadFindMatch | null;
@@ -290,7 +292,7 @@ export function MessagesTimeline(props: MessagesTimelineProps) {
290292

291293
const ConversationTimeline = memo(function ConversationTimeline({
292294
citationRequest = null,
293-
citationHistoryLoading = false,
295+
citationHistory = CITED_HISTORY_LOADING,
294296
onCiteAssistantText,
295297
isWorking,
296298
runlessWorkActive = false,
@@ -362,7 +364,6 @@ const ConversationTimeline = memo(function ConversationTimeline({
362364
emptyPlaceholderInset,
363365
topFadeEnabled = false,
364366
historyControls,
365-
loadEarlier = null,
366367
}: MessagesTimelineProps) {
367368
const listIdentityKey = displayThreadKey ?? routeThreadKey;
368369
// Snapshot restore positions on identity changes; ongoing scroll writes must not move them.
@@ -406,9 +407,6 @@ const ConversationTimeline = memo(function ConversationTimeline({
406407
}
407408
const citationThreadRef = parseScopedThreadKey(routeThreadKey);
408409
const openPullRequest = useOpenPrLink(citationThreadRef ?? undefined);
409-
const expandCitedRun = (runId: RunId) => {
410-
setExpandedRunIds((current) => (current.has(runId) ? current : new Set([...current, runId])));
411-
};
412410
const [minimapStripMap] = useState(() => new Map<string, HTMLSpanElement>());
413411
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
414412
const disclosureAnchorKeyRef = useRef<string | null>(null);
@@ -575,6 +573,39 @@ const ConversationTimeline = memo(function ConversationTimeline({
575573
);
576574
}
577575
}
576+
// 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.
579+
const citedEntry =
580+
citationRequest && citationHistory._tag !== "failed"
581+
? timelineEntries.find(
582+
(entry) =>
583+
entry.kind === "message" &&
584+
entry.message.role === "assistant" &&
585+
entry.message.id === citationRequest.citation.messageId,
586+
)
587+
: undefined;
588+
const citationFoldRunIds = citedEntry
589+
? (findFoldRunIds ??
590+
timelineTurnFoldRunIdsByEntryId({
591+
timelineEntries,
592+
latestRun,
593+
runningRunId,
594+
isWorking,
595+
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+
setCitationExpandedFor(citationRequest.key);
605+
setExpandedRunIds((previous) =>
606+
previous.has(citedRunId) ? previous : new Set(previous).add(citedRunId),
607+
);
608+
}
578609
const visibleExpandedRunIds =
579610
!activeFindRunId || paintedExpandedRunIds.has(activeFindRunId)
580611
? paintedExpandedRunIds
@@ -647,24 +678,15 @@ const ConversationTimeline = memo(function ConversationTimeline({
647678
alwaysRender: citationAlwaysRender,
648679
} = useAssistantCitationTarget({
649680
request: citationRequest,
650-
entries: timelineEntries,
651-
rows,
652-
listRef,
653-
viewport: timelineViewportElement,
654-
historyLoading: citationHistoryLoading,
655-
loadEarlier,
656-
getTurnFoldRunId: (entryId) =>
657-
(
658-
findFoldRunIds ??
659-
timelineTurnFoldRunIdsByEntryId({
660-
timelineEntries,
661-
latestRun,
662-
runningRunId,
663-
isWorking,
664-
runlessWorkActive,
681+
phase: citationRequest
682+
? resolveCitationPhase({
683+
history: citationHistory,
684+
messageId: citationRequest.citation.messageId,
685+
entries: timelineEntries,
686+
rows,
665687
})
666-
).get(entryId),
667-
onExpandTurn: expandCitedRun,
688+
: null,
689+
viewport: timelineViewportElement,
668690
onManualNavigation,
669691
});
670692
const [findListReady, setFindListReady] = useState(false);
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
import { MessageId, RunId } from "@t3tools/contracts";
2+
import { describe, expect, it } from "vite-plus/test";
3+
import type { TimelineEntry } from "../../session-logic";
4+
import {
5+
type CitedThreadSnapshot,
6+
loadCitedHistory,
7+
resolveCitationPhase,
8+
} from "./citationProcedure";
9+
import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
10+
11+
function scriptedHistory(snapshots: ReadonlyArray<CitedThreadSnapshot | null>) {
12+
const controller = new AbortController();
13+
let reads = 0;
14+
let loads = 0;
15+
return {
16+
controller,
17+
get loads() {
18+
return loads;
19+
},
20+
run: (results: ReadonlyArray<"loaded" | "noop" | "error"> = []) =>
21+
loadCitedHistory({
22+
signal: controller.signal,
23+
readThread: async () => snapshots[Math.min(reads++, snapshots.length - 1)] ?? null,
24+
loadThrough: async () => {
25+
const result = results[loads++] ?? "loaded";
26+
return result === "error" ? { _tag: "error", message: "offline" } : { _tag: result };
27+
},
28+
}),
29+
};
30+
}
31+
32+
const notLoaded = { message: null, hasMoreHistory: true } satisfies CitedThreadSnapshot;
33+
34+
describe("loadCitedHistory", () => {
35+
it("finds a cited response that is already loaded without paging", async () => {
36+
const history = scriptedHistory([{ message: "assistant", hasMoreHistory: true }]);
37+
await expect(history.run()).resolves.toEqual({ _tag: "found" });
38+
expect(history.loads).toBe(0);
39+
});
40+
41+
it("pages history toward a response outside the loaded window", async () => {
42+
const history = scriptedHistory([
43+
notLoaded,
44+
notLoaded,
45+
{ message: "assistant", hasMoreHistory: true },
46+
]);
47+
await expect(history.run()).resolves.toEqual({ _tag: "found" });
48+
expect(history.loads).toBe(2);
49+
});
50+
51+
it("reports an unavailable response once the thread has no more history", async () => {
52+
const history = scriptedHistory([notLoaded, { message: null, hasMoreHistory: false }]);
53+
await expect(history.run()).resolves.toMatchObject({
54+
_tag: "failed",
55+
title: "The cited response is unavailable",
56+
});
57+
});
58+
59+
it("rejects a citation that names a user message", async () => {
60+
const history = scriptedHistory([{ message: "other", hasMoreHistory: false }]);
61+
await expect(history.run()).resolves.toMatchObject({
62+
_tag: "failed",
63+
title: "The citation does not refer to an assistant response",
64+
});
65+
});
66+
67+
it("stops on a failed page", async () => {
68+
const history = scriptedHistory([notLoaded]);
69+
await expect(history.run(["error"])).resolves.toMatchObject({
70+
_tag: "failed",
71+
title: "Could not load the cited response",
72+
});
73+
expect(history.loads).toBe(1);
74+
});
75+
76+
it("reports an unavailable response when the store has nothing older to page", async () => {
77+
const history = scriptedHistory([notLoaded]);
78+
await expect(history.run(["noop"])).resolves.toMatchObject({
79+
_tag: "failed",
80+
title: "The cited response is unavailable",
81+
});
82+
expect(history.loads).toBe(1);
83+
});
84+
85+
it("gives up after a bounded number of pages that never reach the response", async () => {
86+
const history = scriptedHistory([notLoaded]);
87+
await expect(history.run()).resolves.toMatchObject({
88+
_tag: "failed",
89+
title: "Could not load the cited response",
90+
});
91+
expect(history.loads).toBe(20);
92+
});
93+
94+
it("ends quietly when the citation is left mid-load", async () => {
95+
const history = scriptedHistory([notLoaded]);
96+
const outcome = history.run();
97+
history.controller.abort();
98+
await expect(outcome).resolves.toEqual({ _tag: "aborted" });
99+
});
100+
});
101+
102+
describe("resolveCitationPhase", () => {
103+
const at = "2026-01-01T00:00:00Z";
104+
const messageId = MessageId.make("cited");
105+
const runId = RunId.make("run-1");
106+
const entry: TimelineEntry = {
107+
kind: "message",
108+
id: "cited-entry",
109+
createdAt: at,
110+
message: {
111+
id: messageId,
112+
role: "assistant",
113+
text: "Answer",
114+
runId,
115+
streaming: false,
116+
createdAt: at,
117+
updatedAt: at,
118+
},
119+
};
120+
const row = {
121+
kind: "message",
122+
id: "cited-row",
123+
message: entry.message,
124+
} as MessagesTimelineRow;
125+
const phase = (input: {
126+
history?: "loading" | "found" | "failed";
127+
entries?: ReadonlyArray<TimelineEntry>;
128+
rows?: ReadonlyArray<MessagesTimelineRow>;
129+
}) =>
130+
resolveCitationPhase({
131+
history: { _tag: input.history ?? "loading" },
132+
messageId,
133+
entries: input.entries ?? [],
134+
rows: input.rows ?? [],
135+
});
136+
137+
it("waits while the cited response is not in the timeline yet", () => {
138+
expect(phase({ history: "found" })).toEqual({ _tag: "loading" });
139+
});
140+
141+
it("expands the turn that folds the cited response", () => {
142+
expect(phase({ entries: [entry] })).toEqual({ _tag: "expanding" });
143+
});
144+
145+
it("is ready once the cited response has a row, even before paging settles", () => {
146+
expect(phase({ entries: [entry], rows: [row] })).toEqual({
147+
_tag: "ready",
148+
rowId: "cited-row",
149+
});
150+
});
151+
152+
it("fails for a citation that names a user message", () => {
153+
const userEntry: TimelineEntry = {
154+
...entry,
155+
message: { ...entry.message, role: "user" },
156+
} as TimelineEntry;
157+
expect(phase({ entries: [userEntry] })).toEqual({ _tag: "failed" });
158+
});
159+
160+
it("fails when the history procedure failed", () => {
161+
expect(phase({ history: "failed", entries: [entry], rows: [row] })).toEqual({
162+
_tag: "failed",
163+
});
164+
});
165+
});

0 commit comments

Comments
 (0)