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

preparingComposerImages.ts

260 lines9.6 KB

1import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2import type { ScopedThreadRef } from "@t3tools/contracts";
3import { useEffect, useRef } from "react";
4import { create } from "zustand";
5​
6import {
7 composerTargetKey,
8 type ComposerThreadTarget,
9 useComposerDraftStore,
10} from "../../composerDraftStore";
11import { useStableCallback } from "../../hooks/useStableCallback";
12import { composerDraftContentChanged } from "./composerSend.logic";
13​
14export interface PreparingComposerImage {
15 readonly id: string;
16 readonly name: string;
17 /** The uncompressed source, thumbnailed so the placeholder shows the image itself. */
18 readonly file: File;
19 /** Looks like an image the draft already has: it holds its slot but shows no tile. */
20 readonly hidden: boolean;
22​
23const NO_PREPARING_IMAGES: ReadonlyArray<PreparingComposerImage> = [];
24​
25/**
26 * Images accepted into a draft but still being compressed, keyed by attachment target. Large
27 * screenshots take a noticeable moment to re-encode, so the strip shows these right away and
28 * they hold their attachment slots until the real image joins the draft.
29 */
30const usePreparingComposerImageStore = create<{
31 readonly byTargetKey: Readonly<Record<string, ReadonlyArray<PreparingComposerImage>>>;
32}>(() => ({ byTargetKey: {} }));
33​
34const movedImageThreads = new WeakMap<PreparingComposerImage, ScopedThreadRef>();
35​
36export function movedPreparingImageThread(image: PreparingComposerImage) {
37 return movedImageThreads.get(image);
39​
40/** Carries the live tiles to the thread, where they can still be removed or awaited. */
41export function movePreparingComposerImagesToThread(
42 sourceKey: string,
43 thread: ScopedThreadRef,
44): void {
45 const images = getPreparingComposerImages(sourceKey);
46 if (images.length === 0) return;
47 const threadKey = scopedThreadKey(thread);
48 for (const image of images) movedImageThreads.set(image, thread);
49 invalidatePendingSubmit(sourceKey);
50 usePreparingComposerImageStore.setState(({ byTargetKey }) => {
51 const next = { ...byTargetKey };
52 delete next[sourceKey];
53 next[threadKey] = [...(next[threadKey] ?? NO_PREPARING_IMAGES), ...images];
54 return { byTargetKey: next };
55 });
57​
58export function usePreparingComposerImages(targetKey: string) {
59 return usePreparingComposerImageStore(
60 (state) => state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES,
61 );
63​
64export function getPreparingComposerImages(
65 targetKey: string,
66): ReadonlyArray<PreparingComposerImage> {
67 return usePreparingComposerImageStore.getState().byTargetKey[targetKey] ?? NO_PREPARING_IMAGES;
69​
70export function countPreparingComposerImages(targetKey: string): number {
71 return getPreparingComposerImages(targetKey).length;
73​
74export function addPreparingComposerImages(
75 targetKey: string,
76 images: ReadonlyArray<PreparingComposerImage>,
77): void {
78 if (images.length > 0) {
79 heldSends.get(targetKey)?.({ status: "cancelled" });
80 }
81 usePreparingComposerImageStore.setState((state) => ({
82 byTargetKey: {
83 ...state.byTargetKey,
84 [targetKey]: [...(state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES), ...images],
85 },
86 }));
88​
89export function isPreparingComposerImage(targetKey: string, imageId: string): boolean {
90 return (
91 usePreparingComposerImageStore
92 .getState()
93 .byTargetKey[targetKey]?.some((image) => image.id === imageId) ?? false
94 );
96​
97/** Returns the ids that were still preparing; any other id was cancelled from the strip. */
98export function removePreparingComposerImages(
99 targetKey: string,
100 imageIds: ReadonlySet<string>,
101 options?: { readonly cancelSubmission?: boolean },
102): ReadonlySet<string> {
103 const current =
104 usePreparingComposerImageStore.getState().byTargetKey[targetKey] ?? NO_PREPARING_IMAGES;
105 const removed = new Set(
106 current.filter((image) => imageIds.has(image.id)).map((image) => image.id),
107 );
108 if (removed.size === 0) return removed;
109 if (options?.cancelSubmission) invalidatePendingSubmit(targetKey);
110 usePreparingComposerImageStore.setState((state) => {
111 const remaining = (state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES).filter(
112 (image) => !removed.has(image.id),
113 );
114 const byTargetKey = { ...state.byTargetKey };
115 if (remaining.length > 0) {
116 byTargetKey[targetKey] = remaining;
117 } else {
118 delete byTargetKey[targetKey];
119 }
120 return { byTargetKey };
121 });
122 return removed;
124​
125// Bumped on cancel so a send held for the cancelled images is dropped rather than released.
126const cancelGenerations = new Map<string, number>();
127​
128export type HeldComposerSendResult =
129 | { readonly status: "ready" }
130 | { readonly status: "cancelled" };
131​
132const heldSends = new Map<string, (result: HeldComposerSendResult) => void>();
133const useHeldSendStore = create<{ readonly targetKeys: Readonly<Record<string, true>> }>(() => ({
134 targetKeys: {},
135}));
136let preparedImagesJoiningDraft = false;
137​
138function invalidatePendingSubmit(targetKey: string) {
139 cancelGenerations.set(targetKey, (cancelGenerations.get(targetKey) ?? 0) + 1);
140 heldSends.get(targetKey)?.({ status: "cancelled" });
142​
143/** Whether a send from the target's draft is waiting on its images to finish preparing. */
144export function useComposerSendHeld(targetKey: string): boolean {
145 return useHeldSendStore((state) => state.targetKeys[targetKey] === true);
147​
148export function cancelHeldComposerSend(targetKey: string): void {
149 heldSends.get(targetKey)?.({ status: "cancelled" });
151​
152/** Inserts finished images into the draft without counting as an edit to a held send. */
153export function joinPreparedImagesToDraft<T>(insert: () => T): T {
154 preparedImagesJoiningDraft = true;
155 try {
156 return insert();
157 } finally {
158 preparedImagesJoiningDraft = false;
159 }
161​
162/**
163 * Holds a send made while the draft still has images compressing. Resolves ready once they join
164 * the draft, or cancelled if the draft is edited or the send cancelled. Null means nothing needs
165 * to wait. Lives outside the composer so leaving the thread still completes the send.
166 */
167export function holdComposerSend(
168 draftTarget: ComposerThreadTarget,
169): Promise<HeldComposerSendResult> | null {
170 const targetKey = composerTargetKey(draftTarget);
171 if (countPreparingComposerImages(targetKey) === 0) return null;
172 if (heldSends.has(targetKey)) return Promise.resolve({ status: "cancelled" });
173 return new Promise((resolve) => {
174 let draft = useComposerDraftStore.getState().getComposerDraft(draftTarget);
175 const settle = (result: HeldComposerSendResult) => {
176 if (heldSends.get(targetKey) !== settle) return;
177 heldSends.delete(targetKey);
178 stopWatchingImages();
179 stopWatchingDraft();
180 useHeldSendStore.setState((state) => {
181 const targetKeys = { ...state.targetKeys };
182 delete targetKeys[targetKey];
183 return { targetKeys };
184 });
185 resolve(result);
186 };
187 heldSends.set(targetKey, settle);
188 const stopWatchingImages = usePreparingComposerImageStore.subscribe((state) => {
189 if (state.byTargetKey[targetKey]) return;
190 // Let joinPreparedImagesToDraft finish inserting compressed images in this tick first.
191 queueMicrotask(() => settle({ status: "ready" }));
192 });
193 const stopWatchingDraft = useComposerDraftStore.subscribe((state) => {
194 const next = state.getComposerDraft(draftTarget);
195 if (
196 !preparedImagesJoiningDraft &&
197 (composerDraftContentChanged(draft, next) ||
198 draft?.modelSelectionByProvider !== next?.modelSelectionByProvider ||
199 draft?.activeProvider !== next?.activeProvider ||
200 draft?.runtimeMode !== next?.runtimeMode ||
201 draft?.interactionMode !== next?.interactionMode)
202 ) {
203 settle({ status: "cancelled" });
204 }
205 draft = next;
206 });
207 useHeldSendStore.setState((state) => ({
208 targetKeys: { ...state.targetKeys, [targetKey]: true },
209 }));
210 });
212​
213/** Drops every image still preparing for the target, so its compression result is discarded. */
214export function cancelPreparingComposerImages(targetKey: string): void {
215 invalidatePendingSubmit(targetKey);
216 if (!usePreparingComposerImageStore.getState().byTargetKey[targetKey]) return;
217 usePreparingComposerImageStore.setState((state) => {
218 const byTargetKey = { ...state.byTargetKey };
219 delete byTargetKey[targetKey];
220 return { byTargetKey };
221 });
223​
224/**
225 * Holds a send made while the target still has images compressing, and runs it once they finish,
226 * so the turn includes them. Returns false when nothing is compressing and the caller should send.
227 */
228export function useSubmitAfterPreparingImages(targetKey: string, blocked = false) {
229 const preparing = usePreparingComposerImages(targetKey);
230 const pendingRef = useRef<{
231 readonly targetKey: string;
232 readonly cancelGeneration: number;
233 readonly submit: () => void;
234 } | null>(null);
235 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sends only after the render where the compressed images joined the draft
236 useEffect(() => {
237 const pending = pendingRef.current;
238 if (!pending) return;
239 if (
240 pending.targetKey !== targetKey ||
241 pending.cancelGeneration !== (cancelGenerations.get(targetKey) ?? 0)
242 ) {
243 pendingRef.current = null;
244 return;
245 }
246 if (preparing.length > 0 || blocked) return;
247 pendingRef.current = null;
248 // After the composer's later effects have synced its draft refs to this render.
249 queueMicrotask(pending.submit);
250 }, [preparing, targetKey, blocked]);
251 return useStableCallback((submit: () => void) => {
252 if (countPreparingComposerImages(targetKey) === 0) return false;
253 pendingRef.current = {
254 targetKey,
255 cancelGeneration: cancelGenerations.get(targetKey) ?? 0,
256 submit,
257 };
258 return true;
259 });