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

use-composer-drafts.ts

764 lines23.2 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 stickyModelSelection: Schema.optional(ModelSelectionSchema),
90});
91​
92const decodePersistedComposerDraftsDocument = Schema.decodeUnknownSync(
93 PersistedComposerDraftsSchema,
94);
95​
96const EMPTY_DRAFT: ComposerDraft = {
97 text: "",
98 attachments: [],
99};
100​
101export const composerDraftsAtom = Atom.make<Record<string, ComposerDraft>>({}).pipe(
102 Atom.keepAlive,
103 Atom.withLabel("mobile:composer-drafts"),
104);
105​
106export const stickyComposerModelSelectionAtom = Atom.make<ModelSelection | null>(null).pipe(
107 Atom.keepAlive,
108 Atom.withLabel("mobile:sticky-composer-model-selection"),
109);
110​
111let loadPromise: Promise<void> | null = null;
112let persistTimer: ReturnType<typeof setTimeout> | null = null;
113const persistenceQueue = new SerializedAsyncQueue();
114​
115/** Resets module-level state between test runs. */
116export function resetComposerDraftsLoadState(): void {
117 loadPromise = null;
119​
120function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
121 if (!draft) {
122 return EMPTY_DRAFT;
123 }
124 return {
125 ...draft,
126 text: draft.text,
127 attachments: draft.attachments,
128 };
130​
131export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
132 return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
134​
135export function isComposerDraftEmpty(draft: ComposerDraft): boolean {
136 return isEmptyDraft(draft);
138​
139function isEmptyDraft(draft: ComposerDraft): boolean {
140 return (
141 draft.text.length === 0 &&
142 draft.attachments.length === 0 &&
143 draft.modelSelection === undefined &&
144 draft.runtimeMode === undefined &&
145 draft.interactionMode === undefined &&
146 draft.workspaceSelection === undefined
147 );
149​
150export function decodePersistedComposerState(value: unknown): {
151 readonly drafts: Record<string, ComposerDraft>;
152 readonly stickyModelSelection: ModelSelection | null;
153} {
154 const parsed = decodePersistedComposerDraftsDocument(value);
155 return {
156 drafts: Object.fromEntries(
157 Object.entries(parsed.drafts)
158 .map(
159 ([key, draft]) =>
160 [
161 key,
162 // Stale new-task drafts left on disk by builds before the
163 // model-precedence fix carry a bare modelSelection with no
164 // other selector settings. Strip it so the next compose pass
165 // re-resolves project → sticky → provider defaults. Drafts
166 // with runtime/interaction/workspace settings or actual text /
167 // attachments were deliberately configured and are left alone.
168 key.startsWith("new-task:") &&
169 draft.modelSelection &&
170 draft.text.length === 0 &&
171 draft.attachments.length === 0 &&
172 draft.runtimeMode === undefined &&
173 draft.interactionMode === undefined &&
174 draft.workspaceSelection === undefined
175 ? { ...draft, modelSelection: undefined }
176 : draft,
177 ] as const,
178 )
179 // importedShareIds are share-import receipts: a contentless draft
180 // carrying one is not empty, or the same native share would be
181 // re-imported after restart.
182 .filter(([, draft]) => !isEmptyDraft(draft) || (draft.importedShareIds?.length ?? 0) > 0),
183 ),
184 stickyModelSelection: parsed.stickyModelSelection ?? null,
185 };
187​
188export function decodePersistedComposerDrafts(value: unknown): Record<string, ComposerDraft> {
189 return decodePersistedComposerState(value).drafts;
191​
192async function getComposerDraftsFile() {
193 const { Directory, File, Paths } = await import("expo-file-system");
194 const directory = new Directory(Paths.document, COMPOSER_DRAFTS_DIRECTORY);
195 directory.create({ idempotent: true, intermediates: true });
196 return new File(directory, COMPOSER_DRAFTS_FILE);
198​
199async function loadPersistedComposerState(): Promise<{
200 readonly drafts: Record<string, ComposerDraft>;
201 readonly stickyModelSelection: ModelSelection | null;
202}> {
203 let operation: ComposerDraftPersistenceError["operation"] = "open";
204 try {
205 const file = await getComposerDraftsFile();
206 if (!file.exists) {
207 return { drafts: {}, stickyModelSelection: null };
208 }
209 operation = "read";
210 const raw = await file.text();
211 operation = "decode";
212 return decodePersistedComposerState(JSON.parse(raw) as unknown);
213 } catch (cause) {
214 console.warn(
215 "[composer-drafts] ignored persisted draft failure",
216 new ComposerDraftPersistenceError({
217 operation,
218 directory: COMPOSER_DRAFTS_DIRECTORY,
219 fileName: COMPOSER_DRAFTS_FILE,
220 cause,
221 }),
222 );
223 return { drafts: {}, stickyModelSelection: null };
224 }
226​
227async function writePersistedComposerState(
228 drafts: Record<string, ComposerDraft>,
229 stickyModelSelection: ModelSelection | null,
230): Promise<void> {
231 let operation: ComposerDraftPersistenceError["operation"] = "open";
232 try {
233 const file = await getComposerDraftsFile();
234 operation = "encode";
235 const nonEmptyDrafts = Object.fromEntries(
236 Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
237 );
238 const document = {
239 schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
240 drafts: nonEmptyDrafts,
241 ...(stickyModelSelection ? { stickyModelSelection } : {}),
242 } as const;
243 const encoded = JSON.stringify(document);
244 operation = "write";
245 await writeFileAtomically(file, encoded);
246 } catch (cause) {
247 throw new ComposerDraftPersistenceError({
248 operation,
249 directory: COMPOSER_DRAFTS_DIRECTORY,
250 fileName: COMPOSER_DRAFTS_FILE,
251 cause,
252 });
253 }
255​
256/**
257 * Lands any debounced or in-flight draft write before the JS runtime is torn
258 * down (app update restart), so the freshest draft state survives it. A write
259 * failure propagates so the caller can decide whether the restart may proceed.
260 */
261export async function flushComposerDrafts(): Promise<void> {
262 // Never land a pre-hydration snapshot: persisted state must merge into the
263 // atoms first, or this write would clobber disk with partial data.
264 ensureComposerDraftsLoaded();
265 if (loadPromise !== null) {
266 await loadPromise;
267 }
268 // An edit during an awaited write schedules another debounced write, so
269 // keep landing snapshots until no debounce is pending after a queue drain.
270 do {
271 while (persistTimer !== null) {
272 clearTimeout(persistTimer);
273 persistTimer = null;
274 await persistenceQueue.run(() =>
275 writePersistedComposerState(
276 appAtomRegistry.get(composerDraftsAtom),
277 appAtomRegistry.get(stickyComposerModelSelectionAtom),
278 ),
279 );
280 }
281 // Draining also waits for an already-fired debounce whose write is still
282 // gated behind its own hydration await inside the queue.
283 await persistenceQueue.run(() => Promise.resolve());
284 } while (persistTimer !== null);
286​
287function schedulePersistComposerState(): void {
288 if (persistTimer !== null) {
289 clearTimeout(persistTimer);
290 }
291 persistTimer = setTimeout(() => {
292 persistTimer = null;
293 ensureComposerDraftsLoaded();
294 // The write enters the serialization queue before waiting on hydration,
295 // so flushComposerDrafts' queue drain cannot resolve ahead of it.
296 void persistenceQueue.run(async () => {
297 if (loadPromise !== null) {
298 await loadPromise;
299 }
300 try {
301 await writePersistedComposerState(
302 appAtomRegistry.get(composerDraftsAtom),
303 appAtomRegistry.get(stickyComposerModelSelectionAtom),
304 );
305 } catch (error) {
306 console.warn("[composer-drafts] failed to persist drafts", error);
307 // Draft persistence is best-effort; in-memory drafts still keep working.
308 }
309 });
310 }, PERSIST_DEBOUNCE_MS);
312​
313export function ensureComposerDraftsLoaded(): void {
314 if (loadPromise !== null) {
315 return;
316 }
317 loadPromise = loadPersistedComposerState()
318 .then((persisted) => {
319 if (Object.keys(persisted.drafts).length > 0) {
320 const current = appAtomRegistry.get(composerDraftsAtom);
321 appAtomRegistry.set(composerDraftsAtom, {
322 ...persisted.drafts,
323 ...current,
324 });
325 }
326 if (
327 persisted.stickyModelSelection !== null &&
328 appAtomRegistry.get(stickyComposerModelSelectionAtom) === null
329 ) {
330 appAtomRegistry.set(stickyComposerModelSelectionAtom, persisted.stickyModelSelection);
331 }
332 })
333 .catch((cause) => {
334 console.warn(
335 "[composer-drafts] failed to hydrate drafts",
336 new ComposerDraftPersistenceError({
337 operation: "hydrate",
338 directory: COMPOSER_DRAFTS_DIRECTORY,
339 fileName: COMPOSER_DRAFTS_FILE,
340 cause,
341 }),
342 );
343 // Draft loading is best-effort; in-memory drafts still keep working.
344 });
346​
347function updateComposerDrafts(
348 update: (current: Record<string, ComposerDraft>) => Record<string, ComposerDraft>,
349): void {
350 const current = appAtomRegistry.get(composerDraftsAtom);
351 const next = update(current);
352 if (next === current) {
353 return;
354 }
355 appAtomRegistry.set(composerDraftsAtom, next);
356 schedulePersistComposerState();
358​
359export function setStickyComposerModelSelection(modelSelection: ModelSelection): void {
360 appAtomRegistry.set(stickyComposerModelSelectionAtom, modelSelection);
361 schedulePersistComposerState();
363​
364export function setComposerDraftText(draftKey: string, value: string): void {
365 updateComposerDrafts((current) => {
366 const draft = {
367 ...normalizeDraft(current[draftKey]),
368 text: value,
369 };
370 if (isEmptyDraft(draft)) {
371 const next = { ...current };
372 delete next[draftKey];
373 return next;
374 }
375 return {
376 ...current,
377 [draftKey]: draft,
378 };
379 });
381​
382export function appendComposerDraftText(draftKey: string, value: string): void {
383 updateComposerDrafts((current) => {
384 const existing = normalizeDraft(current[draftKey]);
385 return {
386 ...current,
387 [draftKey]: {
388 ...existing,
389 text: `${existing.text}${value}`,
390 },
391 };
392 });
394​
395export function appendComposerDraftAttachments(
396 draftKey: string,
397 attachments: ReadonlyArray<DraftComposerImageAttachment>,
398): void {
399 if (attachments.length === 0) {
400 return;
401 }
402 updateComposerDrafts((current) => {
403 const existing = normalizeDraft(current[draftKey]);
404 return {
405 ...current,
406 [draftKey]: {
407 ...existing,
408 attachments: [...existing.attachments, ...attachments],
409 },
410 };
411 });
413​
414export function replaceComposerDraftAttachments(
415 draftKey: string,
416 attachments: ReadonlyArray<DraftComposerImageAttachment>,
417): void {
418 updateComposerDrafts((current) => {
419 const draft = {
420 ...normalizeDraft(current[draftKey]),
421 attachments,
422 };
423 if (isEmptyDraft(draft)) {
424 const next = { ...current };
425 delete next[draftKey];
426 return next;
427 }
428 return {
429 ...current,
430 [draftKey]: draft,
431 };
432 });
434​
435export function removeComposerDraftAttachment(draftKey: string, imageId: string): void {
436 updateComposerDrafts((current) => {
437 const existing = normalizeDraft(current[draftKey]);
438 const draft = {
439 ...existing,
440 attachments: existing.attachments.filter((image) => image.id !== imageId),
441 };
442 if (isEmptyDraft(draft)) {
443 const next = { ...current };
444 delete next[draftKey];
445 return next;
446 }
447 return {
448 ...current,
449 [draftKey]: draft,
450 };
451 });
453​
454export function updateComposerDraftSettings(
455 draftKey: string,
456 settings: Partial<ComposerDraftSettingsUpdate>,
457): void {
458 updateComposerDrafts((current) => {
459 const draft = {
460 ...normalizeDraft(current[draftKey]),
461 ...settings,
462 };
463 if (isEmptyDraft(draft)) {
464 const next = { ...current };
465 delete next[draftKey];
466 return next;
467 }
468 return {
469 ...current,
470 [draftKey]: draft,
471 };
472 });
474​
475export function clearComposerDraftContentState(
476 current: Record<string, ComposerDraft>,
477 draftKey: string,
478 options?: {
479 readonly clearModelSelection?: boolean;
480 readonly clearWorkspaceSelection?: boolean;
481 },
482): Record<string, ComposerDraft> {
483 const existing = current[draftKey];
484 if (!existing) {
485 return current;
486 }
487 const {
488 importedShareIds: _importedShareIds,
489 modelSelection,
490 workspaceSelection,
491 ...retained
492 } = existing;
493 const draft = {
494 ...retained,
495 ...(options?.clearModelSelection || modelSelection === undefined ? {} : { modelSelection }),
496 ...(options?.clearWorkspaceSelection || workspaceSelection === undefined
497 ? {}
498 : { workspaceSelection }),
499 text: "",
500 attachments: [],
501 };
502 if (isEmptyDraft(draft)) {
503 const next = { ...current };
504 delete next[draftKey];
505 return next;
506 }
507 return {
508 ...current,
509 [draftKey]: draft,
510 };
512​
513export function restoreComposerDraftSnapshotState(
514 current: Record<string, ComposerDraft>,
515 draftKey: string,
516 snapshot: ComposerDraft,
517): Record<string, ComposerDraft> {
518 const next = { ...current };
519 if (isEmptyDraft(snapshot)) {
520 delete next[draftKey];
521 } else {
522 next[draftKey] = snapshot;
523 }
524 return next;
526​
527export function copyComposerDraftContentState(
528 current: Record<string, ComposerDraft>,
529 sourceDraftKey: string,
530 targetDraftKey: string,
531): Record<string, ComposerDraft> {
532 if (sourceDraftKey === targetDraftKey) {
533 return current;
534 }
535 const source = normalizeDraft(current[sourceDraftKey]);
536 const target = normalizeDraft(current[targetDraftKey]);
537 const sourceHasContent =
538 source.text.length > 0 ||
539 source.attachments.length > 0 ||
540 (source.importedShareIds?.length ?? 0) > 0;
541 const targetHasContent =
542 target.text.length > 0 ||
543 target.attachments.length > 0 ||
544 (target.importedShareIds?.length ?? 0) > 0;
545 if (!sourceHasContent || targetHasContent) {
546 return current;
547 }
548 return {
549 ...current,
550 [targetDraftKey]: {
551 ...target,
552 text: source.text,
553 attachments: source.attachments,
554 ...(source.importedShareIds ? { importedShareIds: source.importedShareIds } : {}),
555 },
556 };
558​
559export async function copyComposerDraftContentIfEmpty(
560 sourceDraftKey: string,
561 targetDraftKey: string,
562): Promise<void> {
563 ensureComposerDraftsLoaded();
564 if (loadPromise !== null) {
565 await loadPromise;
566 }
567 updateComposerDrafts((current) =>
568 copyComposerDraftContentState(current, sourceDraftKey, targetDraftKey),
569 );
571​
572function mergeComposerDraftText(existing: string, incoming: string): string {
573 if (incoming.length === 0) {
574 return existing;
575 }
576 if (existing.length === 0) {
577 return incoming;
578 }
579 // Import retries are possible after an interrupted native handoff. Keep the
580 // operation idempotent when the same shared text is already present.
581 if (existing === incoming || existing.endsWith(`\n\n${incoming}`)) {
582 return existing;
583 }
584 return `${existing}\n\n${incoming}`;
586​
587export function mergeComposerDraftContentState(
588 current: Record<string, ComposerDraft>,
589 draftKey: string,
590 content: ComposerDraftContent,
591): Record<string, ComposerDraft> {
592 const existing = normalizeDraft(current[draftKey]);
593 if (content.sourceShareId && existing.importedShareIds?.includes(content.sourceShareId)) {
594 return current;
595 }
596 const attachmentIds = new Set(existing.attachments.map((attachment) => attachment.id));
597 const incomingAttachments = content.attachments.filter((attachment) => {
598 if (attachmentIds.has(attachment.id)) {
599 return false;
600 }
601 attachmentIds.add(attachment.id);
602 return true;
603 });
604 const attachments = [...existing.attachments, ...incomingAttachments].slice(
605 0,
606 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
607 );
608 const text = mergeComposerDraftText(existing.text, content.text);
609 const importedShareIds = content.sourceShareId
610 ? [...(existing.importedShareIds ?? []), content.sourceShareId]
611 : existing.importedShareIds;
612 if (
613 text === existing.text &&
614 attachments.length === existing.attachments.length &&
615 importedShareIds === existing.importedShareIds
616 ) {
617 return current;
618 }
619 return {
620 ...current,
621 [draftKey]: {
622 ...existing,
623 text,
624 attachments,
625 ...(importedShareIds ? { importedShareIds } : {}),
626 },
627 };
629​
630/**
631 * Atomically moves an incoming share into a project-scoped composer draft.
632 * The durable write happens before the share inbox item can be acknowledged.
633 */
634export async function mergeComposerDraftContent(
635 draftKey: string,
636 content: ComposerDraftContent,
637): Promise<{ readonly skippedAttachmentCount: number }> {
638 ensureComposerDraftsLoaded();
639 if (loadPromise !== null) {
640 await loadPromise;
641 }
642 if (persistTimer !== null) {
643 clearTimeout(persistTimer);
644 persistTimer = null;
645 }
646 const current = appAtomRegistry.get(composerDraftsAtom);
647 const next = mergeComposerDraftContentState(current, draftKey, content);
648 const currentAttachmentIds = new Set(
649 normalizeDraft(current[draftKey]).attachments.map((attachment) => attachment.id),
650 );
651 const nextAttachmentIds = new Set(
652 normalizeDraft(next[draftKey]).attachments.map((attachment) => attachment.id),
653 );
654 const skippedAttachmentCount = content.attachments.filter(
655 (attachment) =>
656 !currentAttachmentIds.has(attachment.id) && !nextAttachmentIds.has(attachment.id),
657 ).length;
658 // Publish the content and its import receipt together before the filesystem
659 // await. Typing during persistence then builds on the receipt-bearing state,
660 // and its debounced write is serialized after this transaction.
661 if (next !== current) {
662 appAtomRegistry.set(composerDraftsAtom, next);
663 }
664 await persistenceQueue.run(() =>
665 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
666 );
667 return { skippedAttachmentCount };
669​
670/** Restores the exact content/settings captured before an interrupted import. */
671export async function restoreComposerDraftSnapshot(
672 draftKey: string,
673 snapshot: ComposerDraft,
674): Promise<void> {
675 ensureComposerDraftsLoaded();
676 if (loadPromise !== null) {
677 await loadPromise;
678 }
679 if (persistTimer !== null) {
680 clearTimeout(persistTimer);
681 persistTimer = null;
682 }
683 const next = restoreComposerDraftSnapshotState(
684 appAtomRegistry.get(composerDraftsAtom),
685 draftKey,
686 snapshot,
687 );
688 appAtomRegistry.set(composerDraftsAtom, next);
689 await persistenceQueue.run(() =>
690 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
691 );
693​
694export function clearComposerDraftContent(
695 draftKey: string,
696 options?: {
697 readonly clearModelSelection?: boolean;
698 readonly clearWorkspaceSelection?: boolean;
699 },
700): void {
701 updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options));
703​
704export function clearComposerDraft(draftKey: string): void {
705 updateComposerDrafts((current) => {
706 if (!current[draftKey]) {
707 return current;
708 }
709 const next = { ...current };
710 delete next[draftKey];
711 return next;
712 });
714​
715export function removeComposerDraftsForEnvironment(
716 drafts: Record<string, ComposerDraft>,
717 environmentId: EnvironmentId,
718): Record<string, ComposerDraft> {
719 const environmentPrefix = `${environmentId}:`;
720 const newTaskPrefix = `new-task:${environmentId}:`;
721 return Object.fromEntries(
722 Object.entries(drafts).filter(
723 ([draftKey]) =>
724 !draftKey.startsWith(environmentPrefix) && !draftKey.startsWith(newTaskPrefix),
725 ),
726 );
728​
729export async function clearComposerDraftsEnvironment(environmentId: EnvironmentId): Promise<void> {
730 ensureComposerDraftsLoaded();
731 if (loadPromise !== null) {
732 await loadPromise;
733 }
734​
735 const next = removeComposerDraftsForEnvironment(
736 appAtomRegistry.get(composerDraftsAtom),
737 environmentId,
738 );
739​
740 if (persistTimer !== null) {
741 clearTimeout(persistTimer);
742 persistTimer = null;
743 }
744 appAtomRegistry.set(composerDraftsAtom, next);
745 await persistenceQueue.run(() =>
746 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
747 );
749​
750export function useComposerDraft(draftKey: string | null): ComposerDraft {
751 const drafts = useAtomValue(composerDraftsAtom);
752 useEffect(() => {
753 ensureComposerDraftsLoaded();
754 }, []);
755 return draftKey ? normalizeDraft(drafts[draftKey]) : EMPTY_DRAFT;
757​
758export function useStickyComposerModelSelection(): ModelSelection | null {
759 const selection = useAtomValue(stickyComposerModelSelectionAtom);
760 useEffect(() => {
761 ensureComposerDraftsLoaded();
762 }, []);
763 return selection;