Open History to see the last commit
1import {
2 CommandId,
3 type EnvironmentId,
4 type ModelSelection,
5 type ProviderInteractionMode,
6 type ScopedThreadRef,
7 type ThreadId,
8 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
9} from "@t3tools/contracts";
10import {
11 wasBootstrapThreadDeleted,
12 wasBootstrapThreadNotCreated,
13} from "@t3tools/client-runtime/errors";
14import { Atom } from "effect/reactivity";
15import {
16 squashAtomCommandFailure,
17 type AtomCommandResult,
18} from "@t3tools/client-runtime/state/runtime";
19import { readLocalApi } from "../../localApi";
20import { getUploadedAttachments } from "../../lib/attachmentUploadQueue";
21import { findRevertCheckpoint } from "../../session-logic";
22import { type ChatMessage } from "../../types";
23import { randomUUID } from "~/lib/utils";
24import { stackedThreadToast, toastManager } from "../ui/toast";
25import { newThreadId } from "~/lib/utils";
26import {
27 type ComposerFileAttachment,
28 type ComposerImageAttachment,
29 useComposerDraftStore,
30 DraftId,
31} from "../../composerDraftStore";
32import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
33import { createModelSelection } from "@t3tools/shared/model";
34import type { ProviderInstanceEntry } from "../../providerInstances";
35import { getComposerPromptInjectionState, getComposerProviderState } from "./composerProviderState";
36import {
37 formatOutgoingPrompt,
38 getAntigravitySendBlockReason,
39 resolveComposerInteractionMode,
40 cloneComposerImageForRetry,
41 type ComposerSendSnapshot,
42 readFileAsDataUrl,
43 prepareRevertedMessageAttachments,
44 waitForRevertedMessage,
45} from "../ChatView.logic";
46import { readPreparedConnection } from "../../state/session";
47import { recallableComposerPrompt } from "./composerPromptHistory";
48
49// Kept per route so a send in flight, and the multiple-model selections, survive
50// ChatView remounting while the user navigates.
51export const draftFanoutSelectionsAtom = Atom.family((_routeKey: string) =>
52 Atom.make<ReadonlyArray<ModelSelection> | null>(null).pipe(Atom.keepAlive),
53);
54const draftSendStateByRouteKey = new Map<
55 string,
56 {
57 readonly sendInFlight: { current: boolean };
58 readonly uncertainSubmissions: { current: Map<string, ThreadId> };
59 }
60>();
61export function draftSendState(routeKey: string) {
62 let state = draftSendStateByRouteKey.get(routeKey);
63 if (!state) {
64 state = { sendInFlight: { current: false }, uncertainSubmissions: { current: new Map() } };
65 draftSendStateByRouteKey.set(routeKey, state);
66 }
67 return state;
68}
69
70/**
71 * Starts one thread of a multiple-model send. A request that may have
72 * reached the server before failing is remembered by `retryKey`, so sending
73 * again cannot silently create a duplicate thread; its failure toast offers
74 * to open that thread or to allow the retry.
75 */
76export async function startFanoutThread(input: {
77 readonly retryKey: string;
78 readonly model: string;
79 readonly uncertainSubmissions: Map<string, ThreadId>;
80 readonly start: (threadId: ThreadId) => Promise<AtomCommandResult<unknown, unknown>>;
81 readonly openThread: (threadId: ThreadId) => void;
82}): Promise<boolean> {
83 const { retryKey, uncertainSubmissions } = input;
84 const uncertainThreadId = uncertainSubmissions.get(retryKey);
85 const targetThreadId = uncertainThreadId ?? newThreadId();
86 let requestMayHaveStarted = false;
87 try {
88 if (uncertainThreadId) {
89 throw new Error(
90 "The previous request may have started. Open its thread to check before sending again.",
91 );
92 }
93 requestMayHaveStarted = true;
94 const result = await input.start(targetThreadId);
95 if (result._tag === "Failure") {
96 const error = squashAtomCommandFailure(result);
97 if (wasBootstrapThreadDeleted(error) || wasBootstrapThreadNotCreated(error)) {
98 requestMayHaveStarted = false;
99 }
100 throw error;
101 }
102 return true;
103 } catch (error) {
104 if (requestMayHaveStarted && !uncertainSubmissions.has(retryKey)) {
105 uncertainSubmissions.set(retryKey, targetThreadId);
106 }
107 const retainedThreadId = uncertainSubmissions.get(retryKey);
108 const failureToastId = toastManager.add(
109 stackedThreadToast({
110 type: "error",
111 title: `Could not start ${input.model}`,
112 description: error instanceof Error ? error.message : "Failed to send message.",
113 ...(retainedThreadId
114 ? {
115 timeout: 0,
116 data: {
117 secondaryActionProps: {
118 children: "Allow retry",
119 onClick: () => {
120 void readLocalApi()
121 ?.dialogs.confirm(
122 "The previous request may already be running. Check its thread first. Allow another send that could create a duplicate thread?",
123 )
124 .then(
125 (confirmed) => {
126 if (
127 confirmed &&
128 uncertainSubmissions.get(retryKey) === retainedThreadId
129 ) {
130 uncertainSubmissions.delete(retryKey);
131 toastManager.close(failureToastId);
132 }
133 },
134 () => undefined,
135 );
136 },
137 },
138 },
139 actionProps: {
140 children: "Open thread",
141 onClick: () => input.openThread(retainedThreadId),
142 },
143 }
144 : {}),
145 }),
146 );
147 return false;
148 }
149}
150
151/**
152 * Reverts the thread to before `message` and puts that message's text and
153 * attachments back in the composer draft. Returns the restored prompt, or the
154 * error to show; on error the draft is untouched.
155 */
156export async function rewindToMessage(input: {
157 readonly message: ChatMessage;
158 readonly environmentId: EnvironmentId;
159 readonly routeThreadRef: ScopedThreadRef;
160 readonly threadId: ThreadId;
161 readonly turnCount: number;
162 readonly restoreFiles: boolean;
163 readonly checkpoint: ReturnType<typeof findRevertCheckpoint>;
164 readonly draftTarget: ScopedThreadRef | DraftId;
165 readonly composerHasPendingAttachments: boolean;
166 readonly createAssetUrl: Parameters<
167 typeof prepareRevertedMessageAttachments
168 >[0]["createAssetUrl"];
169 readonly revertThreadCheckpoint: (value: {
170 environmentId: EnvironmentId;
171 input: {
172 commandId: CommandId;
173 threadId: ThreadId;
174 turnCount: number;
175 restoreFiles: boolean;
176 checkpointId?: string;
177 scopeId?: string;
178 };
179 }) => Promise<AtomCommandResult<unknown, unknown>>;
180}): Promise<
181 | { readonly error: string; readonly prompt?: never }
182 | { readonly error: null; readonly prompt: string }
183> {
184 const { message, environmentId, draftTarget } = input;
185 try {
186 if (input.composerHasPendingAttachments) {
187 throw new Error("Wait for attachments to finish preparing before rewinding.");
188 }
189 const connection = readPreparedConnection(environmentId);
190 if (!connection) throw new Error("The environment is not connected.");
191 const files = await prepareRevertedMessageAttachments({
192 message,
193 environmentId,
194 httpBaseUrl: connection.httpBaseUrl,
195 createAssetUrl: input.createAssetUrl,
196 });
197 const store = useComposerDraftStore.getState();
198 const draft = store.getComposerDraft(draftTarget);
199 if (
200 (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + files.length >
201 PROVIDER_SEND_TURN_MAX_ATTACHMENTS
202 ) {
203 throw new Error("Make room for this message's attachments in the composer before rewinding.");
204 }
205 const commandId = CommandId.make(randomUUID());
206 await waitForRevertedMessage(input.routeThreadRef, input.turnCount, commandId, async () => {
207 const result = await input.revertThreadCheckpoint({
208 environmentId,
209 input: {
210 commandId,
211 threadId: input.threadId,
212 turnCount: input.turnCount,
213 restoreFiles: input.restoreFiles,
214 ...(input.checkpoint === undefined
215 ? {}
216 : { checkpointId: input.checkpoint.id, scopeId: input.checkpoint.scopeId }),
217 },
218 });
219 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
220 });
221 const currentPrompt = store.getComposerDraft(draftTarget)?.prompt ?? "";
222 const restoredPrompt = recallableComposerPrompt(message.text);
223 const nextPrompt =
224 restoredPrompt.length === 0
225 ? currentPrompt
226 : currentPrompt.length > 0
227 ? `${currentPrompt}\n\n${restoredPrompt}`
228 : restoredPrompt;
229 store.setPrompt(draftTarget, nextPrompt);
230 const images: ComposerImageAttachment[] = [];
231 const restoredFiles: ComposerFileAttachment[] = [];
232 files.forEach((file, index) => {
233 const attachment = {
234 id: randomUUID(),
235 name: file.name,
236 mimeType: file.type,
237 sizeBytes: file.size,
238 file,
239 };
240 if (message.attachments?.[index]?.type === "image") {
241 images.push({ ...attachment, type: "image", previewUrl: URL.createObjectURL(file) });
242 } else {
243 restoredFiles.push({ ...attachment, type: "file" });
244 }
245 });
246 store.addImages(draftTarget, images, { allowDuplicates: true });
247 store.addFiles(draftTarget, restoredFiles, { allowDuplicates: true });
248 return { error: null, prompt: nextPrompt };
249 } catch (error) {
250 return { error: error instanceof Error ? error.message : "Failed to revert thread state." };
251 }
252}
253
254/**
255 * Writes a failed send's composer contents back into its draft. Returns the
256 * restored images, which are fresh copies so their preview URLs outlive the
257 * optimistic row that held the originals.
258 */
259export function restoreComposerDraft(
260 draftTarget: ScopedThreadRef | DraftId,
261 snapshot: ComposerSendSnapshot,
262): ComposerImageAttachment[] {
263 const store = useComposerDraftStore.getState();
264 const images = snapshot.images.map(cloneComposerImageForRetry);
265 store.setPrompt(draftTarget, snapshot.messageText);
266 store.addImages(draftTarget, images);
267 store.addFiles(draftTarget, snapshot.files);
268 store.setTerminalContexts(draftTarget, snapshot.terminalContexts);
269 store.setPreviewAnnotations(draftTarget, snapshot.previewAnnotations);
270 store.setReviewComments(draftTarget, snapshot.reviewComments);
271 store.setThreadContexts(draftTarget, snapshot.threadContexts);
272 return images;
273}
274
275export interface MultipleModelTarget {
276 readonly selection: ModelSelection;
277 readonly text: string;
278 readonly interactionMode: ProviderInteractionMode;
279}
280
281/**
282 * The thread each selected model starts for a multiple-model send, in
283 * selection order, or why that model cannot take the message.
284 */
285export function resolveMultipleModelTargets(input: {
286 readonly selections: ReadonlyArray<ModelSelection>;
287 readonly providerInstanceEntries: ReadonlyArray<ProviderInstanceEntry>;
288 readonly messageText: string;
289 readonly planModeEnabled: boolean;
290 readonly interactionMode: ProviderInteractionMode;
291}): Array<MultipleModelTarget | { readonly error: string }> {
292 const { messageText, planModeEnabled } = input;
293 return input.selections.map((selection) => {
294 const provider = input.providerInstanceEntries.find(
295 (entry) => entry.instanceId === selection.instanceId,
296 );
297 if (!provider?.enabled || !provider.isAvailable || provider.status !== "ready") {
298 return { error: `Provider for ${selection.model} is unavailable.` };
299 }
300 const providerBlockReason = getAntigravitySendBlockReason(provider.snapshot, selection.model);
301 if (providerBlockReason) return { error: providerBlockReason };
302 const providerState = getComposerProviderState({
303 provider: provider.driverKind,
304 model: selection.model,
305 models: provider.models,
306 modelOptions: selection.options,
307 promptInjectionState: getComposerPromptInjectionState(messageText),
308 planModeEnabled,
309 });
310 return {
311 selection: createModelSelection(
312 selection.instanceId,
313 selection.model,
314 providerState.modelOptionsForDispatch,
315 ),
316 text: formatOutgoingPrompt({
317 provider: provider.driverKind,
318 model: selection.model,
319 models: provider.models,
320 effort: providerState.promptEffort,
321 text: messageText || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
322 }),
323 interactionMode: resolveComposerInteractionMode({
324 planModeEnabled,
325 provider: provider.snapshot,
326 interactionMode: input.interactionMode,
327 }).interactionMode,
328 };
329 });
330}
331
332/**
333 * The attachments a turn sends: the server's upload records when it takes uploads, otherwise
334 * images inlined as data URLs. Rejects when an attachment cannot go out.
335 */
336export function prepareTurnAttachments(input: {
337 readonly environmentId: EnvironmentId;
338 readonly attachments: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>;
339 readonly usesAttachmentUploads: boolean;
340}) {
341 const { environmentId, usesAttachmentUploads } = input;
342 return Promise.all(
343 input.attachments.map(async (attachment) => {
344 if (usesAttachmentUploads) {
345 const uploaded = getUploadedAttachments({ environmentId, images: [attachment] })?.[0];
346 if (!uploaded) {
347 throw new Error(`Attachment '${attachment.name}' did not finish uploading.`);
348 }
349 return uploaded;
350 }
351 if (attachment.type !== "image") {
352 throw new Error("This server does not support file attachments.");
353 }
354 return {
355 type: "image" as const,
356 id: attachment.id,
357 name: attachment.name,
358 mimeType: attachment.mimeType,
359 sizeBytes: attachment.sizeBytes,
360 dataUrl: await readFileAsDataUrl(attachment.file),
361 ...(attachment.source ? { source: attachment.source } : {}),
362 };
363 }),
364 );
365}