The best way to control Claude Code, Codex and more from any computer or phone

main
ts 255 lines 9.78 KB
Raw
1 import { useAtomValue } from "@effect/atom-react";
2 import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
3 import { sentMessageFromToolItem } from "@t3tools/shared/toolOutput";
4 import type * as Effect from "effect/Effect";
5 import { Atom, type AtomRegistry } from "effect/reactivity";
6 import { msg } from "gt-react";
7 import { m } from "../../i18n/messages";
8 import type { TimelineEntry } from "../../session-logic";
9 import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
10 import { toastManager } from "../ui/toast";
11 import type { AssistantCitationRequest } from "./AssistantCitationSource";
12 import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
13
14 /** Whether the cited response is in the loaded history, after paging toward it. */
15 export type CitedHistory =
16 | { readonly _tag: "loading" }
17 | { readonly _tag: "found" }
18 | { readonly _tag: "failed" };
19
20 export type CitationPhase =
21 | { readonly _tag: "loading" }
22 | { readonly _tag: "expanding" }
23 | { readonly _tag: "ready"; readonly rowId: string }
24 | { readonly _tag: "failed" };
25
26 export interface CitedThreadSnapshot {
27 readonly message: "assistant" | "other" | null;
28 readonly hasMoreHistory: boolean;
29 readonly loadFailed?: true;
30 }
31
32 export type CitedHistoryOutcome =
33 | { readonly _tag: "found" }
34 | { readonly _tag: "failed"; readonly title: string; readonly description: string }
35 | { readonly _tag: "aborted" };
36
37 type HistoryPageResult = Effect.Success<
38 ReturnType<typeof threadEnvironment.loadEarlierHistory.run>
39 >;
40
41 const MAX_CITATION_PAGES = 20;
42 const HISTORY_COMMAND_LABEL = "load cited thread history";
43 const HISTORY_LOAD_ERROR = "Could not load history.";
44
45 const 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
53 const 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 */
65 export 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 }
91 }
92
93 /** Where the citation stands for the rows the timeline currently shows. */
94 export 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.id === input.messageId),
105 );
106 // The history store can hold the message a render before the entries do.
107 if (!source) return { _tag: "loading" };
108 if (source.kind === "message" && source.message.role !== "assistant") return { _tag: "failed" };
109 const row = input.rows.find(
110 (candidate) =>
111 (candidate.kind === "message" && candidate.message.id === input.messageId) ||
112 (candidate.kind === "sent-message" && candidate.id === input.messageId),
113 );
114 if (row) return { _tag: "ready", rowId: row.id };
115 return { _tag: "expanding" };
116 }
117
118 type ThreadDetail<K extends keyof typeof environmentThreadDetails> = Atom.Type<
119 ReturnType<(typeof environmentThreadDetails)[K]>
120 >;
121
122 /**
123 * The cited thread as `loadCitedHistory` reads it, or null while it is still
124 * settling. A thread that failed to load before any projection arrived counts
125 * as settled, so the citation fails instead of waiting on the stream's retries.
126 */
127 export function citedThreadSnapshot(input: {
128 readonly thread: ThreadDetail<"quietThreadAtom">;
129 readonly history: ThreadDetail<"historyAtom">;
130 readonly status: ThreadDetail<"statusAtom">;
131 readonly error: ThreadDetail<"errorAtom">;
132 readonly messageId: string;
133 }): CitedThreadSnapshot | null {
134 if (input.history.loading) return null;
135 if (input.thread === null) {
136 if (input.status === "deleted") return { message: null, hasMoreHistory: false };
137 return input.error === null ? null : { message: null, hasMoreHistory: false, loadFailed: true };
138 }
139 // Older pages merge into the visible turn items, not the message list.
140 const item = input.thread.projection.visibleTurnItems.find(
141 ({ item }) =>
142 ((item.type === "assistant_message" || item.type === "user_message") &&
143 item.messageId === input.messageId) ||
144 (item.type === "dynamic_tool" &&
145 item.id === input.messageId &&
146 item.status === "completed" &&
147 sentMessageFromToolItem(item) !== undefined),
148 )?.item;
149 return {
150 message: item === undefined ? null : item.type === "user_message" ? "other" : "assistant",
151 hasMoreHistory: input.history.hasMoreHistory,
152 };
153 }
154
155 interface CitedHistoryKey {
156 readonly key: string;
157 readonly environmentId: AssistantCitationRequest["citation"]["environmentId"];
158 readonly threadId: AssistantCitationRequest["citation"]["threadId"];
159 readonly messageId: AssistantCitationRequest["citation"]["messageId"];
160 }
161
162 function waitForSettledThread(
163 registry: AtomRegistry.AtomRegistry,
164 atom: Atom.Atom<CitedThreadSnapshot | null>,
165 signal: AbortSignal,
166 ): Promise<CitedThreadSnapshot | null> {
167 return new Promise((resolve) => {
168 let unsubscribe: (() => void) | null = null;
169 let settled = false;
170 const finish = (value: CitedThreadSnapshot | null) => {
171 if (settled) return;
172 settled = true;
173 unsubscribe?.();
174 signal.removeEventListener("abort", onAbort);
175 resolve(value);
176 };
177 const onAbort = () => finish(null);
178 const check = (value: CitedThreadSnapshot | null) => {
179 if (value !== null) finish(value);
180 };
181 signal.addEventListener("abort", onAbort);
182 unsubscribe = registry.subscribe(atom, check);
183 if (settled) unsubscribe();
184 else check(registry.get(atom));
185 });
186 }
187
188 /**
189 * The citation procedure for one activation (the location key). Mounting it
190 * starts paging; leaving the location unmounts it and the finalizer stops it.
191 * Plain-object keys compare structurally, so one activation is one procedure.
192 */
193 const citedHistoryAtom = Atom.family(
194 ({ key, environmentId, threadId, messageId }: CitedHistoryKey) => {
195 const ref = { environmentId, threadId };
196 const threadAtom = environmentThreadDetails.quietThreadAtom(ref);
197 const historyAtom = environmentThreadDetails.historyAtom(ref);
198 const statusAtom = environmentThreadDetails.statusAtom(ref);
199 const errorAtom = environmentThreadDetails.errorAtom(ref);
200 const settledThreadAtom = Atom.make((get) =>
201 citedThreadSnapshot({
202 thread: get(threadAtom),
203 history: get(historyAtom),
204 status: get(statusAtom),
205 error: get(errorAtom),
206 messageId,
207 }),
208 );
209 return Atom.make((get): CitedHistory => {
210 const controller = new AbortController();
211 get.addFinalizer(() => controller.abort());
212 void loadCitedHistory({
213 signal: controller.signal,
214 readThread: () => waitForSettledThread(get.registry, settledThreadAtom, controller.signal),
215 loadThrough: async () => {
216 const result = await runAtomCommand(
217 get.registry,
218 threadEnvironment.loadEarlierHistory,
219 { environmentId, input: { threadId, throughEntryId: messageId } },
220 { label: HISTORY_COMMAND_LABEL, reportFailure: false },
221 );
222 return result._tag === "Success"
223 ? result.value
224 : { _tag: "error", message: HISTORY_LOAD_ERROR };
225 },
226 }).then((outcome) => {
227 if (outcome._tag === "aborted") return;
228 if (outcome._tag === "failed") {
229 toastManager.add({
230 type: "warning",
231 title: m(outcome.title),
232 description: m(outcome.description),
233 });
234 }
235 get.setSelf({ _tag: outcome._tag });
236 });
237 return { _tag: "loading" };
238 }).pipe(Atom.withLabel(`assistant-citation:history:${key}`));
239 },
240 );
241
242 const NO_CITED_HISTORY_ATOM = Atom.make<CitedHistory>({ _tag: "loading" });
243
244 export function useCitedHistory(request: AssistantCitationRequest | null): CitedHistory {
245 return useAtomValue(
246 request === null
247 ? NO_CITED_HISTORY_ATOM
248 : citedHistoryAtom({
249 key: request.key,
250 environmentId: request.citation.environmentId,
251 threadId: request.citation.threadId,
252 messageId: request.citation.messageId,
253 }),
254 );
255 }