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

use-composer-drafts.ts

657 lines19.4 KB

1import { useAtomValue } from "@effect/atom-react";
2import {
3 ModelSelection as ModelSelectionSchema,
4 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
5 ProviderInteractionMode as ProviderInteractionModeSchema,
6 RuntimeMode as RuntimeModeSchema,
7 type EnvironmentId,
8 type ModelSelection,
9 type ProviderInteractionMode,
10 type RuntimeMode,
11} from "@t3tools/contracts";
12import * as Schema from "effect/Schema";
13import { useEffect } from "react";
14import { Atom } from "effect/unstable/reactivity";
15​
16import { writeFileAtomically } from "../lib/atomic-file";
17import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
18import type { DraftComposerImageAttachment } from "../lib/composerImages";
19import { SerializedAsyncQueue } from "../lib/serialized-async-queue";
20import { appAtomRegistry } from "./atom-registry";
21​
22const COMPOSER_DRAFTS_SCHEMA_VERSION = 1;
23const COMPOSER_DRAFTS_DIRECTORY = "composer-drafts";
24const COMPOSER_DRAFTS_FILE = "drafts.json";
25const PERSIST_DEBOUNCE_MS = 200;
26​
27export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<ComposerDraftPersistenceError>()(
28 "ComposerDraftPersistenceError",
29 {
30 operation: Schema.Literals(["open", "read", "decode", "encode", "write", "hydrate"]),
31 directory: Schema.String,
32 fileName: Schema.String,
33 cause: Schema.Defect(),
34 },
35) {
36 override get message(): string {
37 return `Composer draft persistence operation ${this.operation} failed for ${this.directory}/${this.fileName}.`;
38 }
40​
41export interface ComposerDraft {
42 readonly text: string;
43 readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
44 readonly importedShareIds?: ReadonlyArray<string>;
45 readonly modelSelection?: ModelSelection;
46 readonly runtimeMode?: RuntimeMode;
47 readonly interactionMode?: ProviderInteractionMode;
48 readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
50​
51export interface ComposerDraftContent {
52 readonly text: string;
53 readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
54 readonly sourceShareId?: string;
56​
57export interface ComposerDraftWorkspaceSelection {
58 readonly mode: "local" | "worktree";
59 readonly branch: string | null;
60 readonly worktreePath: string | null;
61 readonly startFromOrigin?: boolean;
63​
64export type ComposerDraftSettingsUpdate = Pick<
65 ComposerDraft,
66 "modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection"
67>;
68​
69const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
70 mode: Schema.Literals(["local", "worktree"]),
71 branch: Schema.NullOr(Schema.String),
72 worktreePath: Schema.NullOr(Schema.String),
73 startFromOrigin: Schema.optional(Schema.Boolean),
74});
75​
76const ComposerDraftSchema = Schema.Struct({
77 text: Schema.String,
78 attachments: Schema.Array(DraftComposerImageAttachmentSchema),
79 importedShareIds: Schema.optional(Schema.Array(Schema.String)),
80 modelSelection: Schema.optional(ModelSelectionSchema),
81 runtimeMode: Schema.optional(RuntimeModeSchema),
82 interactionMode: Schema.optional(ProviderInteractionModeSchema),
83 workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema),
84});
85​
86const PersistedComposerDraftsSchema = Schema.Struct({
87 schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION),
88 drafts: Schema.Record(Schema.String, ComposerDraftSchema),
89});
90​
91const decodePersistedComposerDraftsDocument = Schema.decodeUnknownSync(
92 PersistedComposerDraftsSchema,
93);
94​
95const EMPTY_DRAFT: ComposerDraft = {
96 text: "",
97 attachments: [],
98};
99​
100export const composerDraftsAtom = Atom.make<Record<string, ComposerDraft>>({}).pipe(
101 Atom.keepAlive,
102 Atom.withLabel("mobile:composer-drafts"),
103);
104​
105let loadPromise: Promise<void> | null = null;
106let persistTimer: ReturnType<typeof setTimeout> | null = null;
107const persistenceQueue = new SerializedAsyncQueue();
108​
109function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
110 if (!draft) {
111 return EMPTY_DRAFT;
112 }
113 return {
114 ...draft,
115 text: draft.text,
116 attachments: draft.attachments,
117 };
119​
120export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
121 return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
123​
124export function isComposerDraftEmpty(draft: ComposerDraft): boolean {
125 return isEmptyDraft(draft);
127​
128function isEmptyDraft(draft: ComposerDraft): boolean {
129 return (
130 draft.text.length === 0 &&
131 draft.attachments.length === 0 &&
132 draft.modelSelection === undefined &&
133 draft.runtimeMode === undefined &&
134 draft.interactionMode === undefined &&
135 draft.workspaceSelection === undefined
136 );
138​
139export function decodePersistedComposerDrafts(value: unknown): Record<string, ComposerDraft> {
140 const parsed = decodePersistedComposerDraftsDocument(value);
141 return Object.fromEntries(
142 Object.entries(parsed.drafts).filter(([, draft]) => !isEmptyDraft(draft)),
143 );
145​
146async function getComposerDraftsFile() {
147 const { Directory, File, Paths } = await import("expo-file-system");
148 const directory = new Directory(Paths.document, COMPOSER_DRAFTS_DIRECTORY);
149 directory.create({ idempotent: true, intermediates: true });
150 return new File(directory, COMPOSER_DRAFTS_FILE);
152​
153async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDraft>> {
154 let operation: ComposerDraftPersistenceError["operation"] = "open";
155 try {
156 const file = await getComposerDraftsFile();
157 if (!file.exists) {
158 return {};
159 }
160 operation = "read";
161 const raw = await file.text();
162 operation = "decode";
163 return decodePersistedComposerDrafts(JSON.parse(raw) as unknown);
164 } catch (cause) {
165 console.warn(
166 "[composer-drafts] ignored persisted draft failure",
167 new ComposerDraftPersistenceError({
168 operation,
169 directory: COMPOSER_DRAFTS_DIRECTORY,
170 fileName: COMPOSER_DRAFTS_FILE,
171 cause,
172 }),
173 );
174 return {};
175 }
177​
178async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft>): Promise<void> {
179 let operation: ComposerDraftPersistenceError["operation"] = "open";
180 try {
181 const file = await getComposerDraftsFile();
182 operation = "encode";
183 const nonEmptyDrafts = Object.fromEntries(
184 Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
185 );
186 const document = {
187 schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
188 drafts: nonEmptyDrafts,
189 } as const;
190 const encoded = JSON.stringify(document);
191 operation = "write";
192 await writeFileAtomically(file, encoded);
193 } catch (cause) {
194 throw new ComposerDraftPersistenceError({
195 operation,
196 directory: COMPOSER_DRAFTS_DIRECTORY,
197 fileName: COMPOSER_DRAFTS_FILE,
198 cause,
199 });
200 }
202​
203async function savePersistedComposerDrafts(drafts: Record<string, ComposerDraft>): Promise<void> {
204 try {
205 await persistenceQueue.run(() => writePersistedComposerDrafts(drafts));
206 } catch (error) {
207 console.warn("[composer-drafts] failed to persist drafts", error);
208 // Draft persistence is best-effort; in-memory drafts still keep working.
209 }
211​
212/**
213 * Lands any debounced or in-flight draft write before the JS runtime is torn
214 * down (app update restart), so the freshest draft state survives it. A write
215 * failure propagates so the caller can decide whether the restart may proceed.
216 */
217export async function flushComposerDrafts(): Promise<void> {
218 // An edit during an awaited write schedules another debounced write, so
219 // keep landing snapshots until no debounce is pending after a queue drain.
220 do {
221 while (persistTimer !== null) {
222 clearTimeout(persistTimer);
223 persistTimer = null;
224 await persistenceQueue.run(() =>
225 writePersistedComposerDrafts(appAtomRegistry.get(composerDraftsAtom)),
226 );
227 }
228 await persistenceQueue.run(() => Promise.resolve());
229 } while (persistTimer !== null);
231​
232function schedulePersistComposerDrafts(drafts: Record<string, ComposerDraft>): void {
233 if (persistTimer !== null) {
234 clearTimeout(persistTimer);
235 }
236 persistTimer = setTimeout(() => {
237 persistTimer = null;
238 void savePersistedComposerDrafts(drafts);
239 }, PERSIST_DEBOUNCE_MS);
241​
242export function ensureComposerDraftsLoaded(): void {
243 if (loadPromise !== null) {
244 return;
245 }
246 loadPromise = loadPersistedComposerDrafts()
247 .then((persistedDrafts) => {
248 if (Object.keys(persistedDrafts).length === 0) {
249 return;
250 }
251 const current = appAtomRegistry.get(composerDraftsAtom);
252 appAtomRegistry.set(composerDraftsAtom, {
253 ...persistedDrafts,
254 ...current,
255 });
256 })
257 .catch((cause) => {
258 console.warn(
259 "[composer-drafts] failed to hydrate drafts",
260 new ComposerDraftPersistenceError({
261 operation: "hydrate",
262 directory: COMPOSER_DRAFTS_DIRECTORY,
263 fileName: COMPOSER_DRAFTS_FILE,
264 cause,
265 }),
266 );
267 // Draft loading is best-effort; in-memory drafts still keep working.
268 });
270​
271function updateComposerDrafts(
272 update: (current: Record<string, ComposerDraft>) => Record<string, ComposerDraft>,
273): void {
274 const current = appAtomRegistry.get(composerDraftsAtom);
275 const next = update(current);
276 if (next === current) {
277 return;
278 }
279 appAtomRegistry.set(composerDraftsAtom, next);
280 schedulePersistComposerDrafts(next);
282​
283export function setComposerDraftText(draftKey: string, value: string): void {
284 updateComposerDrafts((current) => {
285 const draft = {
286 ...normalizeDraft(current[draftKey]),
287 text: value,
288 };
289 if (isEmptyDraft(draft)) {
290 const next = { ...current };
291 delete next[draftKey];
292 return next;
293 }
294 return {
295 ...current,
296 [draftKey]: draft,
297 };
298 });
300​
301export function appendComposerDraftText(draftKey: string, value: string): void {
302 updateComposerDrafts((current) => {
303 const existing = normalizeDraft(current[draftKey]);
304 return {
305 ...current,
306 [draftKey]: {
307 ...existing,
308 text: `${existing.text}${value}`,
309 },
310 };
311 });
313​
314export function appendComposerDraftAttachments(
315 draftKey: string,
316 attachments: ReadonlyArray<DraftComposerImageAttachment>,
317): void {
318 if (attachments.length === 0) {
319 return;
320 }
321 updateComposerDrafts((current) => {
322 const existing = normalizeDraft(current[draftKey]);
323 return {
324 ...current,
325 [draftKey]: {
326 ...existing,
327 attachments: [...existing.attachments, ...attachments],
328 },
329 };
330 });
332​
333export function replaceComposerDraftAttachments(
334 draftKey: string,
335 attachments: ReadonlyArray<DraftComposerImageAttachment>,
336): void {
337 updateComposerDrafts((current) => {
338 const draft = {
339 ...normalizeDraft(current[draftKey]),
340 attachments,
341 };
342 if (isEmptyDraft(draft)) {
343 const next = { ...current };
344 delete next[draftKey];
345 return next;
346 }
347 return {
348 ...current,
349 [draftKey]: draft,
350 };
351 });
353​
354export function removeComposerDraftAttachment(draftKey: string, imageId: string): void {
355 updateComposerDrafts((current) => {
356 const existing = normalizeDraft(current[draftKey]);
357 const draft = {
358 ...existing,
359 attachments: existing.attachments.filter((image) => image.id !== imageId),
360 };
361 if (isEmptyDraft(draft)) {
362 const next = { ...current };
363 delete next[draftKey];
364 return next;
365 }
366 return {
367 ...current,
368 [draftKey]: draft,
369 };
370 });
372​
373export function updateComposerDraftSettings(
374 draftKey: string,
375 settings: Partial<ComposerDraftSettingsUpdate>,
376): void {
377 updateComposerDrafts((current) => {
378 const draft = {
379 ...normalizeDraft(current[draftKey]),
380 ...settings,
381 };
382 if (isEmptyDraft(draft)) {
383 const next = { ...current };
384 delete next[draftKey];
385 return next;
386 }
387 return {
388 ...current,
389 [draftKey]: draft,
390 };
391 });
393​
394export function clearComposerDraftContentState(
395 current: Record<string, ComposerDraft>,
396 draftKey: string,
397 options?: { readonly clearWorkspaceSelection?: boolean },
398): Record<string, ComposerDraft> {
399 const existing = current[draftKey];
400 if (!existing) {
401 return current;
402 }
403 const { importedShareIds: _importedShareIds, workspaceSelection, ...retained } = existing;
404 const draft = {
405 ...retained,
406 ...(options?.clearWorkspaceSelection || workspaceSelection === undefined
407 ? {}
408 : { workspaceSelection }),
409 text: "",
410 attachments: [],
411 };
412 if (isEmptyDraft(draft)) {
413 const next = { ...current };
414 delete next[draftKey];
415 return next;
416 }
417 return {
418 ...current,
419 [draftKey]: draft,
420 };
422​
423export function restoreComposerDraftSnapshotState(
424 current: Record<string, ComposerDraft>,
425 draftKey: string,
426 snapshot: ComposerDraft,
427): Record<string, ComposerDraft> {
428 const next = { ...current };
429 if (isEmptyDraft(snapshot)) {
430 delete next[draftKey];
431 } else {
432 next[draftKey] = snapshot;
433 }
434 return next;
436​
437export function copyComposerDraftContentState(
438 current: Record<string, ComposerDraft>,
439 sourceDraftKey: string,
440 targetDraftKey: string,
441): Record<string, ComposerDraft> {
442 if (sourceDraftKey === targetDraftKey) {
443 return current;
444 }
445 const source = normalizeDraft(current[sourceDraftKey]);
446 const target = normalizeDraft(current[targetDraftKey]);
447 const sourceHasContent =
448 source.text.length > 0 ||
449 source.attachments.length > 0 ||
450 (source.importedShareIds?.length ?? 0) > 0;
451 const targetHasContent =
452 target.text.length > 0 ||
453 target.attachments.length > 0 ||
454 (target.importedShareIds?.length ?? 0) > 0;
455 if (!sourceHasContent || targetHasContent) {
456 return current;
457 }
458 return {
459 ...current,
460 [targetDraftKey]: {
461 ...target,
462 text: source.text,
463 attachments: source.attachments,
464 ...(source.importedShareIds ? { importedShareIds: source.importedShareIds } : {}),
465 },
466 };
468​
469export async function copyComposerDraftContentIfEmpty(
470 sourceDraftKey: string,
471 targetDraftKey: string,
472): Promise<void> {
473 ensureComposerDraftsLoaded();
474 if (loadPromise !== null) {
475 await loadPromise;
476 }
477 updateComposerDrafts((current) =>
478 copyComposerDraftContentState(current, sourceDraftKey, targetDraftKey),
479 );
481​
482function mergeComposerDraftText(existing: string, incoming: string): string {
483 if (incoming.length === 0) {
484 return existing;
485 }
486 if (existing.length === 0) {
487 return incoming;
488 }
489 // Import retries are possible after an interrupted native handoff. Keep the
490 // operation idempotent when the same shared text is already present.
491 if (existing === incoming || existing.endsWith(`\n\n${incoming}`)) {
492 return existing;
493 }
494 return `${existing}\n\n${incoming}`;
496​
497export function mergeComposerDraftContentState(
498 current: Record<string, ComposerDraft>,
499 draftKey: string,
500 content: ComposerDraftContent,
501): Record<string, ComposerDraft> {
502 const existing = normalizeDraft(current[draftKey]);
503 if (content.sourceShareId && existing.importedShareIds?.includes(content.sourceShareId)) {
504 return current;
505 }
506 const attachmentIds = new Set(existing.attachments.map((attachment) => attachment.id));
507 const incomingAttachments = content.attachments.filter((attachment) => {
508 if (attachmentIds.has(attachment.id)) {
509 return false;
510 }
511 attachmentIds.add(attachment.id);
512 return true;
513 });
514 const attachments = [...existing.attachments, ...incomingAttachments].slice(
515 0,
516 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
517 );
518 const text = mergeComposerDraftText(existing.text, content.text);
519 const importedShareIds = content.sourceShareId
520 ? [...(existing.importedShareIds ?? []), content.sourceShareId]
521 : existing.importedShareIds;
522 if (
523 text === existing.text &&
524 attachments.length === existing.attachments.length &&
525 importedShareIds === existing.importedShareIds
526 ) {
527 return current;
528 }
529 return {
530 ...current,
531 [draftKey]: {
532 ...existing,
533 text,
534 attachments,
535 ...(importedShareIds ? { importedShareIds } : {}),
536 },
537 };
539​
540/**
541 * Atomically moves an incoming share into a project-scoped composer draft.
542 * The durable write happens before the share inbox item can be acknowledged.
543 */
544export async function mergeComposerDraftContent(
545 draftKey: string,
546 content: ComposerDraftContent,
547): Promise<{ readonly skippedAttachmentCount: number }> {
548 ensureComposerDraftsLoaded();
549 if (loadPromise !== null) {
550 await loadPromise;
551 }
552 if (persistTimer !== null) {
553 clearTimeout(persistTimer);
554 persistTimer = null;
555 }
556 const current = appAtomRegistry.get(composerDraftsAtom);
557 const next = mergeComposerDraftContentState(current, draftKey, content);
558 const currentAttachmentIds = new Set(
559 normalizeDraft(current[draftKey]).attachments.map((attachment) => attachment.id),
560 );
561 const nextAttachmentIds = new Set(
562 normalizeDraft(next[draftKey]).attachments.map((attachment) => attachment.id),
563 );
564 const skippedAttachmentCount = content.attachments.filter(
565 (attachment) =>
566 !currentAttachmentIds.has(attachment.id) && !nextAttachmentIds.has(attachment.id),
567 ).length;
568 // Publish the content and its import receipt together before the filesystem
569 // await. Typing during persistence then builds on the receipt-bearing state,
570 // and its debounced write is serialized after this transaction.
571 if (next !== current) {
572 appAtomRegistry.set(composerDraftsAtom, next);
573 }
574 await persistenceQueue.run(() => writePersistedComposerDrafts(next));
575 return { skippedAttachmentCount };
577​
578/** Restores the exact content/settings captured before an interrupted import. */
579export async function restoreComposerDraftSnapshot(
580 draftKey: string,
581 snapshot: ComposerDraft,
582): Promise<void> {
583 ensureComposerDraftsLoaded();
584 if (loadPromise !== null) {
585 await loadPromise;
586 }
587 if (persistTimer !== null) {
588 clearTimeout(persistTimer);
589 persistTimer = null;
590 }
591 const next = restoreComposerDraftSnapshotState(
592 appAtomRegistry.get(composerDraftsAtom),
593 draftKey,
594 snapshot,
595 );
596 appAtomRegistry.set(composerDraftsAtom, next);
597 await persistenceQueue.run(() => writePersistedComposerDrafts(next));
599​
600export function clearComposerDraftContent(
601 draftKey: string,
602 options?: { readonly clearWorkspaceSelection?: boolean },
603): void {
604 updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options));
606​
607export function clearComposerDraft(draftKey: string): void {
608 updateComposerDrafts((current) => {
609 if (!current[draftKey]) {
610 return current;
611 }
612 const next = { ...current };
613 delete next[draftKey];
614 return next;
615 });
617​
618export function removeComposerDraftsForEnvironment(
619 drafts: Record<string, ComposerDraft>,
620 environmentId: EnvironmentId,
621): Record<string, ComposerDraft> {
622 const environmentPrefix = `${environmentId}:`;
623 const newTaskPrefix = `new-task:${environmentId}:`;
624 return Object.fromEntries(
625 Object.entries(drafts).filter(
626 ([draftKey]) =>
627 !draftKey.startsWith(environmentPrefix) && !draftKey.startsWith(newTaskPrefix),
628 ),
629 );
631​
632export async function clearComposerDraftsEnvironment(environmentId: EnvironmentId): Promise<void> {
633 ensureComposerDraftsLoaded();
634 if (loadPromise !== null) {
635 await loadPromise;
636 }
637​
638 const next = removeComposerDraftsForEnvironment(
639 appAtomRegistry.get(composerDraftsAtom),
640 environmentId,
641 );
642​
643 if (persistTimer !== null) {
644 clearTimeout(persistTimer);
645 persistTimer = null;
646 }
647 appAtomRegistry.set(composerDraftsAtom, next);
648 await persistenceQueue.run(() => writePersistedComposerDrafts(next));
650​
651export function useComposerDraft(draftKey: string | null): ComposerDraft {
652 const drafts = useAtomValue(composerDraftsAtom);
653 useEffect(() => {
654 ensureComposerDraftsLoaded();
655 }, []);
656 return draftKey ? normalizeDraft(drafts[draftKey]) : EMPTY_DRAFT;