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

use-composer-drafts.ts

1,498 lines51.1 KB

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 }
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;
77​
78export interface ComposerDraftProject {
79 readonly environmentId: EnvironmentId;
80 readonly projectId: ProjectId;
81 readonly createdAt: string;
83​
84export interface ComposerDraftContent {
85 readonly text: string;
86 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
87 readonly sourceShareId?: string;
89​
90export interface ComposerDraftWorkspaceSelection {
91 readonly mode: "local" | "worktree";
92 readonly branch: string | null;
93 readonly worktreePath: string | null;
94 readonly startFromOrigin?: boolean;
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>;
165​
166interface ComposerCloudDraftState {
167 readonly accountId: string | null;
168 readonly signedOut: Record<string, SignedOutDrafts>;
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;
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 };
197​
198export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
199 return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
201​
202export function isComposerDraftEmpty(draft: ComposerDraft): boolean {
203 return isEmptyDraft(draft);
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 );
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 };
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)}`;
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 ];
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 };
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);
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 }
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 }
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);
445​
446function signedOutAttachmentOwners() {
447 return Object.values(appAtomRegistry.get(composerCloudDraftsAtom).signedOut).flatMap((saved) => [
448 ...Object.values(saved.drafts),
449 ...saved.queuedMessages,
450 ]);
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 );
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 );
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 }
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 });
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 });
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);
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 });
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 }
691​
692export async function getComposerCloudAccountId(): Promise<string | null> {
693 await waitForComposerDraftsLoaded();
694 return appAtomRegistry.get(composerCloudDraftsAtom).accountId;
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();
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 );
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 }
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();
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();
889​
890export function setStickyComposerModelSelection(modelSelection: ModelSelection): void {
891 appAtomRegistry.set(stickyComposerModelSelectionAtom, modelSelection);
892 schedulePersistComposerState();
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 });
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 });
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;
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 );
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 );
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
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,
1021 : candidate,
1022 ),
1023 },
1024 };
1025 });
1026 if (previous) scheduleUnusedComposerAttachmentCleanup([previous]);
1027 return previous !== undefined;
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 });
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;
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;
1079 return {
1080 ...current,
1081 [draftKey]: draft,
1082 };
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;
1096 return next;
1098​
1099function stripAttachmentUploadReference(
1100 attachment: DraftComposerAttachment,
1101): DraftComposerAttachment {
1102 const { uploadedAttachmentId: _id, uploadEnvironmentId: _environmentId, ...rest } = attachment;
1103 return rest;
1105​
1106function mergeComposerDraftText(existing: string, incoming: string): string {
1107 if (incoming.length === 0) {
1108 return existing;
1110 if (existing.length === 0) {
1111 return incoming;
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;
1118 return `${existing}\n\n${incoming}`;
1120​
1121export function mergeComposerDraftContentState(
1122 current: Record<string, ComposerDraft>,
1123 draftKey: string,
1124 content: ComposerDraftContent,
1125 settings?: Partial<ComposerDraftSettingsUpdate>,
1126): Record<string, ComposerDraft> {
1127 const existing = normalizeDraft(current[draftKey]);
1128 if (content.sourceShareId && existing.importedShareIds?.includes(content.sourceShareId)) {
1129 return current;
1131 const attachmentIds = new Set(existing.attachments.map((attachment) => attachment.id));
1132 const incomingAttachments = content.attachments.filter((attachment) => {
1133 if (attachmentIds.has(attachment.id)) {
1134 return false;
1136 attachmentIds.add(attachment.id);
1137 return true;
1138 });
1139 const attachments = [...existing.attachments, ...incomingAttachments].slice(
1140 0,
1141 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
1142 );
1143 const text = mergeComposerDraftText(existing.text, content.text);
1144 const importedShareIds = content.sourceShareId
1145 ? [...(existing.importedShareIds ?? []), content.sourceShareId]
1146 : existing.importedShareIds;
1147 if (
1148 settings === undefined &&
1149 text === existing.text &&
1150 attachments.length === existing.attachments.length &&
1151 importedShareIds === existing.importedShareIds
1152 ) {
1153 return current;
1155 return {
1156 ...current,
1157 [draftKey]: {
1158 ...existing,
1159 text,
1160 attachments,
1161 ...(importedShareIds ? { importedShareIds } : {}),
1162 ...settings,
1163 },
1164 };
1166​
1167/**
1168 * Atomically merges incoming content, its receipt, and optional destination
1169 * settings into a project-scoped composer draft. The durable write happens
1170 * before the share inbox item can be acknowledged.
1171 */
1172export async function mergeComposerDraftContent(
1173 draftKey: string,
1174 content: ComposerDraftContent,
1175 settings?: Partial<ComposerDraftSettingsUpdate>,
1176): Promise<{ readonly skippedAttachmentCount: number }> {
1177 ensureComposerDraftsLoaded();
1178 if (loadPromise !== null) {
1179 await loadPromise;
1181 if (persistTimer !== null) {
1182 clearTimeout(persistTimer);
1183 persistTimer = null;
1185 const current = appAtomRegistry.get(composerDraftsAtom);
1186 const next = mergeComposerDraftContentState(current, draftKey, content, settings);
1187 const currentAttachmentIds = new Set(
1188 normalizeDraft(current[draftKey]).attachments.map((attachment) => attachment.id),
1189 );
1190 const nextAttachmentIds = new Set(
1191 normalizeDraft(next[draftKey]).attachments.map((attachment) => attachment.id),
1192 );
1193 const skippedAttachmentCount = content.attachments.filter(
1194 (attachment) =>
1195 !currentAttachmentIds.has(attachment.id) && !nextAttachmentIds.has(attachment.id),
1196 ).length;
1197 // Publish the content and its import receipt together before the filesystem
1198 // await. Typing during persistence then builds on the receipt-bearing state,
1199 // and its debounced write is serialized after this transaction.
1200 if (next !== current) {
1201 appAtomRegistry.set(composerDraftsAtom, next);
1203 await persistenceQueue.run(() =>
1204 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1205 );
1206 return { skippedAttachmentCount };
1208​
1209/** Restores the exact content/settings captured before an interrupted import. */
1210export async function restoreComposerDraftSnapshot(
1211 draftKey: string,
1212 snapshot: ComposerDraft,
1213): Promise<void> {
1214 ensureComposerDraftsLoaded();
1215 if (loadPromise !== null) {
1216 await loadPromise;
1218 if (persistTimer !== null) {
1219 clearTimeout(persistTimer);
1220 persistTimer = null;
1222 const next = restoreComposerDraftSnapshotState(
1223 appAtomRegistry.get(composerDraftsAtom),
1224 draftKey,
1225 snapshot,
1226 );
1227 appAtomRegistry.set(composerDraftsAtom, next);
1228 await persistenceQueue.run(() =>
1229 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1230 );
1232​
1233export function sameComposerDraftState(a: ComposerDraft, b: ComposerDraft): boolean {
1234 return (
1235 a.text === b.text &&
1236 a.attachments === b.attachments &&
1237 a.importedShareIds === b.importedShareIds &&
1238 a.modelSelection === b.modelSelection &&
1239 a.runtimeMode === b.runtimeMode &&
1240 a.interactionMode === b.interactionMode &&
1241 a.workspaceSelection === b.workspaceSelection
1242 );
1244​
1245/**
1246 * Undoes an abandoned mergeComposerDraftContent. When the draft is untouched
1247 * since `merged` (the state captured right after the merge), the pre-merge
1248 * snapshot comes back exactly. When the user edited the draft during the
1249 * merge's awaits, only what the merge inserted (the appended text and the new
1250 * attachments) is taken back out, so the user's edits survive the rollback.
1251 */
1252export function undoComposerDraftMergeState(
1253 current: Record<string, ComposerDraft>,
1254 draftKey: string,
1255 snapshot: ComposerDraft,
1256 merged: ComposerDraft,
1257): Record<string, ComposerDraft> {
1258 const existing = normalizeDraft(current[draftKey]);
1259 if (sameComposerDraftState(existing, merged)) {
1260 return restoreComposerDraftSnapshotState(current, draftKey, snapshot);
1262 const insertedText = merged.text.startsWith(snapshot.text)
1263 ? merged.text.slice(snapshot.text.length)
1264 : "";
1265 const snapshotAttachmentIds = new Set(snapshot.attachments.map((attachment) => attachment.id));
1266 const insertedAttachmentIds = new Set(
1267 merged.attachments
1268 .filter((attachment) => !snapshotAttachmentIds.has(attachment.id))
1269 .map((attachment) => attachment.id),
1270 );
1271 // A setting still holding the merge's value is the merge's doing: restore
1272 // the snapshot's. One the user changed since the merge stays theirs.
1273 const undoSetting = <
1274 K extends "modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection",
1275 >(
1276 key: K,
1277 ): ComposerDraft[K] => (existing[key] === merged[key] ? snapshot[key] : existing[key]);
1278 const text =
1279 insertedText.length > 0 && existing.text.startsWith(merged.text)
1280 ? snapshot.text + existing.text.slice(merged.text.length)
1281 : insertedText.length > 0 && existing.text.endsWith(insertedText)
1282 ? existing.text.slice(0, existing.text.length - insertedText.length)
1283 : existing.text;
1284 const draft = {
1285 ...existing,
1286 text,
1287 attachments: existing.attachments.filter(
1288 (attachment) => !insertedAttachmentIds.has(attachment.id),
1289 ),
1290 modelSelection: undoSetting("modelSelection"),
1291 runtimeMode: undoSetting("runtimeMode"),
1292 interactionMode: undoSetting("interactionMode"),
1293 workspaceSelection: undoSetting("workspaceSelection"),
1294 };
1295 return withComposerDraft(current, draftKey, draft);
1297​
1298/** Applies undoComposerDraftMergeState and lands it durably. */
1299export async function undoComposerDraftMerge(
1300 draftKey: string,
1301 snapshot: ComposerDraft,
1302 merged: ComposerDraft,
1303): Promise<void> {
1304 ensureComposerDraftsLoaded();
1305 if (loadPromise !== null) {
1306 await loadPromise;
1308 if (persistTimer !== null) {
1309 clearTimeout(persistTimer);
1310 persistTimer = null;
1312 const next = undoComposerDraftMergeState(
1313 appAtomRegistry.get(composerDraftsAtom),
1314 draftKey,
1315 snapshot,
1316 merged,
1317 );
1318 appAtomRegistry.set(composerDraftsAtom, next);
1319 await persistenceQueue.run(() =>
1320 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1321 );
1323​
1324export function clearComposerDraftContent(
1325 draftKey: string,
1326 options?: {
1327 readonly clearModelSelection?: boolean;
1328 readonly clearWorkspaceSelection?: boolean;
1329 // Send clears the draft while the durable outbox write is still in
1330 // flight. Sweeping then would race the write: a failed enqueue rolls the
1331 // message out of the queue mid-sweep and its files get deleted right
1332 // before the failure handler restores them. The sender re-schedules
1333 // cleanup once the write settles.
1334 readonly deferAttachmentCleanup?: boolean;
1335 },
1336): void {
1337 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1338 updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options));
1339 if (!options?.deferAttachmentCleanup) {
1340 scheduleUnusedComposerAttachmentCleanup(previousAttachments);
1343​
1344export function clearComposerDraft(
1345 draftKey: string,
1346 options?: { readonly deferAttachmentCleanup?: boolean },
1347): void {
1348 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1349 updateComposerDrafts((current) => {
1350 if (!current[draftKey]) {
1351 return current;
1353 const next = { ...current };
1354 delete next[draftKey];
1355 return next;
1356 });
1357 if (!options?.deferAttachmentCleanup) {
1358 scheduleUnusedComposerAttachmentCleanup(previousAttachments);
1361​
1362export function removeComposerDraftsForEnvironment(
1363 drafts: Record<string, ComposerDraft>,
1364 environmentId: EnvironmentId,
1365): Record<string, ComposerDraft> {
1366 const environmentPrefix = `${environmentId}:`;
1367 return Object.fromEntries(
1368 Object.entries(drafts).filter(
1369 ([draftKey, draft]) =>
1370 !draftKey.startsWith(environmentPrefix) && draft.project?.environmentId !== environmentId,
1371 ),
1372 );
1374​
1375/**
1376 * Mints a new-task draft for a project. The entry is published immediately so
1377 * the composer can bind to its key before the user types; it stays out of the
1378 * list until it has content, and the empty-draft sweep drops it on persist if
1379 * nothing is ever written.
1380 */
1381export function createNewTaskDraft(project: {
1382 readonly environmentId: EnvironmentId;
1383 readonly projectId: ProjectId;
1384}): string {
1385 const draftKey = newTaskDraftKey(newDraftId());
1386 const stamp: ComposerDraftProject = {
1387 environmentId: project.environmentId,
1388 projectId: project.projectId,
1389 createdAt: new Date().toISOString(),
1390 };
1391 updateComposerDrafts((current) => ({
1392 ...current,
1393 [draftKey]: { ...EMPTY_DRAFT, project: stamp },
1394 }));
1395 return draftKey;
1397​
1398/**
1399 * Points an existing new-task draft at a different project, keeping its
1400 * content and identity. Workspace selection is project-specific (branch,
1401 * worktree), so it is cleared; model and mode choices carry over.
1402 */
1403export function retargetNewTaskDraft(
1404 draftKey: string,
1405 project: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId },
1406): void {
1407 updateComposerDrafts((current) => {
1408 const existing = current[draftKey];
1409 const stamp = existing?.project;
1410 if (
1411 stamp !== undefined &&
1412 stamp.environmentId === project.environmentId &&
1413 stamp.projectId === project.projectId
1414 ) {
1415 return current;
1417 const { workspaceSelection: _workspaceSelection, ...retained } = normalizeDraft(existing);
1418 // Pending uploads live on one server. Crossing environments keeps the
1419 // local bytes (the upload worker re-sends them to the new environment)
1420 // but drops the old stamp, so it cannot pin the source environment's
1421 // pending upload alive from the moved draft.
1422 const attachments = retained.attachments.map((attachment) =>
1423 attachment.uploadEnvironmentId !== undefined &&
1424 attachment.uploadEnvironmentId !== project.environmentId
1425 ? stripAttachmentUploadReference(attachment)
1426 : attachment,
1427 );
1428 return {
1429 ...current,
1430 [draftKey]: {
1431 ...retained,
1432 attachments,
1433 project: {
1434 environmentId: project.environmentId,
1435 projectId: project.projectId,
1436 createdAt: stamp?.createdAt ?? new Date().toISOString(),
1437 },
1438 },
1439 };
1440 });
1442​
1443/** New-task drafts for a project, newest first. */
1444export function findNewTaskDraftKeys(
1445 drafts: Readonly<Record<string, ComposerDraft>>,
1446 project: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId },
1447): ReadonlyArray<string> {
1448 return Object.entries(drafts)
1449 .filter(
1450 ([key, draft]) =>
1451 isNewTaskDraftKey(key) &&
1452 draft.project?.environmentId === project.environmentId &&
1453 draft.project.projectId === project.projectId,
1455 .sort(([, left], [, right]) =>
1456 (right.project?.createdAt ?? "").localeCompare(left.project?.createdAt ?? ""),
1458 .map(([key]) => key);
1460​
1461export async function clearComposerDraftsEnvironment(environmentId: EnvironmentId): Promise<void> {
1462 ensureComposerDraftsLoaded();
1463 if (loadPromise !== null) {
1464 await loadPromise;
1466​
1467 const current = appAtomRegistry.get(composerDraftsAtom);
1468 const next = removeComposerDraftsForEnvironment(current, environmentId);
1469 const removedAttachments = Object.entries(current)
1470 .filter(([draftKey]) => next[draftKey] === undefined)
1471 .flatMap(([, draft]) => draft.attachments);
1472​
1473 if (persistTimer !== null) {
1474 clearTimeout(persistTimer);
1475 persistTimer = null;
1477 appAtomRegistry.set(composerDraftsAtom, next);
1478 await persistenceQueue.run(() =>
1479 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1480 );
1481 await releaseUnusedComposerAttachmentFiles(removedAttachments);
1483​
1484export function useComposerDraft(draftKey: string | null): ComposerDraft {
1485 const drafts = useAtomValue(composerDraftsAtom);
1486 useEffect(() => {
1487 ensureComposerDraftsLoaded();
1488 }, []);
1489 return draftKey ? normalizeDraft(drafts[draftKey]) : EMPTY_DRAFT;
1491​
1492export function useStickyComposerModelSelection(): ModelSelection | null {
1493 const selection = useAtomValue(stickyComposerModelSelectionAtom);
1494 useEffect(() => {
1495 ensureComposerDraftsLoaded();
1496 }, []);
1497 return selection;