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

chatViewSend.ts

371 lines13.8 KB

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