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

useQueuedRunEdit.ts

364 lines13.6 KB

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