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

citationProcedure.ts

258 lines9.7 KB

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