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

queuedMessageEdit.ts

182 lines6.7 KB

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