Open History to see the last commit
1import { resolveQueuedEditExit } from "@t3tools/client-runtime/queued-run-edit";
2import type { ChatAttachment } from "@t3tools/contracts";
3import {
4 composerDraftHasUserContent,
5 useComposerDraftStore,
6 type ComposerFileAttachment,
7 type ComposerImageAttachment,
8 type ComposerThreadTarget,
9} from "../../composerDraftStore";
10
11export function recoverQueuedMessageEdit(input: {
12 readonly editTarget: ComposerThreadTarget;
13 readonly threadTarget: ComposerThreadTarget;
14 readonly originalText: string;
15 readonly removedExistingAttachment?: boolean;
16}): "kept" | "discarded" | "clean" {
17 const store = useComposerDraftStore.getState();
18 const draft = store.getComposerDraft(input.editTarget);
19 const recovery = resolveQueuedEditExit({
20 editChanged:
21 input.removedExistingAttachment === true ||
22 (draft !== null &&
23 (draft.prompt !== input.originalText || draft.images.length > 0 || draft.files.length > 0)),
24 // A cleared edit has nothing to put back, so it can only be discarded.
25 threadDraftEmpty:
26 composerDraftHasUserContent(draft) &&
27 !composerDraftHasUserContent(store.getComposerDraft(input.threadTarget)),
28 });
29 if (recovery === "kept") {
30 store.moveComposerPromptAndImages(input.editTarget, input.threadTarget);
31 } else {
32 store.clearComposerContent(input.editTarget);
33 }
34 return recovery;
35}
36
37export async function prepareQueuedEditAttachments(input: {
38 readonly existingAttachments: ReadonlyArray<ChatAttachment>;
39 readonly images: ReadonlyArray<ComposerImageAttachment>;
40 readonly files: ReadonlyArray<ComposerFileAttachment>;
41 readonly uploadFiles: (
42 files: ReadonlyArray<ComposerFileAttachment>,
43 ) => Promise<ReadonlyArray<ChatAttachment>>;
44 readonly readImage: (file: File) => Promise<string>;
45}) {
46 const files = input.files.length === 0 ? [] : await input.uploadFiles(input.files);
47 if (files.length !== input.files.length)
48 throw new Error("Retry or remove failed uploads before saving.");
49 const images = await Promise.all(
50 input.images.map(async (image) => ({
51 type: "image" as const,
52 id: image.id,
53 name: image.name,
54 mimeType: image.mimeType,
55 sizeBytes: image.sizeBytes,
56 dataUrl: await input.readImage(image.file),
57 ...(image.source ? { source: image.source } : {}),
58 })),
59 );
60 return [...input.existingAttachments, ...images, ...files];
61}