Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useAssistantCitationTarget.ts

199 lines6.8 KB

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;
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 // A target belongs to one request, so returning to an earlier key never reuses it.
49 if (ready !== null && ready.key !== request?.key) {
50 setReady(null);
51 }
52 if (!request && finishedKey !== null) {
53 setFinishedKey(null);
54 }
55​
56 useEffect(() => {
57 if (navigationRef.current && navigationRef.current.target.key !== request?.key) {
58 navigationRef.current.target.activationRef.current.dismissed = true;
59 navigationRef.current.target.activationRef.current.cancelScroll?.();
60 }
61 if (!request) {
62 navigationRef.current = null;
63 return;
64 }
65 if (navigationRef.current?.target.key !== request.key) {
66 const target: AssistantCitationTarget = {
67 ...request,
68 activationRef: { current: { scrolled: false, dismissed: false } },
69 onComplete: () => {
70 if (navigationRef.current?.target !== target) return;
71 navigationRef.current.done = true;
72 // ChatView's thread-open effect can run after our initial opt-out.
73 onManualNavigation();
74 setFinishedKey(target.key);
75 },
76 };
77 navigationRef.current = {
78 target,
79 requestedPages: new Set(),
80 done: false,
81 };
82 onManualNavigation();
83 }
84 if (!viewport || historyLoading) return;
85 const navigation = navigationRef.current;
86 if (navigation.done || navigation.target.activationRef.current.dismissed) return;
87 const fail = (title: string, description: string) => {
88 navigation.done = true;
89 setFinishedKey(navigation.target.key);
90 toastManager.add({ type: "warning", title, description });
91 };
92 const source = entries.find(
93 (entry) =>
94 entry.kind === "message" && entry.message.id === navigation.target.citation.messageId,
95 );
96 if (!source) {
97 if (loadEarlier) {
98 if (loadEarlier.loading) return;
99 const cursor = loadEarlier.cursor ?? entries[0]?.id ?? "first";
100 if (navigation.requestedPages.has(cursor) || navigation.requestedPages.size >= 20) {
101 fail(
102 "Could not load the cited response",
103 "Load earlier turns, then click the citation to try again. Your saved quote is unchanged.",
104 );
105 return;
106 }
107 navigation.requestedPages.add(cursor);
108 loadEarlier.onLoadEarlier();
109 return;
110 }
111 fail(
112 "The cited response is unavailable",
113 "It may have been removed. The selected text is still saved in your citation.",
114 );
115 return;
116 }
117 if (source.kind !== "message" || source.message.role !== "assistant") {
118 fail(
119 "The citation does not refer to an assistant response",
120 "The selected text is still saved in your citation.",
121 );
122 return;
123 }
124 const index = rows.findIndex(
125 (row) => row.kind === "message" && row.message.id === navigation.target.citation.messageId,
126 );
127 if (index < 0) {
128 const foldRunId = getTurnFoldRunId(source.id);
129 if (foldRunId) onExpandTurn(foldRunId);
130 return;
131 }
132 if (listLoaded && listRef.current) setReady(navigation.target);
133 }, [
134 entries,
135 getTurnFoldRunId,
136 historyLoading,
137 listLoaded,
138 listRef,
139 loadEarlier,
140 onExpandTurn,
141 onManualNavigation,
142 request,
143 rows,
144 viewport,
145 ]);
146​
147 useEffect(() => {
148 if (!request) return;
149 const dismiss = (onlyPending: boolean) => {
150 const navigation = navigationRef.current;
151 if (!navigation || navigation.target.key !== request.key) return;
152 const activation = navigation.target.activationRef.current;
153 if (activation.dismissed || (onlyPending && (activation.scrolled || navigation.done))) return;
154 activation.dismissed = true;
155 activation.cancelScroll?.();
156 if (!activation.scrolled && !navigation.done) onManualNavigation();
157 navigation.done = true;
158 setReady(null);
159 setFinishedKey(request.key);
160 };
161 const onKeyDown = (event: KeyboardEvent) => {
162 if (event.key === "Escape") {
163 dismiss(false);
164 } else if (
165 viewport?.contains(event.target as Node) &&
166 ["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "].includes(event.key)
167 ) {
168 dismiss(true);
169 }
170 };
171 const onWheel = (event: WheelEvent) => {
172 if (event.deltaY !== 0) dismiss(true);
173 };
174 const onNavigation = () => dismiss(true);
175 document.addEventListener("keydown", onKeyDown);
176 document.addEventListener("pointerdown", onNavigation, true);
177 viewport?.addEventListener("wheel", onWheel, { passive: true });
178 viewport?.addEventListener("touchmove", onNavigation, { passive: true });
179 return () => {
180 document.removeEventListener("keydown", onKeyDown);
181 document.removeEventListener("pointerdown", onNavigation, true);
182 viewport?.removeEventListener("wheel", onWheel);
183 viewport?.removeEventListener("touchmove", onNavigation);
184 };
185 }, [onManualNavigation, request, viewport]);
186​
187 const target = ready?.key === request?.key ? ready : null;
188 const positioning = request !== null && finishedKey !== request.key;
189 const sourceRow =
190 target && positioning
191 ? rows.find((row) => row.kind === "message" && row.message.id === target.citation.messageId)
192 : undefined;
193 return {
194 target,
195 positioning,
196 onListLoad,
197 alwaysRender: sourceRow ? { keys: [sourceRow.id] } : undefined,
198 };