Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { type AtomCommandSuccess, runAtomCommand } from "@t3tools/client-runtime/state/runtime";
3import { Atom, type AtomRegistry } from "effect/reactivity";
4import type { TimelineEntry } from "../../session-logic";
5import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
6import { toastManager } from "../ui/toast";
7import type { AssistantCitationRequest } from "./AssistantCitationSource";
8import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
9
10/** Whether the cited response is in the loaded history, after paging toward it. */
11export type CitedHistory =
12 | { readonly _tag: "loading" }
13 | { readonly _tag: "found" }
14 | { readonly _tag: "failed" };
15
16export type CitationPhase =
17 | { readonly _tag: "loading" }
18 | { readonly _tag: "expanding" }
19 | { readonly _tag: "ready"; readonly rowId: string }
20 | { readonly _tag: "failed" };
21
22export interface CitedThreadSnapshot {
23 readonly message: "assistant" | "other" | null;
24 readonly hasMoreHistory: boolean;
25 readonly loadFailed?: true;
26}
27
28export type CitedHistoryOutcome =
29 | { readonly _tag: "found" }
30 | { readonly _tag: "failed"; readonly title: string; readonly description: string }
31 | { readonly _tag: "aborted" };
32
33type HistoryPageResult = AtomCommandSuccess<
34 Awaited<ReturnType<typeof threadEnvironment.loadEarlierHistory.run>>
35>;
36
37const MAX_CITATION_PAGES = 20;
38
39const 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
46const 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 */
58export 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. */
87export 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
107type 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 */
116export 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
140interface 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
147function 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 */
178const 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
227const NO_CITED_HISTORY_ATOM = Atom.make<CitedHistory>({ _tag: "loading" });
228
229export 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}