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