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

use-composer-drafts.ts

583 lines17.0 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): Record<string, ComposerDraft> {
376 const existing = current[draftKey];
377 if (!existing) {
378 return current;
379 }
380 const { importedShareIds: _importedShareIds, ...retained } = existing;
381 const draft = {
382 ...retained,
383 text: "",
384 attachments: [],
385 };
386 if (isEmptyDraft(draft)) {
387 const next = { ...current };
388 delete next[draftKey];
389 return next;
390 }
391 return {
392 ...current,
393 [draftKey]: draft,
394 };
396​
397export function restoreComposerDraftSnapshotState(
398 current: Record<string, ComposerDraft>,
399 draftKey: string,
400 snapshot: ComposerDraft,
401): Record<string, ComposerDraft> {
402 const next = { ...current };
403 if (isEmptyDraft(snapshot)) {
404 delete next[draftKey];
405 } else {
406 next[draftKey] = snapshot;
407 }
408 return next;
410​
411function mergeComposerDraftText(existing: string, incoming: string): string {
412 if (incoming.length === 0) {
413 return existing;
414 }
415 if (existing.length === 0) {
416 return incoming;
417 }
418 // Import retries are possible after an interrupted native handoff. Keep the
419 // operation idempotent when the same shared text is already present.
420 if (existing === incoming || existing.endsWith(`\n\n${incoming}`)) {
421 return existing;
422 }
423 return `${existing}\n\n${incoming}`;
425​
426export function mergeComposerDraftContentState(
427 current: Record<string, ComposerDraft>,
428 draftKey: string,
429 content: ComposerDraftContent,
430): Record<string, ComposerDraft> {
431 const existing = normalizeDraft(current[draftKey]);
432 if (content.sourceShareId && existing.importedShareIds?.includes(content.sourceShareId)) {
433 return current;
434 }
435 const attachmentIds = new Set(existing.attachments.map((attachment) => attachment.id));
436 const incomingAttachments = content.attachments.filter((attachment) => {
437 if (attachmentIds.has(attachment.id)) {
438 return false;
439 }
440 attachmentIds.add(attachment.id);
441 return true;
442 });
443 const attachments = [...existing.attachments, ...incomingAttachments].slice(
444 0,
445 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
446 );
447 const text = mergeComposerDraftText(existing.text, content.text);
448 const importedShareIds = content.sourceShareId
449 ? [...(existing.importedShareIds ?? []), content.sourceShareId]
450 : existing.importedShareIds;
451 if (
452 text === existing.text &&
453 attachments.length === existing.attachments.length &&
454 importedShareIds === existing.importedShareIds
455 ) {
456 return current;
457 }
458 return {
459 ...current,
460 [draftKey]: {
461 ...existing,
462 text,
463 attachments,
464 ...(importedShareIds ? { importedShareIds } : {}),
465 },
466 };
468​
469/**
470 * Atomically moves an incoming share into a project-scoped composer draft.
471 * The durable write happens before the share inbox item can be acknowledged.
472 */
473export async function mergeComposerDraftContent(
474 draftKey: string,
475 content: ComposerDraftContent,
476): Promise<{ readonly skippedAttachmentCount: number }> {
477 ensureComposerDraftsLoaded();
478 if (loadPromise !== null) {
479 await loadPromise;
480 }
481 if (persistTimer !== null) {
482 clearTimeout(persistTimer);
483 persistTimer = null;
484 }
485 const current = appAtomRegistry.get(composerDraftsAtom);
486 const next = mergeComposerDraftContentState(current, draftKey, content);
487 const currentAttachmentIds = new Set(
488 normalizeDraft(current[draftKey]).attachments.map((attachment) => attachment.id),
489 );
490 const nextAttachmentIds = new Set(
491 normalizeDraft(next[draftKey]).attachments.map((attachment) => attachment.id),
492 );
493 const skippedAttachmentCount = content.attachments.filter(
494 (attachment) =>
495 !currentAttachmentIds.has(attachment.id) && !nextAttachmentIds.has(attachment.id),
496 ).length;
497 // Publish the content and its import receipt together before the filesystem
498 // await. Typing during persistence then builds on the receipt-bearing state,
499 // and its debounced write is serialized after this transaction.
500 if (next !== current) {
501 appAtomRegistry.set(composerDraftsAtom, next);
502 }
503 await persistenceQueue.run(() => writePersistedComposerDrafts(next));
504 return { skippedAttachmentCount };
506​
507/** Restores the exact content/settings captured before an interrupted import. */
508export async function restoreComposerDraftSnapshot(
509 draftKey: string,
510 snapshot: ComposerDraft,
511): Promise<void> {
512 ensureComposerDraftsLoaded();
513 if (loadPromise !== null) {
514 await loadPromise;
515 }
516 if (persistTimer !== null) {
517 clearTimeout(persistTimer);
518 persistTimer = null;
519 }
520 const next = restoreComposerDraftSnapshotState(
521 appAtomRegistry.get(composerDraftsAtom),
522 draftKey,
523 snapshot,
524 );
525 appAtomRegistry.set(composerDraftsAtom, next);
526 await persistenceQueue.run(() => writePersistedComposerDrafts(next));
528​
529export function clearComposerDraftContent(draftKey: string): void {
530 updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey));
532​
533export function clearComposerDraft(draftKey: string): void {
534 updateComposerDrafts((current) => {
535 if (!current[draftKey]) {
536 return current;
537 }
538 const next = { ...current };
539 delete next[draftKey];
540 return next;
541 });
543​
544export function removeComposerDraftsForEnvironment(
545 drafts: Record<string, ComposerDraft>,
546 environmentId: EnvironmentId,
547): Record<string, ComposerDraft> {
548 const environmentPrefix = `${environmentId}:`;
549 const newTaskPrefix = `new-task:${environmentId}:`;
550 return Object.fromEntries(
551 Object.entries(drafts).filter(
552 ([draftKey]) =>
553 !draftKey.startsWith(environmentPrefix) && !draftKey.startsWith(newTaskPrefix),
554 ),
555 );
557​
558export async function clearComposerDraftsEnvironment(environmentId: EnvironmentId): Promise<void> {
559 ensureComposerDraftsLoaded();
560 if (loadPromise !== null) {
561 await loadPromise;
562 }
563​
564 const next = removeComposerDraftsForEnvironment(
565 appAtomRegistry.get(composerDraftsAtom),
566 environmentId,
567 );
568​
569 if (persistTimer !== null) {
570 clearTimeout(persistTimer);
571 persistTimer = null;
572 }
573 appAtomRegistry.set(composerDraftsAtom, next);
574 await writePersistedComposerDrafts(next);
576​
577export function useComposerDraft(draftKey: string | null): ComposerDraft {
578 const drafts = useAtomValue(composerDraftsAtom);
579 useEffect(() => {
580 ensureComposerDraftsLoaded();
581 }, []);
582 return draftKey ? normalizeDraft(drafts[draftKey]) : EMPTY_DRAFT;