The best way to control Claude Code, Codex and more from any computer or phone

main
ts 170 lines 6.16 KB
Raw
1 import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2 import type { ScopedThreadRef } from "@t3tools/contracts";
3 import { useEffect, useRef } from "react";
4 import { create } from "zustand";
5
6 import { useStableCallback } from "../../hooks/useStableCallback";
7
8 export interface PreparingComposerImage {
9 readonly id: string;
10 readonly name: string;
11 /** The uncompressed source, thumbnailed so the placeholder shows the image itself. */
12 readonly file: File;
13 /** Looks like an image the draft already has: it holds its slot but shows no tile. */
14 readonly hidden: boolean;
15 }
16
17 const NO_PREPARING_IMAGES: ReadonlyArray<PreparingComposerImage> = [];
18
19 /**
20 * Images accepted into a draft but still being compressed, keyed by attachment target. Large
21 * screenshots take a noticeable moment to re-encode, so the strip shows these right away and
22 * they hold their attachment slots until the real image joins the draft.
23 */
24 const usePreparingComposerImageStore = create<{
25 readonly byTargetKey: Readonly<Record<string, ReadonlyArray<PreparingComposerImage>>>;
26 }>(() => ({ byTargetKey: {} }));
27
28 const movedImageThreads = new WeakMap<PreparingComposerImage, ScopedThreadRef>();
29
30 export function movedPreparingImageThread(image: PreparingComposerImage) {
31 return movedImageThreads.get(image);
32 }
33
34 /** Carries the live tiles to the thread, where they can still be removed or awaited. */
35 export function movePreparingComposerImagesToThread(
36 sourceKey: string,
37 thread: ScopedThreadRef,
38 ): void {
39 const images = getPreparingComposerImages(sourceKey);
40 if (images.length === 0) return;
41 const threadKey = scopedThreadKey(thread);
42 for (const image of images) movedImageThreads.set(image, thread);
43 invalidatePendingSubmit(sourceKey);
44 usePreparingComposerImageStore.setState(({ byTargetKey }) => {
45 const next = { ...byTargetKey };
46 delete next[sourceKey];
47 next[threadKey] = [...(next[threadKey] ?? NO_PREPARING_IMAGES), ...images];
48 return { byTargetKey: next };
49 });
50 }
51
52 export function usePreparingComposerImages(targetKey: string) {
53 return usePreparingComposerImageStore(
54 (state) => state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES,
55 );
56 }
57
58 export function getPreparingComposerImages(
59 targetKey: string,
60 ): ReadonlyArray<PreparingComposerImage> {
61 return usePreparingComposerImageStore.getState().byTargetKey[targetKey] ?? NO_PREPARING_IMAGES;
62 }
63
64 export function countPreparingComposerImages(targetKey: string): number {
65 return getPreparingComposerImages(targetKey).length;
66 }
67
68 export function addPreparingComposerImages(
69 targetKey: string,
70 images: ReadonlyArray<PreparingComposerImage>,
71 ): void {
72 usePreparingComposerImageStore.setState((state) => ({
73 byTargetKey: {
74 ...state.byTargetKey,
75 [targetKey]: [...(state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES), ...images],
76 },
77 }));
78 }
79
80 export function isPreparingComposerImage(targetKey: string, imageId: string): boolean {
81 return (
82 usePreparingComposerImageStore
83 .getState()
84 .byTargetKey[targetKey]?.some((image) => image.id === imageId) ?? false
85 );
86 }
87
88 /** Returns the ids that were still preparing; any other id was cancelled from the strip. */
89 export function removePreparingComposerImages(
90 targetKey: string,
91 imageIds: ReadonlySet<string>,
92 options?: { readonly cancelSubmission?: boolean },
93 ): ReadonlySet<string> {
94 const current =
95 usePreparingComposerImageStore.getState().byTargetKey[targetKey] ?? NO_PREPARING_IMAGES;
96 const removed = new Set(
97 current.filter((image) => imageIds.has(image.id)).map((image) => image.id),
98 );
99 if (removed.size === 0) return removed;
100 if (options?.cancelSubmission) invalidatePendingSubmit(targetKey);
101 usePreparingComposerImageStore.setState((state) => {
102 const remaining = (state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES).filter(
103 (image) => !removed.has(image.id),
104 );
105 const byTargetKey = { ...state.byTargetKey };
106 if (remaining.length > 0) {
107 byTargetKey[targetKey] = remaining;
108 } else {
109 delete byTargetKey[targetKey];
110 }
111 return { byTargetKey };
112 });
113 return removed;
114 }
115
116 // Bumped on cancel so a send held for the cancelled images is dropped rather than released.
117 const cancelGenerations = new Map<string, number>();
118
119 function invalidatePendingSubmit(targetKey: string) {
120 cancelGenerations.set(targetKey, (cancelGenerations.get(targetKey) ?? 0) + 1);
121 }
122
123 /** Drops every image still preparing for the target, so its compression result is discarded. */
124 export function cancelPreparingComposerImages(targetKey: string): void {
125 invalidatePendingSubmit(targetKey);
126 if (!usePreparingComposerImageStore.getState().byTargetKey[targetKey]) return;
127 usePreparingComposerImageStore.setState((state) => {
128 const byTargetKey = { ...state.byTargetKey };
129 delete byTargetKey[targetKey];
130 return { byTargetKey };
131 });
132 }
133
134 /**
135 * Holds a send made while the target still has images compressing, and runs it once they finish,
136 * so the turn includes them. Returns false when nothing is compressing and the caller should send.
137 */
138 export function useSubmitAfterPreparingImages(targetKey: string, blocked = false) {
139 const preparing = usePreparingComposerImages(targetKey);
140 const pendingRef = useRef<{
141 readonly targetKey: string;
142 readonly cancelGeneration: number;
143 readonly submit: () => void;
144 } | null>(null);
145 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sends only after the render where the compressed images joined the draft
146 useEffect(() => {
147 const pending = pendingRef.current;
148 if (!pending) return;
149 if (
150 pending.targetKey !== targetKey ||
151 pending.cancelGeneration !== (cancelGenerations.get(targetKey) ?? 0)
152 ) {
153 pendingRef.current = null;
154 return;
155 }
156 if (preparing.length > 0 || blocked) return;
157 pendingRef.current = null;
158 // After the composer's later effects have synced its draft refs to this render.
159 queueMicrotask(pending.submit);
160 }, [preparing, targetKey, blocked]);
161 return useStableCallback((submit: () => void) => {
162 if (countPreparingComposerImages(targetKey) === 0) return false;
163 pendingRef.current = {
164 targetKey,
165 cancelGeneration: cancelGenerations.get(targetKey) ?? 0,
166 submit,
167 };
168 return true;
169 });
170 }