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

citationProcedure.ts

254 lines9.8 KB

1import { useAtomValue } from "@effect/atom-react";
2import { type AtomCommandSuccess, runAtomCommand } from "@t3tools/client-runtime/state/runtime";
3import { sentMessageFromToolItem } from "@t3tools/shared/toolOutput";
4import { Atom, type AtomRegistry } from "effect/reactivity";
5import { msg } from "gt-react";
6import { m } from "../../i18n/messages";
7import type { TimelineEntry } from "../../session-logic";
8import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
9import { toastManager } from "../ui/toast";
10import type { AssistantCitationRequest } from "./AssistantCitationSource";
11import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
12​
13/** Whether the cited response is in the loaded history, after paging toward it. */
14export type CitedHistory =
15 | { readonly _tag: "loading" }
16 | { readonly _tag: "found" }
17 | { readonly _tag: "failed" };
18​
19export type CitationPhase =
20 | { readonly _tag: "loading" }
21 | { readonly _tag: "expanding" }
22 | { readonly _tag: "ready"; readonly rowId: string }
23 | { readonly _tag: "failed" };
24​
25export interface CitedThreadSnapshot {
26 readonly message: "assistant" | "other" | null;
27 readonly hasMoreHistory: boolean;
28 readonly loadFailed?: true;
30​
31export type CitedHistoryOutcome =
32 | { readonly _tag: "found" }
33 | { readonly _tag: "failed"; readonly title: string; readonly description: string }
34 | { readonly _tag: "aborted" };
35​
36type HistoryPageResult = AtomCommandSuccess<
37 Awaited<ReturnType<typeof threadEnvironment.loadEarlierHistory.run>>
38>;
39​
40const MAX_CITATION_PAGES = 20;
41const HISTORY_COMMAND_LABEL = "load cited thread history";
42const HISTORY_LOAD_ERROR = "Could not load history.";
43​
44const COULD_NOT_LOAD = {
45 _tag: "failed",
46 title: msg("Could not load the cited response"),
47 description: msg(
48 "Load earlier turns, then click the citation to try again. Your saved quote is unchanged.",
49 ),
50} as const;
51​
52const UNAVAILABLE = {
53 _tag: "failed",
54 title: msg("The cited response is unavailable"),
55 description: msg("It may have been removed. The selected text is still saved in your citation."),
56} as const;
57​
58/**
59 * Pages history toward the cited message until it is loaded, the thread runs
60 * out of history, or loading fails. `readThread` resolves once the thread
61 * detail is settled (loaded and no history page in flight), or with null when
62 * the signal aborts.
63 */
64export async function loadCitedHistory(input: {
65 readonly signal: AbortSignal;
66 readonly readThread: () => Promise<CitedThreadSnapshot | null>;
67 readonly loadThrough: () => Promise<HistoryPageResult>;
68}): Promise<CitedHistoryOutcome> {
69 for (let attempts = 0; ; attempts += 1) {
70 const thread = await input.readThread();
71 if (thread === null || input.signal.aborted) return { _tag: "aborted" };
72 if (thread.loadFailed) return COULD_NOT_LOAD;
73 if (thread.message === "assistant") return { _tag: "found" };
74 if (thread.message === "other") {
75 return {
76 _tag: "failed",
77 title: msg("The citation does not refer to an assistant response"),
78 description: msg("The selected text is still saved in your citation."),
79 };
80 }
81 if (!thread.hasMoreHistory) return UNAVAILABLE;
82 if (attempts >= MAX_CITATION_PAGES) return COULD_NOT_LOAD;
83 const result = await input.loadThrough();
84 if (input.signal.aborted) return { _tag: "aborted" };
85 if (result._tag === "error") return COULD_NOT_LOAD;
86 // A noop page means the store has nothing older to load (no cursor, or the
87 // thread is gone), so re-reading would only spin on the same snapshot.
88 if (result._tag === "noop") return UNAVAILABLE;
89 }
91​
92/** Where the citation stands for the rows the timeline currently shows. */
93export function resolveCitationPhase(input: {
94 readonly history: CitedHistory;
95 readonly messageId: string;
96 readonly entries: ReadonlyArray<TimelineEntry>;
97 readonly rows: ReadonlyArray<MessagesTimelineRow>;
98}): CitationPhase {
99 if (input.history._tag === "failed") return { _tag: "failed" };
100 const source = input.entries.find(
101 (entry) =>
102 (entry.kind === "message" && entry.message.id === input.messageId) ||
103 (entry.kind === "sent-message" && entry.id === input.messageId),
104 );
105 // The history store can hold the message a render before the entries do.
106 if (!source) return { _tag: "loading" };
107 if (source.kind === "message" && source.message.role !== "assistant") return { _tag: "failed" };
108 const row = input.rows.find(
109 (candidate) =>
110 (candidate.kind === "message" && candidate.message.id === input.messageId) ||
111 (candidate.kind === "sent-message" && candidate.id === input.messageId),
112 );
113 if (row) return { _tag: "ready", rowId: row.id };
114 return { _tag: "expanding" };
116​
117type ThreadDetail<K extends keyof typeof environmentThreadDetails> = Atom.Type<
118 ReturnType<(typeof environmentThreadDetails)[K]>
119>;
120​
121/**
122 * The cited thread as `loadCitedHistory` reads it, or null while it is still
123 * settling. A thread that failed to load before any projection arrived counts
124 * as settled, so the citation fails instead of waiting on the stream's retries.
125 */
126export function citedThreadSnapshot(input: {
127 readonly thread: ThreadDetail<"quietThreadAtom">;
128 readonly history: ThreadDetail<"historyAtom">;
129 readonly status: ThreadDetail<"statusAtom">;
130 readonly error: ThreadDetail<"errorAtom">;
131 readonly messageId: string;
132}): CitedThreadSnapshot | null {
133 if (input.history.loading) return null;
134 if (input.thread === null) {
135 if (input.status === "deleted") return { message: null, hasMoreHistory: false };
136 return input.error === null ? null : { message: null, hasMoreHistory: false, loadFailed: true };
137 }
138 // Older pages merge into the visible turn items, not the message list.
139 const item = input.thread.projection.visibleTurnItems.find(
140 ({ item }) =>
141 ((item.type === "assistant_message" || item.type === "user_message") &&
142 item.messageId === input.messageId) ||
143 (item.type === "dynamic_tool" &&
144 item.id === input.messageId &&
145 item.status === "completed" &&
146 sentMessageFromToolItem(item) !== undefined),
147 )?.item;
148 return {
149 message: item === undefined ? null : item.type === "user_message" ? "other" : "assistant",
150 hasMoreHistory: input.history.hasMoreHistory,
151 };
153​
154interface CitedHistoryKey {
155 readonly key: string;
156 readonly environmentId: AssistantCitationRequest["citation"]["environmentId"];
157 readonly threadId: AssistantCitationRequest["citation"]["threadId"];
158 readonly messageId: AssistantCitationRequest["citation"]["messageId"];
160​
161function waitForSettledThread(
162 registry: AtomRegistry.AtomRegistry,
163 atom: Atom.Atom<CitedThreadSnapshot | null>,
164 signal: AbortSignal,
165): Promise<CitedThreadSnapshot | null> {
166 return new Promise((resolve) => {
167 let unsubscribe: (() => void) | null = null;
168 let settled = false;
169 const finish = (value: CitedThreadSnapshot | null) => {
170 if (settled) return;
171 settled = true;
172 unsubscribe?.();
173 signal.removeEventListener("abort", onAbort);
174 resolve(value);
175 };
176 const onAbort = () => finish(null);
177 const check = (value: CitedThreadSnapshot | null) => {
178 if (value !== null) finish(value);
179 };
180 signal.addEventListener("abort", onAbort);
181 unsubscribe = registry.subscribe(atom, check);
182 if (settled) unsubscribe();
183 else check(registry.get(atom));
184 });
186​
187/**
188 * The citation procedure for one activation (the location key). Mounting it
189 * starts paging; leaving the location unmounts it and the finalizer stops it.
190 * Plain-object keys compare structurally, so one activation is one procedure.
191 */
192const citedHistoryAtom = Atom.family(
193 ({ key, environmentId, threadId, messageId }: CitedHistoryKey) => {
194 const ref = { environmentId, threadId };
195 const threadAtom = environmentThreadDetails.quietThreadAtom(ref);
196 const historyAtom = environmentThreadDetails.historyAtom(ref);
197 const statusAtom = environmentThreadDetails.statusAtom(ref);
198 const errorAtom = environmentThreadDetails.errorAtom(ref);
199 const settledThreadAtom = Atom.make((get) =>
200 citedThreadSnapshot({
201 thread: get(threadAtom),
202 history: get(historyAtom),
203 status: get(statusAtom),
204 error: get(errorAtom),
205 messageId,
206 }),
207 );
208 return Atom.make((get): CitedHistory => {
209 const controller = new AbortController();
210 get.addFinalizer(() => controller.abort());
211 void loadCitedHistory({
212 signal: controller.signal,
213 readThread: () => waitForSettledThread(get.registry, settledThreadAtom, controller.signal),
214 loadThrough: async () => {
215 const result = await runAtomCommand(
216 get.registry,
217 threadEnvironment.loadEarlierHistory,
218 { environmentId, input: { threadId, throughEntryId: messageId } },
219 { label: HISTORY_COMMAND_LABEL, reportFailure: false },
220 );
221 return result._tag === "Success"
222 ? result.value
223 : { _tag: "error", message: HISTORY_LOAD_ERROR };
224 },
225 }).then((outcome) => {
226 if (outcome._tag === "aborted") return;
227 if (outcome._tag === "failed") {
228 toastManager.add({
229 type: "warning",
230 title: m(outcome.title),
231 description: m(outcome.description),
232 });
233 }
234 get.setSelf({ _tag: outcome._tag });
235 });
236 return { _tag: "loading" };
237 }).pipe(Atom.withLabel(`assistant-citation:history:${key}`));
238 },
239);
240​
241const NO_CITED_HISTORY_ATOM = Atom.make<CitedHistory>({ _tag: "loading" });
242​
243export function useCitedHistory(request: AssistantCitationRequest | null): CitedHistory {
244 return useAtomValue(
245 request === null
246 ? NO_CITED_HISTORY_ATOM
247 : citedHistoryAtom({
248 key: request.key,
249 environmentId: request.citation.environmentId,
250 threadId: request.citation.threadId,
251 messageId: request.citation.messageId,
252 }),
253 );