The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { useEffect } from "react"; |
| 2 | import { |
| 3 | EnvironmentId, |
| 4 | ProjectId, |
| 5 | PROVIDER_SEND_TURN_MAX_ATTACHMENTS, |
| 6 | RuntimeRequestId, |
| 7 | ThreadId, |
| 8 | } from "@t3tools/contracts"; |
| 9 | import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 10 | import { makeThreadRequestsResolvedAnnouncer } from "@t3tools/client-runtime/state/thread-requests"; |
| 11 | import { expect, it, vi } from "vite-plus/test"; |
| 12 | import { AsyncResult } from "effect/reactivity"; |
| 13 | |
| 14 | import { act, render } from "../../../test/render"; |
| 15 | import { |
| 16 | type ComposerImageAttachment, |
| 17 | DraftId, |
| 18 | composerTargetKey, |
| 19 | hydrateImagesFromPersisted, |
| 20 | useComposerDraftStore, |
| 21 | } from "../../composerDraftStore"; |
| 22 | import { showThreadUndoNotice } from "../../hooks/showThreadUndoNotice"; |
| 23 | import { discardComposerDraft } from "../../lib/discardComposerDraft"; |
| 24 | import { questionAttachmentDraftId } from "../../questionAttachments"; |
| 25 | import { readComposerImageBytes } from "./composerAttachmentFiles"; |
| 26 | import { |
| 27 | getPreparingComposerImages, |
| 28 | useSubmitAfterPreparingImages, |
| 29 | } from "./preparingComposerImages"; |
| 30 | import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; |
| 31 | |
| 32 | const compression = vi.hoisted(() => ({ prepare: vi.fn() })); |
| 33 | vi.mock("../../lib/imageCompression", async (importOriginal) => ({ |
| 34 | ...(await importOriginal<typeof import("../../lib/imageCompression")>()), |
| 35 | prepareImageForAttachment: compression.prepare, |
| 36 | })); |
| 37 | vi.mock("../../hooks/showThreadUndoNotice", () => ({ showThreadUndoNotice: vi.fn() })); |
| 38 | |
| 39 | type IntakeInput = Parameters<typeof useComposerAttachmentIntake>[0]; |
| 40 | type Intake = ReturnType<typeof useComposerAttachmentIntake>; |
| 41 | |
| 42 | function Harness({ input, ready }: { input: IntakeInput; ready: (value: Intake) => void }) { |
| 43 | const intake = useComposerAttachmentIntake(input); |
| 44 | useEffect(() => ready(intake)); |
| 45 | return null; |
| 46 | } |
| 47 | |
| 48 | function SendProbe(props: { |
| 49 | target: string; |
| 50 | ready: (holdSend: ReturnType<typeof useSubmitAfterPreparingImages>) => void; |
| 51 | }) { |
| 52 | const holdSend = useSubmitAfterPreparingImages(props.target); |
| 53 | useEffect(() => props.ready(holdSend)); |
| 54 | return null; |
| 55 | } |
| 56 | |
| 57 | function deferred<T>() { |
| 58 | let resolve!: (value: T) => void; |
| 59 | const promise = new Promise<T>((fulfill) => { |
| 60 | resolve = fulfill; |
| 61 | }); |
| 62 | return { promise, resolve }; |
| 63 | } |
| 64 | |
| 65 | // A clipboard image arrives as a new File named image.png on every paste. |
| 66 | const pastedImage = (fill = 0) => |
| 67 | new File([new Uint8Array(100).fill(fill)], "image.png", { type: "image/png" }); |
| 68 | // Compression shrinks an image, so the draft's copy no longer matches the pasted bytes; images |
| 69 | // with different pixels compress to different sizes. |
| 70 | const compress = async (source: File) => { |
| 71 | const [firstByte = 0] = new Uint8Array(await source.arrayBuffer()); |
| 72 | return { |
| 73 | ok: true as const, |
| 74 | file: new File([new Uint8Array(60 + firstByte)], "image.png", { type: "image/png" }), |
| 75 | recompressed: true as const, |
| 76 | }; |
| 77 | }; |
| 78 | const visiblePreparing = (targetKey: string) => |
| 79 | getPreparingComposerImages(targetKey).filter((image) => !image.hidden); |
| 80 | |
| 81 | it.each(["available", "full", "duplicate"] as const)( |
| 82 | "finishes a cancelled question's screenshot and handles a waiting send (%s)", |
| 83 | async (capacity) => { |
| 84 | const store = useComposerDraftStore.getState(); |
| 85 | const environmentId = EnvironmentId.make(`intake-recovery-${capacity}`); |
| 86 | const threadId = ThreadId.make("thread"); |
| 87 | const requestId = RuntimeRequestId.make("question"); |
| 88 | const target = scopeThreadRef(environmentId, threadId); |
| 89 | const question = questionAttachmentDraftId(environmentId, threadId, requestId, "image"); |
| 90 | using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) }; |
| 91 | if (capacity !== "available") { |
| 92 | store.addFiles( |
| 93 | target, |
| 94 | Array.from( |
| 95 | { length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - (capacity === "duplicate" ? 1 : 0) }, |
| 96 | (_, index) => { |
| 97 | const name = `notes-${index}.txt`; |
| 98 | return { |
| 99 | type: "file" as const, |
| 100 | id: name, |
| 101 | name, |
| 102 | mimeType: "text/plain", |
| 103 | sizeBytes: 1, |
| 104 | file: new File(["a"], name, { type: "text/plain" }), |
| 105 | }; |
| 106 | }, |
| 107 | ), |
| 108 | ); |
| 109 | } |
| 110 | if (capacity === "duplicate") { |
| 111 | const { file } = await compress(pastedImage()); |
| 112 | await readComposerImageBytes(file); |
| 113 | store.addImages(target, [ |
| 114 | { |
| 115 | type: "image", |
| 116 | id: "existing-image", |
| 117 | name: file.name, |
| 118 | mimeType: file.type, |
| 119 | sizeBytes: file.size, |
| 120 | file, |
| 121 | previewUrl: URL.createObjectURL(file), |
| 122 | }, |
| 123 | ]); |
| 124 | } |
| 125 | const resumeCompression = deferred<void>(); |
| 126 | compression.prepare.mockReset().mockImplementation(async (file: File) => { |
| 127 | await resumeCompression.promise; |
| 128 | return compress(file); |
| 129 | }); |
| 130 | const setThreadError = vi.fn(); |
| 131 | let intake!: Intake; |
| 132 | let holdSend!: ReturnType<typeof useSubmitAfterPreparingImages>; |
| 133 | const send = vi.fn(); |
| 134 | await using _screen = await render( |
| 135 | <> |
| 136 | <Harness |
| 137 | input={{ |
| 138 | activeThreadId: threadId, |
| 139 | activePendingProgress: null, |
| 140 | activePendingIsResponding: false, |
| 141 | pendingUserInputs: [], |
| 142 | supportsQuestionAttachments: true, |
| 143 | isLiteralPendingAnswer: true, |
| 144 | projectSelectionRequired: false, |
| 145 | questionAttachmentTarget: question, |
| 146 | attachmentTargetKey: question, |
| 147 | fileStagingLimit: null, |
| 148 | promptRef: { current: "" }, |
| 149 | composerImagesRef: { current: [] }, |
| 150 | composerFilesRef: { current: [] }, |
| 151 | composerEditorRef: { current: null }, |
| 152 | isRevertingCheckpointRef: { current: false }, |
| 153 | setThreadError, |
| 154 | countReservedAttachments: () => 0, |
| 155 | addComposerImage: (image) => store.addImages(question, [image]), |
| 156 | addComposerImagesToDraft: (images) => store.addImages(question, images), |
| 157 | addComposerFilesToDraft: () => [], |
| 158 | removeComposerImageFromDraft: () => {}, |
| 159 | insertAttachmentReferences: () => false, |
| 160 | }} |
| 161 | ready={(value) => { |
| 162 | intake = value; |
| 163 | }} |
| 164 | /> |
| 165 | {capacity !== "available" && ( |
| 166 | <SendProbe |
| 167 | target={composerTargetKey(target)} |
| 168 | ready={(value) => { |
| 169 | holdSend = value; |
| 170 | }} |
| 171 | /> |
| 172 | )} |
| 173 | </>, |
| 174 | ); |
| 175 | const attaching = intake.addComposerAttachments([pastedImage()]); |
| 176 | makeThreadRequestsResolvedAnnouncer( |
| 177 | environmentId, |
| 178 | threadId, |
| 179 | )([{ id: requestId, status: "cancelled" }]); |
| 180 | if (capacity !== "available") { |
| 181 | expect(holdSend(send)).toBe(true); |
| 182 | } |
| 183 | await act(async () => { |
| 184 | resumeCompression.resolve(); |
| 185 | await attaching; |
| 186 | }); |
| 187 | |
| 188 | if (capacity === "full") { |
| 189 | expect(send).not.toHaveBeenCalled(); |
| 190 | expect(store.getComposerDraft(target)?.images).toEqual([]); |
| 191 | expect(setThreadError).toHaveBeenLastCalledWith( |
| 192 | threadId, |
| 193 | expect.stringContaining("image.png could not be restored"), |
| 194 | ); |
| 195 | } else if (capacity === "duplicate") { |
| 196 | expect(send).toHaveBeenCalledOnce(); |
| 197 | expect(store.getComposerDraft(target)?.images.map(({ id }) => id)).toEqual([ |
| 198 | "existing-image", |
| 199 | ]); |
| 200 | expect(setThreadError).toHaveBeenLastCalledWith(threadId, null); |
| 201 | } else { |
| 202 | expect(store.getComposerDraft(target)?.persistedAttachments).toEqual([ |
| 203 | expect.objectContaining({ |
| 204 | name: "image.png", |
| 205 | dataUrl: expect.stringContaining("data:image/png;base64,"), |
| 206 | }), |
| 207 | ]); |
| 208 | expect(setThreadError).toHaveBeenLastCalledWith(threadId, null); |
| 209 | } |
| 210 | }, |
| 211 | ); |
| 212 | |
| 213 | it("saves recovered image records alongside existing records and drops stale results", async () => { |
| 214 | const target = DraftId.make("intake-recovery-persisted-records"); |
| 215 | const store = useComposerDraftStore.getState(); |
| 216 | using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) }; |
| 217 | const saved = { |
| 218 | id: "saved", |
| 219 | name: "saved.png", |
| 220 | mimeType: "image/png", |
| 221 | sizeBytes: 1, |
| 222 | dataUrl: "data:image/png;base64,AQ==", |
| 223 | }; |
| 224 | const recovered = { ...saved, id: "recovered", dataUrl: "data:image/png;base64,Ag==" }; |
| 225 | const stale = { ...saved, id: "replaced", dataUrl: "data:image/png;base64,Aw==" }; |
| 226 | const images = hydrateImagesFromPersisted([saved, recovered, stale]); |
| 227 | store.addImages(target, images); |
| 228 | await store.syncPersistedAttachments(target, [saved]); |
| 229 | store.removeImage(target, stale.id); |
| 230 | const replacement = hydrateImagesFromPersisted([ |
| 231 | { ...stale, dataUrl: "data:image/png;base64,BA==" }, |
| 232 | ]); |
| 233 | expect(store.addImages(target, replacement)).toEqual([stale.id]); |
| 234 | |
| 235 | await store.appendPersistedAttachments(target, images, [recovered, stale]); |
| 236 | |
| 237 | expect(store.getComposerDraft(target)?.persistedAttachments).toEqual([saved, recovered]); |
| 238 | }); |
| 239 | |
| 240 | it("prepares a repeated paste without a tile, and still keeps a different image", async () => { |
| 241 | const target = DraftId.make("intake-repeat-paste"); |
| 242 | const store = useComposerDraftStore.getState(); |
| 243 | using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) }; |
| 244 | const firstCompression = deferred<void>(); |
| 245 | compression.prepare |
| 246 | .mockReset() |
| 247 | .mockImplementationOnce(async (file: File) => { |
| 248 | await firstCompression.promise; |
| 249 | return compress(file); |
| 250 | }) |
| 251 | .mockImplementation(compress); |
| 252 | const composerImagesRef = { current: [] as ComposerImageAttachment[] }; |
| 253 | const addImages = (images: ComposerImageAttachment[]) => { |
| 254 | const ids = store.addImages(target, images); |
| 255 | composerImagesRef.current = |
| 256 | useComposerDraftStore.getState().getComposerDraft(target)?.images ?? []; |
| 257 | return ids; |
| 258 | }; |
| 259 | const input = { |
| 260 | activeThreadId: ThreadId.make("thread"), |
| 261 | activePendingProgress: null, |
| 262 | activePendingIsResponding: false, |
| 263 | pendingUserInputs: [], |
| 264 | supportsQuestionAttachments: false, |
| 265 | isLiteralPendingAnswer: false, |
| 266 | projectSelectionRequired: false, |
| 267 | questionAttachmentTarget: null, |
| 268 | attachmentTargetKey: target, |
| 269 | fileStagingLimit: null, |
| 270 | promptRef: { current: "" }, |
| 271 | composerImagesRef, |
| 272 | composerFilesRef: { current: [] }, |
| 273 | composerEditorRef: { current: null }, |
| 274 | isRevertingCheckpointRef: { current: false }, |
| 275 | setThreadError: () => {}, |
| 276 | countReservedAttachments: () => |
| 277 | composerImagesRef.current.length + getPreparingComposerImages(target).length, |
| 278 | addComposerImage: (image) => addImages([image]), |
| 279 | addComposerImagesToDraft: addImages, |
| 280 | addComposerFilesToDraft: () => [], |
| 281 | removeComposerImageFromDraft: () => {}, |
| 282 | insertAttachmentReferences: () => false, |
| 283 | } satisfies IntakeInput; |
| 284 | let intake!: Intake; |
| 285 | await using _screen = await render( |
| 286 | <Harness |
| 287 | input={input} |
| 288 | ready={(value) => { |
| 289 | intake = value; |
| 290 | }} |
| 291 | />, |
| 292 | ); |
| 293 | |
| 294 | const first = intake.addComposerAttachments([pastedImage()]); |
| 295 | const whileCompressing = intake.addComposerAttachments([pastedImage()]); |
| 296 | expect(visiblePreparing(target)).toHaveLength(1); |
| 297 | await act(async () => { |
| 298 | firstCompression.resolve(); |
| 299 | await Promise.all([first, whileCompressing]); |
| 300 | }); |
| 301 | |
| 302 | const afterCompression = intake.addComposerAttachments([pastedImage()]); |
| 303 | expect(visiblePreparing(target)).toHaveLength(0); |
| 304 | await act(() => afterCompression); |
| 305 | expect(composerImagesRef.current).toHaveLength(1); |
| 306 | |
| 307 | // Same name, type and size, different pixels: it compresses differently and is kept. |
| 308 | const different = intake.addComposerAttachments([pastedImage(7)]); |
| 309 | expect(visiblePreparing(target)).toHaveLength(0); |
| 310 | await act(() => different); |
| 311 | expect(composerImagesRef.current).toHaveLength(2); |
| 312 | }); |
| 313 | |
| 314 | // The thread row's discard runs after the composer left that thread; a draft session's discard |
| 315 | // unmounts its composer afterwards. |
| 316 | it.each(["thread", "session"] as const)( |
| 317 | "a %s draft discarded while an image compresses stays discarded and can be restored", |
| 318 | async (kind) => { |
| 319 | const store = useComposerDraftStore.getState(); |
| 320 | const environmentId = EnvironmentId.make(`intake-discard-${kind}`); |
| 321 | const threadId = ThreadId.make("thread"); |
| 322 | const target = |
| 323 | kind === "session" ? DraftId.make("intake-discard") : scopeThreadRef(environmentId, threadId); |
| 324 | if (typeof target === "string") { |
| 325 | store.setProjectDraftThreadId(scopeProjectRef(environmentId, ProjectId.make("p")), target); |
| 326 | } |
| 327 | store.setPrompt(target, "half-written prompt"); |
| 328 | using _draft = { |
| 329 | [Symbol.dispose]: () => { |
| 330 | if (typeof target === "string") store.clearDraftThread(target); |
| 331 | else store.clearComposerContent(target); |
| 332 | }, |
| 333 | }; |
| 334 | const targetKey = composerTargetKey(target); |
| 335 | |
| 336 | const compressing = deferred<void>(); |
| 337 | const resumeCompression = deferred<void>(); |
| 338 | compression.prepare.mockReset().mockImplementation(async (file: File) => { |
| 339 | compressing.resolve(); |
| 340 | await resumeCompression.promise; |
| 341 | return compress(file); |
| 342 | }); |
| 343 | |
| 344 | const input = { |
| 345 | activeThreadId: threadId, |
| 346 | activePendingProgress: null, |
| 347 | activePendingIsResponding: false, |
| 348 | pendingUserInputs: [], |
| 349 | supportsQuestionAttachments: false, |
| 350 | isLiteralPendingAnswer: false, |
| 351 | projectSelectionRequired: false, |
| 352 | questionAttachmentTarget: null, |
| 353 | attachmentTargetKey: targetKey, |
| 354 | fileStagingLimit: null, |
| 355 | promptRef: { current: "half-written prompt" }, |
| 356 | composerImagesRef: { current: [] }, |
| 357 | composerFilesRef: { current: [] }, |
| 358 | composerEditorRef: { current: null }, |
| 359 | isRevertingCheckpointRef: { current: false }, |
| 360 | setThreadError: () => {}, |
| 361 | countReservedAttachments: () => getPreparingComposerImages(targetKey).length, |
| 362 | addComposerImage: (image) => store.addImages(target, [image]), |
| 363 | addComposerImagesToDraft: (images) => store.addImages(target, images), |
| 364 | addComposerFilesToDraft: () => [], |
| 365 | removeComposerImageFromDraft: (id) => store.removeImage(target, id), |
| 366 | insertAttachmentReferences: () => false, |
| 367 | } satisfies IntakeInput; |
| 368 | let intake!: Intake; |
| 369 | await using screen = await render( |
| 370 | <Harness |
| 371 | input={input} |
| 372 | ready={(value) => { |
| 373 | intake = value; |
| 374 | }} |
| 375 | />, |
| 376 | ); |
| 377 | const attaching = intake.addComposerAttachments([pastedImage()]); |
| 378 | await compressing.promise; |
| 379 | |
| 380 | if (kind === "session") { |
| 381 | discardComposerDraft(target); |
| 382 | await screen.unmount(); |
| 383 | } else { |
| 384 | await screen.unmount(); |
| 385 | discardComposerDraft(target); |
| 386 | } |
| 387 | await act(async () => { |
| 388 | resumeCompression.resolve(); |
| 389 | await attaching; |
| 390 | }); |
| 391 | |
| 392 | expect(getPreparingComposerImages(targetKey)).toHaveLength(0); |
| 393 | expect(useComposerDraftStore.getState().getComposerDraft(target)).toBeNull(); |
| 394 | const undo = vi.mocked(showThreadUndoNotice).mock.calls.at(-1)![0].undo; |
| 395 | expect(AsyncResult.isSuccess(await undo())).toBe(true); |
| 396 | const restored = useComposerDraftStore.getState().getComposerDraft(target); |
| 397 | expect(restored?.prompt).toBe("half-written prompt"); |
| 398 | expect(restored?.images).toEqual([]); |
| 399 | }, |
| 400 | ); |