Open History to see the last commit
1import type { LegendListRef } from "@legendapp/list/react";
2import type { RunId } from "@t3tools/contracts";
3import { useEffect, useRef, useState, type RefObject } from "react";
4import type { TimelineEntry } from "../../session-logic";
5import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
6import type { AssistantCitationRequest, AssistantCitationTarget } from "./AssistantCitationSource";
7import { toastManager } from "../ui/toast";
8
9export interface CitationHistoryPage {
10 readonly loading: boolean;
11 readonly cursor?: string | null;
12 readonly onLoadEarlier: () => void;
13}
14
15export function useAssistantCitationTarget({
16 request,
17 entries,
18 rows,
19 listRef,
20 viewport,
21 historyLoading,
22 loadEarlier,
23 getTurnFoldRunId,
24 onExpandTurn,
25 onManualNavigation,
26}: {
27 request: AssistantCitationRequest | null;
28 entries: ReadonlyArray<TimelineEntry>;
29 rows: ReadonlyArray<MessagesTimelineRow>;
30 listRef: RefObject<LegendListRef | null>;
31 viewport: HTMLElement | null;
32 historyLoading: boolean;
33 loadEarlier: CitationHistoryPage | null;
34 getTurnFoldRunId: (entryId: string) => RunId | undefined;
35 onExpandTurn: (runId: RunId) => void;
36 onManualNavigation: () => void;
37}) {
38 const [ready, setReady] = useState<AssistantCitationTarget | null>(null);
39 const [finishedKey, setFinishedKey] = useState<string | null>(null);
40 const [listLoaded, setListLoaded] = useState(false);
41 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);
50 }
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 });
90 };
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);
159 };
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 }
169 };
170 const onWheel = (event: WheelEvent) => {
171 if (event.deltaY !== 0) dismiss(true);
172 };
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);
183 };
184 }, [onManualNavigation, request, viewport]);
185
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;
192 return {
193 target,
194 positioning,
195 onListLoad,
196 alwaysRender: sourceRow ? { keys: [sourceRow.id] } : undefined,
197 };
198}