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

useQueuedRunEdit.ts

475 lines18.3 KB

1import { useAtomValue } from "@effect/atom-react";
2import {
3 makeQueuedRunEditStore,
4 makeQueuedRunsAtom,
5} from "@t3tools/client-runtime/queued-run-edit";
6import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
7import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
8import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows";
9import {
10 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
11 type ChatAttachment,
12 type ComposerContextRecord,
13 type EnvironmentContextRecord,
14 type ResponseContextRecord,
15 type EnvironmentId,
16 type MessageId,
17 type OrchestrationMessageContext,
18 type PreviewAnnotationPayload,
19 type RunId,
20 type ScopedThreadRef,
21 type ThreadContextRecord,
22 type ThreadId,
23} from "@t3tools/contracts";
24import { scopedThreadKey } from "@t3tools/client-runtime/environment";
25import {
26 restoreAttachmentOnlyBootstrapPrompt,
27 stripAttachmentOnlyBootstrapPrompt,
28} from "@t3tools/shared/composerContextReferences";
29import { Atom } from "effect/reactivity";
30import type { RefObject } from "react";
31import { useAssetUrls } from "../../assets/assetUrls";
32import {
33 queuedRunEditDraftId,
34 useComposerDraftStore,
35 type ComposerFileAttachment,
36 type ComposerImageAttachment,
37 type ComposerThreadTarget,
38} from "../../composerDraftStore";
39import { useStableCallback } from "../../hooks/useStableCallback";
40import {
41 awaitAttachmentUploads,
42 getUploadedAttachments,
43 refreshExpiredAttachmentUploads,
44 releaseDraftAttachments,
45 startAttachmentUpload,
46} from "../../lib/attachmentUploadQueue";
47import { buildMessageContext, isResponseContextRecord } from "../../lib/composerContextRecords";
48import {
49 collectInlineContextIds,
50 removeInlineContextReference,
51} from "../../lib/composerContextReferences";
52import { readFileAsDataUrl } from "../../lib/imageCompression";
53import type { TerminalContextDraft } from "../../lib/terminalContext";
54import type { ComposerSubmissionIntent } from "../../composer-logic";
55import type { ReviewCommentContext } from "../../reviewCommentContext";
56import { appAtomRegistry } from "../../rpc/atomRegistry";
57import { environmentServerConfigsAtom } from "../../state/server";
58import {
59 environmentThreadDetails,
60 environmentThreadShells,
61 threadEnvironment,
62} from "../../state/threads";
63import { useAtomCommand } from "../../state/use-atom-command";
64import { stackedThreadToast, toastManager } from "../ui/toast";
65import type { ChatComposerHandle } from "./ChatComposer";
66import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles";
67import { composerDraftContentChanged } from "./composerSend.logic";
68import {
69 discardQueuedEditDraft,
70 prepareQueuedEditAttachments,
71 recoverQueuedMessageEdit,
72} from "./queuedMessageEdit";
73import type { EditQueuedRunRequest } from "./QueuedRunsControl";
74​
75interface EditingQueuedRun {
76 readonly threadId: ThreadId;
77 readonly runId: RunId;
78 readonly messageId: MessageId;
79 readonly originalText: string;
80 readonly existingAttachments: ReadonlyArray<ChatAttachment>;
81 readonly context?: OrchestrationMessageContext | undefined;
82 /** Removing a server attachment changes the message even when the draft looks untouched. */
83 readonly removedExistingAttachment?: true;
85​
86// Keyed by the route thread, so an edit survives navigating away and back.
87const queuedRunEdits = makeQueuedRunEditStore<EditingQueuedRun>({
88 registry: appAtomRegistry,
89 label: "web-queued-run-edits",
90});
91​
92interface QueuedRunEditContent {
93 readonly prompt: string;
94 readonly images: ReadonlyArray<ComposerImageAttachment>;
95 readonly files: ReadonlyArray<ComposerFileAttachment>;
96 readonly terminalContexts: ReadonlyArray<TerminalContextDraft>;
97 readonly reviewComments: ReadonlyArray<ReviewCommentContext>;
98 readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
99 readonly threadContexts: ReadonlyArray<ThreadContextRecord>;
100 readonly environmentContexts: ReadonlyArray<EnvironmentContextRecord>;
101 readonly replyTo?: ResponseContextRecord | null;
103​
104const isDraftOwnedRecord = (record: ComposerContextRecord) =>
105 record.kind === "thread" || record.kind === "environment";
106​
107async function submitQueuedRunEdit(input: {
108 readonly environmentId: EnvironmentId;
109 readonly draftTarget: ComposerThreadTarget;
110 readonly editing: EditingQueuedRun;
111 readonly content: QueuedRunEditContent;
112 readonly editQueuedRun: ReturnType<typeof useEditQueuedRunCommand>;
113 readonly draftChanged: () => boolean;
114}): Promise<string | null> {
115 const { environmentId, draftTarget, editing, content } = input;
116 const editText = content.prompt.trim();
117 const newAttachments = [...content.images, ...content.files];
118 const uploadFiles = async (files: ReadonlyArray<ComposerFileAttachment>) => {
119 const validateFiles = () => {
120 const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null;
121 const reason = fileAttachmentCapabilityBlockReason({
122 files,
123 attachmentUploadsCapabilityKnown: config !== null,
124 supportsAttachmentUploads: config !== null,
125 maxFileAttachmentBytes:
126 config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null,
127 });
128 if (reason !== null) throw new Error(reason);
129 };
130 validateFiles();
131 for (const file of files) startAttachmentUpload({ environmentId, image: file, draftTarget });
132 await awaitAttachmentUploads(files.map((file) => file.id));
133 await refreshExpiredAttachmentUploads({ environmentId, images: files, draftTarget });
134 validateFiles();
135 const uploaded = getUploadedAttachments({ environmentId, images: files });
136 if (uploaded === null) throw new Error("Retry or remove failed uploads before saving.");
137 return uploaded;
138 };
139 try {
140 const uploads = await prepareQueuedEditAttachments({
141 existingAttachments: editing.existingAttachments,
142 images: content.images,
143 files: content.files,
144 readImage: readFileAsDataUrl,
145 uploadFiles,
146 });
147 if (input.draftChanged())
148 return "Draft changed while preparing this message. Review it and save again.";
149 // The edit draft owns thread and machine mentions, so a chip removed while editing is dropped.
150 const keptRecords = (editing.context?.records ?? []).filter(
151 (record) =>
152 !isDraftOwnedRecord(record) &&
153 (!("attachmentId" in record) ||
154 editing.existingAttachments.some((attachment) => attachment.id === record.attachmentId)),
155 );
156 const newRecords =
157 buildMessageContext({
158 terminalContexts: content.terminalContexts.filter(
159 (context) => context.text.trim().length > 0,
160 ),
161 reviewComments: content.reviewComments,
162 previewAnnotations: content.previewAnnotations,
163 threadContexts: content.threadContexts,
164 environmentContexts: content.environmentContexts,
165 replyTo: content.replyTo ?? null,
166 attachments: newAttachments.map((attachment, index) => ({
167 attachment,
168 attachmentId: uploads[editing.existingAttachments.length + index]?.id ?? attachment.id,
169 })),
170 })?.records ?? [];
171 const result = await input.editQueuedRun({
172 environmentId,
173 input: {
174 threadId: editing.threadId,
175 runId: editing.runId,
176 text: restoreAttachmentOnlyBootstrapPrompt(editText, uploads.length > 0),
177 edit: {
178 messageId: editing.messageId,
179 attachments: uploads,
180 context: {
181 version: 1,
182 records: [
183 ...new Map(
184 [...keptRecords, ...newRecords].map(
185 (record) => [record.contextId, record] as const,
186 ),
187 ).values(),
188 ],
189 },
190 },
191 },
192 });
193 return result._tag === "Failure" ? "Could not save the edited queued message." : null;
194 } catch (error) {
195 return error instanceof Error ? error.message : "Could not save the edited queued message.";
196 }
198​
199function useEditQueuedRunCommand() {
200 return useAtomCommand(threadEnvironment.editQueuedRun, { reportFailure: false });
202​
203/** Edits preserve the thread draft; attachment removals stay local until save. */
204export function useQueuedRunEdit(input: {
205 readonly environmentId: EnvironmentId;
206 readonly routeThreadRef: ScopedThreadRef;
207 readonly threadDraftTarget: ComposerThreadTarget;
208 readonly activeThreadId: ThreadId | null;
209 readonly serverProjection: ThreadStructure | null;
210 readonly promptRef: { current: string };
211 readonly composerRef: RefObject<ChatComposerHandle | null>;
212}) {
213 const {
214 environmentId,
215 routeThreadRef,
216 threadDraftTarget,
217 activeThreadId,
218 serverProjection,
219 promptRef,
220 composerRef,
221 } = input;
222 const editQueuedRunCommand = useEditQueuedRunCommand();
223 const promoteQueuedRun = useAtomCommand(threadEnvironment.promoteQueuedRun);
224 const editKey = scopedThreadKey(routeThreadRef);
225 const storedEdit = useAtomValue(queuedRunEdits.atom)[editKey] ?? null;
226 const editing = activeThreadId === null ? null : storedEdit;
227 const isSaving = useAtomValue(queuedRunEdits.savingAtom)[editKey] === true;
228 const draftTarget =
229 editing === null ? threadDraftTarget : queuedRunEditDraftId(routeThreadRef, editing.runId);
230​
231 const imageResources = (editing?.existingAttachments ?? [])
232 .filter((attachment) => attachment.type === "image")
233 .map((attachment) => ({ _tag: "attachment" as const, attachmentId: attachment.id }));
234 const imageUrls = useAssetUrls(environmentId, imageResources);
235 const urlByAttachmentId = new Map(
236 imageResources.map((resource, index) => [resource.attachmentId, imageUrls[index] ?? null]),
237 );
238 const editingAttachments =
239 editing === null
240 ? null
241 : editing.existingAttachments.map((attachment) => ({
242 attachment,
243 url: urlByAttachmentId.get(attachment.id) ?? null,
244 }));
245​
246 const focusComposerSoon = () => {
247 window.requestAnimationFrame(() => composerRef.current?.focusAtEnd());
248 };
249 const clearEditDraft = (runId: RunId) => {
250 const target = queuedRunEditDraftId(routeThreadRef, runId);
251 // A save in flight still sends these uploads.
252 if (isSaving) useComposerDraftStore.getState().clearComposerContent(target);
253 else discardQueuedEditDraft(target);
254 };
255​
256 const beginEdit = useStableCallback((request: EditQueuedRunRequest) => {
257 if (activeThreadId === null) return;
258 if (editing !== null && editing.runId !== request.runId) clearEditDraft(editing.runId);
259 const target = queuedRunEditDraftId(routeThreadRef, request.runId);
260 const sentText = stripAttachmentOnlyBootstrapPrompt(request.text);
261 const context = serverProjection?.messages.find(
262 (message) => message.id === request.messageId,
263 )?.context;
264 const referenced = new Set(collectInlineContextIds(sentText));
265 const records = (context?.records ?? []).filter((record) => referenced.has(record.contextId));
266 // A reply shows above the composer while its message is edited, not as a chip in the text.
267 // Only the reply the text still points at: a removed or replaced one stays behind as a record.
268 const reply = records.find(isResponseContextRecord);
269 const text = reply ? removeInlineContextReference(sentText, reply.contextId).prompt : sentText;
270 const store = useComposerDraftStore.getState();
271 store.clearComposerContent(target);
272 store.setPrompt(target, text);
273 store.setThreadContexts(
274 target,
275 records.filter((record): record is ThreadContextRecord => record.kind === "thread"),
276 );
277 store.setEnvironmentContexts(
278 target,
279 records.filter((record): record is EnvironmentContextRecord => record.kind === "environment"),
280 );
281 if (reply) store.setReplyTo(target, reply);
282 const threadRef = { environmentId, threadId: activeThreadId };
283 queuedRunEdits.begin(
284 editKey,
285 {
286 threadId: activeThreadId,
287 runId: request.runId,
288 messageId: request.messageId,
289 originalText: text,
290 existingAttachments: request.attachments,
291 context,
292 },
293 {
294 runs: makeQueuedRunsAtom({
295 threadId: activeThreadId,
296 snapshot: threadEnvironment.snapshotAtom(environmentId),
297 detailStatus: environmentThreadDetails.statusAtom(threadRef),
298 runs: Atom.make(
299 (get) =>
300 get(environmentThreadDetails.quietThreadAtom(threadRef))?.projection.runs ?? null,
301 ),
302 }),
303 // The run started or was cancelled from another client. A changed
304 // edit moves into the thread's own draft when that draft is empty;
305 // otherwise it is dropped. Edits outlive navigation, so the toast is
306 // unscoped and names the thread: the user may be anywhere by now.
307 onRunLeftQueue: (_, edit) => {
308 const recovery = recoverQueuedMessageEdit({
309 editTarget: queuedRunEditDraftId(routeThreadRef, edit.runId),
310 threadTarget: threadDraftTarget,
311 originalText: edit.originalText,
312 removedExistingAttachment: edit.removedExistingAttachment === true,
313 });
314 if (recovery === "clean") return;
315 const title = appAtomRegistry.get(
316 environmentThreadShells.threadShellAtom(threadRef),
317 )?.title;
318 const where = title === undefined ? "" : ` in “${title}”`;
319 toastManager.add(
320 stackedThreadToast({
321 type: recovery === "kept" ? "info" : "warning",
322 title: "Queued message is no longer queued",
323 description:
324 recovery === "kept"
325 ? `Your unsaved edit${where} was kept in the composer.`
326 : `Your unsaved edit${where} was discarded.`,
327 }),
328 );
329 },
330 },
331 );
332 focusComposerSoon();
333 });
334 const cancelEdit = useStableCallback(() => {
335 if (editing === null) return;
336 clearEditDraft(editing.runId);
337 queuedRunEdits.end(editKey);
338 focusComposerSoon();
339 });
340 const removeEditingAttachment = useStableCallback((attachmentId: string) => {
341 queuedRunEdits.update(editKey, (current) => ({
342 ...current,
343 removedExistingAttachment: true,
344 existingAttachments: current.existingAttachments.filter(
345 (attachment) => attachment.id !== attachmentId,
346 ),
347 }));
348 });
349​
350 // The same move as the queued row's "Send now" while a turn runs.
351 const steerSavedRun = async (edited: EditingQueuedRun) => {
352 const projection = appAtomRegistry.get(
353 environmentThreadDetails.quietThreadAtom({ environmentId, threadId: edited.threadId }),
354 )?.projection;
355 if (!projection) return;
356 const workflow = deriveThreadQueueWorkflowState(projection);
357 const queued = workflow.queuedRuns.find(({ run }) => run.id === edited.runId);
358 if (
359 queued === undefined ||
360 workflow.activeRun === null ||
361 !workflow.canPromoteToSteer ||
362 (queued.run.freshContext === true && !workflow.promoteSkipsCompaction)
363 ) {
364 return;
365 }
366 await promoteQueuedRun({
367 environmentId,
368 input: {
369 threadId: edited.threadId,
370 queuedRunId: edited.runId,
371 targetRunId: workflow.activeRun.id,
372 },
373 });
374 };
375​
376 const saveEdit = async (
377 content: QueuedRunEditContent,
378 setThreadError: (threadId: ThreadId, error: string | null) => void,
379 submission?: {
380 readonly dispatchMode: ComposerDispatchMode;
381 readonly submissionIntent: ComposerSubmissionIntent;
382 },
383 ) => {
384 if (editing === null || isSaving) return;
385 const newAttachments = [...content.images, ...content.files];
386 if (
387 editing.existingAttachments.length + newAttachments.length >
388 PROVIDER_SEND_TURN_MAX_ATTACHMENTS
389 ) {
390 setThreadError(
391 editing.threadId,
392 `A message can have at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,
393 );
394 return;
395 }
396 if (
397 content.prompt.trim().length === 0 &&
398 editing.existingAttachments.length === 0 &&
399 newAttachments.length === 0
400 ) {
401 return;
402 }
403 // The save's result decides the edit's fate, even if the run starts meanwhile.
404 const finishSave = queuedRunEdits.startSave(editKey);
405 if (finishSave === null) return;
406 const draftBeforeSave = useComposerDraftStore.getState().getComposerDraft(draftTarget);
407 const draftChanged = () =>
408 appAtomRegistry.get(queuedRunEdits.atom)[editKey] !== editing ||
409 composerDraftContentChanged(
410 draftBeforeSave,
411 useComposerDraftStore.getState().getComposerDraft(draftTarget),
412 );
413 const error = await submitQueuedRunEdit({
414 environmentId,
415 draftTarget,
416 editing,
417 content,
418 editQueuedRun: editQueuedRunCommand,
419 draftChanged,
420 });
421 const changedAfterSave = error === null && draftChanged();
422 setThreadError(
423 editing.threadId,
424 changedAfterSave
425 ? "The earlier edit was saved. Review your newer changes and save again."
426 : error,
427 );
428 const current = finishSave(error === null && !changedAfterSave);
429 if (!current) {
430 // A failed save can recover into the thread draft; a newer edit can also retain resources.
431 const drafts = Object.values(useComposerDraftStore.getState().draftsByThreadKey);
432 const retainedIds = new Set(
433 drafts.flatMap((draft) =>
434 [...draft.images, ...draft.files].map((attachment) => attachment.id),
435 ),
436 );
437 releaseDraftAttachments(
438 newAttachments.filter((attachment) => !retainedIds.has(attachment.id)),
439 );
440 const retainedPreviews = new Set(
441 drafts.flatMap((draft) => draft.images.map((image) => image.previewUrl)),
442 );
443 for (const image of content.images) {
444 if (image.previewUrl.startsWith("blob:") && !retainedPreviews.has(image.previewUrl)) {
445 URL.revokeObjectURL(image.previewUrl);
446 }
447 }
448 return;
449 }
450 if (error !== null) return;
451 if (changedAfterSave) return;
452 releaseDraftAttachments(newAttachments);
453 promptRef.current = "";
454 clearEditDraft(editing.runId);
455 composerRef.current?.resetCursorState();
456 focusComposerSoon();
457 // A plain submit means "Update queued message"; only the opposite-action shortcut or
458 // modifier-click asks to steer, as it does for a new follow-up.
459 if (submission?.submissionIntent === "alternate" && submission.dispatchMode === "steer") {
460 await steerSavedRun(editing);
461 }
462 };
463​
464 return {
465 editingRunId: editing?.runId ?? null,
466 isEditing: editing !== null,
467 isSaving,
468 draftTarget,
469 editingAttachments,
470 beginEdit,
471 cancelEdit,
472 removeEditingAttachment,
473 saveEdit,
474 };