Open History to see the last commit
1import { msg } from "gt-react";
2import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3import { m } from "~/i18n/messages";
4import { useAtomValue } from "@effect/atom-react";
5import {
6 makeQueuedRunEditStore,
7 makeQueuedRunsAtom,
8} from "@t3tools/client-runtime/queued-run-edit";
9import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
10import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
11import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows";
12import {
13 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
14 type ChatAttachment,
15 type ComposerContextRecord,
16 type EnvironmentContextRecord,
17 type ResponseContextRecord,
18 type EnvironmentId,
19 type MessageId,
20 type ModelSelection,
21 type OrchestrationMessageContext,
22 type PreviewAnnotationPayload,
23 type RunId,
24 type ScopedThreadRef,
25 type ThreadContextRecord,
26 type ThreadId,
27} from "@t3tools/contracts";
28import { scopedThreadKey } from "@t3tools/client-runtime/environment";
29import {
30 restoreAttachmentOnlyBootstrapPrompt,
31 stripAttachmentOnlyBootstrapPrompt,
32} from "@t3tools/shared/composerContextReferences";
33import { Atom } from "effect/reactivity";
34import type { RefObject } from "react";
35import { useAssetUrls } from "../../assets/assetUrls";
36import {
37 queuedRunEditDraftId,
38 useComposerDraftStore,
39 type ComposerFileAttachment,
40 type ComposerImageAttachment,
41 type ComposerThreadTarget,
42} from "../../composerDraftStore";
43import { useStableCallback } from "../../hooks/useStableCallback";
44import {
45 awaitAttachmentUploads,
46 getUploadedAttachments,
47 refreshExpiredAttachmentUploads,
48 releaseDraftAttachments,
49 startAttachmentUpload,
50} from "../../lib/attachmentUploadQueue";
51import { buildMessageContext, isResponseContextRecord } from "../../lib/composerContextRecords";
52import {
53 collectInlineContextIds,
54 removeInlineContextReference,
55} from "../../lib/composerContextReferences";
56import { readFileAsDataUrl } from "../../lib/imageCompression";
57import type { TerminalContextDraft } from "../../lib/terminalContext";
58import type { ComposerSubmissionIntent } from "../../composer-logic";
59import type { ReviewCommentContext } from "../../reviewCommentContext";
60import { appAtomRegistry } from "../../rpc/atomRegistry";
61import { environmentServerConfigsAtom } from "../../state/server";
62import {
63 environmentThreadDetails,
64 environmentThreadShells,
65 threadEnvironment,
66} from "../../state/threads";
67import { useAtomCommand } from "../../state/use-atom-command";
68import { stackedThreadToast, toastManager } from "../ui/toast";
69import type { ChatComposerHandle } from "./ChatComposer";
70import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles";
71import { composerDraftContentChanged } from "./composerSend.logic";
72import {
73 attachmentContextIdsForRecord,
74 discardQueuedEditDraft,
75 prepareQueuedEditAttachments,
76 recoverQueuedMessageEdit,
77} from "./queuedMessageEdit";
78import type { EditQueuedRunRequest } from "./QueuedRunsControl";
79
80interface EditingQueuedRun {
81 readonly threadId: ThreadId;
82 readonly runId: RunId;
83 readonly messageId: MessageId;
84 readonly originalText: string;
85 readonly originalModelSelection?: ModelSelection;
86 readonly followsThreadSelection: boolean;
87 readonly originalAttachments: ReadonlyArray<ChatAttachment>;
88 readonly existingAttachments: ReadonlyArray<ChatAttachment>;
89 readonly context?: OrchestrationMessageContext | undefined;
90}
91
92// Keyed by the route thread, so an edit survives navigating away and back.
93const queuedRunEdits = makeQueuedRunEditStore<EditingQueuedRun>({
94 registry: appAtomRegistry,
95 label: "web-queued-run-edits",
96});
97
98interface QueuedRunEditContent {
99 readonly modelSelection: ModelSelection;
100 readonly prompt: string;
101 readonly images: ReadonlyArray<ComposerImageAttachment>;
102 readonly files: ReadonlyArray<ComposerFileAttachment>;
103 readonly terminalContexts: ReadonlyArray<TerminalContextDraft>;
104 readonly reviewComments: ReadonlyArray<ReviewCommentContext>;
105 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
106 readonly threadContexts: ReadonlyArray<ThreadContextRecord>;
107 readonly environmentContexts: ReadonlyArray<EnvironmentContextRecord>;
108 readonly replyTo?: ResponseContextRecord | null;
109}
110
111const isDraftOwnedRecord = (record: ComposerContextRecord) =>
112 record.kind === "thread" || record.kind === "environment";
113
114async function submitQueuedRunEdit(input: {
115 readonly environmentId: EnvironmentId;
116 readonly draftTarget: ComposerThreadTarget;
117 readonly editing: EditingQueuedRun;
118 readonly content: QueuedRunEditContent;
119 readonly modelSelection?: ModelSelection;
120 readonly editQueuedRun: ReturnType<typeof useEditQueuedRunCommand>;
121 readonly draftChanged: () => boolean;
122}): Promise<string | null> {
123 const { environmentId, draftTarget, editing, content } = input;
124 const editText = content.prompt.trim();
125 const newAttachments = [...content.images, ...content.files];
126 const uploadFiles = async (files: ReadonlyArray<ComposerFileAttachment>) => {
127 const validateFiles = () => {
128 const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null;
129 const reason = fileAttachmentCapabilityBlockReason({
130 files,
131 attachmentUploadsCapabilityKnown: config !== null,
132 supportsAttachmentUploads: config !== null,
133 maxFileAttachmentBytes:
134 config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null,
135 });
136 if (reason !== null) throw new Error(reason);
137 };
138 validateFiles();
139 for (const file of files) startAttachmentUpload({ environmentId, image: file, draftTarget });
140 await awaitAttachmentUploads(files.map((file) => file.id));
141 await refreshExpiredAttachmentUploads({ environmentId, images: files, draftTarget });
142 validateFiles();
143 const uploaded = getUploadedAttachments({ environmentId, images: files });
144 if (uploaded === null) throw new Error(m(msg("Retry or remove failed uploads before saving.")));
145 return uploaded;
146 };
147 try {
148 const uploads = await prepareQueuedEditAttachments({
149 existingAttachments: editing.existingAttachments,
150 images: content.images,
151 files: content.files,
152 readImage: readFileAsDataUrl,
153 uploadFiles,
154 });
155 if (input.draftChanged())
156 return m(msg("Draft changed while preparing this message. Review it and save again."));
157 // The edit draft owns thread and machine mentions, so a chip removed while editing is dropped.
158 const keptRecords = (editing.context?.records ?? []).filter(
159 (record) =>
160 !isDraftOwnedRecord(record) &&
161 (!("attachmentId" in record) ||
162 editing.existingAttachments.some((attachment) => attachment.id === record.attachmentId)),
163 );
164 const newRecords =
165 buildMessageContext({
166 terminalContexts: content.terminalContexts.filter(
167 (context) => context.text.trim().length > 0,
168 ),
169 reviewComments: content.reviewComments,
170 previewAnnotations: content.previewAnnotations,
171 threadContexts: content.threadContexts,
172 environmentContexts: content.environmentContexts,
173 replyTo: content.replyTo ?? null,
174 attachments: newAttachments.map((attachment, index) => ({
175 attachment,
176 attachmentId: uploads[editing.existingAttachments.length + index]?.id ?? attachment.id,
177 })),
178 })?.records ?? [];
179 const result = await input.editQueuedRun({
180 environmentId,
181 input: {
182 threadId: editing.threadId,
183 runId: editing.runId,
184 text: restoreAttachmentOnlyBootstrapPrompt(editText, uploads.length > 0),
185 ...(input.modelSelection ? { modelSelection: input.modelSelection } : {}),
186 edit: {
187 messageId: editing.messageId,
188 attachments: uploads,
189 context: {
190 version: 1,
191 records: [
192 ...new Map(
193 [...keptRecords, ...newRecords].map(
194 (record) => [record.contextId, record] as const,
195 ),
196 ).values(),
197 ],
198 },
199 },
200 },
201 });
202 return result._tag === "Failure" ? m(msg("Could not save the edited queued message.")) : null;
203 } catch (error) {
204 return thrownErrorMessage(error, m) ?? m(msg("Could not save the edited queued message."));
205 }
206}
207
208function useEditQueuedRunCommand() {
209 return useAtomCommand(threadEnvironment.editQueuedRun, { reportFailure: false });
210}
211
212/** Edits preserve the thread draft; attachment removals stay local until save. */
213export function useQueuedRunEdit(input: {
214 readonly environmentId: EnvironmentId;
215 readonly routeThreadRef: ScopedThreadRef;
216 readonly threadDraftTarget: ComposerThreadTarget;
217 readonly activeThreadId: ThreadId | null;
218 readonly serverProjection: ThreadStructure | null;
219 readonly promptRef: { current: string };
220 readonly composerRef: RefObject<ChatComposerHandle | null>;
221}) {
222 const {
223 environmentId,
224 routeThreadRef,
225 threadDraftTarget,
226 activeThreadId,
227 serverProjection,
228 promptRef,
229 composerRef,
230 } = input;
231 const editQueuedRunCommand = useEditQueuedRunCommand();
232 const promoteQueuedRun = useAtomCommand(threadEnvironment.promoteQueuedRun);
233 const editKey = scopedThreadKey(routeThreadRef);
234 const storedEdit = useAtomValue(queuedRunEdits.atom)[editKey] ?? null;
235 const editing = activeThreadId === null ? null : storedEdit;
236 const isSaving = useAtomValue(queuedRunEdits.savingAtom)[editKey] === true;
237 const draftTarget =
238 editing === null ? threadDraftTarget : queuedRunEditDraftId(routeThreadRef, editing.runId);
239
240 const imageResources = (editing?.existingAttachments ?? [])
241 .filter((attachment) => attachment.type === "image")
242 .map((attachment) => ({ _tag: "attachment" as const, attachmentId: attachment.id }));
243 const imageUrls = useAssetUrls(environmentId, imageResources);
244 const urlByAttachmentId = new Map(
245 imageResources.map((resource, index) => [resource.attachmentId, imageUrls[index] ?? null]),
246 );
247 const originalReferencedContextIds =
248 editing === null ? null : new Set(collectInlineContextIds(editing.originalText));
249 const attachmentContextIds = (attachment: ChatAttachment) =>
250 editing === null
251 ? []
252 : attachmentContextIdsForRecord(editing.context, attachment).filter((contextId) =>
253 originalReferencedContextIds!.has(contextId),
254 );
255 const editingAttachments =
256 editing === null
257 ? null
258 : editing.existingAttachments.map((attachment) => ({
259 attachment,
260 url: urlByAttachmentId.get(attachment.id) ?? null,
261 contextIds: attachmentContextIds(attachment),
262 }));
263 const existingAttachmentIds = new Set(
264 (editing?.existingAttachments ?? []).map((attachment) => attachment.id),
265 );
266 const removedEditingAttachments =
267 editing === null
268 ? []
269 : editing.originalAttachments
270 .filter((attachment) => !existingAttachmentIds.has(attachment.id))
271 .map((attachment) => ({
272 attachment,
273 contextIds: attachmentContextIds(attachment),
274 }));
275
276 const focusComposerSoon = () => {
277 window.requestAnimationFrame(() => composerRef.current?.focusAtEnd());
278 };
279 const clearEditDraft = (runId: RunId) => {
280 const target = queuedRunEditDraftId(routeThreadRef, runId);
281 // A save in flight still sends these uploads.
282 if (isSaving) {
283 const store = useComposerDraftStore.getState();
284 store.clearComposerContent(target);
285 store.clearDraftThread(target);
286 } else discardQueuedEditDraft(target);
287 };
288
289 const beginEdit = useStableCallback((request: EditQueuedRunRequest) => {
290 if (activeThreadId === null) return;
291 if (editing !== null && editing.runId !== request.runId) clearEditDraft(editing.runId);
292 const target = queuedRunEditDraftId(routeThreadRef, request.runId);
293 const sentText = stripAttachmentOnlyBootstrapPrompt(request.text);
294 const message = serverProjection?.messages.find((message) => message.id === request.messageId);
295 const context = message?.context;
296 const referenced = new Set(collectInlineContextIds(sentText));
297 const records = (context?.records ?? []).filter((record) => referenced.has(record.contextId));
298 // A reply shows above the composer while its message is edited, not as a chip in the text.
299 // Only the reply the text still points at: a removed or replaced one stays behind as a record.
300 const reply = records.find(isResponseContextRecord);
301 const text = reply ? removeInlineContextReference(sentText, reply.contextId).prompt : sentText;
302 const store = useComposerDraftStore.getState();
303 store.clearComposerContent(target);
304 store.clearDraftThread(target);
305 store.setPrompt(target, text);
306 const run = serverProjection?.runs.find((run) => run.id === request.runId);
307 const followsThreadSelection = message?.followsThreadSelection === true;
308 const originalModelSelection = followsThreadSelection
309 ? serverProjection?.thread.modelSelection
310 : run?.modelSelection;
311 if (run && !followsThreadSelection)
312 store.setModelSelection(target, run.modelSelection, { explicit: true, replaceOptions: true });
313 store.setThreadContexts(
314 target,
315 records.filter((record): record is ThreadContextRecord => record.kind === "thread"),
316 );
317 store.setEnvironmentContexts(
318 target,
319 records.filter((record): record is EnvironmentContextRecord => record.kind === "environment"),
320 );
321 if (reply) store.setReplyTo(target, reply);
322 const threadRef = { environmentId, threadId: activeThreadId };
323 queuedRunEdits.begin(
324 editKey,
325 {
326 threadId: activeThreadId,
327 runId: request.runId,
328 messageId: request.messageId,
329 originalText: text,
330 followsThreadSelection,
331 ...(originalModelSelection ? { originalModelSelection } : {}),
332 originalAttachments: request.attachments,
333 existingAttachments: request.attachments,
334 context,
335 },
336 {
337 runs: makeQueuedRunsAtom({
338 threadId: activeThreadId,
339 snapshot: threadEnvironment.snapshotAtom(environmentId),
340 detailStatus: environmentThreadDetails.statusAtom(threadRef),
341 runs: Atom.make(
342 (get) =>
343 get(environmentThreadDetails.quietThreadAtom(threadRef))?.projection.runs ?? null,
344 ),
345 }),
346 // The run started or was cancelled from another client. A changed
347 // edit moves into the thread's own draft when that draft is empty;
348 // otherwise it is dropped. Edits outlive navigation, so the toast is
349 // unscoped and names the thread: the user may be anywhere by now.
350 onRunLeftQueue: (_, edit) => {
351 const recovery = recoverQueuedMessageEdit({
352 editTarget: queuedRunEditDraftId(routeThreadRef, edit.runId),
353 threadTarget: threadDraftTarget,
354 originalText: edit.originalText,
355 ...(edit.originalModelSelection
356 ? { originalModelSelection: edit.originalModelSelection }
357 : {}),
358 originalReplyTo: reply ?? null,
359 removedExistingAttachment:
360 edit.existingAttachments.length < edit.originalAttachments.length,
361 existingAttachmentContextIds: (edit.context?.records ?? []).flatMap((record) =>
362 (record.kind === "image" || record.kind === "file") && "attachmentId" in record
363 ? [record.contextId]
364 : [],
365 ),
366 });
367 if (recovery === "clean") return;
368 const title = appAtomRegistry.get(
369 environmentThreadShells.threadShellAtom(threadRef),
370 )?.title;
371 toastManager.add(
372 stackedThreadToast({
373 type: recovery === "kept" ? "info" : "warning",
374 title: m(msg("Queued message is no longer queued")),
375 description:
376 title === undefined
377 ? recovery === "kept"
378 ? m(msg("Your unsaved edit was kept in the composer."))
379 : m(msg("Your unsaved edit was discarded."))
380 : recovery === "kept"
381 ? m(msg("Your unsaved edit in “{title}” was kept in the composer.", { title }))
382 : m(msg("Your unsaved edit in “{title}” was discarded.", { title })),
383 }),
384 );
385 },
386 },
387 );
388 focusComposerSoon();
389 });
390 const cancelEdit = useStableCallback(() => {
391 if (editing === null) return;
392 clearEditDraft(editing.runId);
393 queuedRunEdits.end(editKey);
394 focusComposerSoon();
395 });
396 const removeEditingAttachment = useStableCallback((attachmentId: string) => {
397 const removed = editing?.existingAttachments.find(
398 (attachment) => attachment.id === attachmentId,
399 );
400 const contextIds = removed ? attachmentContextIdsForRecord(editing?.context, removed) : [];
401 queuedRunEdits.update(editKey, (current) => ({
402 ...current,
403 existingAttachments: current.existingAttachments.filter(
404 (attachment) => attachment.id !== attachmentId,
405 ),
406 }));
407 if (editing !== null && contextIds.length > 0) {
408 const target = queuedRunEditDraftId(routeThreadRef, editing.runId);
409 const store = useComposerDraftStore.getState();
410 const currentPrompt = store.getComposerDraft(target)?.prompt ?? "";
411 const nextPrompt = contextIds.reduce(
412 (prompt, contextId) => removeInlineContextReference(prompt, contextId).prompt,
413 currentPrompt,
414 );
415 if (nextPrompt !== currentPrompt) store.setPrompt(target, nextPrompt);
416 }
417 });
418 const restoreEditingAttachment = useStableCallback((attachment: ChatAttachment) => {
419 queuedRunEdits.update(editKey, (current) => {
420 const keptIds = new Set([
421 ...current.existingAttachments.map((entry) => entry.id),
422 attachment.id,
423 ]);
424 // Filtering the originals keeps the restored attachment in its original position.
425 return {
426 ...current,
427 existingAttachments: current.originalAttachments.filter((entry) => keptIds.has(entry.id)),
428 };
429 });
430 });
431
432 // The same move as the queued row's "Send now" while a turn runs.
433 const steerSavedRun = async (edited: EditingQueuedRun) => {
434 const projection = appAtomRegistry.get(
435 environmentThreadDetails.quietThreadAtom({ environmentId, threadId: edited.threadId }),
436 )?.projection;
437 if (!projection) return;
438 const workflow = deriveThreadQueueWorkflowState(projection);
439 const queued = workflow.queuedRuns.find(({ run }) => run.id === edited.runId);
440 if (
441 queued === undefined ||
442 workflow.activeRun === null ||
443 !workflow.canPromoteToSteer ||
444 (queued.run.freshContext === true && !workflow.promoteSkipsCompaction)
445 ) {
446 return;
447 }
448 await promoteQueuedRun({
449 environmentId,
450 input: {
451 threadId: edited.threadId,
452 queuedRunId: edited.runId,
453 targetRunId: workflow.activeRun.id,
454 },
455 });
456 };
457
458 const saveEdit = async (
459 content: QueuedRunEditContent,
460 setThreadError: (threadId: ThreadId, error: string | null) => void,
461 submission?: {
462 readonly dispatchMode: ComposerDispatchMode;
463 readonly submissionIntent: ComposerSubmissionIntent;
464 },
465 ) => {
466 if (editing === null || isSaving) return;
467 const newAttachments = [...content.images, ...content.files];
468 if (
469 editing.existingAttachments.length + newAttachments.length >
470 PROVIDER_SEND_TURN_MAX_ATTACHMENTS
471 ) {
472 setThreadError(
473 editing.threadId,
474 m(
475 msg("A message can have at most {max} attachments.", {
476 max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
477 }),
478 ),
479 );
480 return;
481 }
482 if (
483 content.prompt.trim().length === 0 &&
484 editing.existingAttachments.length === 0 &&
485 newAttachments.length === 0
486 ) {
487 return;
488 }
489 // The save's result decides the edit's fate, even if the run starts meanwhile.
490 const finishSave = queuedRunEdits.startSave(editKey);
491 if (finishSave === null) return;
492 const draftBeforeSave = useComposerDraftStore.getState().getComposerDraft(draftTarget);
493 const draftChanged = () =>
494 appAtomRegistry.get(queuedRunEdits.atom)[editKey] !== editing ||
495 draftBeforeSave?.modelSelectionByProvider !==
496 useComposerDraftStore.getState().getComposerDraft(draftTarget)?.modelSelectionByProvider ||
497 composerDraftContentChanged(
498 draftBeforeSave,
499 useComposerDraftStore.getState().getComposerDraft(draftTarget),
500 );
501 const error = await submitQueuedRunEdit({
502 environmentId,
503 draftTarget,
504 editing,
505 content,
506 ...(!editing.followsThreadSelection || draftBeforeSave?.modelSelectionExplicit
507 ? { modelSelection: content.modelSelection }
508 : {}),
509 editQueuedRun: editQueuedRunCommand,
510 draftChanged,
511 });
512 const changedAfterSave = error === null && draftChanged();
513 setThreadError(
514 editing.threadId,
515 changedAfterSave
516 ? m(msg("The earlier edit was saved. Review your newer changes and save again."))
517 : error,
518 );
519 const current = finishSave(error === null && !changedAfterSave);
520 if (!current) {
521 // A failed save can recover into the thread draft; a newer edit can also retain resources.
522 const drafts = Object.values(useComposerDraftStore.getState().draftsByThreadKey);
523 const retainedIds = new Set(
524 drafts.flatMap((draft) =>
525 [...draft.images, ...draft.files].map((attachment) => attachment.id),
526 ),
527 );
528 releaseDraftAttachments(
529 newAttachments.filter((attachment) => !retainedIds.has(attachment.id)),
530 );
531 const retainedPreviews = new Set(
532 drafts.flatMap((draft) => draft.images.map((image) => image.previewUrl)),
533 );
534 for (const image of content.images) {
535 if (image.previewUrl.startsWith("blob:") && !retainedPreviews.has(image.previewUrl)) {
536 URL.revokeObjectURL(image.previewUrl);
537 }
538 }
539 return;
540 }
541 if (error !== null) return;
542 if (changedAfterSave) return;
543 releaseDraftAttachments(newAttachments);
544 promptRef.current = "";
545 clearEditDraft(editing.runId);
546 composerRef.current?.resetCursorState();
547 focusComposerSoon();
548 // A plain submit means "Update queued message"; only the opposite-action shortcut or
549 // modifier-click asks to steer, as it does for a new follow-up.
550 if (submission?.submissionIntent === "alternate" && submission.dispatchMode === "steer") {
551 await steerSavedRun(editing);
552 }
553 };
554
555 return {
556 editingRunId: editing?.runId ?? null,
557 isEditing: editing !== null,
558 isSaving,
559 draftTarget,
560 editingAttachments,
561 removedEditingAttachments,
562 beginEdit,
563 cancelEdit,
564 removeEditingAttachment,
565 restoreEditingAttachment,
566 saveEdit,
567 };
568}