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

use-composer-drafts.ts

1,487 lines50.7 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.TaggedErrorClass<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 },
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(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - existing.attachments.length);
939 const accepted = attachments.slice(0, remaining);
940 rejected = attachments.slice(remaining);
941 if (accepted.length === 0) {
942 return current;
943 }
944 return {
945 ...current,
946 [draftKey]: {
947 ...existing,
948 attachments: [...existing.attachments, ...accepted],
949 },
950 };
951 });
952 scheduleUnusedComposerAttachmentCleanup(rejected);
953 return rejected.length;
955​
956export function replaceComposerDraftAttachments(
957 draftKey: string,
958 attachments: ReadonlyArray<DraftComposerAttachment>,
959): void {
960 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
961 updateComposerDrafts((current) => {
962 const draft = {
963 ...normalizeDraft(current[draftKey]),
964 attachments,
965 };
966 return withComposerDraft(current, draftKey, draft);
967 });
968 const retainedIds = new Set(attachments.map((attachment) => attachment.id));
969 scheduleUnusedComposerAttachmentCleanup(
970 previousAttachments.filter((attachment) => !retainedIds.has(attachment.id)),
971 );
973​
974export function removeComposerDraftAttachment(draftKey: string, imageId: string): void {
975 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
976 updateComposerDrafts((current) => {
977 const existing = normalizeDraft(current[draftKey]);
978 const draft = {
979 ...existing,
980 attachments: existing.attachments.filter((image) => image.id !== imageId),
981 };
982 return withComposerDraft(current, draftKey, draft);
983 });
984 scheduleUnusedComposerAttachmentCleanup(
985 previousAttachments.filter((attachment) => attachment.id === imageId),
986 );
988​
989/** Stamps a finished upload without overwriting text, removals, or newer attachments. */
990export function setComposerDraftAttachmentUpload(
991 draftKey: string,
992 attachment: DraftComposerAttachment,
993): boolean {
994 let previous: DraftComposerAttachment | undefined;
995 updateComposerDrafts((current) => {
996 const draft = current[draftKey];
997 previous = draft?.attachments.find((candidate) => candidate.id === attachment.id);
998 if (!draft || !previous) return current;
999 if (
1000 previous.uploadedAttachmentId === attachment.uploadedAttachmentId &&
1001 previous.uploadEnvironmentId === attachment.uploadEnvironmentId
1003 return current;
1004 return {
1005 ...current,
1006 [draftKey]: {
1007 ...draft,
1008 attachments: draft.attachments.map((candidate) =>
1009 candidate.id === attachment.id
1010 ? {
1011 ...candidate,
1012 uploadedAttachmentId: attachment.uploadedAttachmentId,
1013 uploadEnvironmentId: attachment.uploadEnvironmentId,
1015 : candidate,
1016 ),
1017 },
1018 };
1019 });
1020 if (previous) scheduleUnusedComposerAttachmentCleanup([previous]);
1021 return previous !== undefined;
1023​
1024export function updateComposerDraftSettings(
1025 draftKey: string,
1026 settings: Partial<ComposerDraftSettingsUpdate>,
1027): void {
1028 updateComposerDrafts((current) => {
1029 const draft = {
1030 ...normalizeDraft(current[draftKey]),
1031 ...settings,
1032 };
1033 return withComposerDraft(current, draftKey, draft);
1034 });
1036​
1037export function clearComposerDraftContentState(
1038 current: Record<string, ComposerDraft>,
1039 draftKey: string,
1040 options?: {
1041 readonly clearModelSelection?: boolean;
1042 readonly clearWorkspaceSelection?: boolean;
1043 },
1044): Record<string, ComposerDraft> {
1045 const existing = current[draftKey];
1046 if (!existing) {
1047 return current;
1049 // Clearing content is the "this draft is done" moment (sent, queued, or
1050 // discarded), so the project stamp goes too and an otherwise-empty new-task
1051 // draft leaves the store rather than lingering as a blank row.
1052 const {
1053 importedShareIds: _importedShareIds,
1054 modelSelection,
1055 workspaceSelection,
1056 project: _project,
1057 ...retained
1058 } = existing;
1059 const draft = {
1060 ...retained,
1061 ...(options?.clearModelSelection || modelSelection === undefined ? {} : { modelSelection }),
1062 ...(options?.clearWorkspaceSelection || workspaceSelection === undefined
1063 ? {}
1064 : { workspaceSelection }),
1065 text: "",
1066 attachments: [],
1067 };
1068 if (isEmptyDraft(draft)) {
1069 const next = { ...current };
1070 delete next[draftKey];
1071 return next;
1073 return {
1074 ...current,
1075 [draftKey]: draft,
1076 };
1078​
1079export function restoreComposerDraftSnapshotState(
1080 current: Record<string, ComposerDraft>,
1081 draftKey: string,
1082 snapshot: ComposerDraft,
1083): Record<string, ComposerDraft> {
1084 const next = { ...current };
1085 if (isEmptyDraft(snapshot)) {
1086 delete next[draftKey];
1087 } else {
1088 next[draftKey] = snapshot;
1090 return next;
1092​
1093function stripAttachmentUploadReference(
1094 attachment: DraftComposerAttachment,
1095): DraftComposerAttachment {
1096 const { uploadedAttachmentId: _id, uploadEnvironmentId: _environmentId, ...rest } = attachment;
1097 return rest;
1099​
1100function mergeComposerDraftText(existing: string, incoming: string): string {
1101 if (incoming.length === 0) {
1102 return existing;
1104 if (existing.length === 0) {
1105 return incoming;
1107 // Import retries are possible after an interrupted native handoff. Keep the
1108 // operation idempotent when the same shared text is already present.
1109 if (existing === incoming || existing.endsWith(`\n\n${incoming}`)) {
1110 return existing;
1112 return `${existing}\n\n${incoming}`;
1114​
1115export function mergeComposerDraftContentState(
1116 current: Record<string, ComposerDraft>,
1117 draftKey: string,
1118 content: ComposerDraftContent,
1119): Record<string, ComposerDraft> {
1120 const existing = normalizeDraft(current[draftKey]);
1121 if (content.sourceShareId && existing.importedShareIds?.includes(content.sourceShareId)) {
1122 return current;
1124 const attachmentIds = new Set(existing.attachments.map((attachment) => attachment.id));
1125 const incomingAttachments = content.attachments.filter((attachment) => {
1126 if (attachmentIds.has(attachment.id)) {
1127 return false;
1129 attachmentIds.add(attachment.id);
1130 return true;
1131 });
1132 const attachments = [...existing.attachments, ...incomingAttachments].slice(
1133 0,
1134 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
1135 );
1136 const text = mergeComposerDraftText(existing.text, content.text);
1137 const importedShareIds = content.sourceShareId
1138 ? [...(existing.importedShareIds ?? []), content.sourceShareId]
1139 : existing.importedShareIds;
1140 if (
1141 text === existing.text &&
1142 attachments.length === existing.attachments.length &&
1143 importedShareIds === existing.importedShareIds
1144 ) {
1145 return current;
1147 return {
1148 ...current,
1149 [draftKey]: {
1150 ...existing,
1151 text,
1152 attachments,
1153 ...(importedShareIds ? { importedShareIds } : {}),
1154 },
1155 };
1157​
1158/**
1159 * Atomically moves an incoming share into a project-scoped composer draft.
1160 * The durable write happens before the share inbox item can be acknowledged.
1161 */
1162export async function mergeComposerDraftContent(
1163 draftKey: string,
1164 content: ComposerDraftContent,
1165): Promise<{ readonly skippedAttachmentCount: number }> {
1166 ensureComposerDraftsLoaded();
1167 if (loadPromise !== null) {
1168 await loadPromise;
1170 if (persistTimer !== null) {
1171 clearTimeout(persistTimer);
1172 persistTimer = null;
1174 const current = appAtomRegistry.get(composerDraftsAtom);
1175 const next = mergeComposerDraftContentState(current, draftKey, content);
1176 const currentAttachmentIds = new Set(
1177 normalizeDraft(current[draftKey]).attachments.map((attachment) => attachment.id),
1178 );
1179 const nextAttachmentIds = new Set(
1180 normalizeDraft(next[draftKey]).attachments.map((attachment) => attachment.id),
1181 );
1182 const skippedAttachmentCount = content.attachments.filter(
1183 (attachment) =>
1184 !currentAttachmentIds.has(attachment.id) && !nextAttachmentIds.has(attachment.id),
1185 ).length;
1186 // Publish the content and its import receipt together before the filesystem
1187 // await. Typing during persistence then builds on the receipt-bearing state,
1188 // and its debounced write is serialized after this transaction.
1189 if (next !== current) {
1190 appAtomRegistry.set(composerDraftsAtom, next);
1192 await persistenceQueue.run(() =>
1193 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1194 );
1195 return { skippedAttachmentCount };
1197​
1198/** Restores the exact content/settings captured before an interrupted import. */
1199export async function restoreComposerDraftSnapshot(
1200 draftKey: string,
1201 snapshot: ComposerDraft,
1202): Promise<void> {
1203 ensureComposerDraftsLoaded();
1204 if (loadPromise !== null) {
1205 await loadPromise;
1207 if (persistTimer !== null) {
1208 clearTimeout(persistTimer);
1209 persistTimer = null;
1211 const next = restoreComposerDraftSnapshotState(
1212 appAtomRegistry.get(composerDraftsAtom),
1213 draftKey,
1214 snapshot,
1215 );
1216 appAtomRegistry.set(composerDraftsAtom, next);
1217 await persistenceQueue.run(() =>
1218 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1219 );
1221​
1222export function sameComposerDraftState(a: ComposerDraft, b: ComposerDraft): boolean {
1223 return (
1224 a.text === b.text &&
1225 a.attachments === b.attachments &&
1226 a.importedShareIds === b.importedShareIds &&
1227 a.modelSelection === b.modelSelection &&
1228 a.runtimeMode === b.runtimeMode &&
1229 a.interactionMode === b.interactionMode &&
1230 a.workspaceSelection === b.workspaceSelection
1231 );
1233​
1234/**
1235 * Undoes an abandoned mergeComposerDraftContent. When the draft is untouched
1236 * since `merged` (the state captured right after the merge), the pre-merge
1237 * snapshot comes back exactly. When the user edited the draft during the
1238 * merge's awaits, only what the merge inserted (the appended text and the new
1239 * attachments) is taken back out, so the user's edits survive the rollback.
1240 */
1241export function undoComposerDraftMergeState(
1242 current: Record<string, ComposerDraft>,
1243 draftKey: string,
1244 snapshot: ComposerDraft,
1245 merged: ComposerDraft,
1246): Record<string, ComposerDraft> {
1247 const existing = normalizeDraft(current[draftKey]);
1248 if (sameComposerDraftState(existing, merged)) {
1249 return restoreComposerDraftSnapshotState(current, draftKey, snapshot);
1251 const insertedText = merged.text.startsWith(snapshot.text)
1252 ? merged.text.slice(snapshot.text.length)
1253 : "";
1254 const snapshotAttachmentIds = new Set(snapshot.attachments.map((attachment) => attachment.id));
1255 const insertedAttachmentIds = new Set(
1256 merged.attachments
1257 .filter((attachment) => !snapshotAttachmentIds.has(attachment.id))
1258 .map((attachment) => attachment.id),
1259 );
1260 // A setting still holding the merge's value is the merge's doing: restore
1261 // the snapshot's. One the user changed since the merge stays theirs.
1262 const undoSetting = <
1263 K extends "modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection",
1264 >(
1265 key: K,
1266 ): ComposerDraft[K] => (existing[key] === merged[key] ? snapshot[key] : existing[key]);
1267 const text =
1268 insertedText.length > 0 && existing.text.startsWith(merged.text)
1269 ? snapshot.text + existing.text.slice(merged.text.length)
1270 : insertedText.length > 0 && existing.text.endsWith(insertedText)
1271 ? existing.text.slice(0, existing.text.length - insertedText.length)
1272 : existing.text;
1273 const draft = {
1274 ...existing,
1275 text,
1276 attachments: existing.attachments.filter(
1277 (attachment) => !insertedAttachmentIds.has(attachment.id),
1278 ),
1279 modelSelection: undoSetting("modelSelection"),
1280 runtimeMode: undoSetting("runtimeMode"),
1281 interactionMode: undoSetting("interactionMode"),
1282 workspaceSelection: undoSetting("workspaceSelection"),
1283 };
1284 return withComposerDraft(current, draftKey, draft);
1286​
1287/** Applies undoComposerDraftMergeState and lands it durably. */
1288export async function undoComposerDraftMerge(
1289 draftKey: string,
1290 snapshot: ComposerDraft,
1291 merged: ComposerDraft,
1292): Promise<void> {
1293 ensureComposerDraftsLoaded();
1294 if (loadPromise !== null) {
1295 await loadPromise;
1297 if (persistTimer !== null) {
1298 clearTimeout(persistTimer);
1299 persistTimer = null;
1301 const next = undoComposerDraftMergeState(
1302 appAtomRegistry.get(composerDraftsAtom),
1303 draftKey,
1304 snapshot,
1305 merged,
1306 );
1307 appAtomRegistry.set(composerDraftsAtom, next);
1308 await persistenceQueue.run(() =>
1309 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1310 );
1312​
1313export function clearComposerDraftContent(
1314 draftKey: string,
1315 options?: {
1316 readonly clearModelSelection?: boolean;
1317 readonly clearWorkspaceSelection?: boolean;
1318 // Send clears the draft while the durable outbox write is still in
1319 // flight. Sweeping then would race the write: a failed enqueue rolls the
1320 // message out of the queue mid-sweep and its files get deleted right
1321 // before the failure handler restores them. The sender re-schedules
1322 // cleanup once the write settles.
1323 readonly deferAttachmentCleanup?: boolean;
1324 },
1325): void {
1326 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1327 updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options));
1328 if (!options?.deferAttachmentCleanup) {
1329 scheduleUnusedComposerAttachmentCleanup(previousAttachments);
1332​
1333export function clearComposerDraft(
1334 draftKey: string,
1335 options?: { readonly deferAttachmentCleanup?: boolean },
1336): void {
1337 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1338 updateComposerDrafts((current) => {
1339 if (!current[draftKey]) {
1340 return current;
1342 const next = { ...current };
1343 delete next[draftKey];
1344 return next;
1345 });
1346 if (!options?.deferAttachmentCleanup) {
1347 scheduleUnusedComposerAttachmentCleanup(previousAttachments);
1350​
1351export function removeComposerDraftsForEnvironment(
1352 drafts: Record<string, ComposerDraft>,
1353 environmentId: EnvironmentId,
1354): Record<string, ComposerDraft> {
1355 const environmentPrefix = `${environmentId}:`;
1356 return Object.fromEntries(
1357 Object.entries(drafts).filter(
1358 ([draftKey, draft]) =>
1359 !draftKey.startsWith(environmentPrefix) && draft.project?.environmentId !== environmentId,
1360 ),
1361 );
1363​
1364/**
1365 * Mints a new-task draft for a project. The entry is published immediately so
1366 * the composer can bind to its key before the user types; it stays out of the
1367 * list until it has content, and the empty-draft sweep drops it on persist if
1368 * nothing is ever written.
1369 */
1370export function createNewTaskDraft(project: {
1371 readonly environmentId: EnvironmentId;
1372 readonly projectId: ProjectId;
1373}): string {
1374 const draftKey = newTaskDraftKey(newDraftId());
1375 const stamp: ComposerDraftProject = {
1376 environmentId: project.environmentId,
1377 projectId: project.projectId,
1378 createdAt: new Date().toISOString(),
1379 };
1380 updateComposerDrafts((current) => ({
1381 ...current,
1382 [draftKey]: { ...EMPTY_DRAFT, project: stamp },
1383 }));
1384 return draftKey;
1386​
1387/**
1388 * Points an existing new-task draft at a different project, keeping its
1389 * content and identity. Workspace selection is project-specific (branch,
1390 * worktree), so it is cleared; model and mode choices carry over.
1391 */
1392export function retargetNewTaskDraft(
1393 draftKey: string,
1394 project: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId },
1395): void {
1396 updateComposerDrafts((current) => {
1397 const existing = current[draftKey];
1398 const stamp = existing?.project;
1399 if (
1400 stamp !== undefined &&
1401 stamp.environmentId === project.environmentId &&
1402 stamp.projectId === project.projectId
1403 ) {
1404 return current;
1406 const { workspaceSelection: _workspaceSelection, ...retained } = normalizeDraft(existing);
1407 // Pending uploads live on one server. Crossing environments keeps the
1408 // local bytes (the upload worker re-sends them to the new environment)
1409 // but drops the old stamp, so it cannot pin the source environment's
1410 // pending upload alive from the moved draft.
1411 const attachments = retained.attachments.map((attachment) =>
1412 attachment.uploadEnvironmentId !== undefined &&
1413 attachment.uploadEnvironmentId !== project.environmentId
1414 ? stripAttachmentUploadReference(attachment)
1415 : attachment,
1416 );
1417 return {
1418 ...current,
1419 [draftKey]: {
1420 ...retained,
1421 attachments,
1422 project: {
1423 environmentId: project.environmentId,
1424 projectId: project.projectId,
1425 createdAt: stamp?.createdAt ?? new Date().toISOString(),
1426 },
1427 },
1428 };
1429 });
1431​
1432/** New-task drafts for a project, newest first. */
1433export function findNewTaskDraftKeys(
1434 drafts: Readonly<Record<string, ComposerDraft>>,
1435 project: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId },
1436): ReadonlyArray<string> {
1437 return Object.entries(drafts)
1438 .filter(
1439 ([key, draft]) =>
1440 isNewTaskDraftKey(key) &&
1441 draft.project?.environmentId === project.environmentId &&
1442 draft.project.projectId === project.projectId,
1444 .sort(([, left], [, right]) =>
1445 (right.project?.createdAt ?? "").localeCompare(left.project?.createdAt ?? ""),
1447 .map(([key]) => key);
1449​
1450export async function clearComposerDraftsEnvironment(environmentId: EnvironmentId): Promise<void> {
1451 ensureComposerDraftsLoaded();
1452 if (loadPromise !== null) {
1453 await loadPromise;
1455​
1456 const current = appAtomRegistry.get(composerDraftsAtom);
1457 const next = removeComposerDraftsForEnvironment(current, environmentId);
1458 const removedAttachments = Object.entries(current)
1459 .filter(([draftKey]) => next[draftKey] === undefined)
1460 .flatMap(([, draft]) => draft.attachments);
1461​
1462 if (persistTimer !== null) {
1463 clearTimeout(persistTimer);
1464 persistTimer = null;
1466 appAtomRegistry.set(composerDraftsAtom, next);
1467 await persistenceQueue.run(() =>
1468 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1469 );
1470 await releaseUnusedComposerAttachmentFiles(removedAttachments);
1472​
1473export function useComposerDraft(draftKey: string | null): ComposerDraft {
1474 const drafts = useAtomValue(composerDraftsAtom);
1475 useEffect(() => {
1476 ensureComposerDraftsLoaded();
1477 }, []);
1478 return draftKey ? normalizeDraft(drafts[draftKey]) : EMPTY_DRAFT;
1480​
1481export function useStickyComposerModelSelection(): ModelSelection | null {
1482 const selection = useAtomValue(stickyComposerModelSelectionAtom);
1483 useEffect(() => {
1484 ensureComposerDraftsLoaded();
1485 }, []);
1486 return selection;