Open History to see the last commit
1import { afterEach, describe, expect, it } from "@effect/vitest";
2import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
3import { vi } from "vite-plus/test";
4
5const composerDraftFileMocks = vi.hoisted(() => {
6 let document = "";
7 let writeError: Error | null = null;
8 let releaseRead: (() => void) | null = null;
9 let readBarrier = Promise.resolve();
10 let nextWriteBarrier: Promise<void> | null = null;
11 let onWrite: (() => void) | null = null;
12 const writes: string[] = [];
13
14 return {
15 blockRead() {
16 readBarrier = new Promise<void>((resolve) => {
17 releaseRead = resolve;
18 });
19 },
20 releaseRead() {
21 releaseRead?.();
22 releaseRead = null;
23 },
24 getDocument() {
25 return document;
26 },
27 setDocument(value: unknown) {
28 document = JSON.stringify(value);
29 },
30 setWriteError(error: Error | null) {
31 writeError = error;
32 },
33 setNextWriteBarrier(barrier: Promise<void> | null) {
34 nextWriteBarrier = barrier;
35 },
36 setOnWrite(callback: (() => void) | null) {
37 onWrite = callback;
38 },
39 getWrites(): ReadonlyArray<string> {
40 return writes;
41 },
42 resetWrites() {
43 writes.length = 0;
44 },
45 Directory: class {
46 create() {}
47 },
48 File: class {
49 exists = true;
50 parentDirectory = null;
51
52 create() {}
53
54 moveSync() {}
55
56 async text() {
57 await readBarrier;
58 return document;
59 }
60
61 write(value: string) {
62 if (writeError) {
63 throw writeError;
64 }
65 if (nextWriteBarrier) {
66 const barrier = nextWriteBarrier;
67 nextWriteBarrier = null;
68 return barrier.then(() => {
69 document = value;
70 writes.push(value);
71 onWrite?.();
72 });
73 }
74 document = value;
75 writes.push(value);
76 onWrite?.();
77 }
78 },
79 };
80});
81
82vi.mock("expo-file-system", () => ({
83 Directory: composerDraftFileMocks.Directory,
84 File: composerDraftFileMocks.File,
85 Paths: { document: "/documents" },
86}));
87
88import { appAtomRegistry } from "./atom-registry";
89import {
90 clearComposerDraftContentState,
91 clearComposerDraftsEnvironment,
92 ComposerDraftPersistenceError,
93 composerDraftsAtom,
94 copyComposerDraftContentIfEmpty,
95 copyComposerDraftContentState,
96 decodePersistedComposerState,
97 decodePersistedComposerDrafts,
98 ensureComposerDraftsLoaded,
99 type ComposerDraft,
100 flushComposerDrafts,
101 getComposerDraftSnapshot,
102 mergeComposerDraftContentState,
103 removeComposerDraftsForEnvironment,
104 resetComposerDraftsLoadState,
105 restoreComposerDraftSnapshotState,
106 setComposerDraftText,
107 setStickyComposerModelSelection,
108 stickyComposerModelSelectionAtom,
109} from "./use-composer-drafts";
110
111const DRAFT: ComposerDraft = {
112 text: "hello",
113 attachments: [],
114};
115
116afterEach(() => {
117 vi.useRealTimers();
118 resetComposerDraftsLoadState();
119 composerDraftFileMocks.setDocument("");
120 composerDraftFileMocks.setWriteError(null);
121 composerDraftFileMocks.setNextWriteBarrier(null);
122 composerDraftFileMocks.setOnWrite(null);
123 composerDraftFileMocks.resetWrites();
124 appAtomRegistry.set(composerDraftsAtom, {});
125 appAtomRegistry.set(stickyComposerModelSelectionAtom, null);
126});
127
128describe("mobile composer drafts", () => {
129 it("hydrates selector state even when the message content is empty", () => {
130 expect(
131 decodePersistedComposerDrafts({
132 schemaVersion: 1,
133 drafts: {
134 "new-task:environment-1:project-1": {
135 text: "",
136 attachments: [],
137 modelSelection: {
138 instanceId: "codex",
139 model: "gpt-5.4",
140 options: [{ id: "reasoningEffort", value: "xhigh" }],
141 },
142 runtimeMode: "approval-required",
143 interactionMode: "plan",
144 workspaceSelection: {
145 mode: "worktree",
146 branch: "main",
147 worktreePath: null,
148 },
149 },
150 },
151 }),
152 ).toEqual({
153 "new-task:environment-1:project-1": {
154 text: "",
155 attachments: [],
156 modelSelection: {
157 instanceId: "codex",
158 model: "gpt-5.4",
159 options: [{ id: "reasoningEffort", value: "xhigh" }],
160 },
161 runtimeMode: "approval-required",
162 interactionMode: "plan",
163 workspaceSelection: {
164 mode: "worktree",
165 branch: "main",
166 worktreePath: null,
167 },
168 },
169 });
170 });
171
172 it("keeps legacy content-only drafts and rejects invalid selector state", () => {
173 expect(
174 decodePersistedComposerDrafts({
175 schemaVersion: 1,
176 drafts: {
177 "environment-1:thread-1": DRAFT,
178 },
179 }),
180 ).toEqual({
181 "environment-1:thread-1": DRAFT,
182 });
183
184 expect(() =>
185 decodePersistedComposerDrafts({
186 schemaVersion: 1,
187 drafts: {
188 "environment-1:thread-1": {
189 ...DRAFT,
190 runtimeMode: "sometimes-safe",
191 },
192 },
193 }),
194 ).toThrow();
195 });
196
197 it("keeps share-import receipts on otherwise contentless new-task drafts", () => {
198 const receiptDraft: ComposerDraft = {
199 text: "",
200 attachments: [],
201 importedShareIds: ["share-1"],
202 };
203 // The stale-model strip must not touch receipt-bearing drafts, and the
204 // empty filter must keep them — or the same share would re-import after
205 // restart.
206 expect(
207 decodePersistedComposerState({
208 schemaVersion: 1,
209 drafts: {
210 "new-task:environment-1:project-1": {
211 ...receiptDraft,
212 modelSelection: {
213 instanceId: "codex",
214 model: "gpt-5.4",
215 },
216 },
217 },
218 }).drafts,
219 ).toEqual({
220 "new-task:environment-1:project-1": {
221 text: "",
222 attachments: [],
223 importedShareIds: ["share-1"],
224 },
225 });
226
227 expect(
228 decodePersistedComposerState({
229 schemaVersion: 1,
230 drafts: { "new-task:environment-1:project-1": receiptDraft },
231 }).drafts,
232 ).toEqual({ "new-task:environment-1:project-1": receiptDraft });
233 });
234
235 it("hydrates the global sticky model selection", () => {
236 expect(
237 decodePersistedComposerState({
238 schemaVersion: 1,
239 drafts: {},
240 stickyModelSelection: {
241 instanceId: "codex",
242 model: "gpt-5.6-sol",
243 },
244 }).stickyModelSelection,
245 ).toEqual({
246 instanceId: "codex",
247 model: "gpt-5.6-sol",
248 });
249 });
250
251 it("waits for hydration before persisting the latest composer state", async () => {
252 vi.useFakeTimers();
253 composerDraftFileMocks.setDocument({
254 schemaVersion: 1,
255 drafts: {
256 "environment-1:thread-1": DRAFT,
257 },
258 stickyModelSelection: {
259 instanceId: "codex",
260 model: "gpt-5.6-sol",
261 },
262 });
263 composerDraftFileMocks.blockRead();
264 composerDraftFileMocks.resetWrites();
265
266 ensureComposerDraftsLoaded();
267 await Promise.resolve();
268 // The read is blocked, hydration is pending.
269 setComposerDraftText("new-task:environment-1:project-1", "New prompt");
270 await vi.advanceTimersByTimeAsync(200);
271
272 // Write should still be deferred — hydration has not resolved.
273 expect(composerDraftFileMocks.getWrites()).toHaveLength(0);
274
275 composerDraftFileMocks.releaseRead();
276 // Let the loadPromise settle and chain into the deferred persist.
277 await vi.runAllTimersAsync();
278
279 expect(JSON.parse(composerDraftFileMocks.getWrites()[0]!)).toEqual({
280 schemaVersion: 1,
281 drafts: {
282 "environment-1:thread-1": DRAFT,
283 "new-task:environment-1:project-1": {
284 text: "New prompt",
285 attachments: [],
286 },
287 },
288 stickyModelSelection: {
289 instanceId: "codex",
290 model: "gpt-5.6-sol",
291 },
292 });
293 });
294
295 it("flush waits for pending hydration instead of clobbering disk", async () => {
296 vi.useFakeTimers();
297 composerDraftFileMocks.setDocument({
298 schemaVersion: 1,
299 drafts: {
300 "environment-1:thread-1": DRAFT,
301 },
302 stickyModelSelection: {
303 instanceId: "codex",
304 model: "gpt-5.6-sol",
305 },
306 });
307 composerDraftFileMocks.blockRead();
308 composerDraftFileMocks.resetWrites();
309
310 ensureComposerDraftsLoaded();
311 await Promise.resolve();
312 // An edit lands before hydration finishes; its debounced write is gated
313 // behind the blocked read.
314 setComposerDraftText("new-task:environment-1:project-1", "New prompt");
315
316 const flush = flushComposerDrafts();
317 await vi.advanceTimersByTimeAsync(200);
318 // The flush must not have written the pre-hydration snapshot over disk.
319 expect(composerDraftFileMocks.getWrites()).toHaveLength(0);
320
321 composerDraftFileMocks.releaseRead();
322 await flush;
323
324 const written = JSON.parse(composerDraftFileMocks.getDocument());
325 expect(written.drafts["environment-1:thread-1"]).toEqual(DRAFT);
326 expect(written.drafts["new-task:environment-1:project-1"]).toEqual({
327 text: "New prompt",
328 attachments: [],
329 });
330 expect(written.stickyModelSelection).toEqual({
331 instanceId: "codex",
332 model: "gpt-5.6-sol",
333 });
334 });
335
336 it("serializes environment cleanup after an older queued write", async () => {
337 vi.useFakeTimers();
338 composerDraftFileMocks.setDocument(JSON.stringify({ schemaVersion: 1, drafts: {} }));
339 composerDraftFileMocks.resetWrites();
340 let releaseFirstWrite!: () => void;
341 const firstWriteBarrier = new Promise<void>((resolve) => {
342 releaseFirstWrite = resolve;
343 });
344 composerDraftFileMocks.setNextWriteBarrier(firstWriteBarrier);
345 let writeCount = 0;
346 const bothWritesCommitted = new Promise<void>((resolve) => {
347 composerDraftFileMocks.setOnWrite(() => {
348 writeCount += 1;
349 if (writeCount === 2) {
350 resolve();
351 }
352 });
353 });
354
355 appAtomRegistry.set(composerDraftsAtom, {
356 "environment-1:thread-1": DRAFT,
357 "environment-2:thread-2": { text: "keep", attachments: [] },
358 });
359 setStickyComposerModelSelection({
360 instanceId: ProviderInstanceId.make("codex"),
361 model: "gpt-5.6-sol",
362 });
363 await vi.advanceTimersByTimeAsync(200);
364
365 const clear = clearComposerDraftsEnvironment(EnvironmentId.make("environment-1"));
366 await Promise.resolve();
367 // Cleanup write is queued behind the still-blocked debounced write.
368 expect(composerDraftFileMocks.getWrites()).toHaveLength(0);
369
370 releaseFirstWrite();
371 await clear;
372 await bothWritesCommitted;
373
374 expect(JSON.parse(composerDraftFileMocks.getDocument())).toEqual({
375 schemaVersion: 1,
376 drafts: {
377 "environment-2:thread-2": { text: "keep", attachments: [] },
378 },
379 stickyModelSelection: {
380 instanceId: "codex",
381 model: "gpt-5.6-sol",
382 },
383 });
384 });
385
386 it("clears sent content without clearing the selected model or workspace", () => {
387 const draftKey = "environment-1:thread-1";
388 const draft: ComposerDraft = {
389 text: "send this",
390 attachments: [],
391 importedShareIds: ["share-1"],
392 modelSelection: {
393 instanceId: ProviderInstanceId.make("codex"),
394 model: "gpt-5.4",
395 options: [{ id: "reasoningEffort", value: "xhigh" }],
396 },
397 workspaceSelection: {
398 mode: "worktree",
399 branch: "main",
400 worktreePath: null,
401 },
402 };
403
404 expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({
405 [draftKey]: {
406 modelSelection: draft.modelSelection,
407 workspaceSelection: draft.workspaceSelection,
408 text: "",
409 attachments: [],
410 },
411 });
412 });
413
414 it("drops draft-local model and workspace selections after sending a new task", () => {
415 const draftKey = "new-task:environment-1:project-1";
416 const draft: ComposerDraft = {
417 text: "send this",
418 attachments: [],
419 modelSelection: {
420 instanceId: ProviderInstanceId.make("codex"),
421 model: "gpt-5.4",
422 },
423 workspaceSelection: {
424 mode: "worktree",
425 branch: "main",
426 worktreePath: null,
427 startFromOrigin: false,
428 },
429 };
430
431 expect(
432 clearComposerDraftContentState({ [draftKey]: draft }, draftKey, {
433 clearModelSelection: true,
434 clearWorkspaceSelection: true,
435 }),
436 ).toEqual({});
437 });
438
439 it("reads the latest selector state synchronously for send", () => {
440 const draftKey = "environment-1:thread-1";
441 const selectedDraft: ComposerDraft = {
442 text: "send this",
443 attachments: [],
444 modelSelection: {
445 instanceId: ProviderInstanceId.make("codex"),
446 model: "gpt-5.4",
447 options: [{ id: "reasoningEffort", value: "xhigh" }],
448 },
449 };
450 appAtomRegistry.set(composerDraftsAtom, { [draftKey]: selectedDraft });
451
452 expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);
453 });
454
455 it("carries unfinished content to a newly selected project without overwriting its settings", () => {
456 const sourceKey = "new-task:environment-1:project-1";
457 const targetKey = "new-task:environment-1:project-2";
458 const source: ComposerDraft = {
459 text: "Keep this task",
460 attachments: [],
461 importedShareIds: ["share-1"],
462 workspaceSelection: {
463 mode: "worktree",
464 branch: "feature/source",
465 worktreePath: null,
466 },
467 };
468 const target: ComposerDraft = {
469 text: "",
470 attachments: [],
471 runtimeMode: "approval-required",
472 };
473
474 expect(
475 copyComposerDraftContentState(
476 { [sourceKey]: source, [targetKey]: target },
477 sourceKey,
478 targetKey,
479 ),
480 ).toEqual({
481 [sourceKey]: source,
482 [targetKey]: {
483 ...target,
484 text: source.text,
485 attachments: source.attachments,
486 importedShareIds: source.importedShareIds,
487 },
488 });
489 });
490
491 it("does not overwrite unfinished content already stored for the selected project", () => {
492 const sourceKey = "new-task:environment-1:project-1";
493 const targetKey = "new-task:environment-1:project-2";
494 const drafts: Record<string, ComposerDraft> = {
495 [sourceKey]: { text: "Source task", attachments: [] },
496 [targetKey]: { text: "Target task", attachments: [] },
497 };
498
499 expect(copyComposerDraftContentState(drafts, sourceKey, targetKey)).toBe(drafts);
500 });
501
502 it("merges shared content into a project draft without duplicating retries", () => {
503 const draftKey = "new-task:environment-1:project-1";
504 const sharedAttachment = {
505 id: "share-1:image:0",
506 type: "image" as const,
507 name: "Screenshot.png",
508 mimeType: "image/png",
509 sizeBytes: 3,
510 dataUrl: "data:image/png;base64,YWJj",
511 previewUri: "data:image/png;base64,YWJj",
512 };
513 const existing: Record<string, ComposerDraft> = {
514 [draftKey]: { text: "Existing context", attachments: [] },
515 };
516 const content = {
517 text: "Shared note",
518 attachments: [sharedAttachment],
519 sourceShareId: "share-1",
520 };
521
522 const merged = mergeComposerDraftContentState(existing, draftKey, content);
523 expect(merged[draftKey]).toMatchObject({
524 text: "Existing context\n\nShared note",
525 attachments: [sharedAttachment],
526 importedShareIds: ["share-1"],
527 });
528 expect(mergeComposerDraftContentState(merged, draftKey, content)).toBe(merged);
529
530 const edited = {
531 ...merged,
532 [draftKey]: { ...merged[draftKey]!, text: "User edited the imported context" },
533 };
534 expect(mergeComposerDraftContentState(edited, draftKey, content)).toBe(edited);
535 });
536
537 it("preserves existing images when shared content exceeds the draft attachment limit", () => {
538 const draftKey = "new-task:environment-1:project-1";
539 const image = (id: string) => ({
540 id,
541 type: "image" as const,
542 name: `${id}.png`,
543 mimeType: "image/png",
544 sizeBytes: 3,
545 dataUrl: "data:image/png;base64,YWJj",
546 previewUri: "data:image/png;base64,YWJj",
547 });
548 const existingImage = image("existing");
549 const sharedImages = Array.from({ length: 8 }, (_, index) => image(`shared-${index}`));
550
551 const merged = mergeComposerDraftContentState(
552 { [draftKey]: { text: "", attachments: [existingImage] } },
553 draftKey,
554 { text: "", attachments: sharedImages },
555 );
556
557 expect(merged[draftKey]?.attachments).toHaveLength(8);
558 expect(merged[draftKey]?.attachments[0]).toEqual(existingImage);
559 expect(merged[draftKey]?.attachments.at(-1)?.id).toBe("shared-6");
560 });
561
562 it("restores the exact draft captured before an interrupted share import", () => {
563 const draftKey = "new-task:environment-1:project-1";
564 const beforeImport: ComposerDraft = {
565 text: "Existing context",
566 attachments: [],
567 runtimeMode: "approval-required",
568 };
569 const imported: ComposerDraft = {
570 ...beforeImport,
571 text: "Existing context\n\nShared note",
572 importedShareIds: ["share-1"],
573 };
574
575 expect(
576 restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, beforeImport),
577 ).toEqual({ [draftKey]: beforeImport });
578 expect(
579 restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, {
580 text: "",
581 attachments: [],
582 }),
583 ).toEqual({});
584 });
585
586 it("removes only drafts owned by the selected environment", () => {
587 const environmentId = EnvironmentId.make("environment-cloud");
588 const retainedEnvironmentId = EnvironmentId.make("environment-local");
589
590 expect(
591 removeComposerDraftsForEnvironment(
592 {
593 [`${environmentId}:thread-cloud`]: DRAFT,
594 [`new-task:${environmentId}:project-cloud`]: DRAFT,
595 [`${retainedEnvironmentId}:thread-local`]: DRAFT,
596 [`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
597 },
598 environmentId,
599 ),
600 ).toEqual({
601 [`${retainedEnvironmentId}:thread-local`]: DRAFT,
602 [`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
603 });
604 });
605
606 it("waits for persisted drafts before copying content between projects", async () => {
607 const sourceKey = "new-task:environment-1:project-1";
608 const targetKey = "new-task:environment-1:project-2";
609 const unrelatedKey = "environment-1:thread-1";
610 const source = { text: "Current task", attachments: [] } satisfies ComposerDraft;
611 const target = { text: "Persisted target", attachments: [] } satisfies ComposerDraft;
612 const unrelated = { text: "Keep me", attachments: [] } satisfies ComposerDraft;
613
614 composerDraftFileMocks.setDocument({
615 schemaVersion: 1,
616 drafts: {
617 [targetKey]: target,
618 [unrelatedKey]: unrelated,
619 },
620 });
621 composerDraftFileMocks.blockRead();
622 appAtomRegistry.set(composerDraftsAtom, { [sourceKey]: source });
623
624 const copy = copyComposerDraftContentIfEmpty(sourceKey, targetKey);
625 expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({ [sourceKey]: source });
626
627 composerDraftFileMocks.releaseRead();
628 await copy;
629
630 expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({
631 [sourceKey]: source,
632 [targetKey]: target,
633 [unrelatedKey]: unrelated,
634 });
635 });
636
637 it("lands a still-debounced draft write when flushed", async () => {
638 const draftKey = "environment-1:thread-1";
639 setComposerDraftText(draftKey, "typed right before the restart");
640
641 await flushComposerDrafts();
642
643 expect(JSON.parse(composerDraftFileMocks.getDocument())).toMatchObject({
644 drafts: { [draftKey]: { text: "typed right before the restart" } },
645 });
646 });
647
648 it("propagates a flush write failure instead of resolving as saved", async () => {
649 const draftKey = "environment-1:thread-1";
650 setComposerDraftText(draftKey, "unsaved");
651 composerDraftFileMocks.setWriteError(new Error("storage unavailable"));
652
653 try {
654 await expect(flushComposerDrafts()).rejects.toBeInstanceOf(ComposerDraftPersistenceError);
655 } finally {
656 composerDraftFileMocks.setWriteError(null);
657 }
658 });
659});