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