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