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