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

chatViewSend.ts

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