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

citationProcedure.ts

259 lines10.1 KB

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