Open History to see the last commit
1import { resolveQueuedEditExit } from "@t3tools/client-runtime/queued-run-edit";
2import type {
3 ChatAttachment,
4 ChatFileAttachment,
5 ChatImageAttachment,
6 ComposerContextId,
7 ComposerContextRecord,
8 EnvironmentId,
9 OrchestrationMessageContext,
10 ResponseContextRecord,
11} from "@t3tools/contracts";
12import * as Equal from "effect/Equal";
13import {
14 composerDraftHasUserContent,
15 useComposerDraftStore,
16 type ComposerFileAttachment,
17 type ComposerImageAttachment,
18 type ComposerThreadTarget,
19} from "../../composerDraftStore";
20import { msg } from "gt-react";
21import { m } from "../../i18n/messages";
22import { releaseDraftAttachments } from "../../lib/attachmentUploadQueue";
23import {
24 attachmentContextRecord,
25 isSameComposerContextPayload,
26} from "../../lib/composerContextRecords";
27import { removeInlineContextReference } from "../../lib/composerContextReferences";
28
29export function isQueuedImageAttachment(
30 attachment: ChatAttachment,
31): attachment is ChatImageAttachment {
32 return attachment.type === "image";
33}
34
35export function isQueuedFileAttachment(
36 attachment: ChatAttachment,
37): attachment is ChatFileAttachment {
38 return attachment.type === "file";
39}
40
41export function attachmentContextIdsForRecord(
42 context: OrchestrationMessageContext | undefined,
43 attachment: Pick<ChatAttachment, "id" | "type">,
44): ComposerContextId[] {
45 return (context?.records ?? []).flatMap((record) =>
46 record.kind === attachment.type &&
47 "attachmentId" in record &&
48 record.attachmentId === attachment.id
49 ? [record.contextId]
50 : [],
51 );
52}
53
54export function matchRestorableQueuedAttachment(input: {
55 readonly environmentId: EnvironmentId;
56 readonly sourceEnvironmentId: EnvironmentId | null;
57 readonly record: Extract<ComposerContextRecord, { kind: "image" | "file" }>;
58 readonly removedQueuedAttachments: ReadonlyArray<{
59 readonly attachment: ChatAttachment;
60 readonly contextIds: ReadonlyArray<ComposerContextId>;
61 }>;
62}): { readonly attachment: ChatAttachment; readonly contextId: ComposerContextId } | null {
63 if (input.sourceEnvironmentId !== input.environmentId) return null;
64 const match = input.removedQueuedAttachments.find(
65 ({ attachment, contextIds }) =>
66 (isQueuedImageAttachment(attachment) || isQueuedFileAttachment(attachment)) &&
67 attachment.type === input.record.kind &&
68 contextIds.some((contextId) =>
69 isSameComposerContextPayload(
70 attachmentContextRecord({
71 attachment,
72 attachmentId: attachment.id,
73 contextId,
74 }),
75 input.record,
76 ),
77 ),
78 );
79 if (!match || match.contextIds.length === 0) return null;
80 const contextId =
81 match.contextIds.find((candidate) => candidate === input.record.contextId) ??
82 match.contextIds[0]!;
83 return { attachment: match.attachment, contextId };
84}
85
86/** Staged attachments upload as soon as they are added, so a dropped edit must release them. */
87export function discardQueuedEditDraft(target: ComposerThreadTarget): void {
88 const store = useComposerDraftStore.getState();
89 const draft = store.getComposerDraft(target);
90 if (draft) {
91 releaseDraftAttachments([...draft.images, ...draft.files]);
92 for (const image of draft.images) {
93 if (image.previewUrl.startsWith("blob:")) URL.revokeObjectURL(image.previewUrl);
94 }
95 }
96 store.clearComposerContent(target);
97}
98
99export function recoverQueuedMessageEdit(input: {
100 readonly editTarget: ComposerThreadTarget;
101 readonly threadTarget: ComposerThreadTarget;
102 readonly originalText: string;
103 readonly originalReplyTo: ResponseContextRecord | null;
104 readonly removedExistingAttachment?: boolean;
105 readonly existingAttachmentContextIds?: ReadonlyArray<string>;
106}): "kept" | "discarded" | "clean" {
107 const store = useComposerDraftStore.getState();
108 const draft = store.getComposerDraft(input.editTarget);
109 const strippedPrompt =
110 draft && (input.existingAttachmentContextIds?.length ?? 0) > 0
111 ? input.existingAttachmentContextIds!.reduce(
112 (prompt, contextId) => removeInlineContextReference(prompt, contextId).prompt,
113 draft.prompt,
114 )
115 : draft?.prompt;
116 const recoveredDraft =
117 draft && strippedPrompt !== undefined && strippedPrompt !== draft.prompt
118 ? { ...draft, prompt: strippedPrompt }
119 : draft;
120 const recovery = resolveQueuedEditExit({
121 editChanged:
122 input.removedExistingAttachment === true ||
123 !Equal.equals(draft?.replyTo ?? null, input.originalReplyTo) ||
124 (draft !== null &&
125 (draft.prompt !== input.originalText || draft.images.length > 0 || draft.files.length > 0)),
126 // A cleared edit has nothing to put back, so it can only be discarded.
127 threadDraftEmpty:
128 composerDraftHasUserContent(recoveredDraft) &&
129 !composerDraftHasUserContent(store.getComposerDraft(input.threadTarget)),
130 });
131 if (recovery === "kept") {
132 if (draft && strippedPrompt !== undefined && strippedPrompt !== draft.prompt) {
133 store.setPrompt(input.editTarget, strippedPrompt);
134 }
135 store.moveComposerContent(input.editTarget, input.threadTarget);
136 store.clearComposerContent(input.editTarget);
137 } else {
138 discardQueuedEditDraft(input.editTarget);
139 }
140 return recovery;
141}
142
143export async function prepareQueuedEditAttachments(input: {
144 readonly existingAttachments: ReadonlyArray<ChatAttachment>;
145 readonly images: ReadonlyArray<ComposerImageAttachment>;
146 readonly files: ReadonlyArray<ComposerFileAttachment>;
147 readonly uploadFiles: (
148 files: ReadonlyArray<ComposerFileAttachment>,
149 ) => Promise<ReadonlyArray<ChatAttachment>>;
150 readonly readImage: (file: File) => Promise<string>;
151}) {
152 const files = input.files.length === 0 ? [] : await input.uploadFiles(input.files);
153 if (files.length !== input.files.length)
154 throw new Error(m(msg("Retry or remove failed uploads before saving.")));
155 const images = await Promise.all(
156 input.images.map(async (image) => ({
157 type: "image" as const,
158 id: image.id,
159 name: image.name,
160 mimeType: image.mimeType,
161 sizeBytes: image.sizeBytes,
162 dataUrl: await input.readImage(image.file),
163 ...(image.source ? { source: image.source } : {}),
164 })),
165 );
166 return [...input.existingAttachments, ...images, ...files];
167}