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