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 22, 15:45 UTC
fix(web): citations to older responses load their history instead of failing (#25371)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 26, 2026 at 02:10 UTC
1316d48b0c68151afd8b47eb0c11a114cf0b4daa
6 files changed
+731
-199
apps/web/src/components/ChatView.tsx
+3
-1
@@ -258,6 +258,7 @@ import {
258
RevertConfirmHost,
259
} from "./chat/ChatOverlayHosts";
260
import type { AssistantCitationRequest } from "./chat/AssistantCitationSource";
261
+import { useCitedHistory } from "./chat/citationProcedure";
262
import type { MessagesTimelineHistoryControls } from "./chat/MessagesTimeline";
263
import { ThreadTimeline } from "./chat/ThreadTimeline";
264
import { ProviderSubagentBar } from "./chat/ProviderSubagentBar";
@@ -566,6 +567,7 @@ export default function ChatView(props: ChatViewProps) {
567
? { citation, key: citationLocation.key ?? citationLocation.href }
568
: null;
569
})() as AssistantCitationRequest | null;
570
+ const citationHistory = useCitedHistory(citationRequest);
571
const { resolvedTheme } = useTheme();
572
const composerRuntimeMode = useComposerDraftStore(
573
(store) => store.getComposerDraft(composerDraftTarget)?.runtimeMode ?? null,
@@ -3217,7 +3219,7 @@ export default function ChatView(props: ChatViewProps) {
3219
readyMarkdownCwd={gitCwd}
3220
readyWorkspaceRoot={activeWorkspaceRoot ?? null}
3221
citationRequest={paintOnlyDisplayedTimeline ? null : citationRequest}
3220
- citationHistoryLoading={threadDetailLoading}
3222
+ citationHistory={citationHistory}
3223
{...(!paintOnlyDisplayedTimeline
3224
? {
3225
onCiteAssistantText: citeAssistantTextStable,
apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+115
-4
@@ -1,9 +1,16 @@
1
import { AudioPreview } from "../files/AudioPreview";
2
import { onTestFinished } from "vite-plus/test";
3
import { stubGlobal } from "../../../test/render";
4
-import { EnvironmentId, MessageId, RunId, ScheduledTaskId, ThreadId } from "@t3tools/contracts";
4
+import {
5
+ EnvironmentId,
6
+ MessageId,
7
+ RunAttemptId,
8
+ RunId,
9
+ ScheduledTaskId,
10
+ ThreadId,
11
+} from "@t3tools/contracts";
12
import type { LegendListRef } from "@legendapp/list/react";
6
-import { createRef, Profiler, type ComponentProps, type ReactElement } from "react";
13
+import { createRef, Profiler, StrictMode, type ComponentProps, type ReactElement } from "react";
14
import { describe, expect, it, vi } from "vite-plus/test";
15
16
import "~/index.css";
@@ -15,6 +22,8 @@ import { deriveTimelineEntriesFromVisibleTurnItems } from "../../session-logic";
22
import { remarkThoughtPreview } from "./TimelineWorkEntryRow.logic";
23
import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
24
import { collectThreadFindRanges } from "./threadFindHighlights";
25
+import { toastManager } from "../ui/toast";
26
+import type { CitedHistory } from "./citationProcedure";
27
28
const environmentQuery = vi.hoisted(() => ({
29
error: "Pull request not found",
@@ -108,10 +117,10 @@ function message(
117
};
118
}
119
111
-async function renderElement(element: ReactElement) {
120
+async function renderElement(element: ReactElement, options: { router?: false } = {}) {
121
const container = document.createElement("div");
122
container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
114
- const screen = await render(element, { container });
123
+ const screen = await render(element, { container, ...options });
124
const buttons = (name: string | RegExp) =>
125
[...container.querySelectorAll<HTMLElement>("button, [role=button]")].filter((button) => {
126
const label = button.getAttribute("aria-label") ?? button.textContent ?? "";
@@ -237,6 +246,108 @@ describe("MessagesTimeline messages", () => {
246
});
247
});
248
249
+const CITATION_REQUEST = {
250
+ key: "activation-1",
251
+ citation: {
252
+ version: 1,
253
+ environmentId: ENVIRONMENT_ID,
254
+ threadId: ThreadId.make("thread-cited"),
255
+ messageId: MessageId.make("cited"),
256
+ text: "the cited answer",
257
+ start: 0,
258
+ end: 16,
259
+ prefix: "",
260
+ suffix: "",
261
+ },
262
+} satisfies NonNullable<TimelineProps["citationRequest"]>;
263
+
264
+describe("MessagesTimeline citations", () => {
265
+ it("lands a citation present at mount under StrictMode", async () => {
266
+ await using _screen = await renderElement(
267
+ <StrictMode>
268
+ <MessagesTimeline
269
+ {...baseProps()}
270
+ timelineEntries={[
271
+ message("A question", {}, "question"),
272
+ message("the cited answer", { role: "assistant" }, "cited"),
273
+ ]}
274
+ citationRequest={CITATION_REQUEST}
275
+ citationHistory={{ _tag: "found" }}
276
+ />
277
+ </StrictMode>,
278
+ // The test router mounts route content without StrictMode's effect replay.
279
+ { router: false },
280
+ );
281
+ // StrictMode replays effect cleanups on mount; the activation must survive them.
282
+ await vi.waitFor(() =>
283
+ expect(document.querySelector("[data-citation-highlighted]")?.textContent).toContain(
284
+ "the cited answer",
285
+ ),
286
+ );
287
+ });
288
+
289
+ it("opens the superseded attempt that folds the cited response", async () => {
290
+ const runId = RunId.make("run-steered");
291
+ const attempt = (id: string, ordinal: number, status: "superseded" | "running") => ({
292
+ id: RunAttemptId.make(id),
293
+ runId,
294
+ attemptOrdinal: ordinal,
295
+ rootNodeId: `node-${id}` as never,
296
+ status,
297
+ completedAt: null,
298
+ });
299
+ const superseded = attempt("attempt-1", 1, "superseded");
300
+ const active = attempt("attempt-2", 2, "running");
301
+ const inAttempt = (entry: Entry, entryAttempt: typeof superseded): Entry => ({
302
+ ...entry,
303
+ attempt: entryAttempt,
304
+ });
305
+ await using _screen = await renderTimeline(
306
+ [
307
+ inAttempt(message("Build it", { runId }, "question"), superseded),
308
+ inAttempt(message("the cited answer", { role: "assistant", runId }, "cited"), superseded),
309
+ inAttempt(message("Change direction", { runId }, "steer"), active),
310
+ inAttempt(message("Current response", { role: "assistant", runId }, "current"), active),
311
+ ],
312
+ {
313
+ latestRun: { runId, status: "running", startedAt: CREATED_AT, completedAt: null },
314
+ citationRequest: CITATION_REQUEST,
315
+ citationHistory: { _tag: "found" },
316
+ },
317
+ );
318
+ await vi.waitFor(() =>
319
+ expect(document.querySelector("[data-citation-highlighted]")?.textContent).toContain(
320
+ "the cited answer",
321
+ ),
322
+ );
323
+ });
324
+
325
+ it("waits for cited history to load before giving up on a response outside the window", async () => {
326
+ using toast = vi.spyOn(toastManager, "add");
327
+ const props = baseProps();
328
+ const citationRequest = CITATION_REQUEST;
329
+ const recent = message("A recent question", {}, "recent");
330
+ const timeline = (entries: Entry[], citationHistory: CitedHistory) => (
331
+ <MessagesTimeline
332
+ {...props}
333
+ timelineEntries={entries}
334
+ citationRequest={citationRequest}
335
+ citationHistory={citationHistory}
336
+ />
337
+ );
338
+ await using screen = await renderElement(timeline([recent], { _tag: "loading" }));
339
+ await expect.element(screen.getByText("A recent question")).toBeVisible();
340
+
341
+ await screen.rerender(
342
+ timeline([message("the cited answer", { role: "assistant" }, "cited"), recent], {
343
+ _tag: "found",
344
+ }),
345
+ );
346
+ await expect.element(screen.getByText("the cited answer")).toBeVisible();
347
+ expect(toast).not.toHaveBeenCalled();
348
+ });
349
+});
350
+
351
describe("MessagesTimeline automation prompts", () => {
352
it("folds an automation prompt into a bubble titled by its task", async () => {
353
setup({ scheduledTasks: [{ id: TASK_ID, title: "Nightly triage" }] });
apps/web/src/components/chat/MessagesTimeline.tsx
+57
-25
@@ -59,7 +59,8 @@ import {
59
import { AssistantSelectionToolbar } from "./AssistantSelectionToolbar";
60
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
61
import { type AssistantCitationRequest } from "./AssistantCitationSource";
62
-import { useAssistantCitationTarget, type CitationHistoryPage } from "./useAssistantCitationTarget";
62
+import { useAssistantCitationTarget } from "./useAssistantCitationTarget";
63
+import { resolveCitationPhase, type CitedHistory } from "./citationProcedure";
64
import {
65
resolveTimelineIsAtEnd,
66
resolveTimelineMinimapHasPersistentGutter,
@@ -168,6 +169,8 @@ const TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH = {
169
animated: true,
170
} as const satisfies MaintainScrollAtEndOptions;
171
172
+const CITED_HISTORY_LOADING: CitedHistory = { _tag: "loading" };
173
+
174
export interface MessagesTimelineHistoryControls {
175
readonly hasMoreHistory: boolean;
176
readonly loading: boolean;
@@ -177,7 +180,7 @@ export interface MessagesTimelineHistoryControls {
180
181
interface MessagesTimelineProps {
182
citationRequest?: AssistantCitationRequest | null;
180
- citationHistoryLoading?: boolean;
183
+ citationHistory?: CitedHistory;
184
onCiteAssistantText?: (
185
citation: AssistantCitation,
186
sourceAnchor: AssistantCitationSourceAnchor,
@@ -265,7 +268,6 @@ interface MessagesTimelineProps {
268
emptyPlaceholderInset: number;
269
topFadeEnabled?: boolean;
270
historyControls?: MessagesTimelineHistoryControls | undefined;
268
- loadEarlier?: CitationHistoryPage | null;
271
findExpanded?: boolean;
272
findQuery?: string;
273
activeFindMatch?: ThreadFindMatch | null;
@@ -290,7 +292,7 @@ export function MessagesTimeline(props: MessagesTimelineProps) {
292
293
const ConversationTimeline = memo(function ConversationTimeline({
294
citationRequest = null,
293
- citationHistoryLoading = false,
295
+ citationHistory = CITED_HISTORY_LOADING,
296
onCiteAssistantText,
297
isWorking,
298
runlessWorkActive = false,
@@ -362,7 +364,6 @@ const ConversationTimeline = memo(function ConversationTimeline({
364
emptyPlaceholderInset,
365
topFadeEnabled = false,
366
historyControls,
365
- loadEarlier = null,
367
}: MessagesTimelineProps) {
368
const listIdentityKey = displayThreadKey ?? routeThreadKey;
369
// Snapshot restore positions on identity changes; ongoing scroll writes must not move them.
@@ -406,9 +407,6 @@ const ConversationTimeline = memo(function ConversationTimeline({
407
}
408
const citationThreadRef = parseScopedThreadKey(routeThreadKey);
409
const openPullRequest = useOpenPrLink(citationThreadRef ?? undefined);
409
- const expandCitedRun = (runId: RunId) => {
410
- setExpandedRunIds((current) => (current.has(runId) ? current : new Set([...current, runId])));
411
- };
410
const [minimapStripMap] = useState(() => new Map<string, HTMLSpanElement>());
411
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
412
const disclosureAnchorKeyRef = useRef<string | null>(null);
@@ -575,6 +573,49 @@ const ConversationTimeline = memo(function ConversationTimeline({
573
);
574
}
575
}
576
+ // A cited response folded inside a turn opens its fold once per activation;
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);
584
+ const citedEntry =
585
+ citationRequest &&
586
+ citationExpandedFor !== citationRequest.key &&
587
+ citationHistory._tag !== "failed"
588
+ ? timelineEntries.find(
589
+ (entry) =>
590
+ entry.kind === "message" &&
591
+ entry.message.role === "assistant" &&
592
+ entry.message.id === citationRequest.citation.messageId,
593
+ )
594
+ : undefined;
595
+ if (citationRequest && citedEntry) {
596
+ const citedRunId = (
597
+ findFoldRunIds ??
598
+ timelineTurnFoldRunIdsByEntryId({
599
+ timelineEntries,
600
+ latestRun,
601
+ runningRunId,
602
+ isWorking,
603
+ runlessWorkActive,
604
+ })
605
+ ).get(citedEntry.id);
606
+ setCitationExpandedFor(citationRequest.key);
607
+ if (citedRunId) {
608
+ setExpandedRunIds((previous) =>
609
+ previous.has(citedRunId) ? previous : new Set(previous).add(citedRunId),
610
+ );
611
+ }
612
+ const citedAttempt = citedEntry.attempt;
613
+ if (citedAttempt?.status === "superseded") {
614
+ setExpandedAttemptIds((previous) =>
615
+ previous.has(citedAttempt.id) ? previous : new Set(previous).add(citedAttempt.id),
616
+ );
617
+ }
618
+ }
619
const visibleExpandedRunIds =
620
!activeFindRunId || paintedExpandedRunIds.has(activeFindRunId)
621
? paintedExpandedRunIds
@@ -647,24 +688,15 @@ const ConversationTimeline = memo(function ConversationTimeline({
688
alwaysRender: citationAlwaysRender,
689
} = useAssistantCitationTarget({
690
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,
691
+ phase: citationRequest
692
+ ? resolveCitationPhase({
693
+ history: citationHistory,
694
+ messageId: citationRequest.citation.messageId,
695
+ entries: timelineEntries,
696
+ rows,
697
})
666
- ).get(entryId),
667
- onExpandTurn: expandCitedRun,
698
+ : null,
699
+ viewport: timelineViewportElement,
700
onManualNavigation,
701
});
702
const [findListReady, setFindListReady] = useState(false);
apps/web/src/components/chat/citationProcedure.test.ts
new
+197
@@ -0,0 +1,197 @@
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
+ citedThreadSnapshot,
7
+ loadCitedHistory,
8
+ resolveCitationPhase,
9
+} from "./citationProcedure";
10
+import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
11
+
12
+function scriptedHistory(snapshots: ReadonlyArray<CitedThreadSnapshot | null>) {
13
+ const controller = new AbortController();
14
+ let reads = 0;
15
+ let loads = 0;
16
+ return {
17
+ controller,
18
+ get loads() {
19
+ return loads;
20
+ },
21
+ run: (results: ReadonlyArray<"loaded" | "noop" | "error"> = []) =>
22
+ loadCitedHistory({
23
+ signal: controller.signal,
24
+ readThread: async () => snapshots[Math.min(reads++, snapshots.length - 1)] ?? null,
25
+ loadThrough: async () => {
26
+ const result = results[loads++] ?? "loaded";
27
+ return result === "error" ? { _tag: "error", message: "offline" } : { _tag: result };
28
+ },
29
+ }),
30
+ };
31
+}
32
+
33
+const notLoaded = { message: null, hasMoreHistory: true } satisfies CitedThreadSnapshot;
34
+
35
+describe("loadCitedHistory", () => {
36
+ it("finds a cited response that is already loaded without paging", async () => {
37
+ const history = scriptedHistory([{ message: "assistant", hasMoreHistory: true }]);
38
+ await expect(history.run()).resolves.toEqual({ _tag: "found" });
39
+ expect(history.loads).toBe(0);
40
+ });
41
+
42
+ it("pages history toward a response outside the loaded window", async () => {
43
+ const history = scriptedHistory([
44
+ notLoaded,
45
+ notLoaded,
46
+ { message: "assistant", hasMoreHistory: true },
47
+ ]);
48
+ await expect(history.run()).resolves.toEqual({ _tag: "found" });
49
+ expect(history.loads).toBe(2);
50
+ });
51
+
52
+ it("reports an unavailable response once the thread has no more history", async () => {
53
+ const history = scriptedHistory([notLoaded, { message: null, hasMoreHistory: false }]);
54
+ await expect(history.run()).resolves.toMatchObject({
55
+ _tag: "failed",
56
+ title: "The cited response is unavailable",
57
+ });
58
+ });
59
+
60
+ it("rejects a citation that names a user message", async () => {
61
+ const history = scriptedHistory([{ message: "other", hasMoreHistory: false }]);
62
+ await expect(history.run()).resolves.toMatchObject({
63
+ _tag: "failed",
64
+ title: "The citation does not refer to an assistant response",
65
+ });
66
+ });
67
+
68
+ it("stops on a failed page", async () => {
69
+ const history = scriptedHistory([notLoaded]);
70
+ await expect(history.run(["error"])).resolves.toMatchObject({
71
+ _tag: "failed",
72
+ title: "Could not load the cited response",
73
+ });
74
+ expect(history.loads).toBe(1);
75
+ });
76
+
77
+ it("reports an unavailable response when the store has nothing older to page", async () => {
78
+ const history = scriptedHistory([notLoaded]);
79
+ await expect(history.run(["noop"])).resolves.toMatchObject({
80
+ _tag: "failed",
81
+ title: "The cited response is unavailable",
82
+ });
83
+ expect(history.loads).toBe(1);
84
+ });
85
+
86
+ it("gives up after a bounded number of pages that never reach the response", async () => {
87
+ const history = scriptedHistory([notLoaded]);
88
+ await expect(history.run()).resolves.toMatchObject({
89
+ _tag: "failed",
90
+ title: "Could not load the cited response",
91
+ });
92
+ expect(history.loads).toBe(20);
93
+ });
94
+
95
+ it("ends quietly when the citation is left mid-load", async () => {
96
+ const history = scriptedHistory([notLoaded]);
97
+ const outcome = history.run();
98
+ history.controller.abort();
99
+ await expect(outcome).resolves.toEqual({ _tag: "aborted" });
100
+ });
101
+});
102
+
103
+describe("citedThreadSnapshot", () => {
104
+ const settledHistory = {
105
+ historyCursor: null,
106
+ hasMoreHistory: false,
107
+ loading: false,
108
+ error: null,
109
+ expanded: false,
110
+ latestLocalTurnOrdinal: null,
111
+ };
112
+ const unloaded = {
113
+ thread: null,
114
+ history: settledHistory,
115
+ status: "synchronizing",
116
+ error: null,
117
+ messageId: "cited",
118
+ } satisfies Parameters<typeof citedThreadSnapshot>[0];
119
+
120
+ it("keeps waiting while a thread that has not loaded yet is still synchronizing", () => {
121
+ expect(citedThreadSnapshot(unloaded)).toBeNull();
122
+ });
123
+
124
+ it("fails the citation when the thread could not load at all", async () => {
125
+ const snapshot = citedThreadSnapshot({ ...unloaded, error: "Thread not found." });
126
+ expect(snapshot).not.toBeNull();
127
+ await expect(scriptedHistory([snapshot]).run()).resolves.toMatchObject({
128
+ _tag: "failed",
129
+ title: "Could not load the cited response",
130
+ });
131
+ });
132
+});
133
+
134
+describe("resolveCitationPhase", () => {
135
+ const at = "2026-01-01T00:00:00Z";
136
+ const messageId = MessageId.make("cited");
137
+ const runId = RunId.make("run-1");
138
+ const entry: TimelineEntry = {
139
+ kind: "message",
140
+ id: "cited-entry",
141
+ createdAt: at,
142
+ message: {
143
+ id: messageId,
144
+ role: "assistant",
145
+ text: "Answer",
146
+ runId,
147
+ streaming: false,
148
+ createdAt: at,
149
+ updatedAt: at,
150
+ },
151
+ };
152
+ const row = {
153
+ kind: "message",
154
+ id: "cited-row",
155
+ message: entry.message,
156
+ } as MessagesTimelineRow;
157
+ const phase = (input: {
158
+ history?: "loading" | "found" | "failed";
159
+ entries?: ReadonlyArray<TimelineEntry>;
160
+ rows?: ReadonlyArray<MessagesTimelineRow>;
161
+ }) =>
162
+ resolveCitationPhase({
163
+ history: { _tag: input.history ?? "loading" },
164
+ messageId,
165
+ entries: input.entries ?? [],
166
+ rows: input.rows ?? [],
167
+ });
168
+
169
+ it("waits while the cited response is not in the timeline yet", () => {
170
+ expect(phase({ history: "found" })).toEqual({ _tag: "loading" });
171
+ });
172
+
173
+ it("expands the turn that folds the cited response", () => {
174
+ expect(phase({ entries: [entry] })).toEqual({ _tag: "expanding" });
175
+ });
176
+
177
+ it("is ready once the cited response has a row, even before paging settles", () => {
178
+ expect(phase({ entries: [entry], rows: [row] })).toEqual({
179
+ _tag: "ready",
180
+ rowId: "cited-row",
181
+ });
182
+ });
183
+
184
+ it("fails for a citation that names a user message", () => {
185
+ const userEntry: TimelineEntry = {
186
+ ...entry,
187
+ message: { ...entry.message, role: "user" },
188
+ } as TimelineEntry;
189
+ expect(phase({ entries: [userEntry] })).toEqual({ _tag: "failed" });
190
+ });
191
+
192
+ it("fails when the history procedure failed", () => {
193
+ expect(phase({ history: "failed", entries: [entry], rows: [row] })).toEqual({
194
+ _tag: "failed",
195
+ });
196
+ });
197
+});
apps/web/src/components/chat/citationProcedure.ts
new
+240
@@ -0,0 +1,240 @@
1
+import { useAtomValue } from "@effect/atom-react";
2
+import { type AtomCommandSuccess, runAtomCommand } from "@t3tools/client-runtime/state/runtime";
3
+import { Atom, type AtomRegistry } from "effect/reactivity";
4
+import type { TimelineEntry } from "../../session-logic";
5
+import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
6
+import { toastManager } from "../ui/toast";
7
+import type { AssistantCitationRequest } from "./AssistantCitationSource";
8
+import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
9
+
10
+/** Whether the cited response is in the loaded history, after paging toward it. */
11
+export type CitedHistory =
12
+ | { readonly _tag: "loading" }
13
+ | { readonly _tag: "found" }
14
+ | { readonly _tag: "failed" };
15
+
16
+export type CitationPhase =
17
+ | { readonly _tag: "loading" }
18
+ | { readonly _tag: "expanding" }
19
+ | { readonly _tag: "ready"; readonly rowId: string }
20
+ | { readonly _tag: "failed" };
21
+
22
+export interface CitedThreadSnapshot {
23
+ readonly message: "assistant" | "other" | null;
24
+ readonly hasMoreHistory: boolean;
25
+ readonly loadFailed?: true;
26
+}
27
+
28
+export type CitedHistoryOutcome =
29
+ | { readonly _tag: "found" }
30
+ | { readonly _tag: "failed"; readonly title: string; readonly description: string }
31
+ | { readonly _tag: "aborted" };
32
+
33
+type HistoryPageResult = AtomCommandSuccess<
34
+ Awaited<ReturnType<typeof threadEnvironment.loadEarlierHistory.run>>
35
+>;
36
+
37
+const MAX_CITATION_PAGES = 20;
38
+
39
+const COULD_NOT_LOAD = {
40
+ _tag: "failed",
41
+ title: "Could not load the cited response",
42
+ description:
43
+ "Load earlier turns, then click the citation to try again. Your saved quote is unchanged.",
44
+} as const;
45
+
46
+const UNAVAILABLE = {
47
+ _tag: "failed",
48
+ title: "The cited response is unavailable",
49
+ description: "It may have been removed. The selected text is still saved in your citation.",
50
+} as const;
51
+
52
+/**
53
+ * Pages history toward the cited message until it is loaded, the thread runs
54
+ * out of history, or loading fails. `readThread` resolves once the thread
55
+ * detail is settled (loaded and no history page in flight), or with null when
56
+ * the signal aborts.
57
+ */
58
+export async function loadCitedHistory(input: {
59
+ readonly signal: AbortSignal;
60
+ readonly readThread: () => Promise<CitedThreadSnapshot | null>;
61
+ readonly loadThrough: () => Promise<HistoryPageResult>;
62
+}): Promise<CitedHistoryOutcome> {
63
+ for (let attempts = 0; ; attempts += 1) {
64
+ const thread = await input.readThread();
65
+ if (thread === null || input.signal.aborted) return { _tag: "aborted" };
66
+ if (thread.loadFailed) return COULD_NOT_LOAD;
67
+ if (thread.message === "assistant") return { _tag: "found" };
68
+ if (thread.message === "other") {
69
+ return {
70
+ _tag: "failed",
71
+ title: "The citation does not refer to an assistant response",
72
+ description: "The selected text is still saved in your citation.",
73
+ };
74
+ }
75
+ if (!thread.hasMoreHistory) return UNAVAILABLE;
76
+ if (attempts >= MAX_CITATION_PAGES) return COULD_NOT_LOAD;
77
+ const result = await input.loadThrough();
78
+ if (input.signal.aborted) return { _tag: "aborted" };
79
+ if (result._tag === "error") return COULD_NOT_LOAD;
80
+ // A noop page means the store has nothing older to load (no cursor, or the
81
+ // thread is gone), so re-reading would only spin on the same snapshot.
82
+ if (result._tag === "noop") return UNAVAILABLE;
83
+ }
84
+}
85
+
86
+/** Where the citation stands for the rows the timeline currently shows. */
87
+export function resolveCitationPhase(input: {
88
+ readonly history: CitedHistory;
89
+ readonly messageId: string;
90
+ readonly entries: ReadonlyArray<TimelineEntry>;
91
+ readonly rows: ReadonlyArray<MessagesTimelineRow>;
92
+}): CitationPhase {
93
+ if (input.history._tag === "failed") return { _tag: "failed" };
94
+ const source = input.entries.find(
95
+ (entry) => entry.kind === "message" && entry.message.id === input.messageId,
96
+ );
97
+ // The history store can hold the message a render before the entries do.
98
+ if (!source) return { _tag: "loading" };
99
+ if (source.kind !== "message" || source.message.role !== "assistant") return { _tag: "failed" };
100
+ const row = input.rows.find(
101
+ (candidate) => candidate.kind === "message" && candidate.message.id === input.messageId,
102
+ );
103
+ if (row) return { _tag: "ready", rowId: row.id };
104
+ return { _tag: "expanding" };
105
+}
106
+
107
+type ThreadDetail<K extends keyof typeof environmentThreadDetails> = Atom.Type<
108
+ ReturnType<(typeof environmentThreadDetails)[K]>
109
+>;
110
+
111
+/**
112
+ * The cited thread as `loadCitedHistory` reads it, or null while it is still
113
+ * settling. A thread that failed to load before any projection arrived counts
114
+ * as settled, so the citation fails instead of waiting on the stream's retries.
115
+ */
116
+export function citedThreadSnapshot(input: {
117
+ readonly thread: ThreadDetail<"quietThreadAtom">;
118
+ readonly history: ThreadDetail<"historyAtom">;
119
+ readonly status: ThreadDetail<"statusAtom">;
120
+ readonly error: ThreadDetail<"errorAtom">;
121
+ readonly messageId: string;
122
+}): CitedThreadSnapshot | null {
123
+ if (input.history.loading) return null;
124
+ if (input.thread === null) {
125
+ if (input.status === "deleted") return { message: null, hasMoreHistory: false };
126
+ return input.error === null ? null : { message: null, hasMoreHistory: false, loadFailed: true };
127
+ }
128
+ // Older pages merge into the visible turn items, not the message list.
129
+ const item = input.thread.projection.visibleTurnItems.find(
130
+ (row) =>
131
+ (row.item.type === "assistant_message" || row.item.type === "user_message") &&
132
+ row.item.messageId === input.messageId,
133
+ )?.item;
134
+ return {
135
+ message: item === undefined ? null : item.type === "assistant_message" ? "assistant" : "other",
136
+ hasMoreHistory: input.history.hasMoreHistory,
137
+ };
138
+}
139
+
140
+interface CitedHistoryKey {
141
+ readonly key: string;
142
+ readonly environmentId: AssistantCitationRequest["citation"]["environmentId"];
143
+ readonly threadId: AssistantCitationRequest["citation"]["threadId"];
144
+ readonly messageId: AssistantCitationRequest["citation"]["messageId"];
145
+}
146
+
147
+function waitForSettledThread(
148
+ registry: AtomRegistry.AtomRegistry,
149
+ atom: Atom.Atom<CitedThreadSnapshot | null>,
150
+ signal: AbortSignal,
151
+): Promise<CitedThreadSnapshot | null> {
152
+ return new Promise((resolve) => {
153
+ let unsubscribe: (() => void) | null = null;
154
+ let settled = false;
155
+ const finish = (value: CitedThreadSnapshot | null) => {
156
+ if (settled) return;
157
+ settled = true;
158
+ unsubscribe?.();
159
+ signal.removeEventListener("abort", onAbort);
160
+ resolve(value);
161
+ };
162
+ const onAbort = () => finish(null);
163
+ const check = (value: CitedThreadSnapshot | null) => {
164
+ if (value !== null) finish(value);
165
+ };
166
+ signal.addEventListener("abort", onAbort);
167
+ unsubscribe = registry.subscribe(atom, check);
168
+ if (settled) unsubscribe();
169
+ else check(registry.get(atom));
170
+ });
171
+}
172
+
173
+/**
174
+ * The citation procedure for one activation (the location key). Mounting it
175
+ * starts paging; leaving the location unmounts it and the finalizer stops it.
176
+ * Plain-object keys compare structurally, so one activation is one procedure.
177
+ */
178
+const citedHistoryAtom = Atom.family(
179
+ ({ key, environmentId, threadId, messageId }: CitedHistoryKey) => {
180
+ const ref = { environmentId, threadId };
181
+ const threadAtom = environmentThreadDetails.quietThreadAtom(ref);
182
+ const historyAtom = environmentThreadDetails.historyAtom(ref);
183
+ const statusAtom = environmentThreadDetails.statusAtom(ref);
184
+ const errorAtom = environmentThreadDetails.errorAtom(ref);
185
+ const settledThreadAtom = Atom.make((get) =>
186
+ citedThreadSnapshot({
187
+ thread: get(threadAtom),
188
+ history: get(historyAtom),
189
+ status: get(statusAtom),
190
+ error: get(errorAtom),
191
+ messageId,
192
+ }),
193
+ );
194
+ return Atom.make((get): CitedHistory => {
195
+ const controller = new AbortController();
196
+ get.addFinalizer(() => controller.abort());
197
+ void loadCitedHistory({
198
+ signal: controller.signal,
199
+ readThread: () => waitForSettledThread(get.registry, settledThreadAtom, controller.signal),
200
+ loadThrough: async () => {
201
+ const result = await runAtomCommand(
202
+ get.registry,
203
+ threadEnvironment.loadEarlierHistory,
204
+ { environmentId, input: { threadId, throughEntryId: messageId } },
205
+ { label: "load cited thread history", reportFailure: false },
206
+ );
207
+ return result._tag === "Success"
208
+ ? result.value
209
+ : { _tag: "error", message: "Could not load history." };
210
+ },
211
+ }).then((outcome) => {
212
+ if (outcome._tag === "aborted") return;
213
+ if (outcome._tag === "failed") {
214
+ toastManager.add({
215
+ type: "warning",
216
+ title: outcome.title,
217
+ description: outcome.description,
218
+ });
219
+ }
220
+ get.setSelf({ _tag: outcome._tag });
221
+ });
222
+ return { _tag: "loading" };
223
+ }).pipe(Atom.withLabel(`assistant-citation:history:${key}`));
224
+ },
225
+);
226
+
227
+const NO_CITED_HISTORY_ATOM = Atom.make<CitedHistory>({ _tag: "loading" });
228
+
229
+export function useCitedHistory(request: AssistantCitationRequest | null): CitedHistory {
230
+ return useAtomValue(
231
+ request === null
232
+ ? NO_CITED_HISTORY_ATOM
233
+ : citedHistoryAtom({
234
+ key: request.key,
235
+ environmentId: request.citation.environmentId,
236
+ threadId: request.citation.threadId,
237
+ messageId: request.citation.messageId,
238
+ }),
239
+ );
240
+}
apps/web/src/components/chat/useAssistantCitationTarget.ts
+119
-169
@@ -1,198 +1,148 @@
1
-import type { LegendListRef } from "@legendapp/list/react";
2
-import type { RunId } from "@t3tools/contracts";
3
-import { useEffect, useRef, useState, type RefObject } from "react";
4
-import type { TimelineEntry } from "../../session-logic";
5
-import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
1
+import { useEffect, useRef, useState } from "react";
2
import type { AssistantCitationRequest, AssistantCitationTarget } from "./AssistantCitationSource";
7
-import { toastManager } from "../ui/toast";
3
+import type { CitationPhase } from "./citationProcedure";
4
9
-export interface CitationHistoryPage {
10
- readonly loading: boolean;
11
- readonly cursor?: string | null;
12
- readonly onLoadEarlier: () => void;
5
+const CITATION_SCROLL_KEYS = new Set([
6
+ "ArrowUp",
7
+ "ArrowDown",
8
+ "PageUp",
9
+ "PageDown",
10
+ "Home",
11
+ "End",
12
+ " ",
13
+]);
14
+
15
+/** One activation of a citation; virtual row remounts and listeners share it. */
16
+interface CitationNavigation {
17
+ readonly target: AssistantCitationTarget;
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;
22
+ /** Listens for user navigation that stops this activation's pending scroll. */
23
+ readonly attachDismissal: (viewport: HTMLElement | null) => () => void;
24
+}
25
+
26
+interface CitationSettlement {
27
+ /** Per activation, not per key: Back/Forward can restore an earlier key. */
28
+ readonly target: AssistantCitationTarget;
29
+ /** Dismissed citations also drop their highlight; completed ones keep it. */
30
+ readonly dismissed: boolean;
31
}
32
33
export function useAssistantCitationTarget({
34
request,
17
- entries,
18
- rows,
19
- listRef,
35
+ phase,
36
viewport,
21
- historyLoading,
22
- loadEarlier,
23
- getTurnFoldRunId,
24
- onExpandTurn,
37
onManualNavigation,
38
}: {
39
request: AssistantCitationRequest | null;
28
- entries: ReadonlyArray<TimelineEntry>;
29
- rows: ReadonlyArray<MessagesTimelineRow>;
30
- listRef: RefObject<LegendListRef | null>;
40
+ phase: CitationPhase | null;
41
viewport: HTMLElement | null;
32
- historyLoading: boolean;
33
- loadEarlier: CitationHistoryPage | null;
34
- getTurnFoldRunId: (entryId: string) => RunId | undefined;
35
- onExpandTurn: (runId: RunId) => void;
42
onManualNavigation: () => void;
43
}) {
38
- const [ready, setReady] = useState<AssistantCitationTarget | null>(null);
39
- const [finishedKey, setFinishedKey] = useState<string | null>(null);
44
+ const [settlement, setSettlement] = useState<CitationSettlement | null>(null);
45
const [listLoaded, setListLoaded] = useState(false);
46
const onListLoad = () => setListLoaded(true);
42
- const navigationRef = useRef<{
43
- target: AssistantCitationTarget;
44
- requestedPages: Set<string>;
45
- done: boolean;
46
- } | null>(null);
47
48
- if (ready !== null && ready.key !== request?.key) {
49
- setReady(null);
48
+ // Rows and listeners mutate the activation, so it lives as long as its
49
+ // request; a target belongs to one request, so returning to an earlier key
50
+ // never reuses it.
51
+ const [navigation, setNavigation] = useState<CitationNavigation | null>(null);
52
+ let current = navigation;
53
+ if ((request?.key ?? null) !== (navigation?.target.key ?? null)) {
54
+ current = request ? createCitationNavigation(request) : null;
55
+ setNavigation(current);
56
}
51
- if (!request && finishedKey !== null) {
52
- setFinishedKey(null);
53
- }
54
-
55
- useEffect(() => {
56
- if (navigationRef.current && navigationRef.current.target.key !== request?.key) {
57
- navigationRef.current.target.activationRef.current.dismissed = true;
58
- navigationRef.current.target.activationRef.current.cancelScroll?.();
59
- }
60
- if (!request) {
61
- navigationRef.current = null;
62
- return;
63
- }
64
- if (navigationRef.current?.target.key !== request.key) {
65
- const target: AssistantCitationTarget = {
66
- ...request,
67
- activationRef: { current: { scrolled: false, dismissed: false } },
68
- onComplete: () => {
69
- if (navigationRef.current?.target !== target) return;
70
- navigationRef.current.done = true;
71
- // ChatView's thread-open effect can run after our initial opt-out.
72
- onManualNavigation();
73
- setFinishedKey(target.key);
74
- },
75
- };
76
- navigationRef.current = {
77
- target,
78
- requestedPages: new Set(),
79
- done: false,
80
- };
81
- onManualNavigation();
82
- }
83
- if (!viewport || historyLoading) return;
84
- const navigation = navigationRef.current;
85
- if (navigation.done || navigation.target.activationRef.current.dismissed) return;
86
- const fail = (title: string, description: string) => {
87
- navigation.done = true;
88
- setFinishedKey(navigation.target.key);
89
- toastManager.add({ type: "warning", title, description });
57
+ function createCitationNavigation(next: AssistantCitationRequest): CitationNavigation {
58
+ let done = false;
59
+ const activationRef: AssistantCitationTarget["activationRef"] = {
60
+ current: { scrolled: false, dismissed: false },
61
};
91
- const source = entries.find(
92
- (entry) =>
93
- entry.kind === "message" && entry.message.id === navigation.target.citation.messageId,
94
- );
95
- if (!source) {
96
- if (loadEarlier) {
97
- if (loadEarlier.loading) return;
98
- const cursor = loadEarlier.cursor ?? entries[0]?.id ?? "first";
99
- if (navigation.requestedPages.has(cursor) || navigation.requestedPages.size >= 20) {
100
- fail(
101
- "Could not load the cited response",
102
- "Load earlier turns, then click the citation to try again. Your saved quote is unchanged.",
103
- );
104
- return;
105
- }
106
- navigation.requestedPages.add(cursor);
107
- loadEarlier.onLoadEarlier();
108
- return;
109
- }
110
- fail(
111
- "The cited response is unavailable",
112
- "It may have been removed. The selected text is still saved in your citation.",
113
- );
114
- return;
115
- }
116
- if (source.kind !== "message" || source.message.role !== "assistant") {
117
- fail(
118
- "The citation does not refer to an assistant response",
119
- "The selected text is still saved in your citation.",
120
- );
121
- return;
122
- }
123
- const index = rows.findIndex(
124
- (row) => row.kind === "message" && row.message.id === navigation.target.citation.messageId,
125
- );
126
- if (index < 0) {
127
- const foldRunId = getTurnFoldRunId(source.id);
128
- if (foldRunId) onExpandTurn(foldRunId);
129
- return;
130
- }
131
- if (listLoaded && listRef.current) setReady(navigation.target);
132
- }, [
133
- entries,
134
- getTurnFoldRunId,
135
- historyLoading,
136
- listLoaded,
137
- listRef,
138
- loadEarlier,
139
- onExpandTurn,
140
- onManualNavigation,
141
- request,
142
- rows,
143
- viewport,
144
- ]);
145
-
146
- useEffect(() => {
147
- if (!request) return;
148
- const dismiss = (onlyPending: boolean) => {
149
- const navigation = navigationRef.current;
150
- if (!navigation || navigation.target.key !== request.key) return;
151
- const activation = navigation.target.activationRef.current;
152
- if (activation.dismissed || (onlyPending && (activation.scrolled || navigation.done))) return;
153
- activation.dismissed = true;
154
- activation.cancelScroll?.();
155
- if (!activation.scrolled && !navigation.done) onManualNavigation();
156
- navigation.done = true;
157
- setReady(null);
158
- setFinishedKey(request.key);
62
+ const target: AssistantCitationTarget = {
63
+ ...next,
64
+ activationRef,
65
+ onComplete: () => {
66
+ done = true;
67
+ // The thread-open follow can run after the scroll started.
68
+ onManualNavigation();
69
+ setSettlement({ target, dismissed: false });
70
+ },
71
};
160
- const onKeyDown = (event: KeyboardEvent) => {
161
- if (event.key === "Escape") {
162
- dismiss(false);
163
- } else if (
164
- viewport?.contains(event.target as Node) &&
165
- ["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "].includes(event.key)
166
- ) {
167
- dismiss(true);
168
- }
72
+ const activate = () => {
73
+ // The follow must yield before the citation row starts scrolling.
74
+ if (!done) onManualNavigation();
75
};
170
- const onWheel = (event: WheelEvent) => {
171
- if (event.deltaY !== 0) dismiss(true);
76
+ const retire = () => {
77
+ activationRef.current.dismissed = true;
78
+ activationRef.current.cancelScroll?.();
79
};
173
- const onNavigation = () => dismiss(true);
174
- document.addEventListener("keydown", onKeyDown);
175
- document.addEventListener("pointerdown", onNavigation, true);
176
- viewport?.addEventListener("wheel", onWheel, { passive: true });
177
- viewport?.addEventListener("touchmove", onNavigation, { passive: true });
178
- return () => {
179
- document.removeEventListener("keydown", onKeyDown);
180
- document.removeEventListener("pointerdown", onNavigation, true);
181
- viewport?.removeEventListener("wheel", onWheel);
182
- viewport?.removeEventListener("touchmove", onNavigation);
80
+ const attachDismissal = (citationViewport: HTMLElement | null) => {
81
+ // User navigation stops a pending citation scroll; Escape dismisses it outright.
82
+ const dismiss = (onlyPending: boolean) => {
83
+ const activation = activationRef.current;
84
+ if (activation.dismissed || (onlyPending && (activation.scrolled || done))) return;
85
+ activation.dismissed = true;
86
+ activation.cancelScroll?.();
87
+ if (!activation.scrolled && !done) onManualNavigation();
88
+ done = true;
89
+ setSettlement({ target, dismissed: true });
90
+ };
91
+ const onKeyDown = (event: KeyboardEvent) => {
92
+ if (event.key === "Escape") {
93
+ dismiss(false);
94
+ } else if (
95
+ CITATION_SCROLL_KEYS.has(event.key) &&
96
+ event.target instanceof Node &&
97
+ citationViewport?.contains(event.target)
98
+ ) {
99
+ dismiss(true);
100
+ }
101
+ };
102
+ const onWheel = (event: WheelEvent) => {
103
+ if (event.deltaY !== 0) dismiss(true);
104
+ };
105
+ const onNavigation = () => dismiss(true);
106
+ document.addEventListener("keydown", onKeyDown);
107
+ document.addEventListener("pointerdown", onNavigation, true);
108
+ citationViewport?.addEventListener("wheel", onWheel, { passive: true });
109
+ citationViewport?.addEventListener("touchmove", onNavigation, { passive: true });
110
+ return () => {
111
+ document.removeEventListener("keydown", onKeyDown);
112
+ document.removeEventListener("pointerdown", onNavigation, true);
113
+ citationViewport?.removeEventListener("wheel", onWheel);
114
+ citationViewport?.removeEventListener("touchmove", onNavigation);
115
+ };
116
};
184
- }, [onManualNavigation, request, viewport]);
117
+ return { target, activate, retire, attachDismissal };
118
+ }
119
+
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);
124
+ useEffect(() => {
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]);
133
+
134
+ const settled = current !== null && settlement?.target === current.target ? settlement : null;
135
+ const target =
136
+ current !== null && phase?._tag === "ready" && listLoaded && settled?.dismissed !== true
137
+ ? current.target
138
+ : null;
139
+ const positioning = current !== null && phase?._tag !== "failed" && settled === null;
140
186
- const target = ready?.key === request?.key ? ready : null;
187
- const positioning = request !== null && finishedKey !== request.key;
188
- const sourceRow =
189
- target && positioning
190
- ? rows.find((row) => row.kind === "message" && row.message.id === target.citation.messageId)
191
- : undefined;
141
return {
142
target,
143
positioning,
144
onListLoad,
196
- alwaysRender: sourceRow ? { keys: [sourceRow.id] } : undefined,
145
+ alwaysRender:
146
+ target && positioning && phase?._tag === "ready" ? { keys: [phase.rowId] } : undefined,
147
};
148
}