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, DraftComposerFileAttachment } 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;
151const persistenceQueue = new SerializedAsyncQueue();
152
153/** Resets module-level state between test runs. */
154export function resetComposerDraftsLoadState(): void {
155 loadPromise = null;
156}
157
158function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
159 if (!draft) {
160 return EMPTY_DRAFT;
161 }
162 return {
163 ...draft,
164 text: draft.text,
165 attachments: draft.attachments,
166 };
167}
168
169export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
170 return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
171}
172
173export function isComposerDraftEmpty(draft: ComposerDraft): boolean {
174 return isEmptyDraft(draft);
175}
176
177function isEmptyDraft(draft: ComposerDraft): boolean {
178 return (
179 draft.text.length === 0 &&
180 draft.attachments.length === 0 &&
181 draft.modelSelection === undefined &&
182 draft.runtimeMode === undefined &&
183 draft.interactionMode === undefined &&
184 draft.workspaceSelection === undefined
185 );
186}
187
188export function decodePersistedComposerState(value: unknown): {
189 readonly drafts: Record<string, ComposerDraft>;
190 readonly stickyModelSelection: ModelSelection | null;
191 readonly cloudDrafts: ComposerCloudDraftState;
192} {
193 const parsed = decodePersistedComposerDraftsDocument(value);
194 return {
195 drafts: Object.fromEntries(
196 Object.entries(parsed.drafts)
197 .map(
198 ([key, draft]) =>
199 [
200 key,
201 // Stale new-task drafts left on disk by builds before the
202 // model-precedence fix carry a bare modelSelection with no
203 // other selector settings. Strip it so the next compose pass
204 // re-resolves project → sticky → provider defaults. Drafts
205 // with runtime/interaction/workspace settings or actual text /
206 // attachments were deliberately configured and are left alone.
207 key.startsWith("new-task:") &&
208 draft.modelSelection &&
209 draft.text.length === 0 &&
210 draft.attachments.length === 0 &&
211 draft.runtimeMode === undefined &&
212 draft.interactionMode === undefined &&
213 draft.workspaceSelection === undefined
214 ? { ...draft, modelSelection: undefined }
215 : draft,
216 ] as const,
217 )
218 // importedShareIds are share-import receipts: a contentless draft
219 // carrying one is not empty, or the same native share would be
220 // re-imported after restart.
221 .filter(([, draft]) => !isEmptyDraft(draft) || (draft.importedShareIds?.length ?? 0) > 0),
222 ),
223 stickyModelSelection: parsed.stickyModelSelection ?? null,
224 cloudDrafts: {
225 accountId: parsed.cloudAccountId ?? null,
226 signedOut: Object.fromEntries(
227 Object.entries(parsed.signedOutDrafts ?? {}).map(([id, saved]) => [
228 id,
229 {
230 drafts: saved.drafts,
231 queuedMessages: saved.queuedMessages.map(decodeQueuedThreadMessage),
232 },
233 ]),
234 ),
235 },
236 };
237}
238
239export function decodePersistedComposerDrafts(value: unknown): Record<string, ComposerDraft> {
240 return decodePersistedComposerState(value).drafts;
241}
242
243async function getComposerDraftsFile() {
244 const { Directory, File, Paths } = await import("expo-file-system");
245 const directory = new Directory(Paths.document, COMPOSER_DRAFTS_DIRECTORY);
246 directory.create({ idempotent: true, intermediates: true });
247 return new File(directory, COMPOSER_DRAFTS_FILE);
248}
249
250async function loadPersistedComposerState(): Promise<
251 ReturnType<typeof decodePersistedComposerState>
252> {
253 let operation: ComposerDraftPersistenceError["operation"] = "open";
254 try {
255 const file = await getComposerDraftsFile();
256 if (!file.exists) {
257 return {
258 drafts: {},
259 stickyModelSelection: null,
260 cloudDrafts: { accountId: null, signedOut: {} },
261 };
262 }
263 operation = "read";
264 const raw = await file.text();
265 operation = "decode";
266 return decodePersistedComposerState(JSON.parse(raw) as unknown);
267 } catch (cause) {
268 console.warn(
269 "[composer-drafts] ignored persisted draft failure",
270 new ComposerDraftPersistenceError({
271 operation,
272 directory: COMPOSER_DRAFTS_DIRECTORY,
273 fileName: COMPOSER_DRAFTS_FILE,
274 cause,
275 }),
276 );
277 return {
278 drafts: {},
279 stickyModelSelection: null,
280 cloudDrafts: { accountId: null, signedOut: {} },
281 };
282 }
283}
284
285async function writePersistedComposerState(
286 drafts: Record<string, ComposerDraft>,
287 stickyModelSelection: ModelSelection | null,
288 cloudDrafts = appAtomRegistry.get(composerCloudDraftsAtom),
289): Promise<void> {
290 let operation: ComposerDraftPersistenceError["operation"] = "open";
291 try {
292 const file = await getComposerDraftsFile();
293 operation = "encode";
294 const nonEmptyDrafts = Object.fromEntries(
295 Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
296 );
297 const document = {
298 schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
299 drafts: nonEmptyDrafts,
300 ...(stickyModelSelection ? { stickyModelSelection } : {}),
301 ...(cloudDrafts.accountId ? { cloudAccountId: cloudDrafts.accountId } : {}),
302 ...(Object.keys(cloudDrafts.signedOut).length > 0
303 ? {
304 signedOutDrafts: Object.fromEntries(
305 Object.entries(cloudDrafts.signedOut).map(([id, saved]) => [
306 id,
307 {
308 drafts: saved.drafts,
309 queuedMessages: saved.queuedMessages.map(encodeQueuedThreadMessage),
310 },
311 ]),
312 ),
313 }
314 : {}),
315 } as const;
316 const encoded = JSON.stringify(document);
317 operation = "write";
318 await writeFileAtomically(file, encoded);
319 } catch (cause) {
320 throw new ComposerDraftPersistenceError({
321 operation,
322 directory: COMPOSER_DRAFTS_DIRECTORY,
323 fileName: COMPOSER_DRAFTS_FILE,
324 cause,
325 });
326 }
327}
328
329/**
330 * Lands any debounced or in-flight draft write before the JS runtime is torn
331 * down (app update restart), so the freshest draft state survives it. A write
332 * failure propagates so the caller can decide whether the restart may proceed.
333 */
334export async function flushComposerDrafts(): Promise<void> {
335 // Never land a pre-hydration snapshot: persisted state must merge into the
336 // atoms first, or this write would clobber disk with partial data.
337 ensureComposerDraftsLoaded();
338 if (loadPromise !== null) {
339 await loadPromise;
340 }
341 // An edit during an awaited write schedules another debounced write, so
342 // keep landing snapshots until no debounce is pending after a queue drain.
343 do {
344 while (persistTimer !== null) {
345 clearTimeout(persistTimer);
346 persistTimer = null;
347 await persistenceQueue.run(() =>
348 writePersistedComposerState(
349 appAtomRegistry.get(composerDraftsAtom),
350 appAtomRegistry.get(stickyComposerModelSelectionAtom),
351 ),
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);
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.type === "file" &&
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
407 .filter((attachment) => attachment.type === "file")
408 .map((attachment) => attachment.fileUri),
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.type === "file"
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) => attachment.type === "file" || attachment.uploadedAttachmentId !== undefined,
513 )
514 ) {
515 return;
516 }
517 void releaseUnusedComposerAttachmentFiles(attachments).catch((error) => {
518 console.warn("[composer-attachments] could not remove unused files", error);
519 });
520}
521
522/** Keeps a native preview or upload readable until it finishes, then retries ownership cleanup. */
523export function retainComposerAttachmentFileForPreview(
524 attachment: DraftComposerFileAttachment,
525): () => void {
526 return retainComposerAttachmentFile(attachment.fileUri, () => {
527 scheduleUnusedComposerAttachmentCleanup([attachment]);
528 });
529}
530
531function schedulePersistComposerState(): void {
532 if (persistTimer !== null) {
533 clearTimeout(persistTimer);
534 }
535 persistTimer = setTimeout(() => {
536 persistTimer = null;
537 ensureComposerDraftsLoaded();
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 if (loadPromise !== null) {
542 await loadPromise;
543 }
544 try {
545 await writePersistedComposerState(
546 appAtomRegistry.get(composerDraftsAtom),
547 appAtomRegistry.get(stickyComposerModelSelectionAtom),
548 );
549 } catch (error) {
550 console.warn("[composer-drafts] failed to persist drafts", error);
551 // Draft persistence is best-effort; in-memory drafts still keep working.
552 }
553 });
554 }, PERSIST_DEBOUNCE_MS);
555}
556
557export function ensureComposerDraftsLoaded(): void {
558 if (loadPromise !== null) {
559 return;
560 }
561 loadPromise = loadPersistedComposerState()
562 .then((persisted) => {
563 appAtomRegistry.set(composerCloudDraftsAtom, persisted.cloudDrafts);
564 if (Object.keys(persisted.drafts).length > 0) {
565 const current = appAtomRegistry.get(composerDraftsAtom);
566 appAtomRegistry.set(composerDraftsAtom, {
567 ...persisted.drafts,
568 ...current,
569 });
570 }
571 if (
572 persisted.stickyModelSelection !== null &&
573 appAtomRegistry.get(stickyComposerModelSelectionAtom) === null
574 ) {
575 appAtomRegistry.set(stickyComposerModelSelectionAtom, persisted.stickyModelSelection);
576 }
577 })
578 .catch((cause) => {
579 console.warn(
580 "[composer-drafts] failed to hydrate drafts",
581 new ComposerDraftPersistenceError({
582 operation: "hydrate",
583 directory: COMPOSER_DRAFTS_DIRECTORY,
584 fileName: COMPOSER_DRAFTS_FILE,
585 cause,
586 }),
587 );
588 // Draft loading is best-effort; in-memory drafts still keep working.
589 });
590}
591
592/** Wait until persisted drafts have been merged into the in-memory composer state. */
593export async function waitForComposerDraftsLoaded(): Promise<void> {
594 ensureComposerDraftsLoaded();
595 if (loadPromise !== null) {
596 await loadPromise;
597 }
598}
599
600export async function getComposerCloudAccountId(): Promise<string | null> {
601 await waitForComposerDraftsLoaded();
602 return appAtomRegistry.get(composerCloudDraftsAtom).accountId;
603}
604
605/** Save an account's local work before its relay environments are removed. */
606export async function archiveCloudComposerDrafts(
607 accountId: string | null,
608 environmentIds: ReadonlySet<EnvironmentId>,
609): Promise<void> {
610 await waitForComposerDraftsLoaded();
611 if (!(await threadOutboxManager.load())) throw new Error("Could not preserve queued messages.");
612 await flushThreadOutbox();
613 const cloud = appAtomRegistry.get(composerCloudDraftsAtom);
614 const owner = accountId ?? cloud.accountId;
615 if (owner === null) return;
616 const queued = Object.values(
617 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
618 ).flat();
619 const current = appAtomRegistry.get(composerDraftsAtom);
620 const remaining = { ...current };
621 const savedDrafts = { ...cloud.signedOut[owner]?.drafts };
622 for (const [key, draft] of Object.entries(current)) {
623 const environmentId = composerDraftEnvironmentId(key, queued);
624 if (environmentId !== null && environmentIds.has(environmentId)) {
625 savedDrafts[key] = draft;
626 delete remaining[key];
627 }
628 }
629 const savedMessages = new Map(
630 (cloud.signedOut[owner]?.queuedMessages ?? []).map((message) => [message.messageId, message]),
631 );
632 for (const message of queued) {
633 if (environmentIds.has(message.environmentId)) savedMessages.set(message.messageId, message);
634 }
635 appAtomRegistry.set(composerDraftsAtom, remaining);
636 appAtomRegistry.set(composerCloudDraftsAtom, {
637 // Keep the owner through removal. A crash or failed cleanup can retry it
638 // on cold start before a different account activates.
639 accountId: owner,
640 signedOut: {
641 ...cloud.signedOut,
642 [owner]: { drafts: savedDrafts, queuedMessages: [...savedMessages.values()] },
643 },
644 });
645 schedulePersistComposerState();
646 await flushComposerDrafts();
647}
648
649function sameDraftAttachmentIds(
650 left: ReadonlyArray<DraftComposerAttachment>,
651 right: ReadonlyArray<DraftComposerAttachment>,
652): boolean {
653 return (
654 left.length === right.length &&
655 left.every((attachment, index) => attachment.id === right[index]?.id)
656 );
657}
658
659/** An in-flight delivery can finish after sign-out took its snapshot. */
660export async function removeDeliveredCloudQueuedMessage(
661 message: QueuedThreadMessage,
662): Promise<void> {
663 await waitForComposerDraftsLoaded();
664 const cloud = appAtomRegistry.get(composerCloudDraftsAtom);
665 const signedOut = { ...cloud.signedOut };
666 let changed = false;
667 for (const [accountId, saved] of Object.entries(signedOut)) {
668 const archived = saved.queuedMessages.find(
669 (candidate) =>
670 candidate.environmentId === message.environmentId &&
671 candidate.messageId === message.messageId,
672 );
673 if (
674 !archived ||
675 archived.commandId !== message.commandId ||
676 archived.threadId !== message.threadId ||
677 archived.text !== message.text ||
678 !sameDraftAttachmentIds(archived.attachments, message.attachments)
679 )
680 continue;
681 // Upload ids may change during preparation; user edits must remain recoverable.
682 if (
683 JSON.stringify([
684 archived.modelSelection,
685 archived.runtimeMode,
686 archived.interactionMode,
687 archived.creation,
688 ]) !==
689 JSON.stringify([
690 message.modelSelection,
691 message.runtimeMode,
692 message.interactionMode,
693 message.creation,
694 ])
695 )
696 continue;
697 const editorKey = `pending-task:${message.messageId}`;
698 const editor = saved.drafts[editorKey];
699 if (
700 editor &&
701 (editor.text !== message.text ||
702 !sameDraftAttachmentIds(editor.attachments, message.attachments) ||
703 (editor.modelSelection !== undefined &&
704 JSON.stringify(editor.modelSelection) !== JSON.stringify(message.modelSelection)) ||
705 (editor.runtimeMode !== undefined && editor.runtimeMode !== message.runtimeMode) ||
706 (editor.interactionMode !== undefined &&
707 editor.interactionMode !== message.interactionMode) ||
708 (editor.workspaceSelection !== undefined &&
709 (editor.workspaceSelection.mode !== message.creation?.workspaceMode ||
710 editor.workspaceSelection.branch !== message.creation?.branch ||
711 editor.workspaceSelection.worktreePath !== message.creation?.worktreePath ||
712 (editor.workspaceSelection.startFromOrigin ?? false) !==
713 (message.creation?.startFromOrigin ?? false))))
714 )
715 continue;
716 const drafts = { ...saved.drafts };
717 delete drafts[editorKey];
718 signedOut[accountId] = {
719 drafts,
720 queuedMessages: saved.queuedMessages.filter((candidate) => candidate !== archived),
721 };
722 changed = true;
723 }
724 if (!changed) return;
725 appAtomRegistry.set(composerCloudDraftsAtom, { ...cloud, signedOut });
726 schedulePersistComposerState();
727 try {
728 await flushComposerDrafts();
729 } catch (error) {
730 // The live outbox can still remove this acknowledged message. Keep the
731 // archive update pending so a later successful flush lands it too.
732 schedulePersistComposerState();
733 throw error;
734 }
735}
736
737/** Restores only this account, before its connections can deliver queued turns. */
738export async function restoreCloudComposerDrafts(accountId: string): Promise<void> {
739 await waitForComposerDraftsLoaded();
740 const cloud = appAtomRegistry.get(composerCloudDraftsAtom);
741 const saved = cloud.signedOut[accountId];
742 if (saved) {
743 if (!(await threadOutboxManager.load())) throw new Error("Could not restore queued messages.");
744 for (const message of saved.queuedMessages) {
745 const alreadyQueued = Object.values(
746 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
747 )
748 .flat()
749 .some((current) => current.messageId === message.messageId);
750 if (!alreadyQueued) await threadOutboxManager.enqueue(message);
751 }
752 updateComposerDrafts((current) => {
753 const restored = { ...current };
754 for (const [key, draft] of Object.entries(saved.drafts)) {
755 const existing = current[key];
756 const attachmentIds = new Set(existing?.attachments.map((attachment) => attachment.id));
757 restored[key] = existing
758 ? {
759 ...draft,
760 ...existing,
761 text: mergeComposerDraftText(existing.text, draft.text),
762 // A concurrent import must not lose files, even above the send limit.
763 attachments: [
764 ...existing.attachments,
765 ...draft.attachments.filter((attachment) => !attachmentIds.has(attachment.id)),
766 ],
767 importedShareIds: [
768 ...new Set([
769 ...(existing.importedShareIds ?? []),
770 ...(draft.importedShareIds ?? []),
771 ]),
772 ],
773 }
774 : draft;
775 }
776 return restored;
777 });
778 }
779 const signedOut = { ...cloud.signedOut };
780 delete signedOut[accountId];
781 appAtomRegistry.set(composerCloudDraftsAtom, { accountId, signedOut });
782 schedulePersistComposerState();
783 await flushComposerDrafts();
784}
785
786function updateComposerDrafts(
787 update: (current: Record<string, ComposerDraft>) => Record<string, ComposerDraft>,
788): void {
789 const current = appAtomRegistry.get(composerDraftsAtom);
790 const next = update(current);
791 if (next === current) {
792 return;
793 }
794 appAtomRegistry.set(composerDraftsAtom, next);
795 schedulePersistComposerState();
796}
797
798export function setStickyComposerModelSelection(modelSelection: ModelSelection): void {
799 appAtomRegistry.set(stickyComposerModelSelectionAtom, modelSelection);
800 schedulePersistComposerState();
801}
802
803export function setComposerDraftText(draftKey: string, value: string): void {
804 updateComposerDrafts((current) => {
805 const draft = {
806 ...normalizeDraft(current[draftKey]),
807 text: value,
808 };
809 if (isEmptyDraft(draft)) {
810 const next = { ...current };
811 delete next[draftKey];
812 return next;
813 }
814 return {
815 ...current,
816 [draftKey]: draft,
817 };
818 });
819}
820
821export function appendComposerDraftText(draftKey: string, value: string): void {
822 updateComposerDrafts((current) => {
823 const existing = normalizeDraft(current[draftKey]);
824 return {
825 ...current,
826 [draftKey]: {
827 ...existing,
828 text: `${existing.text}${value}`,
829 },
830 };
831 });
832}
833
834/**
835 * Appends attachments to a draft, capped at the send limit against the draft's
836 * live state (callers may have counted before an await; the picker can race
837 * concurrent adds). Overflowed file attachments are released. Returns how many
838 * were rejected. Restore paths pass allowOverflow so a failed send never drops
839 * the message's own attachments.
840 */
841export function appendComposerDraftAttachments(
842 draftKey: string,
843 attachments: ReadonlyArray<DraftComposerAttachment>,
844 options?: { readonly allowOverflow?: boolean },
845): number {
846 if (attachments.length === 0) {
847 return 0;
848 }
849 let rejected: ReadonlyArray<DraftComposerAttachment> = [];
850 updateComposerDrafts((current) => {
851 const existing = normalizeDraft(current[draftKey]);
852 const remaining = options?.allowOverflow
853 ? attachments.length
854 : Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - existing.attachments.length);
855 const accepted = attachments.slice(0, remaining);
856 rejected = attachments.slice(remaining);
857 if (accepted.length === 0) {
858 return current;
859 }
860 return {
861 ...current,
862 [draftKey]: {
863 ...existing,
864 attachments: [...existing.attachments, ...accepted],
865 },
866 };
867 });
868 scheduleUnusedComposerAttachmentCleanup(rejected);
869 return rejected.length;
870}
871
872export function replaceComposerDraftAttachments(
873 draftKey: string,
874 attachments: ReadonlyArray<DraftComposerAttachment>,
875): void {
876 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
877 updateComposerDrafts((current) => {
878 const draft = {
879 ...normalizeDraft(current[draftKey]),
880 attachments,
881 };
882 if (isEmptyDraft(draft)) {
883 const next = { ...current };
884 delete next[draftKey];
885 return next;
886 }
887 return {
888 ...current,
889 [draftKey]: draft,
890 };
891 });
892 const retainedIds = new Set(attachments.map((attachment) => attachment.id));
893 scheduleUnusedComposerAttachmentCleanup(
894 previousAttachments.filter((attachment) => !retainedIds.has(attachment.id)),
895 );
896}
897
898export function removeComposerDraftAttachment(draftKey: string, imageId: string): void {
899 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
900 updateComposerDrafts((current) => {
901 const existing = normalizeDraft(current[draftKey]);
902 const draft = {
903 ...existing,
904 attachments: existing.attachments.filter((image) => image.id !== imageId),
905 };
906 if (isEmptyDraft(draft)) {
907 const next = { ...current };
908 delete next[draftKey];
909 return next;
910 }
911 return {
912 ...current,
913 [draftKey]: draft,
914 };
915 });
916 scheduleUnusedComposerAttachmentCleanup(
917 previousAttachments.filter((attachment) => attachment.id === imageId),
918 );
919}
920
921/** Stamps a finished upload without overwriting text, removals, or newer attachments. */
922export function setComposerDraftAttachmentUpload(
923 draftKey: string,
924 attachment: DraftComposerAttachment,
925): boolean {
926 let previous: DraftComposerAttachment | undefined;
927 updateComposerDrafts((current) => {
928 const draft = current[draftKey];
929 previous = draft?.attachments.find((candidate) => candidate.id === attachment.id);
930 if (!draft || !previous) return current;
931 if (
932 previous.uploadedAttachmentId === attachment.uploadedAttachmentId &&
933 previous.uploadEnvironmentId === attachment.uploadEnvironmentId
934 )
935 return current;
936 return {
937 ...current,
938 [draftKey]: {
939 ...draft,
940 attachments: draft.attachments.map((candidate) =>
941 candidate.id === attachment.id
942 ? {
943 ...candidate,
944 uploadedAttachmentId: attachment.uploadedAttachmentId,
945 uploadEnvironmentId: attachment.uploadEnvironmentId,
946 }
947 : candidate,
948 ),
949 },
950 };
951 });
952 if (previous) scheduleUnusedComposerAttachmentCleanup([previous]);
953 return previous !== undefined;
954}
955
956export function updateComposerDraftSettings(
957 draftKey: string,
958 settings: Partial<ComposerDraftSettingsUpdate>,
959): void {
960 updateComposerDrafts((current) => {
961 const draft = {
962 ...normalizeDraft(current[draftKey]),
963 ...settings,
964 };
965 if (isEmptyDraft(draft)) {
966 const next = { ...current };
967 delete next[draftKey];
968 return next;
969 }
970 return {
971 ...current,
972 [draftKey]: draft,
973 };
974 });
975}
976
977export function clearComposerDraftContentState(
978 current: Record<string, ComposerDraft>,
979 draftKey: string,
980 options?: {
981 readonly clearModelSelection?: boolean;
982 readonly clearWorkspaceSelection?: boolean;
983 },
984): Record<string, ComposerDraft> {
985 const existing = current[draftKey];
986 if (!existing) {
987 return current;
988 }
989 const {
990 importedShareIds: _importedShareIds,
991 modelSelection,
992 workspaceSelection,
993 ...retained
994 } = existing;
995 const draft = {
996 ...retained,
997 ...(options?.clearModelSelection || modelSelection === undefined ? {} : { modelSelection }),
998 ...(options?.clearWorkspaceSelection || workspaceSelection === undefined
999 ? {}
1000 : { workspaceSelection }),
1001 text: "",
1002 attachments: [],
1003 };
1004 if (isEmptyDraft(draft)) {
1005 const next = { ...current };
1006 delete next[draftKey];
1007 return next;
1008 }
1009 return {
1010 ...current,
1011 [draftKey]: draft,
1012 };
1013}
1014
1015export function restoreComposerDraftSnapshotState(
1016 current: Record<string, ComposerDraft>,
1017 draftKey: string,
1018 snapshot: ComposerDraft,
1019): Record<string, ComposerDraft> {
1020 const next = { ...current };
1021 if (isEmptyDraft(snapshot)) {
1022 delete next[draftKey];
1023 } else {
1024 next[draftKey] = snapshot;
1025 }
1026 return next;
1027}
1028
1029export function copyComposerDraftContentState(
1030 current: Record<string, ComposerDraft>,
1031 sourceDraftKey: string,
1032 targetDraftKey: string,
1033): Record<string, ComposerDraft> {
1034 if (sourceDraftKey === targetDraftKey) {
1035 return current;
1036 }
1037 const source = normalizeDraft(current[sourceDraftKey]);
1038 const target = normalizeDraft(current[targetDraftKey]);
1039 const sourceHasContent =
1040 source.text.length > 0 ||
1041 source.attachments.length > 0 ||
1042 (source.importedShareIds?.length ?? 0) > 0;
1043 const targetHasContent =
1044 target.text.length > 0 ||
1045 target.attachments.length > 0 ||
1046 (target.importedShareIds?.length ?? 0) > 0;
1047 if (!sourceHasContent || targetHasContent) {
1048 return current;
1049 }
1050 return {
1051 ...current,
1052 [targetDraftKey]: {
1053 ...target,
1054 text: source.text,
1055 attachments: source.attachments,
1056 ...(source.importedShareIds ? { importedShareIds: source.importedShareIds } : {}),
1057 },
1058 };
1059}
1060
1061export async function copyComposerDraftContentIfEmpty(
1062 sourceDraftKey: string,
1063 targetDraftKey: string,
1064): Promise<void> {
1065 ensureComposerDraftsLoaded();
1066 if (loadPromise !== null) {
1067 await loadPromise;
1068 }
1069 updateComposerDrafts((current) =>
1070 copyComposerDraftContentState(current, sourceDraftKey, targetDraftKey),
1071 );
1072}
1073
1074function mergeComposerDraftText(existing: string, incoming: string): string {
1075 if (incoming.length === 0) {
1076 return existing;
1077 }
1078 if (existing.length === 0) {
1079 return incoming;
1080 }
1081 // Import retries are possible after an interrupted native handoff. Keep the
1082 // operation idempotent when the same shared text is already present.
1083 if (existing === incoming || existing.endsWith(`\n\n${incoming}`)) {
1084 return existing;
1085 }
1086 return `${existing}\n\n${incoming}`;
1087}
1088
1089export function mergeComposerDraftContentState(
1090 current: Record<string, ComposerDraft>,
1091 draftKey: string,
1092 content: ComposerDraftContent,
1093): Record<string, ComposerDraft> {
1094 const existing = normalizeDraft(current[draftKey]);
1095 if (content.sourceShareId && existing.importedShareIds?.includes(content.sourceShareId)) {
1096 return current;
1097 }
1098 const attachmentIds = new Set(existing.attachments.map((attachment) => attachment.id));
1099 const incomingAttachments = content.attachments.filter((attachment) => {
1100 if (attachmentIds.has(attachment.id)) {
1101 return false;
1102 }
1103 attachmentIds.add(attachment.id);
1104 return true;
1105 });
1106 const attachments = [...existing.attachments, ...incomingAttachments].slice(
1107 0,
1108 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
1109 );
1110 const text = mergeComposerDraftText(existing.text, content.text);
1111 const importedShareIds = content.sourceShareId
1112 ? [...(existing.importedShareIds ?? []), content.sourceShareId]
1113 : existing.importedShareIds;
1114 if (
1115 text === existing.text &&
1116 attachments.length === existing.attachments.length &&
1117 importedShareIds === existing.importedShareIds
1118 ) {
1119 return current;
1120 }
1121 return {
1122 ...current,
1123 [draftKey]: {
1124 ...existing,
1125 text,
1126 attachments,
1127 ...(importedShareIds ? { importedShareIds } : {}),
1128 },
1129 };
1130}
1131
1132/**
1133 * Atomically moves an incoming share into a project-scoped composer draft.
1134 * The durable write happens before the share inbox item can be acknowledged.
1135 */
1136export async function mergeComposerDraftContent(
1137 draftKey: string,
1138 content: ComposerDraftContent,
1139): Promise<{ readonly skippedAttachmentCount: number }> {
1140 ensureComposerDraftsLoaded();
1141 if (loadPromise !== null) {
1142 await loadPromise;
1143 }
1144 if (persistTimer !== null) {
1145 clearTimeout(persistTimer);
1146 persistTimer = null;
1147 }
1148 const current = appAtomRegistry.get(composerDraftsAtom);
1149 const next = mergeComposerDraftContentState(current, draftKey, content);
1150 const currentAttachmentIds = new Set(
1151 normalizeDraft(current[draftKey]).attachments.map((attachment) => attachment.id),
1152 );
1153 const nextAttachmentIds = new Set(
1154 normalizeDraft(next[draftKey]).attachments.map((attachment) => attachment.id),
1155 );
1156 const skippedAttachmentCount = content.attachments.filter(
1157 (attachment) =>
1158 !currentAttachmentIds.has(attachment.id) && !nextAttachmentIds.has(attachment.id),
1159 ).length;
1160 // Publish the content and its import receipt together before the filesystem
1161 // await. Typing during persistence then builds on the receipt-bearing state,
1162 // and its debounced write is serialized after this transaction.
1163 if (next !== current) {
1164 appAtomRegistry.set(composerDraftsAtom, next);
1165 }
1166 await persistenceQueue.run(() =>
1167 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1168 );
1169 return { skippedAttachmentCount };
1170}
1171
1172/** Restores the exact content/settings captured before an interrupted import. */
1173export async function restoreComposerDraftSnapshot(
1174 draftKey: string,
1175 snapshot: ComposerDraft,
1176): Promise<void> {
1177 ensureComposerDraftsLoaded();
1178 if (loadPromise !== null) {
1179 await loadPromise;
1180 }
1181 if (persistTimer !== null) {
1182 clearTimeout(persistTimer);
1183 persistTimer = null;
1184 }
1185 const next = restoreComposerDraftSnapshotState(
1186 appAtomRegistry.get(composerDraftsAtom),
1187 draftKey,
1188 snapshot,
1189 );
1190 appAtomRegistry.set(composerDraftsAtom, next);
1191 await persistenceQueue.run(() =>
1192 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1193 );
1194}
1195
1196export function sameComposerDraftState(a: ComposerDraft, b: ComposerDraft): boolean {
1197 return (
1198 a.text === b.text &&
1199 a.attachments === b.attachments &&
1200 a.importedShareIds === b.importedShareIds &&
1201 a.modelSelection === b.modelSelection &&
1202 a.runtimeMode === b.runtimeMode &&
1203 a.interactionMode === b.interactionMode &&
1204 a.workspaceSelection === b.workspaceSelection
1205 );
1206}
1207
1208/**
1209 * Undoes an abandoned mergeComposerDraftContent. When the draft is untouched
1210 * since `merged` (the state captured right after the merge), the pre-merge
1211 * snapshot comes back exactly. When the user edited the draft during the
1212 * merge's awaits, only what the merge inserted (the appended text and the new
1213 * attachments) is taken back out, so the user's edits survive the rollback.
1214 */
1215export function undoComposerDraftMergeState(
1216 current: Record<string, ComposerDraft>,
1217 draftKey: string,
1218 snapshot: ComposerDraft,
1219 merged: ComposerDraft,
1220): Record<string, ComposerDraft> {
1221 const existing = normalizeDraft(current[draftKey]);
1222 if (sameComposerDraftState(existing, merged)) {
1223 return restoreComposerDraftSnapshotState(current, draftKey, snapshot);
1224 }
1225 const insertedText = merged.text.startsWith(snapshot.text)
1226 ? merged.text.slice(snapshot.text.length)
1227 : "";
1228 const snapshotAttachmentIds = new Set(snapshot.attachments.map((attachment) => attachment.id));
1229 const insertedAttachmentIds = new Set(
1230 merged.attachments
1231 .filter((attachment) => !snapshotAttachmentIds.has(attachment.id))
1232 .map((attachment) => attachment.id),
1233 );
1234 // A setting still holding the merge's value is the merge's doing: restore
1235 // the snapshot's. One the user changed since the merge stays theirs.
1236 const undoSetting = <
1237 K extends "modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection",
1238 >(
1239 key: K,
1240 ): ComposerDraft[K] => (existing[key] === merged[key] ? snapshot[key] : existing[key]);
1241 const text =
1242 insertedText.length > 0 && existing.text.startsWith(merged.text)
1243 ? snapshot.text + existing.text.slice(merged.text.length)
1244 : insertedText.length > 0 && existing.text.endsWith(insertedText)
1245 ? existing.text.slice(0, existing.text.length - insertedText.length)
1246 : existing.text;
1247 const draft = {
1248 ...existing,
1249 text,
1250 attachments: existing.attachments.filter(
1251 (attachment) => !insertedAttachmentIds.has(attachment.id),
1252 ),
1253 modelSelection: undoSetting("modelSelection"),
1254 runtimeMode: undoSetting("runtimeMode"),
1255 interactionMode: undoSetting("interactionMode"),
1256 workspaceSelection: undoSetting("workspaceSelection"),
1257 };
1258 if (isEmptyDraft(draft)) {
1259 const next = { ...current };
1260 delete next[draftKey];
1261 return next;
1262 }
1263 return {
1264 ...current,
1265 [draftKey]: draft,
1266 };
1267}
1268
1269/** Applies undoComposerDraftMergeState and lands it durably. */
1270export async function undoComposerDraftMerge(
1271 draftKey: string,
1272 snapshot: ComposerDraft,
1273 merged: ComposerDraft,
1274): Promise<void> {
1275 ensureComposerDraftsLoaded();
1276 if (loadPromise !== null) {
1277 await loadPromise;
1278 }
1279 if (persistTimer !== null) {
1280 clearTimeout(persistTimer);
1281 persistTimer = null;
1282 }
1283 const next = undoComposerDraftMergeState(
1284 appAtomRegistry.get(composerDraftsAtom),
1285 draftKey,
1286 snapshot,
1287 merged,
1288 );
1289 appAtomRegistry.set(composerDraftsAtom, next);
1290 await persistenceQueue.run(() =>
1291 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1292 );
1293}
1294
1295export function clearComposerDraftContent(
1296 draftKey: string,
1297 options?: {
1298 readonly clearModelSelection?: boolean;
1299 readonly clearWorkspaceSelection?: boolean;
1300 // Send clears the draft while the durable outbox write is still in
1301 // flight. Sweeping then would race the write: a failed enqueue rolls the
1302 // message out of the queue mid-sweep and its files get deleted right
1303 // before the failure handler restores them. The sender re-schedules
1304 // cleanup once the write settles.
1305 readonly deferAttachmentCleanup?: boolean;
1306 },
1307): void {
1308 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1309 updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options));
1310 if (!options?.deferAttachmentCleanup) {
1311 scheduleUnusedComposerAttachmentCleanup(previousAttachments);
1312 }
1313}
1314
1315export function clearComposerDraft(
1316 draftKey: string,
1317 options?: { readonly deferAttachmentCleanup?: boolean },
1318): void {
1319 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1320 updateComposerDrafts((current) => {
1321 if (!current[draftKey]) {
1322 return current;
1323 }
1324 const next = { ...current };
1325 delete next[draftKey];
1326 return next;
1327 });
1328 if (!options?.deferAttachmentCleanup) {
1329 scheduleUnusedComposerAttachmentCleanup(previousAttachments);
1330 }
1331}
1332
1333export function removeComposerDraftsForEnvironment(
1334 drafts: Record<string, ComposerDraft>,
1335 environmentId: EnvironmentId,
1336): Record<string, ComposerDraft> {
1337 const environmentPrefix = `${environmentId}:`;
1338 const newTaskPrefix = `new-task:${environmentId}:`;
1339 return Object.fromEntries(
1340 Object.entries(drafts).filter(
1341 ([draftKey]) =>
1342 !draftKey.startsWith(environmentPrefix) && !draftKey.startsWith(newTaskPrefix),
1343 ),
1344 );
1345}
1346
1347export async function clearComposerDraftsEnvironment(environmentId: EnvironmentId): Promise<void> {
1348 ensureComposerDraftsLoaded();
1349 if (loadPromise !== null) {
1350 await loadPromise;
1351 }
1352
1353 const current = appAtomRegistry.get(composerDraftsAtom);
1354 const next = removeComposerDraftsForEnvironment(current, environmentId);
1355 const removedAttachments = Object.entries(current)
1356 .filter(([draftKey]) => next[draftKey] === undefined)
1357 .flatMap(([, draft]) => draft.attachments);
1358
1359 if (persistTimer !== null) {
1360 clearTimeout(persistTimer);
1361 persistTimer = null;
1362 }
1363 appAtomRegistry.set(composerDraftsAtom, next);
1364 await persistenceQueue.run(() =>
1365 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1366 );
1367 await releaseUnusedComposerAttachmentFiles(removedAttachments);
1368}
1369
1370export function useComposerDraft(draftKey: string | null): ComposerDraft {
1371 const drafts = useAtomValue(composerDraftsAtom);
1372 useEffect(() => {
1373 ensureComposerDraftsLoaded();
1374 }, []);
1375 return draftKey ? normalizeDraft(drafts[draftKey]) : EMPTY_DRAFT;
1376}
1377
1378export function useStickyComposerModelSelection(): ModelSelection | null {
1379 const selection = useAtomValue(stickyComposerModelSelectionAtom);
1380 useEffect(() => {
1381 ensureComposerDraftsLoaded();
1382 }, []);
1383 return selection;
1384}