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