Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useQueuedRunEdit.ts

346 lines13.0 KB

1import {
2 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
3 type ChatAttachment,
4 type EnvironmentId,
5 type MessageId,
6 type OrchestrationMessageContext,
7 type OrchestrationV2ThreadProjection,
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;
54​
55/** What the composer holds when the user saves a queued-message edit. */
56export interface QueuedRunEditContent {
57 readonly prompt: string;
58 readonly images: ReadonlyArray<ComposerImageAttachment>;
59 readonly files: ReadonlyArray<ComposerFileAttachment>;
60 readonly terminalContexts: ReadonlyArray<TerminalContextDraft>;
61 readonly reviewComments: ReadonlyArray<ReviewCommentContext>;
62 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
63 readonly threadContexts: ReadonlyArray<ThreadContextRecord>;
65​
66/** Draft id for editing a queued run of the route thread. */
67function queuedEditDraftTarget(routeThreadRef: ScopedThreadRef, runId: RunId) {
68 return DraftId.make(`queued-edit:${scopedThreadKey(routeThreadRef)}:${runId}`);
70​
71/** Uploads the edit's new attachments and saves it. Returns the error to show, or null. */
72async function submitQueuedRunEdit(input: {
73 readonly environmentId: EnvironmentId;
74 readonly draftTarget: ComposerThreadTarget;
75 readonly editing: EditingQueuedRun;
76 readonly content: QueuedRunEditContent;
77 readonly editQueuedRun: ReturnType<typeof useEditQueuedRunCommand>;
78}): Promise<string | null> {
79 const { environmentId, draftTarget, editing, content } = input;
80 const editText = content.prompt.trim();
81 const newAttachments = [...content.images, ...content.files];
82 const uploadFiles = async (files: ReadonlyArray<ComposerFileAttachment>) => {
83 const validateFiles = () => {
84 const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null;
85 const reason = fileAttachmentCapabilityBlockReason({
86 files,
87 attachmentUploadsCapabilityKnown: config !== null,
88 supportsAttachmentUploads: config?.environment.capabilities.attachmentUploads === true,
89 maxFileAttachmentBytes:
90 config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null,
91 });
92 if (reason !== null) throw new Error(reason);
93 };
94 validateFiles();
95 for (const file of files) startAttachmentUpload({ environmentId, image: file, draftTarget });
96 await awaitAttachmentUploads(files.map((file) => file.id));
97 validateFiles();
98 const uploaded = getUploadedAttachments({ environmentId, images: files });
99 if (uploaded === null) throw new Error("Retry or remove failed uploads before saving.");
100 return uploaded;
101 };
102 try {
103 const uploads = await prepareQueuedEditAttachments({
104 existingAttachments: editing.existingAttachments,
105 images: content.images,
106 files: content.files,
107 readImage: readFileAsDataUrl,
108 uploadFiles,
109 });
110 // Kept records for removed attachments would point at nothing.
111 const keptRecords = (editing.context?.records ?? []).filter(
112 (record) =>
113 !("attachmentId" in record) ||
114 editing.existingAttachments.some((attachment) => attachment.id === record.attachmentId),
115 );
116 const newRecords =
117 buildMessageContext({
118 terminalContexts: content.terminalContexts.filter(
119 (context) => context.text.trim().length > 0,
120 ),
121 reviewComments: content.reviewComments,
122 previewAnnotations: content.previewAnnotations,
123 threadContexts: content.threadContexts,
124 attachments: newAttachments.map((attachment, index) => ({
125 attachment,
126 attachmentId: uploads[editing.existingAttachments.length + index]?.id ?? attachment.id,
127 })),
128 })?.records ?? [];
129 const result = await input.editQueuedRun({
130 environmentId,
131 input: {
132 threadId: editing.threadId,
133 runId: editing.runId,
134 text: editText.length === 0 ? ATTACHMENT_ONLY_BOOTSTRAP_PROMPT : editText,
135 edit: {
136 messageId: editing.messageId,
137 attachments: uploads,
138 context: {
139 version: 1,
140 records: [
141 ...new Map(
142 [...keptRecords, ...newRecords].map(
143 (record) => [record.contextId, record] as const,
144 ),
145 ).values(),
146 ],
147 },
148 },
149 },
150 });
151 return result._tag === "Failure" ? "Could not save the edited queued message." : null;
152 } catch (error) {
153 return error instanceof Error ? error.message : "Could not save the edited queued message.";
154 }
156​
157function useEditQueuedRunCommand() {
158 return useAtomCommand(threadEnvironment.editQueuedRun, { reportFailure: false });
160​
161/**
162 * Queued-message edit mode. While active, the composer is retargeted to a
163 * per-run edit draft so the user's in-progress draft on the thread survives
164 * untouched; `existingAttachments` tracks which stored attachments the edit
165 * keeps (removal is client state until save).
166 */
167export function useQueuedRunEdit(input: {
168 readonly environmentId: EnvironmentId;
169 readonly routeThreadRef: ScopedThreadRef;
170 readonly threadDraftTarget: ComposerThreadTarget;
171 // Null while the route has no thread yet; an edit needs one to target.
172 readonly activeThreadId: ThreadId | null;
173 readonly serverProjection: OrchestrationV2ThreadProjection | null;
174 readonly promptRef: { current: string };
175 readonly composerRef: RefObject<ChatComposerHandle | null>;
176}) {
177 const {
178 environmentId,
179 routeThreadRef,
180 threadDraftTarget,
181 activeThreadId,
182 serverProjection,
183 promptRef,
184 composerRef,
185 } = input;
186 const editQueuedRunCommand = useEditQueuedRunCommand();
187 const [editing, setEditing] = useState<EditingQueuedRun | null>(null);
188 const saveInFlightRef = useRef(false);
189 const [isSaving, setIsSaving] = useState(false);
190 // Navigating to another thread ends the edit; its draft stays for later.
191 if (editing !== null && activeThreadId !== editing.threadId) {
192 setEditing(null);
193 }
194 const draftTarget =
195 editing === null ? threadDraftTarget : queuedEditDraftTarget(routeThreadRef, editing.runId);
196​
197 const imageResources = (editing?.existingAttachments ?? [])
198 .filter((attachment) => attachment.type === "image")
199 .map((attachment) => ({ _tag: "attachment" as const, attachmentId: attachment.id }));
200 const imageUrls = useAssetUrls(environmentId, imageResources);
201 const urlByAttachmentId = new Map(
202 imageResources.map((resource, index) => [resource.attachmentId, imageUrls[index] ?? null]),
203 );
204 const editingAttachments =
205 editing === null
206 ? null
207 : editing.existingAttachments.map((attachment) => ({
208 attachment,
209 url: urlByAttachmentId.get(attachment.id) ?? null,
210 }));
211​
212 const focusComposerSoon = () => {
213 window.requestAnimationFrame(() => composerRef.current?.focusAtEnd());
214 };
215 const clearEditDraft = (runId: RunId) =>
216 useComposerDraftStore
217 .getState()
218 .clearComposerContent(queuedEditDraftTarget(routeThreadRef, runId));
219​
220 const beginEdit = useStableCallback((request: EditQueuedRunRequest) => {
221 if (activeThreadId === null) return;
222 if (editing !== null && editing.runId !== request.runId) clearEditDraft(editing.runId);
223 const target = queuedEditDraftTarget(routeThreadRef, request.runId);
224 const store = useComposerDraftStore.getState();
225 store.clearComposerContent(target);
226 store.setPrompt(target, request.text);
227 setEditing({
228 threadId: activeThreadId,
229 runId: request.runId,
230 messageId: request.messageId,
231 originalText: request.text,
232 existingAttachments: request.attachments,
233 context: serverProjection?.messages.find((message) => message.id === request.messageId)
234 ?.context,
235 });
236 focusComposerSoon();
237 });
238 const cancelEdit = useStableCallback(() => {
239 if (editing === null) return;
240 clearEditDraft(editing.runId);
241 setEditing(null);
242 focusComposerSoon();
243 });
244 const removeEditingAttachment = useStableCallback((attachmentId: string) => {
245 setEditing((current) =>
246 current === null
247 ? current
248 : {
249 ...current,
250 existingAttachments: current.existingAttachments.filter(
251 (attachment) => attachment.id !== attachmentId,
252 ),
253 },
254 );
255 });
256​
257 // Exit edit mode when the edited run leaves the queue (it started, or was
258 // cancelled from another client). A dirty edit moves into the thread's own
259 // draft when that draft is empty; otherwise it is dropped with a toast.
260 useEffect(() => {
261 if (editing === null || activeThreadId !== editing.threadId) return;
262 if (serverProjection === null) return;
263 const run = serverProjection.runs.find((candidate) => candidate.id === editing.runId);
264 if (run !== undefined && run.status === "queued") return;
265 const recovery = recoverQueuedMessageEdit({
266 editTarget: queuedEditDraftTarget(routeThreadRef, editing.runId),
267 threadTarget: threadDraftTarget,
268 originalText: editing.originalText,
269 });
270 if (recovery !== "clean") {
271 toastManager.add(
272 stackedThreadToast({
273 type: recovery === "kept" ? "info" : "warning",
274 title: "Queued message is no longer queued",
275 description:
276 recovery === "kept"
277 ? "Your unsaved edit was kept in the composer."
278 : "Your unsaved edit was discarded.",
279 }),
280 );
281 }
282 // 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.
283 setEditing(null);
284 }, [activeThreadId, editing, routeThreadRef, serverProjection, threadDraftTarget]);
285​
286 /**
287 * Saves the composer content into the queued message being edited. Reports
288 * failures through `setThreadError`, which callers own because the error
289 * banner lives with the thread.
290 */
291 const saveEdit = async (
292 content: QueuedRunEditContent,
293 setThreadError: (threadId: ThreadId, error: string | null) => void,
294 ) => {
295 if (editing === null || saveInFlightRef.current) return;
296 const newAttachments = [...content.images, ...content.files];
297 if (
298 editing.existingAttachments.length + newAttachments.length >
299 PROVIDER_SEND_TURN_MAX_ATTACHMENTS
300 ) {
301 setThreadError(
302 editing.threadId,
303 `A message can have at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,
304 );
305 return;
306 }
307 if (
308 content.prompt.trim().length === 0 &&
309 editing.existingAttachments.length === 0 &&
310 newAttachments.length === 0
311 ) {
312 return;
313 }
314 saveInFlightRef.current = true;
315 setIsSaving(true);
316 const error = await submitQueuedRunEdit({
317 environmentId,
318 draftTarget,
319 editing,
320 content,
321 editQueuedRun: editQueuedRunCommand,
322 });
323 saveInFlightRef.current = false;
324 setIsSaving(false);
325 setThreadError(editing.threadId, error);
326 if (error !== null) return;
327 releaseDraftAttachments(newAttachments);
328 promptRef.current = "";
329 clearEditDraft(editing.runId);
330 composerRef.current?.resetCursorState();
331 setEditing(null);
332 focusComposerSoon();
333 };
334​
335 return {
336 editingRunId: editing?.runId ?? null,
337 isEditing: editing !== null,
338 isSaving,
339 draftTarget,
340 editingAttachments,
341 beginEdit,
342 cancelEdit,
343 removeEditingAttachment,
344 saveEdit,
345 };