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