Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 makeQueuedRunEditStore,
4 makeQueuedRunsAtom,
5} from "@t3tools/client-runtime/queued-run-edit";
6import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
7import {
8 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
9 type ChatAttachment,
10 type ComposerContextRecord,
11 type EnvironmentContextRecord,
12 type ResponseContextRecord,
13 type EnvironmentId,
14 type MessageId,
15 type OrchestrationMessageContext,
16 type PreviewAnnotationPayload,
17 type RunId,
18 type ScopedThreadRef,
19 type ThreadContextRecord,
20 type ThreadId,
21} from "@t3tools/contracts";
22import { scopedThreadKey } from "@t3tools/client-runtime/environment";
23import {
24 restoreAttachmentOnlyBootstrapPrompt,
25 stripAttachmentOnlyBootstrapPrompt,
26} from "@t3tools/shared/composerContextReferences";
27import { Atom } from "effect/reactivity";
28import type { RefObject } from "react";
29import { useAssetUrls } from "../../assets/assetUrls";
30import {
31 queuedRunEditDraftId,
32 useComposerDraftStore,
33 type ComposerFileAttachment,
34 type ComposerImageAttachment,
35 type ComposerThreadTarget,
36} from "../../composerDraftStore";
37import { useStableCallback } from "../../hooks/useStableCallback";
38import {
39 awaitAttachmentUploads,
40 getUploadedAttachments,
41 releaseDraftAttachments,
42 startAttachmentUpload,
43} from "../../lib/attachmentUploadQueue";
44import { buildMessageContext, isResponseContextRecord } from "../../lib/composerContextRecords";
45import {
46 collectInlineContextIds,
47 removeInlineContextReference,
48} from "../../lib/composerContextReferences";
49import { readFileAsDataUrl } from "../../lib/imageCompression";
50import type { TerminalContextDraft } from "../../lib/terminalContext";
51import type { ReviewCommentContext } from "../../reviewCommentContext";
52import { appAtomRegistry } from "../../rpc/atomRegistry";
53import { environmentServerConfigsAtom } from "../../state/server";
54import {
55 environmentThreadDetails,
56 environmentThreadShells,
57 threadEnvironment,
58} from "../../state/threads";
59import { useAtomCommand } from "../../state/use-atom-command";
60import { stackedThreadToast, toastManager } from "../ui/toast";
61import type { ChatComposerHandle } from "./ChatComposer";
62import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles";
63import { prepareQueuedEditAttachments, recoverQueuedMessageEdit } from "./queuedMessageEdit";
64import type { EditQueuedRunRequest } from "./QueuedRunsControl";
65
66interface EditingQueuedRun {
67 readonly threadId: ThreadId;
68 readonly runId: RunId;
69 readonly messageId: MessageId;
70 readonly originalText: string;
71 readonly existingAttachments: ReadonlyArray<ChatAttachment>;
72 readonly context?: OrchestrationMessageContext | undefined;
73 /** Removing a server attachment changes the message even when the draft looks untouched. */
74 readonly removedExistingAttachment?: true;
75}
76
77// Keyed by the route thread, so an edit survives navigating away and back.
78const queuedRunEdits = makeQueuedRunEditStore<EditingQueuedRun>({
79 registry: appAtomRegistry,
80 label: "web-queued-run-edits",
81});
82
83interface QueuedRunEditContent {
84 readonly prompt: string;
85 readonly images: ReadonlyArray<ComposerImageAttachment>;
86 readonly files: ReadonlyArray<ComposerFileAttachment>;
87 readonly terminalContexts: ReadonlyArray<TerminalContextDraft>;
88 readonly reviewComments: ReadonlyArray<ReviewCommentContext>;
89 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
90 readonly threadContexts: ReadonlyArray<ThreadContextRecord>;
91 readonly environmentContexts: ReadonlyArray<EnvironmentContextRecord>;
92 readonly replyTo?: ResponseContextRecord | null;
93}
94
95const isDraftOwnedRecord = (record: ComposerContextRecord) =>
96 record.kind === "thread" || record.kind === "environment";
97
98async function submitQueuedRunEdit(input: {
99 readonly environmentId: EnvironmentId;
100 readonly draftTarget: ComposerThreadTarget;
101 readonly editing: EditingQueuedRun;
102 readonly content: QueuedRunEditContent;
103 readonly editQueuedRun: ReturnType<typeof useEditQueuedRunCommand>;
104}): Promise<string | null> {
105 const { environmentId, draftTarget, editing, content } = input;
106 const editText = content.prompt.trim();
107 const newAttachments = [...content.images, ...content.files];
108 const uploadFiles = async (files: ReadonlyArray<ComposerFileAttachment>) => {
109 const validateFiles = () => {
110 const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null;
111 const reason = fileAttachmentCapabilityBlockReason({
112 files,
113 attachmentUploadsCapabilityKnown: config !== null,
114 supportsAttachmentUploads: config !== null,
115 maxFileAttachmentBytes:
116 config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null,
117 });
118 if (reason !== null) throw new Error(reason);
119 };
120 validateFiles();
121 for (const file of files) startAttachmentUpload({ environmentId, image: file, draftTarget });
122 await awaitAttachmentUploads(files.map((file) => file.id));
123 validateFiles();
124 const uploaded = getUploadedAttachments({ environmentId, images: files });
125 if (uploaded === null) throw new Error("Retry or remove failed uploads before saving.");
126 return uploaded;
127 };
128 try {
129 const uploads = await prepareQueuedEditAttachments({
130 existingAttachments: editing.existingAttachments,
131 images: content.images,
132 files: content.files,
133 readImage: readFileAsDataUrl,
134 uploadFiles,
135 });
136 // The edit draft owns thread and machine mentions, so a chip removed while editing is dropped.
137 const keptRecords = (editing.context?.records ?? []).filter(
138 (record) =>
139 !isDraftOwnedRecord(record) &&
140 (!("attachmentId" in record) ||
141 editing.existingAttachments.some((attachment) => attachment.id === record.attachmentId)),
142 );
143 const newRecords =
144 buildMessageContext({
145 terminalContexts: content.terminalContexts.filter(
146 (context) => context.text.trim().length > 0,
147 ),
148 reviewComments: content.reviewComments,
149 previewAnnotations: content.previewAnnotations,
150 threadContexts: content.threadContexts,
151 environmentContexts: content.environmentContexts,
152 replyTo: content.replyTo ?? null,
153 attachments: newAttachments.map((attachment, index) => ({
154 attachment,
155 attachmentId: uploads[editing.existingAttachments.length + index]?.id ?? attachment.id,
156 })),
157 })?.records ?? [];
158 const result = await input.editQueuedRun({
159 environmentId,
160 input: {
161 threadId: editing.threadId,
162 runId: editing.runId,
163 text: restoreAttachmentOnlyBootstrapPrompt(editText, uploads.length > 0),
164 edit: {
165 messageId: editing.messageId,
166 attachments: uploads,
167 context: {
168 version: 1,
169 records: [
170 ...new Map(
171 [...keptRecords, ...newRecords].map(
172 (record) => [record.contextId, record] as const,
173 ),
174 ).values(),
175 ],
176 },
177 },
178 },
179 });
180 return result._tag === "Failure" ? "Could not save the edited queued message." : null;
181 } catch (error) {
182 return error instanceof Error ? error.message : "Could not save the edited queued message.";
183 }
184}
185
186function useEditQueuedRunCommand() {
187 return useAtomCommand(threadEnvironment.editQueuedRun, { reportFailure: false });
188}
189
190/** Edits preserve the thread draft; attachment removals stay local until save. */
191export function useQueuedRunEdit(input: {
192 readonly environmentId: EnvironmentId;
193 readonly routeThreadRef: ScopedThreadRef;
194 readonly threadDraftTarget: ComposerThreadTarget;
195 readonly activeThreadId: ThreadId | null;
196 readonly serverProjection: ThreadStructure | null;
197 readonly promptRef: { current: string };
198 readonly composerRef: RefObject<ChatComposerHandle | null>;
199}) {
200 const {
201 environmentId,
202 routeThreadRef,
203 threadDraftTarget,
204 activeThreadId,
205 serverProjection,
206 promptRef,
207 composerRef,
208 } = input;
209 const editQueuedRunCommand = useEditQueuedRunCommand();
210 const editKey = scopedThreadKey(routeThreadRef);
211 const storedEdit = useAtomValue(queuedRunEdits.atom)[editKey] ?? null;
212 const editing = activeThreadId === null ? null : storedEdit;
213 const isSaving = useAtomValue(queuedRunEdits.savingAtom)[editKey] === true;
214 const draftTarget =
215 editing === null ? threadDraftTarget : queuedRunEditDraftId(routeThreadRef, editing.runId);
216
217 const imageResources = (editing?.existingAttachments ?? [])
218 .filter((attachment) => attachment.type === "image")
219 .map((attachment) => ({ _tag: "attachment" as const, attachmentId: attachment.id }));
220 const imageUrls = useAssetUrls(environmentId, imageResources);
221 const urlByAttachmentId = new Map(
222 imageResources.map((resource, index) => [resource.attachmentId, imageUrls[index] ?? null]),
223 );
224 const editingAttachments =
225 editing === null
226 ? null
227 : editing.existingAttachments.map((attachment) => ({
228 attachment,
229 url: urlByAttachmentId.get(attachment.id) ?? null,
230 }));
231
232 const focusComposerSoon = () => {
233 window.requestAnimationFrame(() => composerRef.current?.focusAtEnd());
234 };
235 const clearEditDraft = (runId: RunId) =>
236 useComposerDraftStore
237 .getState()
238 .clearComposerContent(queuedRunEditDraftId(routeThreadRef, runId));
239
240 const beginEdit = useStableCallback((request: EditQueuedRunRequest) => {
241 if (activeThreadId === null) return;
242 if (editing !== null && editing.runId !== request.runId) clearEditDraft(editing.runId);
243 const target = queuedRunEditDraftId(routeThreadRef, request.runId);
244 const sentText = stripAttachmentOnlyBootstrapPrompt(request.text);
245 const context = serverProjection?.messages.find(
246 (message) => message.id === request.messageId,
247 )?.context;
248 const referenced = new Set(collectInlineContextIds(sentText));
249 const records = (context?.records ?? []).filter((record) => referenced.has(record.contextId));
250 // A reply shows above the composer while its message is edited, not as a chip in the text.
251 // Only the reply the text still points at: a removed or replaced one stays behind as a record.
252 const reply = records.find(isResponseContextRecord);
253 const text = reply ? removeInlineContextReference(sentText, reply.contextId).prompt : sentText;
254 const store = useComposerDraftStore.getState();
255 store.clearComposerContent(target);
256 store.setPrompt(target, text);
257 store.setThreadContexts(
258 target,
259 records.filter((record): record is ThreadContextRecord => record.kind === "thread"),
260 );
261 store.setEnvironmentContexts(
262 target,
263 records.filter((record): record is EnvironmentContextRecord => record.kind === "environment"),
264 );
265 if (reply) store.setReplyTo(target, reply);
266 const threadRef = { environmentId, threadId: activeThreadId };
267 queuedRunEdits.begin(
268 editKey,
269 {
270 threadId: activeThreadId,
271 runId: request.runId,
272 messageId: request.messageId,
273 originalText: text,
274 existingAttachments: request.attachments,
275 context,
276 },
277 {
278 runs: makeQueuedRunsAtom({
279 threadId: activeThreadId,
280 snapshot: threadEnvironment.snapshotAtom(environmentId),
281 detailStatus: environmentThreadDetails.statusAtom(threadRef),
282 runs: Atom.make(
283 (get) =>
284 get(environmentThreadDetails.quietThreadAtom(threadRef))?.projection.runs ?? null,
285 ),
286 }),
287 // The run started or was cancelled from another client. A changed
288 // edit moves into the thread's own draft when that draft is empty;
289 // otherwise it is dropped. Edits outlive navigation, so the toast is
290 // unscoped and names the thread: the user may be anywhere by now.
291 onRunLeftQueue: (_, edit) => {
292 const recovery = recoverQueuedMessageEdit({
293 editTarget: queuedRunEditDraftId(routeThreadRef, edit.runId),
294 threadTarget: threadDraftTarget,
295 originalText: edit.originalText,
296 removedExistingAttachment: edit.removedExistingAttachment === true,
297 });
298 if (recovery === "clean") return;
299 const title = appAtomRegistry.get(
300 environmentThreadShells.threadShellAtom(threadRef),
301 )?.title;
302 const where = title === undefined ? "" : ` in “${title}”`;
303 toastManager.add(
304 stackedThreadToast({
305 type: recovery === "kept" ? "info" : "warning",
306 title: "Queued message is no longer queued",
307 description:
308 recovery === "kept"
309 ? `Your unsaved edit${where} was kept in the composer.`
310 : `Your unsaved edit${where} was discarded.`,
311 }),
312 );
313 },
314 },
315 );
316 focusComposerSoon();
317 });
318 const cancelEdit = useStableCallback(() => {
319 if (editing === null) return;
320 clearEditDraft(editing.runId);
321 queuedRunEdits.end(editKey);
322 focusComposerSoon();
323 });
324 const removeEditingAttachment = useStableCallback((attachmentId: string) => {
325 queuedRunEdits.update(editKey, (current) => ({
326 ...current,
327 removedExistingAttachment: true,
328 existingAttachments: current.existingAttachments.filter(
329 (attachment) => attachment.id !== attachmentId,
330 ),
331 }));
332 });
333
334 const saveEdit = async (
335 content: QueuedRunEditContent,
336 setThreadError: (threadId: ThreadId, error: string | null) => void,
337 ) => {
338 if (editing === null || isSaving) return;
339 const newAttachments = [...content.images, ...content.files];
340 if (
341 editing.existingAttachments.length + newAttachments.length >
342 PROVIDER_SEND_TURN_MAX_ATTACHMENTS
343 ) {
344 setThreadError(
345 editing.threadId,
346 `A message can have at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,
347 );
348 return;
349 }
350 if (
351 content.prompt.trim().length === 0 &&
352 editing.existingAttachments.length === 0 &&
353 newAttachments.length === 0
354 ) {
355 return;
356 }
357 // The save's result decides the edit's fate, even if the run starts meanwhile.
358 const finishSave = queuedRunEdits.startSave(editKey);
359 if (finishSave === null) return;
360 const error = await submitQueuedRunEdit({
361 environmentId,
362 draftTarget,
363 editing,
364 content,
365 editQueuedRun: editQueuedRunCommand,
366 });
367 setThreadError(editing.threadId, error);
368 const current = finishSave(error === null);
369 if (error !== null) return;
370 releaseDraftAttachments(newAttachments);
371 // The edit was cancelled or begun again while this save ran; its drafts are the newer edit's.
372 if (!current) return;
373 promptRef.current = "";
374 clearEditDraft(editing.runId);
375 composerRef.current?.resetCursorState();
376 focusComposerSoon();
377 };
378
379 return {
380 editingRunId: editing?.runId ?? null,
381 isEditing: editing !== null,
382 isSaving,
383 draftTarget,
384 editingAttachments,
385 beginEdit,
386 cancelEdit,
387 removeEditingAttachment,
388 saveEdit,
389 };
390}