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 } 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}", { 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(
248 "{count, plural, one {{repositories} had no snapshot from before these turns, so it keeps the changes. Check the uncommitted changes there.} other {{repositories} had no snapshot from before these turns, so they keep the changes. Check the uncommitted changes there.}}",
249 { repositories: unrestored.join(", "), count: unrestored.length },
250 ),
251 ),
252 });
253 }
254 const images: ComposerImageAttachment[] = [];
255 const restoredFiles: ComposerFileAttachment[] = [];
256 const chipsByAttachmentId = new Map<string, string>();
257 files.forEach((file, index) => {
258 const attachment = {
259 id: randomUUID(),
260 name: file.name,
261 mimeType: file.type,
262 sizeBytes: file.size,
263 file,
264 };
265 const original = message.attachments?.[index];
266 let reference;
267 if (original?.type === "image") {
268 const image = {
269 ...attachment,
270 type: "image" as const,
271 previewUrl: URL.createObjectURL(file),
272 };
273 images.push(image);
274 reference = imageContextReference(image);
275 } else {
276 const restoredFile = { ...attachment, type: "file" as const };
277 restoredFiles.push(restoredFile);
278 reference = fileContextReference(restoredFile);
279 }
280 if (original) chipsByAttachmentId.set(original.id, formatInlineContextReference(reference));
281 });
282 // The sent text names attachments by their old chip ids; point those chips at the copies.
283 const attachmentChips = new Map(
284 (message.context?.records ?? []).flatMap((record) => {
285 const chip =
286 (record.kind === "image" || record.kind === "file") && "attachmentId" in record
287 ? chipsByAttachmentId.get(record.attachmentId)
288 : undefined;
289 return chip === undefined ? [] : [[record.contextId, chip] as const];
290 }),
291 );
292 const currentPrompt = store.getComposerDraft(draftTarget)?.prompt ?? "";
293 const { prompt: restoredPrompt, mentions } = recallComposerMessage(message, attachmentChips);
294 const nextPrompt =
295 restoredPrompt.length === 0
296 ? currentPrompt
297 : currentPrompt.length > 0
298 ? `${currentPrompt}\n\n${restoredPrompt}`
299 : restoredPrompt;
300 store.setPrompt(draftTarget, nextPrompt);
301 // The restored prompt already carries the chips; these add only their records.
302 store.addThreadContexts(draftTarget, mentions.threadContexts, { appendReference: false });
303 store.addEnvironmentContexts(draftTarget, mentions.environmentContexts, {
304 appendReference: false,
305 });
306 store.addImages(draftTarget, images, { allowDuplicates: true });
307 store.addFiles(draftTarget, restoredFiles, { allowDuplicates: true });
308 return { error: null, prompt: nextPrompt };
309 } catch (error) {
310 return {
311 error: error instanceof Error ? error.message : m(msg("Failed to revert thread state.")),
312 };
313 }
314}
315
316function withRestored<T>(
317 existing: ReadonlyArray<T> | undefined,
318 restored: ReadonlyArray<T>,
319 key: (item: T) => string,
320): T[] {
321 const kept = existing ?? [];
322 return [...kept, ...restored.filter((item) => !kept.some((other) => key(other) === key(item)))];
323}
324
325/**
326 * Writes a failed send's composer contents back into its draft, after anything
327 * typed since. Returns the restored images, which are fresh copies so their
328 * preview URLs outlive the optimistic row that held the originals.
329 */
330export function restoreComposerDraft(
331 draftTarget: ScopedThreadRef | DraftId,
332 snapshot: ComposerSendSnapshot,
333): ComposerImageAttachment[] {
334 const store = useComposerDraftStore.getState();
335 const current = store.getComposerDraft(draftTarget);
336 const images = snapshot.images.map(cloneComposerImageForRetry);
337 store.setPrompt(
338 draftTarget,
339 current?.prompt.trim() ? `${current.prompt}\n\n${snapshot.draftText}` : snapshot.draftText,
340 );
341 store.setReplyTo(draftTarget, current?.replyTo ?? snapshot.replyTo);
342 store.addImages(draftTarget, images);
343 store.addFiles(draftTarget, snapshot.files);
344 store.setTerminalContexts(
345 draftTarget,
346 withRestored(current?.terminalContexts, snapshot.terminalContexts, (context) => context.id),
347 );
348 store.setPreviewAnnotations(
349 draftTarget,
350 withRestored(current?.previewAnnotations, snapshot.previewAnnotations, (entry) => entry.id),
351 );
352 store.setReviewComments(
353 draftTarget,
354 withRestored(current?.reviewComments, snapshot.reviewComments, (comment) => comment.id),
355 );
356 store.setThreadContexts(
357 draftTarget,
358 withRestored(current?.threadContexts, snapshot.threadContexts, (record) => record.contextId),
359 );
360 store.setEnvironmentContexts(
361 draftTarget,
362 withRestored(
363 current?.environmentContexts,
364 snapshot.environmentContexts,
365 (record) => record.contextId,
366 ),
367 );
368 return images;
369}
370
371export interface MultipleModelTarget {
372 readonly selection: ModelSelection;
373 readonly text: string;
374}
375
376/**
377 * The thread each selected model starts for a multiple-model send, in
378 * selection order, or why that model cannot take the message.
379 */
380export function resolveMultipleModelTargets(input: {
381 readonly selections: ReadonlyArray<ModelSelection>;
382 readonly providerInstanceEntries: ReadonlyArray<ProviderInstanceEntry>;
383 readonly messageText: string;
384}): Array<MultipleModelTarget | { readonly error: string }> {
385 const { messageText } = input;
386 return input.selections.map((selection) => {
387 const provider = input.providerInstanceEntries.find(
388 (entry) => entry.instanceId === selection.instanceId,
389 );
390 if (!provider?.enabled || !provider.isAvailable || provider.status !== "ready") {
391 return { error: m(msg("Provider for {model} is unavailable.", { model: selection.model })) };
392 }
393 const providerBlockReason = getAntigravitySendBlockReason(provider.snapshot, selection.model);
394 if (providerBlockReason) return { error: providerBlockReason };
395 const providerState = getComposerProviderState({
396 provider: provider.driverKind,
397 model: selection.model,
398 models: provider.models,
399 modelOptions: selection.options,
400 promptInjectionState: getComposerPromptInjectionState(messageText),
401 });
402 return {
403 selection: createModelSelection(
404 selection.instanceId,
405 selection.model,
406 providerState.modelOptionsForDispatch,
407 ),
408 text: formatOutgoingPrompt({
409 provider: provider.driverKind,
410 model: selection.model,
411 models: provider.models,
412 effort: providerState.promptEffort,
413 text: messageText || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
414 }),
415 };
416 });
417}
418
419/**
420 * The attachments a turn sends: the server's upload records when it takes uploads, otherwise
421 * images inlined as data URLs. Waits for in-flight uploads; rejects when one cannot go out.
422 */
423export function prepareTurnAttachments(input: {
424 readonly environmentId: EnvironmentId;
425 readonly attachments: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>;
426 readonly usesAttachmentUploads: boolean;
427 readonly draftTarget: ComposerThreadTarget;
428}) {
429 const { environmentId, usesAttachmentUploads, draftTarget } = input;
430 return Promise.all(
431 input.attachments.map(async (attachment) => {
432 if (usesAttachmentUploads) {
433 await refreshExpiredAttachmentUploads({
434 environmentId,
435 images: [attachment],
436 draftTarget,
437 });
438 const uploaded = getUploadedAttachments({ environmentId, images: [attachment] })?.[0];
439 if (!uploaded) {
440 throw new Error(
441 m(msg("Attachment ''{name}'' failed to upload.", { name: attachment.name })),
442 );
443 }
444 return uploaded;
445 }
446 if (attachment.type !== "image") {
447 throw new Error(m(msg("This server does not support file attachments.")));
448 }
449 return {
450 type: "image" as const,
451 id: attachment.id,
452 name: attachment.name,
453 mimeType: attachment.mimeType,
454 sizeBytes: attachment.sizeBytes,
455 dataUrl: await readFileAsDataUrl(attachment.file),
456 ...(attachment.source ? { source: attachment.source } : {}),
457 };
458 }),
459 );
460}