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

use-composer-drafts.test.ts

435 lines12.7 KB

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​
11 return {
12 blockRead() {
13 readBarrier = new Promise<void>((resolve) => {
14 releaseRead = resolve;
15 });
16 },
17 releaseRead() {
18 releaseRead?.();
19 releaseRead = null;
20 },
21 getDocument() {
22 return document;
23 },
24 setDocument(value: unknown) {
25 document = JSON.stringify(value);
26 },
27 setWriteError(error: Error | null) {
28 writeError = error;
29 },
30 Directory: class {
31 create() {}
32 },
33 File: class {
34 exists = true;
35 parentDirectory = null;
36​
37 create() {}
38​
39 moveSync() {}
40​
41 async text() {
42 await readBarrier;
43 return document;
44 }
45​
46 write(value: string) {
47 if (writeError) {
48 throw writeError;
49 }
50 document = value;
51 }
52 },
53 };
54});
55​
56vi.mock("expo-file-system", () => ({
57 Directory: composerDraftFileMocks.Directory,
58 File: composerDraftFileMocks.File,
59 Paths: { document: "/documents" },
60}));
61​
62import { appAtomRegistry } from "./atom-registry";
63import {
64 clearComposerDraftContentState,
65 ComposerDraftPersistenceError,
66 composerDraftsAtom,
67 copyComposerDraftContentIfEmpty,
68 copyComposerDraftContentState,
69 decodePersistedComposerDrafts,
70 type ComposerDraft,
71 flushComposerDrafts,
72 getComposerDraftSnapshot,
73 mergeComposerDraftContentState,
74 removeComposerDraftsForEnvironment,
75 restoreComposerDraftSnapshotState,
76 setComposerDraftText,
77} from "./use-composer-drafts";
78​
79const DRAFT: ComposerDraft = {
80 text: "hello",
81 attachments: [],
82};
83​
84afterEach(() => {
85 appAtomRegistry.set(composerDraftsAtom, {});
86});
87​
88describe("mobile composer drafts", () => {
89 it("hydrates selector state even when the message content is empty", () => {
90 expect(
91 decodePersistedComposerDrafts({
92 schemaVersion: 1,
93 drafts: {
94 "new-task:environment-1:project-1": {
95 text: "",
96 attachments: [],
97 modelSelection: {
98 instanceId: "codex",
99 model: "gpt-5.4",
100 options: [{ id: "reasoningEffort", value: "xhigh" }],
101 },
102 runtimeMode: "approval-required",
103 interactionMode: "plan",
104 workspaceSelection: {
105 mode: "worktree",
106 branch: "main",
107 worktreePath: null,
108 },
109 },
110 },
111 }),
112 ).toEqual({
113 "new-task:environment-1:project-1": {
114 text: "",
115 attachments: [],
116 modelSelection: {
117 instanceId: "codex",
118 model: "gpt-5.4",
119 options: [{ id: "reasoningEffort", value: "xhigh" }],
120 },
121 runtimeMode: "approval-required",
122 interactionMode: "plan",
123 workspaceSelection: {
124 mode: "worktree",
125 branch: "main",
126 worktreePath: null,
127 },
128 },
129 });
130 });
131​
132 it("keeps legacy content-only drafts and rejects invalid selector state", () => {
133 expect(
134 decodePersistedComposerDrafts({
135 schemaVersion: 1,
136 drafts: {
137 "environment-1:thread-1": DRAFT,
138 },
139 }),
140 ).toEqual({
141 "environment-1:thread-1": DRAFT,
142 });
143​
144 expect(() =>
145 decodePersistedComposerDrafts({
146 schemaVersion: 1,
147 drafts: {
148 "environment-1:thread-1": {
149 ...DRAFT,
150 runtimeMode: "sometimes-safe",
151 },
152 },
153 }),
154 ).toThrow();
155 });
156​
157 it("clears sent content without clearing the selected model or workspace", () => {
158 const draftKey = "environment-1:thread-1";
159 const draft: ComposerDraft = {
160 text: "send this",
161 attachments: [],
162 importedShareIds: ["share-1"],
163 modelSelection: {
164 instanceId: ProviderInstanceId.make("codex"),
165 model: "gpt-5.4",
166 options: [{ id: "reasoningEffort", value: "xhigh" }],
167 },
168 workspaceSelection: {
169 mode: "worktree",
170 branch: "main",
171 worktreePath: null,
172 },
173 };
174​
175 expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({
176 [draftKey]: {
177 modelSelection: draft.modelSelection,
178 workspaceSelection: draft.workspaceSelection,
179 text: "",
180 attachments: [],
181 },
182 });
183 });
184​
185 it("drops the workspace selection when clearing a sent new-task draft", () => {
186 const draftKey = "new-task:environment-1:project-1";
187 const draft: ComposerDraft = {
188 text: "send this",
189 attachments: [],
190 modelSelection: {
191 instanceId: ProviderInstanceId.make("codex"),
192 model: "gpt-5.4",
193 },
194 workspaceSelection: {
195 mode: "worktree",
196 branch: "main",
197 worktreePath: null,
198 startFromOrigin: false,
199 },
200 };
201​
202 expect(
203 clearComposerDraftContentState({ [draftKey]: draft }, draftKey, {
204 clearWorkspaceSelection: true,
205 }),
206 ).toEqual({
207 [draftKey]: {
208 modelSelection: draft.modelSelection,
209 text: "",
210 attachments: [],
211 },
212 });
213 });
214​
215 it("reads the latest selector state synchronously for send", () => {
216 const draftKey = "environment-1:thread-1";
217 const selectedDraft: ComposerDraft = {
218 text: "send this",
219 attachments: [],
220 modelSelection: {
221 instanceId: ProviderInstanceId.make("codex"),
222 model: "gpt-5.4",
223 options: [{ id: "reasoningEffort", value: "xhigh" }],
224 },
225 };
226 appAtomRegistry.set(composerDraftsAtom, { [draftKey]: selectedDraft });
227​
228 expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);
229 });
230​
231 it("carries unfinished content to a newly selected project without overwriting its settings", () => {
232 const sourceKey = "new-task:environment-1:project-1";
233 const targetKey = "new-task:environment-1:project-2";
234 const source: ComposerDraft = {
235 text: "Keep this task",
236 attachments: [],
237 importedShareIds: ["share-1"],
238 workspaceSelection: {
239 mode: "worktree",
240 branch: "feature/source",
241 worktreePath: null,
242 },
243 };
244 const target: ComposerDraft = {
245 text: "",
246 attachments: [],
247 runtimeMode: "approval-required",
248 };
249​
250 expect(
251 copyComposerDraftContentState(
252 { [sourceKey]: source, [targetKey]: target },
253 sourceKey,
254 targetKey,
255 ),
256 ).toEqual({
257 [sourceKey]: source,
258 [targetKey]: {
259 ...target,
260 text: source.text,
261 attachments: source.attachments,
262 importedShareIds: source.importedShareIds,
263 },
264 });
265 });
266​
267 it("does not overwrite unfinished content already stored for the selected project", () => {
268 const sourceKey = "new-task:environment-1:project-1";
269 const targetKey = "new-task:environment-1:project-2";
270 const drafts: Record<string, ComposerDraft> = {
271 [sourceKey]: { text: "Source task", attachments: [] },
272 [targetKey]: { text: "Target task", attachments: [] },
273 };
274​
275 expect(copyComposerDraftContentState(drafts, sourceKey, targetKey)).toBe(drafts);
276 });
277​
278 it("merges shared content into a project draft without duplicating retries", () => {
279 const draftKey = "new-task:environment-1:project-1";
280 const sharedAttachment = {
281 id: "share-1:image:0",
282 type: "image" as const,
283 name: "Screenshot.png",
284 mimeType: "image/png",
285 sizeBytes: 3,
286 dataUrl: "data:image/png;base64,YWJj",
287 previewUri: "data:image/png;base64,YWJj",
288 };
289 const existing: Record<string, ComposerDraft> = {
290 [draftKey]: { text: "Existing context", attachments: [] },
291 };
292 const content = {
293 text: "Shared note",
294 attachments: [sharedAttachment],
295 sourceShareId: "share-1",
296 };
297​
298 const merged = mergeComposerDraftContentState(existing, draftKey, content);
299 expect(merged[draftKey]).toMatchObject({
300 text: "Existing context\n\nShared note",
301 attachments: [sharedAttachment],
302 importedShareIds: ["share-1"],
303 });
304 expect(mergeComposerDraftContentState(merged, draftKey, content)).toBe(merged);
305​
306 const edited = {
307 ...merged,
308 [draftKey]: { ...merged[draftKey]!, text: "User edited the imported context" },
309 };
310 expect(mergeComposerDraftContentState(edited, draftKey, content)).toBe(edited);
311 });
312​
313 it("preserves existing images when shared content exceeds the draft attachment limit", () => {
314 const draftKey = "new-task:environment-1:project-1";
315 const image = (id: string) => ({
316 id,
317 type: "image" as const,
318 name: `${id}.png`,
319 mimeType: "image/png",
320 sizeBytes: 3,
321 dataUrl: "data:image/png;base64,YWJj",
322 previewUri: "data:image/png;base64,YWJj",
323 });
324 const existingImage = image("existing");
325 const sharedImages = Array.from({ length: 8 }, (_, index) => image(`shared-${index}`));
326​
327 const merged = mergeComposerDraftContentState(
328 { [draftKey]: { text: "", attachments: [existingImage] } },
329 draftKey,
330 { text: "", attachments: sharedImages },
331 );
332​
333 expect(merged[draftKey]?.attachments).toHaveLength(8);
334 expect(merged[draftKey]?.attachments[0]).toEqual(existingImage);
335 expect(merged[draftKey]?.attachments.at(-1)?.id).toBe("shared-6");
336 });
337​
338 it("restores the exact draft captured before an interrupted share import", () => {
339 const draftKey = "new-task:environment-1:project-1";
340 const beforeImport: ComposerDraft = {
341 text: "Existing context",
342 attachments: [],
343 runtimeMode: "approval-required",
344 };
345 const imported: ComposerDraft = {
346 ...beforeImport,
347 text: "Existing context\n\nShared note",
348 importedShareIds: ["share-1"],
349 };
350​
351 expect(
352 restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, beforeImport),
353 ).toEqual({ [draftKey]: beforeImport });
354 expect(
355 restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, {
356 text: "",
357 attachments: [],
358 }),
359 ).toEqual({});
360 });
361​
362 it("removes only drafts owned by the selected environment", () => {
363 const environmentId = EnvironmentId.make("environment-cloud");
364 const retainedEnvironmentId = EnvironmentId.make("environment-local");
365​
366 expect(
367 removeComposerDraftsForEnvironment(
368 {
369 [`${environmentId}:thread-cloud`]: DRAFT,
370 [`new-task:${environmentId}:project-cloud`]: DRAFT,
371 [`${retainedEnvironmentId}:thread-local`]: DRAFT,
372 [`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
373 },
374 environmentId,
375 ),
376 ).toEqual({
377 [`${retainedEnvironmentId}:thread-local`]: DRAFT,
378 [`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
379 });
380 });
381​
382 it("waits for persisted drafts before copying content between projects", async () => {
383 const sourceKey = "new-task:environment-1:project-1";
384 const targetKey = "new-task:environment-1:project-2";
385 const unrelatedKey = "environment-1:thread-1";
386 const source = { text: "Current task", attachments: [] } satisfies ComposerDraft;
387 const target = { text: "Persisted target", attachments: [] } satisfies ComposerDraft;
388 const unrelated = { text: "Keep me", attachments: [] } satisfies ComposerDraft;
389​
390 composerDraftFileMocks.setDocument({
391 schemaVersion: 1,
392 drafts: {
393 [targetKey]: target,
394 [unrelatedKey]: unrelated,
395 },
396 });
397 composerDraftFileMocks.blockRead();
398 appAtomRegistry.set(composerDraftsAtom, { [sourceKey]: source });
399​
400 const copy = copyComposerDraftContentIfEmpty(sourceKey, targetKey);
401 expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({ [sourceKey]: source });
402​
403 composerDraftFileMocks.releaseRead();
404 await copy;
405​
406 expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({
407 [sourceKey]: source,
408 [targetKey]: target,
409 [unrelatedKey]: unrelated,
410 });
411 });
412​
413 it("lands a still-debounced draft write when flushed", async () => {
414 const draftKey = "environment-1:thread-1";
415 setComposerDraftText(draftKey, "typed right before the restart");
416​
417 await flushComposerDrafts();
418​
419 expect(JSON.parse(composerDraftFileMocks.getDocument())).toMatchObject({
420 drafts: { [draftKey]: { text: "typed right before the restart" } },
421 });
422 });
423​
424 it("propagates a flush write failure instead of resolving as saved", async () => {
425 const draftKey = "environment-1:thread-1";
426 setComposerDraftText(draftKey, "unsaved");
427 composerDraftFileMocks.setWriteError(new Error("storage unavailable"));
428​
429 try {
430 await expect(flushComposerDrafts()).rejects.toBeInstanceOf(ComposerDraftPersistenceError);
431 } finally {
432 composerDraftFileMocks.setWriteError(null);
433 }
434 });
435});