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

useQueuedRunEdit.ts

486 lines18.8 KB

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