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

use-composer-drafts.ts

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