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

useComposerAttachmentIntake.browser.test.tsx

219 lines8.3 KB

1import { useEffect } from "react";
2import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
3import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
4import { expect, it, vi } from "vite-plus/test";
5import { AsyncResult } from "effect/reactivity";
6​
7import { act, render } from "../../../test/render";
8import {
9 type ComposerImageAttachment,
10 DraftId,
11 composerTargetKey,
12 useComposerDraftStore,
13} from "../../composerDraftStore";
14import { showThreadUndoNotice } from "../../hooks/showThreadUndoNotice";
15import { discardComposerDraft } from "../../lib/discardComposerDraft";
16import { getPreparingComposerImages } from "./preparingComposerImages";
17import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake";
18​
19const compression = vi.hoisted(() => ({ prepare: vi.fn() }));
20vi.mock("../../lib/imageCompression", async (importOriginal) => ({
21 ...(await importOriginal<typeof import("../../lib/imageCompression")>()),
22 prepareImageForAttachment: compression.prepare,
23}));
24vi.mock("../../hooks/showThreadUndoNotice", () => ({ showThreadUndoNotice: vi.fn() }));
25​
26type IntakeInput = Parameters<typeof useComposerAttachmentIntake>[0];
27type Intake = ReturnType<typeof useComposerAttachmentIntake>;
28​
29function Harness({ input, ready }: { input: IntakeInput; ready: (value: Intake) => void }) {
30 const intake = useComposerAttachmentIntake(input);
31 useEffect(() => ready(intake));
32 return null;
34​
35function deferred<T>() {
36 let resolve!: (value: T) => void;
37 const promise = new Promise<T>((fulfill) => {
38 resolve = fulfill;
39 });
40 return { promise, resolve };
42​
43// A clipboard image arrives as a new File named image.png on every paste.
44const pastedImage = (fill = 0) =>
45 new File([new Uint8Array(100).fill(fill)], "image.png", { type: "image/png" });
46// Compression shrinks an image, so the draft's copy no longer matches the pasted bytes; images
47// with different pixels compress to different sizes.
48const compress = async (source: File) => {
49 const [firstByte = 0] = new Uint8Array(await source.arrayBuffer());
50 return {
51 ok: true as const,
52 file: new File([new Uint8Array(60 + firstByte)], "image.png", { type: "image/png" }),
53 recompressed: true as const,
54 };
55};
56const visiblePreparing = (targetKey: string) =>
57 getPreparingComposerImages(targetKey).filter((image) => !image.hidden);
58​
59it("prepares a repeated paste without a tile, and still keeps a different image", async () => {
60 const target = DraftId.make("intake-repeat-paste");
61 const store = useComposerDraftStore.getState();
62 using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) };
63 const firstCompression = deferred<void>();
64 compression.prepare
65 .mockReset()
66 .mockImplementationOnce(async (file: File) => {
67 await firstCompression.promise;
68 return compress(file);
69 })
70 .mockImplementation(compress);
71 const composerImagesRef = { current: [] as ComposerImageAttachment[] };
72 const addImages = (images: ComposerImageAttachment[]) => {
73 const ids = store.addImages(target, images);
74 composerImagesRef.current =
75 useComposerDraftStore.getState().getComposerDraft(target)?.images ?? [];
76 return ids;
77 };
78 const input = {
79 activeThreadId: ThreadId.make("thread"),
80 activePendingProgress: null,
81 activePendingIsResponding: false,
82 pendingUserInputs: [],
83 supportsQuestionAttachments: false,
84 isLiteralPendingAnswer: false,
85 projectSelectionRequired: false,
86 questionAttachmentTarget: null,
87 attachmentTargetKey: target,
88 fileStagingLimit: null,
89 promptRef: { current: "" },
90 composerImagesRef,
91 composerFilesRef: { current: [] },
92 composerEditorRef: { current: null },
93 isRevertingCheckpointRef: { current: false },
94 setThreadError: () => {},
95 countReservedAttachments: () =>
96 composerImagesRef.current.length + getPreparingComposerImages(target).length,
97 addComposerImage: (image) => addImages([image]),
98 addComposerImagesToDraft: addImages,
99 addComposerFilesToDraft: () => [],
100 removeComposerImageFromDraft: () => {},
101 insertAttachmentReferences: () => false,
102 } satisfies IntakeInput;
103 let intake!: Intake;
104 await using _screen = await render(
105 <Harness
106 input={input}
107 ready={(value) => {
108 intake = value;
109 }}
110 />,
111 );
112​
113 const first = intake.addComposerAttachments([pastedImage()]);
114 const whileCompressing = intake.addComposerAttachments([pastedImage()]);
115 expect(visiblePreparing(target)).toHaveLength(1);
116 await act(async () => {
117 firstCompression.resolve();
118 await Promise.all([first, whileCompressing]);
119 });
120​
121 const afterCompression = intake.addComposerAttachments([pastedImage()]);
122 expect(visiblePreparing(target)).toHaveLength(0);
123 await act(() => afterCompression);
124 expect(composerImagesRef.current).toHaveLength(1);
125​
126 // Same name, type and size, different pixels: it compresses differently and is kept.
127 const different = intake.addComposerAttachments([pastedImage(7)]);
128 expect(visiblePreparing(target)).toHaveLength(0);
129 await act(() => different);
130 expect(composerImagesRef.current).toHaveLength(2);
131});
132​
133// The thread row's discard runs after the composer left that thread; a draft session's discard
134// unmounts its composer afterwards.
135it.each(["thread", "session"] as const)(
136 "a %s draft discarded while an image compresses stays discarded and can be restored",
137 async (kind) => {
138 const store = useComposerDraftStore.getState();
139 const environmentId = EnvironmentId.make(`intake-discard-${kind}`);
140 const threadId = ThreadId.make("thread");
141 const target =
142 kind === "session" ? DraftId.make("intake-discard") : scopeThreadRef(environmentId, threadId);
143 if (typeof target === "string") {
144 store.setProjectDraftThreadId(scopeProjectRef(environmentId, ProjectId.make("p")), target);
145 }
146 store.setPrompt(target, "half-written prompt");
147 using _draft = {
148 [Symbol.dispose]: () => {
149 if (typeof target === "string") store.clearDraftThread(target);
150 else store.clearComposerContent(target);
151 },
152 };
153 const targetKey = composerTargetKey(target);
154​
155 const compressing = deferred<void>();
156 const resumeCompression = deferred<void>();
157 compression.prepare.mockReset().mockImplementation(async (file: File) => {
158 compressing.resolve();
159 await resumeCompression.promise;
160 return compress(file);
161 });
162​
163 const input = {
164 activeThreadId: threadId,
165 activePendingProgress: null,
166 activePendingIsResponding: false,
167 pendingUserInputs: [],
168 supportsQuestionAttachments: false,
169 isLiteralPendingAnswer: false,
170 projectSelectionRequired: false,
171 questionAttachmentTarget: null,
172 attachmentTargetKey: targetKey,
173 fileStagingLimit: null,
174 promptRef: { current: "half-written prompt" },
175 composerImagesRef: { current: [] },
176 composerFilesRef: { current: [] },
177 composerEditorRef: { current: null },
178 isRevertingCheckpointRef: { current: false },
179 setThreadError: () => {},
180 countReservedAttachments: () => getPreparingComposerImages(targetKey).length,
181 addComposerImage: (image) => store.addImages(target, [image]),
182 addComposerImagesToDraft: (images) => store.addImages(target, images),
183 addComposerFilesToDraft: () => [],
184 removeComposerImageFromDraft: (id) => store.removeImage(target, id),
185 insertAttachmentReferences: () => false,
186 } satisfies IntakeInput;
187 let intake!: Intake;
188 await using screen = await render(
189 <Harness
190 input={input}
191 ready={(value) => {
192 intake = value;
193 }}
194 />,
195 );
196 const attaching = intake.addComposerAttachments([pastedImage()]);
197 await compressing.promise;
198​
199 if (kind === "session") {
200 discardComposerDraft(target);
201 await screen.unmount();
202 } else {
203 await screen.unmount();
204 discardComposerDraft(target);
205 }
206 await act(async () => {
207 resumeCompression.resolve();
208 await attaching;
209 });
210​
211 expect(getPreparingComposerImages(targetKey)).toHaveLength(0);
212 expect(useComposerDraftStore.getState().getComposerDraft(target)).toBeNull();
213 const undo = vi.mocked(showThreadUndoNotice).mock.calls.at(-1)![0].undo;
214 expect(AsyncResult.isSuccess(await undo())).toBe(true);
215 const restored = useComposerDraftStore.getState().getComposerDraft(target);
216 expect(restored?.prompt).toBe("half-written prompt");
217 expect(restored?.images).toEqual([]);
218 },
219);