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

preparingComposerImages.ts

328 lines12.4 KB

1import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2import type { ScopedThreadRef } from "@t3tools/contracts";
3import * as Equal from "effect/Equal";
4import { useEffect, useRef } from "react";
5import { create } from "zustand";
6​
7import {
8 composerDraftHasUserContent,
9 composerTargetKey,
10 type ComposerThreadDraftState,
11 type ComposerThreadTarget,
12 useComposerDraftStore,
13} from "../../composerDraftStore";
14import { useStableCallback } from "../../hooks/useStableCallback";
15import { composerDraftContentChanged } from "./composerSend.logic";
16​
17export interface PreparingComposerImage {
18 readonly id: string;
19 readonly name: string;
20 /** The uncompressed source, thumbnailed so the placeholder shows the image itself. */
21 readonly file: File;
22 /** Looks like an image the draft already has: it holds its slot but shows no tile. */
23 readonly hidden: boolean;
25​
26const NO_PREPARING_IMAGES: ReadonlyArray<PreparingComposerImage> = [];
27​
28/**
29 * Images accepted into a draft but still being compressed, keyed by attachment target. Large
30 * screenshots take a noticeable moment to re-encode, so the strip shows these right away and
31 * they hold their attachment slots until the real image joins the draft.
32 */
33const usePreparingComposerImageStore = create<{
34 readonly byTargetKey: Readonly<Record<string, ReadonlyArray<PreparingComposerImage>>>;
35}>(() => ({ byTargetKey: {} }));
36​
37const movedImageThreads = new WeakMap<PreparingComposerImage, ScopedThreadRef>();
38​
39export function movedPreparingImageThread(image: PreparingComposerImage) {
40 return movedImageThreads.get(image);
42​
43/** Carries the live tiles to the thread, where they can still be removed or awaited. */
44export function movePreparingComposerImagesToThread(
45 sourceKey: string,
46 thread: ScopedThreadRef,
47): void {
48 const images = getPreparingComposerImages(sourceKey);
49 if (images.length === 0) return;
50 const threadKey = scopedThreadKey(thread);
51 for (const image of images) movedImageThreads.set(image, thread);
52 invalidatePendingSubmit(sourceKey);
53 usePreparingComposerImageStore.setState(({ byTargetKey }) => {
54 const next = { ...byTargetKey };
55 delete next[sourceKey];
56 next[threadKey] = [...(next[threadKey] ?? NO_PREPARING_IMAGES), ...images];
57 return { byTargetKey: next };
58 });
60​
61export function usePreparingComposerImages(targetKey: string) {
62 return usePreparingComposerImageStore(
63 (state) => state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES,
64 );
66​
67export function getPreparingComposerImages(
68 targetKey: string,
69): ReadonlyArray<PreparingComposerImage> {
70 return usePreparingComposerImageStore.getState().byTargetKey[targetKey] ?? NO_PREPARING_IMAGES;
72​
73export function countPreparingComposerImages(targetKey: string): number {
74 return getPreparingComposerImages(targetKey).length;
76​
77export function addPreparingComposerImages(
78 targetKey: string,
79 images: ReadonlyArray<PreparingComposerImage>,
80): void {
81 if (images.length > 0) {
82 heldSends.get(targetKey)?.({ status: "cancelled" });
83 }
84 usePreparingComposerImageStore.setState((state) => ({
85 byTargetKey: {
86 ...state.byTargetKey,
87 [targetKey]: [...(state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES), ...images],
88 },
89 }));
91​
92export function isPreparingComposerImage(targetKey: string, imageId: string): boolean {
93 return (
94 usePreparingComposerImageStore
95 .getState()
96 .byTargetKey[targetKey]?.some((image) => image.id === imageId) ?? false
97 );
99​
100/** Returns the ids that were still preparing; any other id was cancelled from the strip. */
101export function removePreparingComposerImages(
102 targetKey: string,
103 imageIds: ReadonlySet<string>,
104 options?: { readonly cancelSubmission?: boolean },
105): ReadonlySet<string> {
106 const current =
107 usePreparingComposerImageStore.getState().byTargetKey[targetKey] ?? NO_PREPARING_IMAGES;
108 const removed = new Set(
109 current.filter((image) => imageIds.has(image.id)).map((image) => image.id),
110 );
111 if (removed.size === 0) return removed;
112 if (options?.cancelSubmission) invalidatePendingSubmit(targetKey);
113 usePreparingComposerImageStore.setState((state) => {
114 const remaining = (state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES).filter(
115 (image) => !removed.has(image.id),
116 );
117 const byTargetKey = { ...state.byTargetKey };
118 if (remaining.length > 0) {
119 byTargetKey[targetKey] = remaining;
120 } else {
121 delete byTargetKey[targetKey];
122 }
123 return { byTargetKey };
124 });
125 return removed;
127​
128// Bumped on cancel so a send held for the cancelled images is dropped rather than released.
129const cancelGenerations = new Map<string, number>();
130​
131export type HeldComposerSendResult =
132 | { readonly status: "ready" }
133 | { readonly status: "cancelled" };
134​
135const heldSends = new Map<string, (result: HeldComposerSendResult) => void>();
136const useHeldSendStore = create<{ readonly targetKeys: Readonly<Record<string, true>> }>(() => ({
137 targetKeys: {},
138}));
139let preparedImagesJoiningDraft = false;
140​
141function invalidatePendingSubmit(targetKey: string) {
142 cancelGenerations.set(targetKey, (cancelGenerations.get(targetKey) ?? 0) + 1);
143 heldSends.get(targetKey)?.({ status: "cancelled" });
145​
146/** Whether a send from the target's draft is waiting on its images to finish preparing. */
147export function useComposerSendHeld(targetKey: string): boolean {
148 return useHeldSendStore((state) => state.targetKeys[targetKey] === true);
150​
151export function cancelHeldComposerSend(targetKey: string): void {
152 heldSends.get(targetKey)?.({ status: "cancelled" });
154​
155/** Inserts finished images into the draft without counting as an edit to a held send. */
156export function joinPreparedImagesToDraft<T>(insert: () => T): T {
157 preparedImagesJoiningDraft = true;
158 try {
159 return insert();
160 } finally {
161 preparedImagesJoiningDraft = false;
162 }
164​
165function composerSendSettingsChanged(
166 before: ComposerThreadDraftState | null,
167 after: ComposerThreadDraftState | null,
168): boolean {
169 const modelsChanged =
170 before && after
171 ? !Equal.equals(before.modelSelectionByProvider, after.modelSelectionByProvider)
172 : Object.keys((before ?? after)?.modelSelectionByProvider ?? {}).length > 0;
173 return (
174 modelsChanged ||
175 (before?.activeProvider ?? null) !== (after?.activeProvider ?? null) ||
176 (before?.runtimeMode ?? null) !== (after?.runtimeMode ?? null) ||
177 (before?.interactionMode ?? null) !== (after?.interactionMode ?? null)
178 );
180​
181/** Watches for edits and attachment invalidation while a send waits for routing. */
182export function watchComposerSendEdits(
183 draftTarget: ComposerThreadTarget,
184): () => "ready" | "edited" | "attachments-cancelled" {
185 const targetKey = composerTargetKey(draftTarget);
186 const submittedImages = new Set(getPreparingComposerImages(targetKey));
187 const cancelGeneration = cancelGenerations.get(targetKey);
188 let draft = useComposerDraftStore.getState().getComposerDraft(draftTarget);
189 let changed = false;
190 const stopWatchingDraft = useComposerDraftStore.subscribe((state) => {
191 const next = state.getComposerDraft(draftTarget);
192 if (!preparedImagesJoiningDraft) {
193 changed ||=
194 composerSendSettingsChanged(draft, next) ||
195 (draft && next
196 ? composerDraftContentChanged(draft, next)
197 : composerDraftHasUserContent(draft ?? next));
198 }
199 draft = next;
200 });
201 const stopWatchingImages = usePreparingComposerImageStore.subscribe(() => {
202 if (getPreparingComposerImages(targetKey).some((image) => !submittedImages.has(image))) {
203 changed = true;
204 }
205 });
206 return () => {
207 stopWatchingDraft();
208 stopWatchingImages();
209 if (cancelGenerations.get(targetKey) !== cancelGeneration) return "attachments-cancelled";
210 return changed ? "edited" : "ready";
211 };
213​
214/**
215 * Holds a send made while the draft still has images compressing. Resolves ready once they join
216 * the draft, or cancelled if the draft is edited or the send cancelled. Null means nothing needs
217 * to wait. Lives outside the composer so leaving the thread still completes the send.
218 */
219export function holdComposerSend(
220 draftTarget: ComposerThreadTarget,
221): Promise<HeldComposerSendResult> | null {
222 const targetKey = composerTargetKey(draftTarget);
223 if (countPreparingComposerImages(targetKey) === 0) return null;
224 if (heldSends.has(targetKey)) return Promise.resolve({ status: "cancelled" });
225 return new Promise((resolve) => {
226 let draft = useComposerDraftStore.getState().getComposerDraft(draftTarget);
227 const settle = (result: HeldComposerSendResult) => {
228 if (heldSends.get(targetKey) !== settle) return;
229 heldSends.delete(targetKey);
230 stopWatchingImages();
231 stopWatchingDraft();
232 useHeldSendStore.setState((state) => {
233 const targetKeys = { ...state.targetKeys };
234 delete targetKeys[targetKey];
235 return { targetKeys };
236 });
237 resolve(result);
238 };
239 heldSends.set(targetKey, settle);
240 const stopWatchingImages = usePreparingComposerImageStore.subscribe((state) => {
241 if (state.byTargetKey[targetKey]) return;
242 // Let joinPreparedImagesToDraft finish inserting compressed images in this tick first.
243 queueMicrotask(() => settle({ status: "ready" }));
244 });
245 const stopWatchingDraft = useComposerDraftStore.subscribe((state) => {
246 const next = state.getComposerDraft(draftTarget);
247 if (
248 !preparedImagesJoiningDraft &&
249 (composerDraftContentChanged(draft, next) || composerSendSettingsChanged(draft, next))
250 ) {
251 settle({ status: "cancelled" });
252 }
253 draft = next;
254 });
255 useHeldSendStore.setState((state) => ({
256 targetKeys: { ...state.targetKeys, [targetKey]: true },
257 }));
258 });
260​
261/** Drops every image still preparing for the target, so its compression result is discarded. */
262export function cancelPreparingComposerImages(targetKey: string): void {
263 invalidatePendingSubmit(targetKey);
264 if (!usePreparingComposerImageStore.getState().byTargetKey[targetKey]) return;
265 usePreparingComposerImageStore.setState((state) => {
266 const byTargetKey = { ...state.byTargetKey };
267 delete byTargetKey[targetKey];
268 return { byTargetKey };
269 });
271​
272/**
273 * Holds a send made while the target still has images compressing, and runs it once they finish,
274 * so the turn includes them. Returns false when nothing is compressing and the caller should send.
275 * The held send drops when `revision` (the content it would carry) changes, or when an attachment
276 * is added or a ready one removed; `attachmentIds` are the draft's own attachments.
277 */
278export function useSubmitAfterPreparingImages(
279 targetKey: string,
280 blocked: boolean,
281 revision: string,
282 attachmentIds: ReadonlyArray<string>,
283) {
284 const preparing = usePreparingComposerImages(targetKey);
285 const pendingRef = useRef<{
286 readonly targetKey: string;
287 readonly cancelGeneration: number;
288 readonly revision: string;
289 readonly readyAttachmentIds: Set<string>;
290 readonly attachmentIds: ReadonlySet<string>;
291 readonly submit: () => void;
292 } | null>(null);
293 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sends only after the render where the compressed images joined the draft
294 useEffect(() => {
295 const pending = pendingRef.current;
296 if (!pending) return;
297 const current = new Set([...attachmentIds, ...preparing.map((image) => image.id)]);
298 if (
299 pending.targetKey !== targetKey ||
300 pending.revision !== revision ||
301 pending.cancelGeneration !== (cancelGenerations.get(targetKey) ?? 0) ||
302 [...current].some((id) => !pending.attachmentIds.has(id)) ||
303 [...pending.readyAttachmentIds].some((id) => !current.has(id))
304 ) {
305 pendingRef.current = null;
306 return;
307 }
308 // An image that joins the draft while the send waits counts as ready, so removing it drops it.
309 for (const id of attachmentIds) pending.readyAttachmentIds.add(id);
310 if (preparing.length > 0 || blocked) return;
311 pendingRef.current = null;
312 // After the composer's later effects have synced its draft refs to this render.
313 queueMicrotask(pending.submit);
314 }, [preparing, targetKey, blocked, revision, attachmentIds]);
315 return useStableCallback((submit: () => void) => {
316 const preparingNow = getPreparingComposerImages(targetKey);
317 if (preparingNow.length === 0) return false;
318 pendingRef.current = {
319 targetKey,
320 cancelGeneration: cancelGenerations.get(targetKey) ?? 0,
321 revision,
322 readyAttachmentIds: new Set(attachmentIds),
323 attachmentIds: new Set([...attachmentIds, ...preparingNow.map((image) => image.id)]),
324 submit,
325 };
326 return true;
327 });