Open History to see the last commit
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 { DraftComposerAttachmentSchema } from "../lib/composer-image-schema";
18import {
19 composerAttachmentFileReferenceKey,
20 isComposerAttachmentFileRetained,
21 retainComposerAttachmentFile,
22} from "../lib/composerAttachmentFiles";
23import type { DraftComposerAttachment, FileBackedComposerAttachment } from "../lib/composerImages";
24import { SerializedAsyncQueue } from "../lib/serialized-async-queue";
25import { appAtomRegistry } from "./atom-registry";
26import {
27 decodeQueuedThreadMessage,
28 encodeQueuedThreadMessage,
29 QueuedThreadMessageSchema,
30 type QueuedThreadMessage,
31} from "./thread-outbox-model";
32import { flushThreadOutbox, threadOutboxManager } from "./thread-outbox";
33import { composerDraftEnvironmentId } from "../lib/composerAttachmentUploadQueue";
34
35const COMPOSER_DRAFTS_SCHEMA_VERSION = 1;
36const COMPOSER_DRAFTS_DIRECTORY = "composer-drafts";
37const COMPOSER_DRAFTS_FILE = "drafts.json";
38const PERSIST_DEBOUNCE_MS = 200;
39
40export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<ComposerDraftPersistenceError>()(
41 "ComposerDraftPersistenceError",
42 {
43 operation: Schema.Literals(["open", "read", "decode", "encode", "write", "hydrate"]),
44 directory: Schema.String,
45 fileName: Schema.String,
46 cause: Schema.Defect(),
47 },
48) {
49 override get message(): string {
50 return `Composer draft persistence operation ${this.operation} failed for ${this.directory}/${this.fileName}.`;
51 }
52}
53
54export interface ComposerDraft {
55 readonly text: string;
56 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
57 readonly importedShareIds?: ReadonlyArray<string>;
58 readonly modelSelection?: ModelSelection;
59 readonly runtimeMode?: RuntimeMode;
60 readonly interactionMode?: ProviderInteractionMode;
61 readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
62}
63
64export interface ComposerDraftContent {
65 readonly text: string;
66 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
67 readonly sourceShareId?: string;
68}
69
70export interface ComposerDraftWorkspaceSelection {
71 readonly mode: "local" | "worktree";
72 readonly branch: string | null;
73 readonly worktreePath: string | null;
74 readonly startFromOrigin?: boolean;
75}
76
77export type ComposerDraftSettingsUpdate = Pick<
78 ComposerDraft,
79 "modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection"
80>;
81
82const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
83 mode: Schema.Literals(["local", "worktree"]),
84 branch: Schema.NullOr(Schema.String),
85 worktreePath: Schema.NullOr(Schema.String),
86 startFromOrigin: Schema.optional(Schema.Boolean),
87});
88
89const ComposerDraftSchema = Schema.Struct({
90 text: Schema.String,
91 attachments: Schema.Array(DraftComposerAttachmentSchema),
92 importedShareIds: Schema.optional(Schema.Array(Schema.String)),
93 modelSelection: Schema.optional(ModelSelectionSchema),
94 runtimeMode: Schema.optional(RuntimeModeSchema),
95 interactionMode: Schema.optional(ProviderInteractionModeSchema),
96 workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema),
97});
98
99const PersistedComposerDraftsSchema = Schema.Struct({
100 schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION),
101 drafts: Schema.Record(Schema.String, ComposerDraftSchema),
102 stickyModelSelection: Schema.optional(ModelSelectionSchema),
103 cloudAccountId: Schema.optional(Schema.String),
104 signedOutDrafts: Schema.optional(
105 Schema.Record(
106 Schema.String,
107 Schema.Struct({
108 drafts: Schema.Record(Schema.String, ComposerDraftSchema),
109 queuedMessages: Schema.Array(QueuedThreadMessageSchema),
110 }),
111 ),
112 ),
113});
114
115const decodePersistedComposerDraftsDocument = Schema.decodeUnknownSync(
116 PersistedComposerDraftsSchema,
117);
118
119const EMPTY_DRAFT: ComposerDraft = {
120 text: "",
121 attachments: [],
122};
123
124export const composerDraftsAtom = Atom.make<Record<string, ComposerDraft>>({}).pipe(
125 Atom.keepAlive,
126 Atom.withLabel("mobile:composer-drafts"),
127);
128
129export const stickyComposerModelSelectionAtom = Atom.make<ModelSelection | null>(null).pipe(
130 Atom.keepAlive,
131 Atom.withLabel("mobile:sticky-composer-model-selection"),
132);
133
134interface SignedOutDrafts {
135 readonly drafts: Record<string, ComposerDraft>;
136 readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
137}
138
139interface ComposerCloudDraftState {
140 readonly accountId: string | null;
141 readonly signedOut: Record<string, SignedOutDrafts>;
142}
143
144export const composerCloudDraftsAtom = Atom.make<ComposerCloudDraftState>({
145 accountId: null,
146 signedOut: {},
147}).pipe(Atom.keepAlive);
148
149let loadPromise: Promise<void> | null = null;
150let persistTimer: ReturnType<typeof setTimeout> | null = null;
151let persistRetryNeeded = false;
152const persistenceQueue = new SerializedAsyncQueue();
153
154/** Resets module-level state between test runs. */
155export function resetComposerDraftsLoadState(): void {
156 loadPromise = null;
157 persistRetryNeeded = false;
158}
159
160function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
161 if (!draft) {
162 return EMPTY_DRAFT;
163 }
164 return {
165 ...draft,
166 text: draft.text,
167 attachments: draft.attachments,
168 };
169}
170
171export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
172 return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
173}
174
175export function isComposerDraftEmpty(draft: ComposerDraft): boolean {
176 return isEmptyDraft(draft);
177}
178
179function isEmptyDraft(draft: ComposerDraft): boolean {
180 return (
181 draft.text.length === 0 &&
182 draft.attachments.length === 0 &&
183 draft.modelSelection === undefined &&
184 draft.runtimeMode === undefined &&
185 draft.interactionMode === undefined &&
186 draft.workspaceSelection === undefined
187 );
188}
189
190export function decodePersistedComposerState(value: unknown): {
191 readonly drafts: Record<string, ComposerDraft>;
192 readonly stickyModelSelection: ModelSelection | null;
193 readonly cloudDrafts: ComposerCloudDraftState;
194} {
195 const parsed = decodePersistedComposerDraftsDocument(value);
196 return {
197 drafts: Object.fromEntries(
198 Object.entries(parsed.drafts)
199 .map(
200 ([key, draft]) =>
201 [
202 key,
203 // Stale new-task drafts left on disk by builds before the
204 // model-precedence fix carry a bare modelSelection with no
205 // other selector settings. Strip it so the next compose pass
206 // re-resolves project → sticky → provider defaults. Drafts
207 // with runtime/interaction/workspace settings or actual text /
208 // attachments were deliberately configured and are left alone.
209 key.startsWith("new-task:") &&
210 draft.modelSelection &&
211 draft.text.length === 0 &&
212 draft.attachments.length === 0 &&
213 draft.runtimeMode === undefined &&
214 draft.interactionMode === undefined &&
215 draft.workspaceSelection === undefined
216 ? { ...draft, modelSelection: undefined }
217 : draft,
218 ] as const,
219 )
220 // importedShareIds are share-import receipts: a contentless draft
221 // carrying one is not empty, or the same native share would be
222 // re-imported after restart.
223 .filter(([, draft]) => !isEmptyDraft(draft) || (draft.importedShareIds?.length ?? 0) > 0),
224 ),
225 stickyModelSelection: parsed.stickyModelSelection ?? null,
226 cloudDrafts: {
227 accountId: parsed.cloudAccountId ?? null,
228 signedOut: Object.fromEntries(
229 Object.entries(parsed.signedOutDrafts ?? {}).map(([id, saved]) => [
230 id,
231 {
232 drafts: saved.drafts,
233 queuedMessages: saved.queuedMessages.map(decodeQueuedThreadMessage),
234 },
235 ]),
236 ),
237 },
238 };
239}
240
241export function decodePersistedComposerDrafts(value: unknown): Record<string, ComposerDraft> {
242 return decodePersistedComposerState(value).drafts;
243}
244
245async function getComposerDraftsFile() {
246 const { Directory, File, Paths } = await import("expo-file-system");
247 const directory = new Directory(Paths.document, COMPOSER_DRAFTS_DIRECTORY);
248 directory.create({ idempotent: true, intermediates: true });
249 return new File(directory, COMPOSER_DRAFTS_FILE);
250}
251
252async function loadPersistedComposerState(): Promise<
253 ReturnType<typeof decodePersistedComposerState>
254> {
255 let operation: ComposerDraftPersistenceError["operation"] = "open";
256 try {
257 const file = await getComposerDraftsFile();
258 if (!file.exists) {
259 return {
260 drafts: {},
261 stickyModelSelection: null,
262 cloudDrafts: { accountId: null, signedOut: {} },
263 };
264 }
265 operation = "read";
266 const raw = await file.text();
267 operation = "decode";
268 return decodePersistedComposerState(JSON.parse(raw) as unknown);
269 } catch (cause) {
270 throw new ComposerDraftPersistenceError({
271 operation,
272 directory: COMPOSER_DRAFTS_DIRECTORY,
273 fileName: COMPOSER_DRAFTS_FILE,
274 cause,
275 });
276 }
277}
278
279async function writePersistedComposerState(
280 drafts: Record<string, ComposerDraft>,
281 stickyModelSelection: ModelSelection | null,
282 cloudDrafts = appAtomRegistry.get(composerCloudDraftsAtom),
283): Promise<void> {
284 let operation: ComposerDraftPersistenceError["operation"] = "open";
285 try {
286 const file = await getComposerDraftsFile();
287 operation = "encode";
288 const nonEmptyDrafts = Object.fromEntries(
289 Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
290 );
291 const document = {
292 schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
293 drafts: nonEmptyDrafts,
294 ...(stickyModelSelection ? { stickyModelSelection } : {}),
295 ...(cloudDrafts.accountId ? { cloudAccountId: cloudDrafts.accountId } : {}),
296 ...(Object.keys(cloudDrafts.signedOut).length > 0
297 ? {
298 signedOutDrafts: Object.fromEntries(
299 Object.entries(cloudDrafts.signedOut).map(([id, saved]) => [
300 id,
301 {
302 drafts: saved.drafts,
303 queuedMessages: saved.queuedMessages.map(encodeQueuedThreadMessage),
304 },
305 ]),
306 ),
307 }
308 : {}),
309 } as const;
310 const encoded = JSON.stringify(document);
311 operation = "write";
312 await writeFileAtomically(file, encoded);
313 } catch (cause) {
314 throw new ComposerDraftPersistenceError({
315 operation,
316 directory: COMPOSER_DRAFTS_DIRECTORY,
317 fileName: COMPOSER_DRAFTS_FILE,
318 cause,
319 });
320 }
321}
322
323/**
324 * Lands any debounced or in-flight draft write before the JS runtime is torn
325 * down (app update restart), so the freshest draft state survives it. A write
326 * failure propagates so the caller can decide whether the restart may proceed.
327 */
328export async function flushComposerDrafts(): Promise<void> {
329 // Never land a pre-hydration snapshot: persisted state must merge into the
330 // atoms first, or this write would clobber disk with partial data.
331 ensureComposerDraftsLoaded();
332 if (loadPromise !== null) {
333 await loadPromise;
334 }
335 // An edit during an awaited write schedules another debounced write, so
336 // keep landing snapshots until no debounce is pending after a queue drain.
337 do {
338 while (persistTimer !== null || persistRetryNeeded) {
339 if (persistTimer !== null) clearTimeout(persistTimer);
340 persistTimer = null;
341 persistRetryNeeded = false;
342 try {
343 await persistenceQueue.run(() =>
344 writePersistedComposerState(
345 appAtomRegistry.get(composerDraftsAtom),
346 appAtomRegistry.get(stickyComposerModelSelectionAtom),
347 ),
348 );
349 } catch (error) {
350 persistRetryNeeded = true;
351 throw error;
352 }
353 }
354 // Draining also waits for an already-fired debounce whose write is still
355 // gated behind its own hydration await inside the queue.
356 await persistenceQueue.run(() => Promise.resolve());
357 } while (persistTimer !== null || persistRetryNeeded);
358}
359
360function signedOutAttachmentOwners() {
361 return Object.values(appAtomRegistry.get(composerCloudDraftsAtom).signedOut).flatMap((saved) => [
362 ...Object.values(saved.drafts),
363 ...saved.queuedMessages,
364 ]);
365}
366
367function isComposerAttachmentFileReferenced(fileUri: string): boolean {
368 if (isComposerAttachmentFileRetained(fileUri)) {
369 return true;
370 }
371 const referenceKey = composerAttachmentFileReferenceKey(fileUri);
372 const drafts = Object.values(appAtomRegistry.get(composerDraftsAtom));
373 const queuedMessages = Object.values(
374 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
375 ).flat();
376 return [...drafts, ...queuedMessages, ...signedOutAttachmentOwners()].some((owner) =>
377 owner.attachments.some(
378 (attachment) =>
379 attachment.fileUri !== undefined &&
380 composerAttachmentFileReferenceKey(attachment.fileUri) === referenceKey,
381 ),
382 );
383}
384
385function isComposerAttachmentUploadReferenced(
386 environmentId: EnvironmentId,
387 attachmentId: string,
388): boolean {
389 const drafts = Object.values(appAtomRegistry.get(composerDraftsAtom));
390 const queuedMessages = Object.values(
391 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
392 ).flat();
393 return [...drafts, ...queuedMessages, ...signedOutAttachmentOwners()].some((owner) =>
394 owner.attachments.some(
395 (attachment) =>
396 attachment.uploadEnvironmentId === environmentId &&
397 attachment.uploadedAttachmentId === attachmentId,
398 ),
399 );
400}
401
402export async function releaseUnusedComposerAttachmentFiles(
403 attachments: ReadonlyArray<DraftComposerAttachment>,
404): Promise<void> {
405 const candidates = new Set(
406 attachments.flatMap((attachment) =>
407 attachment.fileUri !== undefined ? [attachment.fileUri] : [],
408 ),
409 );
410 const uploadCandidates = new Map<EnvironmentId, Set<string>>();
411 for (const attachment of attachments) {
412 if (
413 attachment.uploadEnvironmentId === undefined ||
414 attachment.uploadedAttachmentId === undefined
415 ) {
416 continue;
417 }
418 const ids = uploadCandidates.get(attachment.uploadEnvironmentId) ?? new Set<string>();
419 ids.add(attachment.uploadedAttachmentId);
420 uploadCandidates.set(attachment.uploadEnvironmentId, ids);
421 }
422 if (candidates.size === 0 && uploadCandidates.size === 0) {
423 return;
424 }
425
426 // Persisted drafts must hydrate before the reference scan. On a cold start
427 // the atom is still empty, and every file a persisted draft owns would look
428 // unused. Hydrate before flushing so a pending pre-hydration write cannot
429 // land an incomplete snapshot either.
430 await waitForComposerDraftsLoaded();
431 await flushComposerDrafts();
432 if (!(await threadOutboxManager.load())) {
433 // An unreadable outbox store must not look like an empty queue: deleting
434 // now would take bytes a persisted queued message still needs. Skip the
435 // sweep; the next one retries hydration.
436 return;
437 }
438 await flushThreadOutbox();
439
440 const allFilesReferenced = [...candidates].every(isComposerAttachmentFileReferenced);
441 const allUploadsReferenced = [...uploadCandidates].every(([environmentId, attachmentIds]) =>
442 [...attachmentIds].every((attachmentId) =>
443 isComposerAttachmentUploadReferenced(environmentId, attachmentId),
444 ),
445 );
446 if (allFilesReferenced && allUploadsReferenced) {
447 return;
448 }
449
450 let incomingShareFileUris: ReadonlySet<string>;
451 try {
452 const { loadIncomingShareDrafts } = await import("../features/sharing/incoming-share-storage");
453 const incomingShares = await loadIncomingShareDrafts({ strict: true });
454 incomingShareFileUris = new Set(
455 incomingShares.flatMap((share) =>
456 share.attachments.flatMap((attachment) =>
457 attachment.fileUri !== undefined
458 ? [composerAttachmentFileReferenceKey(attachment.fileUri)]
459 : [],
460 ),
461 ),
462 );
463 } catch (error) {
464 console.warn("[composer-attachments] could not verify incoming share ownership", error);
465 return;
466 }
467
468 const { removePersistedComposerAttachmentFile } = await import("../lib/composerImages");
469 for (const fileUri of candidates) {
470 // Re-check ownership immediately before each deletion: a restore or edit
471 // can re-own a file after an earlier scan decided it was unused.
472 if (
473 isComposerAttachmentFileReferenced(fileUri) ||
474 incomingShareFileUris.has(composerAttachmentFileReferenceKey(fileUri))
475 ) {
476 continue;
477 }
478 await removePersistedComposerAttachmentFile(fileUri);
479 }
480
481 if (uploadCandidates.size > 0) {
482 const { releasePendingAttachmentUploads } = await import("../lib/attachmentUpload");
483 for (const [environmentId, attachmentIds] of uploadCandidates) {
484 for (const attachmentId of attachmentIds) {
485 // A different draft or queued message can reuse the same pending
486 // upload with another local URI. Re-check the server-side ownership
487 // key immediately before deletion.
488 if (isComposerAttachmentUploadReferenced(environmentId, attachmentId)) {
489 continue;
490 }
491 try {
492 await releasePendingAttachmentUploads(environmentId, [attachmentId]);
493 } catch (error) {
494 // The server expires stale pending uploads. Local discard must still
495 // complete when the environment is disconnected or deletion fails.
496 console.warn("[composer-attachments] could not remove pending upload", {
497 environmentId,
498 attachmentId,
499 error,
500 });
501 }
502 }
503 }
504 }
505}
506
507export function scheduleUnusedComposerAttachmentCleanup(
508 attachments: ReadonlyArray<DraftComposerAttachment>,
509): void {
510 if (
511 !attachments.some(
512 (attachment) =>
513 attachment.fileUri !== undefined || attachment.uploadedAttachmentId !== undefined,
514 )
515 ) {
516 return;
517 }
518 void releaseUnusedComposerAttachmentFiles(attachments).catch((error) => {
519 console.warn("[composer-attachments] could not remove unused files", error);
520 });
521}
522
523/** Keeps a native preview or upload readable until it finishes, then retries ownership cleanup. */
524export function retainComposerAttachmentFileForPreview(
525 attachment: FileBackedComposerAttachment,
526): () => void {
527 return retainComposerAttachmentFile(attachment.fileUri, () => {
528 scheduleUnusedComposerAttachmentCleanup([attachment]);
529 });
530}
531
532function schedulePersistComposerState(): void {
533 if (persistTimer !== null) {
534 clearTimeout(persistTimer);
535 }
536 persistTimer = setTimeout(() => {
537 persistTimer = null;
538 // The write enters the serialization queue before waiting on hydration,
539 // so flushComposerDrafts' queue drain cannot resolve ahead of it.
540 void persistenceQueue.run(async () => {
541 try {
542 await waitForComposerDraftsLoaded();
543 await writePersistedComposerState(
544 appAtomRegistry.get(composerDraftsAtom),
545 appAtomRegistry.get(stickyComposerModelSelectionAtom),
546 );
547 persistRetryNeeded = false;
548 } catch (error) {
549 // A failed debounce has no timer left. A later final flush must retry
550 // these edits after persisted ownership can be read safely.
551 persistRetryNeeded = true;
552 console.warn("[composer-drafts] failed to persist drafts", error);
553 // Draft persistence is best-effort; in-memory drafts still keep working.
554 }
555 });
556 }, PERSIST_DEBOUNCE_MS);
557}
558
559export function ensureComposerDraftsLoaded(): void {
560 if (loadPromise !== null) {
561 return;
562 }
563 const loading = loadPersistedComposerState().then((persisted) => {
564 appAtomRegistry.set(composerCloudDraftsAtom, persisted.cloudDrafts);
565 if (Object.keys(persisted.drafts).length > 0) {
566 const current = appAtomRegistry.get(composerDraftsAtom);
567 appAtomRegistry.set(composerDraftsAtom, {
568 ...persisted.drafts,
569 ...current,
570 });
571 }
572 if (
573 persisted.stickyModelSelection !== null &&
574 appAtomRegistry.get(stickyComposerModelSelectionAtom) === null
575 ) {
576 appAtomRegistry.set(stickyComposerModelSelectionAtom, persisted.stickyModelSelection);
577 }
578 });
579 loadPromise = loading;
580 // Handle fire-and-forget hook loads without swallowing failures from the
581 // write and cleanup callers that await this same promise. A later call retries.
582 void loading.catch((cause) => {
583 if (loadPromise === loading) loadPromise = null;
584 console.warn(
585 "[composer-drafts] failed to hydrate drafts",
586 cause instanceof ComposerDraftPersistenceError
587 ? cause
588 : new ComposerDraftPersistenceError({
589 operation: "hydrate",
590 directory: COMPOSER_DRAFTS_DIRECTORY,
591 fileName: COMPOSER_DRAFTS_FILE,
592 cause,
593 }),
594 );
595 });
596}
597
598/** Wait until persisted drafts have been merged into the in-memory composer state. */
599export async function waitForComposerDraftsLoaded(): Promise<void> {
600 ensureComposerDraftsLoaded();
601 if (loadPromise !== null) {
602 await loadPromise;
603 }
604}
605
606export async function getComposerCloudAccountId(): Promise<string | null> {
607 await waitForComposerDraftsLoaded();
608 return appAtomRegistry.get(composerCloudDraftsAtom).accountId;
609}
610
611/** Save an account's local work before its relay environments are removed. */
612export async function archiveCloudComposerDrafts(
613 accountId: string | null,
614 environmentIds: ReadonlySet<EnvironmentId>,
615): Promise<void> {
616 await waitForComposerDraftsLoaded();
617 if (!(await threadOutboxManager.load())) throw new Error("Could not preserve queued messages.");
618 await flushThreadOutbox();
619 const cloud = appAtomRegistry.get(composerCloudDraftsAtom);
620 const owner = accountId ?? cloud.accountId;
621 if (owner === null) return;
622 const queued = Object.values(
623 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
624 ).flat();
625 const current = appAtomRegistry.get(composerDraftsAtom);
626 const remaining = { ...current };
627 const savedDrafts = { ...cloud.signedOut[owner]?.drafts };
628 for (const [key, draft] of Object.entries(current)) {
629 const environmentId = composerDraftEnvironmentId(key, queued);
630 if (environmentId !== null && environmentIds.has(environmentId)) {
631 savedDrafts[key] = draft;
632 delete remaining[key];
633 }
634 }
635 const savedMessages = new Map(
636 (cloud.signedOut[owner]?.queuedMessages ?? []).map((message) => [message.messageId, message]),
637 );
638 for (const message of queued) {
639 if (environmentIds.has(message.environmentId)) savedMessages.set(message.messageId, message);
640 }
641 appAtomRegistry.set(composerDraftsAtom, remaining);
642 appAtomRegistry.set(composerCloudDraftsAtom, {
643 // Keep the owner through removal. A crash or failed cleanup can retry it
644 // on cold start before a different account activates.
645 accountId: owner,
646 signedOut: {
647 ...cloud.signedOut,
648 [owner]: { drafts: savedDrafts, queuedMessages: [...savedMessages.values()] },
649 },
650 });
651 schedulePersistComposerState();
652 await flushComposerDrafts();
653}
654
655function sameDraftAttachmentIds(
656 left: ReadonlyArray<DraftComposerAttachment>,
657 right: ReadonlyArray<DraftComposerAttachment>,
658): boolean {
659 return (
660 left.length === right.length &&
661 left.every((attachment, index) => attachment.id === right[index]?.id)
662 );
663}
664
665/** An in-flight delivery can finish after sign-out took its snapshot. */
666export async function removeDeliveredCloudQueuedMessage(
667 message: QueuedThreadMessage,
668): Promise<void> {
669 await waitForComposerDraftsLoaded();
670 const cloud = appAtomRegistry.get(composerCloudDraftsAtom);
671 const signedOut = { ...cloud.signedOut };
672 let changed = false;
673 for (const [accountId, saved] of Object.entries(signedOut)) {
674 const archived = saved.queuedMessages.find(
675 (candidate) =>
676 candidate.environmentId === message.environmentId &&
677 candidate.messageId === message.messageId,
678 );
679 if (
680 !archived ||
681 archived.commandId !== message.commandId ||
682 archived.threadId !== message.threadId ||
683 archived.text !== message.text ||
684 !sameDraftAttachmentIds(archived.attachments, message.attachments)
685 )
686 continue;
687 // Upload ids may change during preparation; user edits must remain recoverable.
688 if (
689 JSON.stringify([
690 archived.modelSelection,
691 archived.runtimeMode,
692 archived.interactionMode,
693 archived.creation,
694 ]) !==
695 JSON.stringify([
696 message.modelSelection,
697 message.runtimeMode,
698 message.interactionMode,
699 message.creation,
700 ])
701 )
702 continue;
703 const editorKey = `pending-task:${message.messageId}`;
704 const editor = saved.drafts[editorKey];
705 if (
706 editor &&
707 (editor.text !== message.text ||
708 !sameDraftAttachmentIds(editor.attachments, message.attachments) ||
709 (editor.modelSelection !== undefined &&
710 JSON.stringify(editor.modelSelection) !== JSON.stringify(message.modelSelection)) ||
711 (editor.runtimeMode !== undefined && editor.runtimeMode !== message.runtimeMode) ||
712 (editor.interactionMode !== undefined &&
713 editor.interactionMode !== message.interactionMode) ||
714 (editor.workspaceSelection !== undefined &&
715 (editor.workspaceSelection.mode !== message.creation?.workspaceMode ||
716 editor.workspaceSelection.branch !== message.creation?.branch ||
717 editor.workspaceSelection.worktreePath !== message.creation?.worktreePath ||
718 (editor.workspaceSelection.startFromOrigin ?? false) !==
719 (message.creation?.startFromOrigin ?? false))))
720 )
721 continue;
722 const drafts = { ...saved.drafts };
723 delete drafts[editorKey];
724 signedOut[accountId] = {
725 drafts,
726 queuedMessages: saved.queuedMessages.filter((candidate) => candidate !== archived),
727 };
728 changed = true;
729 }
730 if (!changed) return;
731 appAtomRegistry.set(composerCloudDraftsAtom, { ...cloud, signedOut });
732 schedulePersistComposerState();
733 try {
734 await flushComposerDrafts();
735 } catch (error) {
736 // The live outbox can still remove this acknowledged message. Keep the
737 // archive update pending so a later successful flush lands it too.
738 schedulePersistComposerState();
739 throw error;
740 }
741}
742
743/** Restores only this account, before its connections can deliver queued turns. */
744export async function restoreCloudComposerDrafts(accountId: string): Promise<void> {
745 await waitForComposerDraftsLoaded();
746 const cloud = appAtomRegistry.get(composerCloudDraftsAtom);
747 const saved = cloud.signedOut[accountId];
748 if (saved) {
749 if (!(await threadOutboxManager.load())) throw new Error("Could not restore queued messages.");
750 for (const message of saved.queuedMessages) {
751 const alreadyQueued = Object.values(
752 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
753 )
754 .flat()
755 .some((current) => current.messageId === message.messageId);
756 if (!alreadyQueued) await threadOutboxManager.enqueue(message);
757 }
758 updateComposerDrafts((current) => {
759 const restored = { ...current };
760 for (const [key, draft] of Object.entries(saved.drafts)) {
761 const existing = current[key];
762 const attachmentIds = new Set(existing?.attachments.map((attachment) => attachment.id));
763 restored[key] = existing
764 ? {
765 ...draft,
766 ...existing,
767 text: mergeComposerDraftText(existing.text, draft.text),
768 // A concurrent import must not lose files, even above the send limit.
769 attachments: [
770 ...existing.attachments,
771 ...draft.attachments.filter((attachment) => !attachmentIds.has(attachment.id)),
772 ],
773 importedShareIds: [
774 ...new Set([
775 ...(existing.importedShareIds ?? []),
776 ...(draft.importedShareIds ?? []),
777 ]),
778 ],
779 }
780 : draft;
781 }
782 return restored;
783 });
784 }
785 const signedOut = { ...cloud.signedOut };
786 delete signedOut[accountId];
787 appAtomRegistry.set(composerCloudDraftsAtom, { accountId, signedOut });
788 schedulePersistComposerState();
789 await flushComposerDrafts();
790}
791
792function updateComposerDrafts(
793 update: (current: Record<string, ComposerDraft>) => Record<string, ComposerDraft>,
794): void {
795 const current = appAtomRegistry.get(composerDraftsAtom);
796 const next = update(current);
797 if (next === current) {
798 return;
799 }
800 appAtomRegistry.set(composerDraftsAtom, next);
801 schedulePersistComposerState();
802}
803
804export function setStickyComposerModelSelection(modelSelection: ModelSelection): void {
805 appAtomRegistry.set(stickyComposerModelSelectionAtom, modelSelection);
806 schedulePersistComposerState();
807}
808
809export function setComposerDraftText(draftKey: string, value: string): void {
810 updateComposerDrafts((current) => {
811 const draft = {
812 ...normalizeDraft(current[draftKey]),
813 text: value,
814 };
815 if (isEmptyDraft(draft)) {
816 const next = { ...current };
817 delete next[draftKey];
818 return next;
819 }
820 return {
821 ...current,
822 [draftKey]: draft,
823 };
824 });
825}
826
827export function appendComposerDraftText(draftKey: string, value: string): void {
828 updateComposerDrafts((current) => {
829 const existing = normalizeDraft(current[draftKey]);
830 return {
831 ...current,
832 [draftKey]: {
833 ...existing,
834 text: `${existing.text}${value}`,
835 },
836 };
837 });
838}
839
840/**
841 * Appends attachments to a draft, capped at the send limit against the draft's
842 * live state (callers may have counted before an await; the picker can race
843 * concurrent adds). Overflowed file attachments are released. Returns how many
844 * were rejected. Restore paths pass allowOverflow so a failed send never drops
845 * the message's own attachments.
846 */
847export function appendComposerDraftAttachments(
848 draftKey: string,
849 attachments: ReadonlyArray<DraftComposerAttachment>,
850 options?: { readonly allowOverflow?: boolean },
851): number {
852 if (attachments.length === 0) {
853 return 0;
854 }
855 let rejected: ReadonlyArray<DraftComposerAttachment> = [];
856 updateComposerDrafts((current) => {
857 const existing = normalizeDraft(current[draftKey]);
858 const remaining = options?.allowOverflow
859 ? attachments.length
860 : Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - existing.attachments.length);
861 const accepted = attachments.slice(0, remaining);
862 rejected = attachments.slice(remaining);
863 if (accepted.length === 0) {
864 return current;
865 }
866 return {
867 ...current,
868 [draftKey]: {
869 ...existing,
870 attachments: [...existing.attachments, ...accepted],
871 },
872 };
873 });
874 scheduleUnusedComposerAttachmentCleanup(rejected);
875 return rejected.length;
876}
877
878export function replaceComposerDraftAttachments(
879 draftKey: string,
880 attachments: ReadonlyArray<DraftComposerAttachment>,
881): void {
882 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
883 updateComposerDrafts((current) => {
884 const draft = {
885 ...normalizeDraft(current[draftKey]),
886 attachments,
887 };
888 if (isEmptyDraft(draft)) {
889 const next = { ...current };
890 delete next[draftKey];
891 return next;
892 }
893 return {
894 ...current,
895 [draftKey]: draft,
896 };
897 });
898 const retainedIds = new Set(attachments.map((attachment) => attachment.id));
899 scheduleUnusedComposerAttachmentCleanup(
900 previousAttachments.filter((attachment) => !retainedIds.has(attachment.id)),
901 );
902}
903
904export function removeComposerDraftAttachment(draftKey: string, imageId: string): void {
905 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
906 updateComposerDrafts((current) => {
907 const existing = normalizeDraft(current[draftKey]);
908 const draft = {
909 ...existing,
910 attachments: existing.attachments.filter((image) => image.id !== imageId),
911 };
912 if (isEmptyDraft(draft)) {
913 const next = { ...current };
914 delete next[draftKey];
915 return next;
916 }
917 return {
918 ...current,
919 [draftKey]: draft,
920 };
921 });
922 scheduleUnusedComposerAttachmentCleanup(
923 previousAttachments.filter((attachment) => attachment.id === imageId),
924 );
925}
926
927/** Stamps a finished upload without overwriting text, removals, or newer attachments. */
928export function setComposerDraftAttachmentUpload(
929 draftKey: string,
930 attachment: DraftComposerAttachment,
931): boolean {
932 let previous: DraftComposerAttachment | undefined;
933 updateComposerDrafts((current) => {
934 const draft = current[draftKey];
935 previous = draft?.attachments.find((candidate) => candidate.id === attachment.id);
936 if (!draft || !previous) return current;
937 if (
938 previous.uploadedAttachmentId === attachment.uploadedAttachmentId &&
939 previous.uploadEnvironmentId === attachment.uploadEnvironmentId
940 )
941 return current;
942 return {
943 ...current,
944 [draftKey]: {
945 ...draft,
946 attachments: draft.attachments.map((candidate) =>
947 candidate.id === attachment.id
948 ? {
949 ...candidate,
950 uploadedAttachmentId: attachment.uploadedAttachmentId,
951 uploadEnvironmentId: attachment.uploadEnvironmentId,
952 }
953 : candidate,
954 ),
955 },
956 };
957 });
958 if (previous) scheduleUnusedComposerAttachmentCleanup([previous]);
959 return previous !== undefined;
960}
961
962export function updateComposerDraftSettings(
963 draftKey: string,
964 settings: Partial<ComposerDraftSettingsUpdate>,
965): void {
966 updateComposerDrafts((current) => {
967 const draft = {
968 ...normalizeDraft(current[draftKey]),
969 ...settings,
970 };
971 if (isEmptyDraft(draft)) {
972 const next = { ...current };
973 delete next[draftKey];
974 return next;
975 }
976 return {
977 ...current,
978 [draftKey]: draft,
979 };
980 });
981}
982
983export function clearComposerDraftContentState(
984 current: Record<string, ComposerDraft>,
985 draftKey: string,
986 options?: {
987 readonly clearModelSelection?: boolean;
988 readonly clearWorkspaceSelection?: boolean;
989 },
990): Record<string, ComposerDraft> {
991 const existing = current[draftKey];
992 if (!existing) {
993 return current;
994 }
995 const {
996 importedShareIds: _importedShareIds,
997 modelSelection,
998 workspaceSelection,
999 ...retained
1000 } = existing;
1001 const draft = {
1002 ...retained,
1003 ...(options?.clearModelSelection || modelSelection === undefined ? {} : { modelSelection }),
1004 ...(options?.clearWorkspaceSelection || workspaceSelection === undefined
1005 ? {}
1006 : { workspaceSelection }),
1007 text: "",
1008 attachments: [],
1009 };
1010 if (isEmptyDraft(draft)) {
1011 const next = { ...current };
1012 delete next[draftKey];
1013 return next;
1014 }
1015 return {
1016 ...current,
1017 [draftKey]: draft,
1018 };
1019}
1020
1021export function restoreComposerDraftSnapshotState(
1022 current: Record<string, ComposerDraft>,
1023 draftKey: string,
1024 snapshot: ComposerDraft,
1025): Record<string, ComposerDraft> {
1026 const next = { ...current };
1027 if (isEmptyDraft(snapshot)) {
1028 delete next[draftKey];
1029 } else {
1030 next[draftKey] = snapshot;
1031 }
1032 return next;
1033}
1034
1035export function copyComposerDraftContentState(
1036 current: Record<string, ComposerDraft>,
1037 sourceDraftKey: string,
1038 targetDraftKey: string,
1039): Record<string, ComposerDraft> {
1040 if (sourceDraftKey === targetDraftKey) {
1041 return current;
1042 }
1043 const source = normalizeDraft(current[sourceDraftKey]);
1044 const target = normalizeDraft(current[targetDraftKey]);
1045 const sourceHasContent =
1046 source.text.length > 0 ||
1047 source.attachments.length > 0 ||
1048 (source.importedShareIds?.length ?? 0) > 0;
1049 const targetHasContent =
1050 target.text.length > 0 ||
1051 target.attachments.length > 0 ||
1052 (target.importedShareIds?.length ?? 0) > 0;
1053 if (!sourceHasContent || targetHasContent) {
1054 return current;
1055 }
1056 return {
1057 ...current,
1058 [targetDraftKey]: {
1059 ...target,
1060 text: source.text,
1061 attachments: source.attachments,
1062 ...(source.importedShareIds ? { importedShareIds: source.importedShareIds } : {}),
1063 },
1064 };
1065}
1066
1067export async function copyComposerDraftContentIfEmpty(
1068 sourceDraftKey: string,
1069 targetDraftKey: string,
1070): Promise<void> {
1071 ensureComposerDraftsLoaded();
1072 if (loadPromise !== null) {
1073 await loadPromise;
1074 }
1075 updateComposerDrafts((current) =>
1076 copyComposerDraftContentState(current, sourceDraftKey, targetDraftKey),
1077 );
1078}
1079
1080function mergeComposerDraftText(existing: string, incoming: string): string {
1081 if (incoming.length === 0) {
1082 return existing;
1083 }
1084 if (existing.length === 0) {
1085 return incoming;
1086 }
1087 // Import retries are possible after an interrupted native handoff. Keep the
1088 // operation idempotent when the same shared text is already present.
1089 if (existing === incoming || existing.endsWith(`\n\n${incoming}`)) {
1090 return existing;
1091 }
1092 return `${existing}\n\n${incoming}`;
1093}
1094
1095export function mergeComposerDraftContentState(
1096 current: Record<string, ComposerDraft>,
1097 draftKey: string,
1098 content: ComposerDraftContent,
1099): Record<string, ComposerDraft> {
1100 const existing = normalizeDraft(current[draftKey]);
1101 if (content.sourceShareId && existing.importedShareIds?.includes(content.sourceShareId)) {
1102 return current;
1103 }
1104 const attachmentIds = new Set(existing.attachments.map((attachment) => attachment.id));
1105 const incomingAttachments = content.attachments.filter((attachment) => {
1106 if (attachmentIds.has(attachment.id)) {
1107 return false;
1108 }
1109 attachmentIds.add(attachment.id);
1110 return true;
1111 });
1112 const attachments = [...existing.attachments, ...incomingAttachments].slice(
1113 0,
1114 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
1115 );
1116 const text = mergeComposerDraftText(existing.text, content.text);
1117 const importedShareIds = content.sourceShareId
1118 ? [...(existing.importedShareIds ?? []), content.sourceShareId]
1119 : existing.importedShareIds;
1120 if (
1121 text === existing.text &&
1122 attachments.length === existing.attachments.length &&
1123 importedShareIds === existing.importedShareIds
1124 ) {
1125 return current;
1126 }
1127 return {
1128 ...current,
1129 [draftKey]: {
1130 ...existing,
1131 text,
1132 attachments,
1133 ...(importedShareIds ? { importedShareIds } : {}),
1134 },
1135 };
1136}
1137
1138/**
1139 * Atomically moves an incoming share into a project-scoped composer draft.
1140 * The durable write happens before the share inbox item can be acknowledged.
1141 */
1142export async function mergeComposerDraftContent(
1143 draftKey: string,
1144 content: ComposerDraftContent,
1145): Promise<{ readonly skippedAttachmentCount: number }> {
1146 ensureComposerDraftsLoaded();
1147 if (loadPromise !== null) {
1148 await loadPromise;
1149 }
1150 if (persistTimer !== null) {
1151 clearTimeout(persistTimer);
1152 persistTimer = null;
1153 }
1154 const current = appAtomRegistry.get(composerDraftsAtom);
1155 const next = mergeComposerDraftContentState(current, draftKey, content);
1156 const currentAttachmentIds = new Set(
1157 normalizeDraft(current[draftKey]).attachments.map((attachment) => attachment.id),
1158 );
1159 const nextAttachmentIds = new Set(
1160 normalizeDraft(next[draftKey]).attachments.map((attachment) => attachment.id),
1161 );
1162 const skippedAttachmentCount = content.attachments.filter(
1163 (attachment) =>
1164 !currentAttachmentIds.has(attachment.id) && !nextAttachmentIds.has(attachment.id),
1165 ).length;
1166 // Publish the content and its import receipt together before the filesystem
1167 // await. Typing during persistence then builds on the receipt-bearing state,
1168 // and its debounced write is serialized after this transaction.
1169 if (next !== current) {
1170 appAtomRegistry.set(composerDraftsAtom, next);
1171 }
1172 await persistenceQueue.run(() =>
1173 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1174 );
1175 return { skippedAttachmentCount };
1176}
1177
1178/** Restores the exact content/settings captured before an interrupted import. */
1179export async function restoreComposerDraftSnapshot(
1180 draftKey: string,
1181 snapshot: ComposerDraft,
1182): Promise<void> {
1183 ensureComposerDraftsLoaded();
1184 if (loadPromise !== null) {
1185 await loadPromise;
1186 }
1187 if (persistTimer !== null) {
1188 clearTimeout(persistTimer);
1189 persistTimer = null;
1190 }
1191 const next = restoreComposerDraftSnapshotState(
1192 appAtomRegistry.get(composerDraftsAtom),
1193 draftKey,
1194 snapshot,
1195 );
1196 appAtomRegistry.set(composerDraftsAtom, next);
1197 await persistenceQueue.run(() =>
1198 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1199 );
1200}
1201
1202export function sameComposerDraftState(a: ComposerDraft, b: ComposerDraft): boolean {
1203 return (
1204 a.text === b.text &&
1205 a.attachments === b.attachments &&
1206 a.importedShareIds === b.importedShareIds &&
1207 a.modelSelection === b.modelSelection &&
1208 a.runtimeMode === b.runtimeMode &&
1209 a.interactionMode === b.interactionMode &&
1210 a.workspaceSelection === b.workspaceSelection
1211 );
1212}
1213
1214/**
1215 * Undoes an abandoned mergeComposerDraftContent. When the draft is untouched
1216 * since `merged` (the state captured right after the merge), the pre-merge
1217 * snapshot comes back exactly. When the user edited the draft during the
1218 * merge's awaits, only what the merge inserted (the appended text and the new
1219 * attachments) is taken back out, so the user's edits survive the rollback.
1220 */
1221export function undoComposerDraftMergeState(
1222 current: Record<string, ComposerDraft>,
1223 draftKey: string,
1224 snapshot: ComposerDraft,
1225 merged: ComposerDraft,
1226): Record<string, ComposerDraft> {
1227 const existing = normalizeDraft(current[draftKey]);
1228 if (sameComposerDraftState(existing, merged)) {
1229 return restoreComposerDraftSnapshotState(current, draftKey, snapshot);
1230 }
1231 const insertedText = merged.text.startsWith(snapshot.text)
1232 ? merged.text.slice(snapshot.text.length)
1233 : "";
1234 const snapshotAttachmentIds = new Set(snapshot.attachments.map((attachment) => attachment.id));
1235 const insertedAttachmentIds = new Set(
1236 merged.attachments
1237 .filter((attachment) => !snapshotAttachmentIds.has(attachment.id))
1238 .map((attachment) => attachment.id),
1239 );
1240 // A setting still holding the merge's value is the merge's doing: restore
1241 // the snapshot's. One the user changed since the merge stays theirs.
1242 const undoSetting = <
1243 K extends "modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection",
1244 >(
1245 key: K,
1246 ): ComposerDraft[K] => (existing[key] === merged[key] ? snapshot[key] : existing[key]);
1247 const text =
1248 insertedText.length > 0 && existing.text.startsWith(merged.text)
1249 ? snapshot.text + existing.text.slice(merged.text.length)
1250 : insertedText.length > 0 && existing.text.endsWith(insertedText)
1251 ? existing.text.slice(0, existing.text.length - insertedText.length)
1252 : existing.text;
1253 const draft = {
1254 ...existing,
1255 text,
1256 attachments: existing.attachments.filter(
1257 (attachment) => !insertedAttachmentIds.has(attachment.id),
1258 ),
1259 modelSelection: undoSetting("modelSelection"),
1260 runtimeMode: undoSetting("runtimeMode"),
1261 interactionMode: undoSetting("interactionMode"),
1262 workspaceSelection: undoSetting("workspaceSelection"),
1263 };
1264 if (isEmptyDraft(draft)) {
1265 const next = { ...current };
1266 delete next[draftKey];
1267 return next;
1268 }
1269 return {
1270 ...current,
1271 [draftKey]: draft,
1272 };
1273}
1274
1275/** Applies undoComposerDraftMergeState and lands it durably. */
1276export async function undoComposerDraftMerge(
1277 draftKey: string,
1278 snapshot: ComposerDraft,
1279 merged: ComposerDraft,
1280): Promise<void> {
1281 ensureComposerDraftsLoaded();
1282 if (loadPromise !== null) {
1283 await loadPromise;
1284 }
1285 if (persistTimer !== null) {
1286 clearTimeout(persistTimer);
1287 persistTimer = null;
1288 }
1289 const next = undoComposerDraftMergeState(
1290 appAtomRegistry.get(composerDraftsAtom),
1291 draftKey,
1292 snapshot,
1293 merged,
1294 );
1295 appAtomRegistry.set(composerDraftsAtom, next);
1296 await persistenceQueue.run(() =>
1297 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1298 );
1299}
1300
1301export function clearComposerDraftContent(
1302 draftKey: string,
1303 options?: {
1304 readonly clearModelSelection?: boolean;
1305 readonly clearWorkspaceSelection?: boolean;
1306 // Send clears the draft while the durable outbox write is still in
1307 // flight. Sweeping then would race the write: a failed enqueue rolls the
1308 // message out of the queue mid-sweep and its files get deleted right
1309 // before the failure handler restores them. The sender re-schedules
1310 // cleanup once the write settles.
1311 readonly deferAttachmentCleanup?: boolean;
1312 },
1313): void {
1314 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1315 updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options));
1316 if (!options?.deferAttachmentCleanup) {
1317 scheduleUnusedComposerAttachmentCleanup(previousAttachments);
1318 }
1319}
1320
1321export function clearComposerDraft(
1322 draftKey: string,
1323 options?: { readonly deferAttachmentCleanup?: boolean },
1324): void {
1325 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1326 updateComposerDrafts((current) => {
1327 if (!current[draftKey]) {
1328 return current;
1329 }
1330 const next = { ...current };
1331 delete next[draftKey];
1332 return next;
1333 });
1334 if (!options?.deferAttachmentCleanup) {
1335 scheduleUnusedComposerAttachmentCleanup(previousAttachments);
1336 }
1337}
1338
1339export function removeComposerDraftsForEnvironment(
1340 drafts: Record<string, ComposerDraft>,
1341 environmentId: EnvironmentId,
1342): Record<string, ComposerDraft> {
1343 const environmentPrefix = `${environmentId}:`;
1344 const newTaskPrefix = `new-task:${environmentId}:`;
1345 return Object.fromEntries(
1346 Object.entries(drafts).filter(
1347 ([draftKey]) =>
1348 !draftKey.startsWith(environmentPrefix) && !draftKey.startsWith(newTaskPrefix),
1349 ),
1350 );
1351}
1352
1353export async function clearComposerDraftsEnvironment(environmentId: EnvironmentId): Promise<void> {
1354 ensureComposerDraftsLoaded();
1355 if (loadPromise !== null) {
1356 await loadPromise;
1357 }
1358
1359 const current = appAtomRegistry.get(composerDraftsAtom);
1360 const next = removeComposerDraftsForEnvironment(current, environmentId);
1361 const removedAttachments = Object.entries(current)
1362 .filter(([draftKey]) => next[draftKey] === undefined)
1363 .flatMap(([, draft]) => draft.attachments);
1364
1365 if (persistTimer !== null) {
1366 clearTimeout(persistTimer);
1367 persistTimer = null;
1368 }
1369 appAtomRegistry.set(composerDraftsAtom, next);
1370 await persistenceQueue.run(() =>
1371 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1372 );
1373 await releaseUnusedComposerAttachmentFiles(removedAttachments);
1374}
1375
1376export function useComposerDraft(draftKey: string | null): ComposerDraft {
1377 const drafts = useAtomValue(composerDraftsAtom);
1378 useEffect(() => {
1379 ensureComposerDraftsLoaded();
1380 }, []);
1381 return draftKey ? normalizeDraft(drafts[draftKey]) : EMPTY_DRAFT;
1382}
1383
1384export function useStickyComposerModelSelection(): ModelSelection | null {
1385 const selection = useAtomValue(stickyComposerModelSelectionAtom);
1386 useEffect(() => {
1387 ensureComposerDraftsLoaded();
1388 }, []);
1389 return selection;
1390}