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