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

use-composer-drafts.ts

1,070 lines34.9 KB

1import { useAtomValue } from "@effect/atom-react";
2import {
3 ModelSelection as ModelSelectionSchema,
4 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
5 ProviderInteractionMode as ProviderInteractionModeSchema,
6 RuntimeMode as RuntimeModeSchema,
7 type EnvironmentId,
8 type ModelSelection,
9 type ProviderInteractionMode,
10 type RuntimeMode,
11} from "@t3tools/contracts";
12import * as Schema from "effect/Schema";
13import { useEffect } from "react";
14import { Atom } from "effect/unstable/reactivity";
15​
16import { writeFileAtomically } from "../lib/atomic-file";
17import { DraftComposerAttachmentSchema } from "../lib/composer-image-schema";
18import { composerAttachmentFileReferenceKey } from "../lib/composerAttachmentFiles";
19import type { DraftComposerAttachment } from "../lib/composerImages";
20import { SerializedAsyncQueue } from "../lib/serialized-async-queue";
21import { appAtomRegistry } from "./atom-registry";
22import { flushThreadOutbox, threadOutboxManager } from "./thread-outbox";
23​
24const COMPOSER_DRAFTS_SCHEMA_VERSION = 1;
25const COMPOSER_DRAFTS_DIRECTORY = "composer-drafts";
26const COMPOSER_DRAFTS_FILE = "drafts.json";
27const PERSIST_DEBOUNCE_MS = 200;
28​
29export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<ComposerDraftPersistenceError>()(
30 "ComposerDraftPersistenceError",
31 {
32 operation: Schema.Literals(["open", "read", "decode", "encode", "write", "hydrate"]),
33 directory: Schema.String,
34 fileName: Schema.String,
35 cause: Schema.Defect(),
36 },
37) {
38 override get message(): string {
39 return `Composer draft persistence operation ${this.operation} failed for ${this.directory}/${this.fileName}.`;
40 }
42​
43export interface ComposerDraft {
44 readonly text: string;
45 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
46 readonly importedShareIds?: ReadonlyArray<string>;
47 readonly modelSelection?: ModelSelection;
48 readonly runtimeMode?: RuntimeMode;
49 readonly interactionMode?: ProviderInteractionMode;
50 readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
52​
53export interface ComposerDraftContent {
54 readonly text: string;
55 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
56 readonly sourceShareId?: string;
58​
59export interface ComposerDraftWorkspaceSelection {
60 readonly mode: "local" | "worktree";
61 readonly branch: string | null;
62 readonly worktreePath: string | null;
63 readonly startFromOrigin?: boolean;
65​
66export type ComposerDraftSettingsUpdate = Pick<
67 ComposerDraft,
68 "modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection"
69>;
70​
71const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
72 mode: Schema.Literals(["local", "worktree"]),
73 branch: Schema.NullOr(Schema.String),
74 worktreePath: Schema.NullOr(Schema.String),
75 startFromOrigin: Schema.optional(Schema.Boolean),
76});
77​
78const ComposerDraftSchema = Schema.Struct({
79 text: Schema.String,
80 attachments: Schema.Array(DraftComposerAttachmentSchema),
81 importedShareIds: Schema.optional(Schema.Array(Schema.String)),
82 modelSelection: Schema.optional(ModelSelectionSchema),
83 runtimeMode: Schema.optional(RuntimeModeSchema),
84 interactionMode: Schema.optional(ProviderInteractionModeSchema),
85 workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema),
86});
87​
88const PersistedComposerDraftsSchema = Schema.Struct({
89 schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION),
90 drafts: Schema.Record(Schema.String, ComposerDraftSchema),
91 stickyModelSelection: Schema.optional(ModelSelectionSchema),
92});
93​
94const decodePersistedComposerDraftsDocument = Schema.decodeUnknownSync(
95 PersistedComposerDraftsSchema,
96);
97​
98const EMPTY_DRAFT: ComposerDraft = {
99 text: "",
100 attachments: [],
101};
102​
103export const composerDraftsAtom = Atom.make<Record<string, ComposerDraft>>({}).pipe(
104 Atom.keepAlive,
105 Atom.withLabel("mobile:composer-drafts"),
106);
107​
108export const stickyComposerModelSelectionAtom = Atom.make<ModelSelection | null>(null).pipe(
109 Atom.keepAlive,
110 Atom.withLabel("mobile:sticky-composer-model-selection"),
111);
112​
113let loadPromise: Promise<void> | null = null;
114let persistTimer: ReturnType<typeof setTimeout> | null = null;
115const persistenceQueue = new SerializedAsyncQueue();
116​
117/** Resets module-level state between test runs. */
118export function resetComposerDraftsLoadState(): void {
119 loadPromise = null;
121​
122function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
123 if (!draft) {
124 return EMPTY_DRAFT;
125 }
126 return {
127 ...draft,
128 text: draft.text,
129 attachments: draft.attachments,
130 };
132​
133export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
134 return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
136​
137export function isComposerDraftEmpty(draft: ComposerDraft): boolean {
138 return isEmptyDraft(draft);
140​
141function isEmptyDraft(draft: ComposerDraft): boolean {
142 return (
143 draft.text.length === 0 &&
144 draft.attachments.length === 0 &&
145 draft.modelSelection === undefined &&
146 draft.runtimeMode === undefined &&
147 draft.interactionMode === undefined &&
148 draft.workspaceSelection === undefined
149 );
151​
152export function decodePersistedComposerState(value: unknown): {
153 readonly drafts: Record<string, ComposerDraft>;
154 readonly stickyModelSelection: ModelSelection | null;
155} {
156 const parsed = decodePersistedComposerDraftsDocument(value);
157 return {
158 drafts: Object.fromEntries(
159 Object.entries(parsed.drafts)
160 .map(
161 ([key, draft]) =>
162 [
163 key,
164 // Stale new-task drafts left on disk by builds before the
165 // model-precedence fix carry a bare modelSelection with no
166 // other selector settings. Strip it so the next compose pass
167 // re-resolves project → sticky → provider defaults. Drafts
168 // with runtime/interaction/workspace settings or actual text /
169 // attachments were deliberately configured and are left alone.
170 key.startsWith("new-task:") &&
171 draft.modelSelection &&
172 draft.text.length === 0 &&
173 draft.attachments.length === 0 &&
174 draft.runtimeMode === undefined &&
175 draft.interactionMode === undefined &&
176 draft.workspaceSelection === undefined
177 ? { ...draft, modelSelection: undefined }
178 : draft,
179 ] as const,
180 )
181 // importedShareIds are share-import receipts: a contentless draft
182 // carrying one is not empty, or the same native share would be
183 // re-imported after restart.
184 .filter(([, draft]) => !isEmptyDraft(draft) || (draft.importedShareIds?.length ?? 0) > 0),
185 ),
186 stickyModelSelection: parsed.stickyModelSelection ?? null,
187 };
189​
190export function decodePersistedComposerDrafts(value: unknown): Record<string, ComposerDraft> {
191 return decodePersistedComposerState(value).drafts;
193​
194async function getComposerDraftsFile() {
195 const { Directory, File, Paths } = await import("expo-file-system");
196 const directory = new Directory(Paths.document, COMPOSER_DRAFTS_DIRECTORY);
197 directory.create({ idempotent: true, intermediates: true });
198 return new File(directory, COMPOSER_DRAFTS_FILE);
200​
201async function loadPersistedComposerState(): Promise<{
202 readonly drafts: Record<string, ComposerDraft>;
203 readonly stickyModelSelection: ModelSelection | null;
204}> {
205 let operation: ComposerDraftPersistenceError["operation"] = "open";
206 try {
207 const file = await getComposerDraftsFile();
208 if (!file.exists) {
209 return { drafts: {}, stickyModelSelection: null };
210 }
211 operation = "read";
212 const raw = await file.text();
213 operation = "decode";
214 return decodePersistedComposerState(JSON.parse(raw) as unknown);
215 } catch (cause) {
216 console.warn(
217 "[composer-drafts] ignored persisted draft failure",
218 new ComposerDraftPersistenceError({
219 operation,
220 directory: COMPOSER_DRAFTS_DIRECTORY,
221 fileName: COMPOSER_DRAFTS_FILE,
222 cause,
223 }),
224 );
225 return { drafts: {}, stickyModelSelection: null };
226 }
228​
229async function writePersistedComposerState(
230 drafts: Record<string, ComposerDraft>,
231 stickyModelSelection: ModelSelection | null,
232): Promise<void> {
233 let operation: ComposerDraftPersistenceError["operation"] = "open";
234 try {
235 const file = await getComposerDraftsFile();
236 operation = "encode";
237 const nonEmptyDrafts = Object.fromEntries(
238 Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
239 );
240 const document = {
241 schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
242 drafts: nonEmptyDrafts,
243 ...(stickyModelSelection ? { stickyModelSelection } : {}),
244 } as const;
245 const encoded = JSON.stringify(document);
246 operation = "write";
247 await writeFileAtomically(file, encoded);
248 } catch (cause) {
249 throw new ComposerDraftPersistenceError({
250 operation,
251 directory: COMPOSER_DRAFTS_DIRECTORY,
252 fileName: COMPOSER_DRAFTS_FILE,
253 cause,
254 });
255 }
257​
258/**
259 * Lands any debounced or in-flight draft write before the JS runtime is torn
260 * down (app update restart), so the freshest draft state survives it. A write
261 * failure propagates so the caller can decide whether the restart may proceed.
262 */
263export async function flushComposerDrafts(): Promise<void> {
264 // Never land a pre-hydration snapshot: persisted state must merge into the
265 // atoms first, or this write would clobber disk with partial data.
266 ensureComposerDraftsLoaded();
267 if (loadPromise !== null) {
268 await loadPromise;
269 }
270 // An edit during an awaited write schedules another debounced write, so
271 // keep landing snapshots until no debounce is pending after a queue drain.
272 do {
273 while (persistTimer !== null) {
274 clearTimeout(persistTimer);
275 persistTimer = null;
276 await persistenceQueue.run(() =>
277 writePersistedComposerState(
278 appAtomRegistry.get(composerDraftsAtom),
279 appAtomRegistry.get(stickyComposerModelSelectionAtom),
280 ),
281 );
282 }
283 // Draining also waits for an already-fired debounce whose write is still
284 // gated behind its own hydration await inside the queue.
285 await persistenceQueue.run(() => Promise.resolve());
286 } while (persistTimer !== null);
288​
289function isComposerAttachmentFileReferenced(fileUri: string): boolean {
290 const referenceKey = composerAttachmentFileReferenceKey(fileUri);
291 const drafts = Object.values(appAtomRegistry.get(composerDraftsAtom));
292 const queuedMessages = Object.values(
293 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
294 ).flat();
295 return [...drafts, ...queuedMessages].some((owner) =>
296 owner.attachments.some(
297 (attachment) =>
298 attachment.type === "file" &&
299 composerAttachmentFileReferenceKey(attachment.fileUri) === referenceKey,
300 ),
301 );
303​
304function isComposerAttachmentUploadReferenced(
305 environmentId: EnvironmentId,
306 attachmentId: string,
307): boolean {
308 const drafts = Object.values(appAtomRegistry.get(composerDraftsAtom));
309 const queuedMessages = Object.values(
310 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
311 ).flat();
312 return [...drafts, ...queuedMessages].some((owner) =>
313 owner.attachments.some(
314 (attachment) =>
315 attachment.type === "file" &&
316 attachment.uploadEnvironmentId === environmentId &&
317 attachment.uploadedAttachmentId === attachmentId,
318 ),
319 );
321​
322export async function releaseUnusedComposerAttachmentFiles(
323 attachments: ReadonlyArray<DraftComposerAttachment>,
324): Promise<void> {
325 const candidates = new Set(
326 attachments
327 .filter((attachment) => attachment.type === "file")
328 .map((attachment) => attachment.fileUri),
329 );
330 const uploadCandidates = new Map<EnvironmentId, Set<string>>();
331 for (const attachment of attachments) {
332 if (
333 attachment.type !== "file" ||
334 attachment.uploadEnvironmentId === undefined ||
335 attachment.uploadedAttachmentId === undefined
336 ) {
337 continue;
338 }
339 const ids = uploadCandidates.get(attachment.uploadEnvironmentId) ?? new Set<string>();
340 ids.add(attachment.uploadedAttachmentId);
341 uploadCandidates.set(attachment.uploadEnvironmentId, ids);
342 }
343 if (candidates.size === 0) {
344 return;
345 }
346​
347 // Persisted drafts must hydrate before the reference scan. On a cold start
348 // the atom is still empty, and every file a persisted draft owns would look
349 // unused. Hydrate before flushing so a pending pre-hydration write cannot
350 // land an incomplete snapshot either.
351 await waitForComposerDraftsLoaded();
352 await flushComposerDrafts();
353 if (!(await threadOutboxManager.load())) {
354 // An unreadable outbox store must not look like an empty queue: deleting
355 // now would take bytes a persisted queued message still needs. Skip the
356 // sweep; the next one retries hydration.
357 return;
358 }
359 await flushThreadOutbox();
360​
361 const allFilesReferenced = [...candidates].every(isComposerAttachmentFileReferenced);
362 const allUploadsReferenced = [...uploadCandidates].every(([environmentId, attachmentIds]) =>
363 [...attachmentIds].every((attachmentId) =>
364 isComposerAttachmentUploadReferenced(environmentId, attachmentId),
365 ),
366 );
367 if (allFilesReferenced && allUploadsReferenced) {
368 return;
369 }
370​
371 let incomingShareFileUris: ReadonlySet<string>;
372 try {
373 const { loadIncomingShareDrafts } = await import("../features/sharing/incoming-share-storage");
374 const incomingShares = await loadIncomingShareDrafts({ strict: true });
375 incomingShareFileUris = new Set(
376 incomingShares.flatMap((share) =>
377 share.attachments.flatMap((attachment) =>
378 attachment.type === "file"
379 ? [composerAttachmentFileReferenceKey(attachment.fileUri)]
380 : [],
381 ),
382 ),
383 );
384 } catch (error) {
385 console.warn("[composer-attachments] could not verify incoming share ownership", error);
386 return;
387 }
388​
389 const { removePersistedComposerAttachmentFile } = await import("../lib/composerImages");
390 for (const fileUri of candidates) {
391 // Re-check ownership immediately before each deletion: a restore or edit
392 // can re-own a file after an earlier scan decided it was unused.
393 if (
394 isComposerAttachmentFileReferenced(fileUri) ||
395 incomingShareFileUris.has(composerAttachmentFileReferenceKey(fileUri))
396 ) {
397 continue;
398 }
399 await removePersistedComposerAttachmentFile(fileUri);
400 }
401​
402 if (uploadCandidates.size > 0) {
403 const { releasePendingAttachmentUploads } = await import("../lib/attachmentUpload");
404 for (const [environmentId, attachmentIds] of uploadCandidates) {
405 for (const attachmentId of attachmentIds) {
406 // A different draft or queued message can reuse the same pending
407 // upload with another local URI. Re-check the server-side ownership
408 // key immediately before deletion.
409 if (isComposerAttachmentUploadReferenced(environmentId, attachmentId)) {
410 continue;
411 }
412 try {
413 await releasePendingAttachmentUploads(environmentId, [attachmentId]);
414 } catch (error) {
415 // The server expires stale pending uploads. Local discard must still
416 // complete when the environment is disconnected or deletion fails.
417 console.warn("[composer-attachments] could not remove pending upload", {
418 environmentId,
419 attachmentId,
420 error,
421 });
422 }
423 }
424 }
425 }
427​
428export function scheduleUnusedComposerAttachmentCleanup(
429 attachments: ReadonlyArray<DraftComposerAttachment>,
430): void {
431 if (!attachments.some((attachment) => attachment.type === "file")) {
432 return;
433 }
434 void releaseUnusedComposerAttachmentFiles(attachments).catch((error) => {
435 console.warn("[composer-attachments] could not remove unused files", error);
436 });
438​
439function schedulePersistComposerState(): void {
440 if (persistTimer !== null) {
441 clearTimeout(persistTimer);
442 }
443 persistTimer = setTimeout(() => {
444 persistTimer = null;
445 ensureComposerDraftsLoaded();
446 // The write enters the serialization queue before waiting on hydration,
447 // so flushComposerDrafts' queue drain cannot resolve ahead of it.
448 void persistenceQueue.run(async () => {
449 if (loadPromise !== null) {
450 await loadPromise;
451 }
452 try {
453 await writePersistedComposerState(
454 appAtomRegistry.get(composerDraftsAtom),
455 appAtomRegistry.get(stickyComposerModelSelectionAtom),
456 );
457 } catch (error) {
458 console.warn("[composer-drafts] failed to persist drafts", error);
459 // Draft persistence is best-effort; in-memory drafts still keep working.
460 }
461 });
462 }, PERSIST_DEBOUNCE_MS);
464​
465export function ensureComposerDraftsLoaded(): void {
466 if (loadPromise !== null) {
467 return;
468 }
469 loadPromise = loadPersistedComposerState()
470 .then((persisted) => {
471 if (Object.keys(persisted.drafts).length > 0) {
472 const current = appAtomRegistry.get(composerDraftsAtom);
473 appAtomRegistry.set(composerDraftsAtom, {
474 ...persisted.drafts,
475 ...current,
476 });
477 }
478 if (
479 persisted.stickyModelSelection !== null &&
480 appAtomRegistry.get(stickyComposerModelSelectionAtom) === null
481 ) {
482 appAtomRegistry.set(stickyComposerModelSelectionAtom, persisted.stickyModelSelection);
483 }
484 })
485 .catch((cause) => {
486 console.warn(
487 "[composer-drafts] failed to hydrate drafts",
488 new ComposerDraftPersistenceError({
489 operation: "hydrate",
490 directory: COMPOSER_DRAFTS_DIRECTORY,
491 fileName: COMPOSER_DRAFTS_FILE,
492 cause,
493 }),
494 );
495 // Draft loading is best-effort; in-memory drafts still keep working.
496 });
498​
499/** Wait until persisted drafts have been merged into the in-memory composer state. */
500export async function waitForComposerDraftsLoaded(): Promise<void> {
501 ensureComposerDraftsLoaded();
502 if (loadPromise !== null) {
503 await loadPromise;
504 }
506​
507function updateComposerDrafts(
508 update: (current: Record<string, ComposerDraft>) => Record<string, ComposerDraft>,
509): void {
510 const current = appAtomRegistry.get(composerDraftsAtom);
511 const next = update(current);
512 if (next === current) {
513 return;
514 }
515 appAtomRegistry.set(composerDraftsAtom, next);
516 schedulePersistComposerState();
518​
519export function setStickyComposerModelSelection(modelSelection: ModelSelection): void {
520 appAtomRegistry.set(stickyComposerModelSelectionAtom, modelSelection);
521 schedulePersistComposerState();
523​
524export function setComposerDraftText(draftKey: string, value: string): void {
525 updateComposerDrafts((current) => {
526 const draft = {
527 ...normalizeDraft(current[draftKey]),
528 text: value,
529 };
530 if (isEmptyDraft(draft)) {
531 const next = { ...current };
532 delete next[draftKey];
533 return next;
534 }
535 return {
536 ...current,
537 [draftKey]: draft,
538 };
539 });
541​
542export function appendComposerDraftText(draftKey: string, value: string): void {
543 updateComposerDrafts((current) => {
544 const existing = normalizeDraft(current[draftKey]);
545 return {
546 ...current,
547 [draftKey]: {
548 ...existing,
549 text: `${existing.text}${value}`,
550 },
551 };
552 });
554​
555/**
556 * Appends attachments to a draft, capped at the send limit against the draft's
557 * live state (callers may have counted before an await; the picker can race
558 * concurrent adds). Overflowed file attachments are released. Returns how many
559 * were rejected. Restore paths pass allowOverflow so a failed send never drops
560 * the message's own attachments.
561 */
562export function appendComposerDraftAttachments(
563 draftKey: string,
564 attachments: ReadonlyArray<DraftComposerAttachment>,
565 options?: { readonly allowOverflow?: boolean },
566): number {
567 if (attachments.length === 0) {
568 return 0;
569 }
570 let rejected: ReadonlyArray<DraftComposerAttachment> = [];
571 updateComposerDrafts((current) => {
572 const existing = normalizeDraft(current[draftKey]);
573 const remaining = options?.allowOverflow
574 ? attachments.length
575 : Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - existing.attachments.length);
576 const accepted = attachments.slice(0, remaining);
577 rejected = attachments.slice(remaining);
578 if (accepted.length === 0) {
579 return current;
580 }
581 return {
582 ...current,
583 [draftKey]: {
584 ...existing,
585 attachments: [...existing.attachments, ...accepted],
586 },
587 };
588 });
589 scheduleUnusedComposerAttachmentCleanup(rejected);
590 return rejected.length;
592​
593export function replaceComposerDraftAttachments(
594 draftKey: string,
595 attachments: ReadonlyArray<DraftComposerAttachment>,
596): void {
597 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
598 updateComposerDrafts((current) => {
599 const draft = {
600 ...normalizeDraft(current[draftKey]),
601 attachments,
602 };
603 if (isEmptyDraft(draft)) {
604 const next = { ...current };
605 delete next[draftKey];
606 return next;
607 }
608 return {
609 ...current,
610 [draftKey]: draft,
611 };
612 });
613 const retainedIds = new Set(attachments.map((attachment) => attachment.id));
614 scheduleUnusedComposerAttachmentCleanup(
615 previousAttachments.filter((attachment) => !retainedIds.has(attachment.id)),
616 );
618​
619export function removeComposerDraftAttachment(draftKey: string, imageId: string): void {
620 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
621 updateComposerDrafts((current) => {
622 const existing = normalizeDraft(current[draftKey]);
623 const draft = {
624 ...existing,
625 attachments: existing.attachments.filter((image) => image.id !== imageId),
626 };
627 if (isEmptyDraft(draft)) {
628 const next = { ...current };
629 delete next[draftKey];
630 return next;
631 }
632 return {
633 ...current,
634 [draftKey]: draft,
635 };
636 });
637 scheduleUnusedComposerAttachmentCleanup(
638 previousAttachments.filter((attachment) => attachment.id === imageId),
639 );
641​
642export function updateComposerDraftSettings(
643 draftKey: string,
644 settings: Partial<ComposerDraftSettingsUpdate>,
645): void {
646 updateComposerDrafts((current) => {
647 const draft = {
648 ...normalizeDraft(current[draftKey]),
649 ...settings,
650 };
651 if (isEmptyDraft(draft)) {
652 const next = { ...current };
653 delete next[draftKey];
654 return next;
655 }
656 return {
657 ...current,
658 [draftKey]: draft,
659 };
660 });
662​
663export function clearComposerDraftContentState(
664 current: Record<string, ComposerDraft>,
665 draftKey: string,
666 options?: {
667 readonly clearModelSelection?: boolean;
668 readonly clearWorkspaceSelection?: boolean;
669 },
670): Record<string, ComposerDraft> {
671 const existing = current[draftKey];
672 if (!existing) {
673 return current;
674 }
675 const {
676 importedShareIds: _importedShareIds,
677 modelSelection,
678 workspaceSelection,
679 ...retained
680 } = existing;
681 const draft = {
682 ...retained,
683 ...(options?.clearModelSelection || modelSelection === undefined ? {} : { modelSelection }),
684 ...(options?.clearWorkspaceSelection || workspaceSelection === undefined
685 ? {}
686 : { workspaceSelection }),
687 text: "",
688 attachments: [],
689 };
690 if (isEmptyDraft(draft)) {
691 const next = { ...current };
692 delete next[draftKey];
693 return next;
694 }
695 return {
696 ...current,
697 [draftKey]: draft,
698 };
700​
701export function restoreComposerDraftSnapshotState(
702 current: Record<string, ComposerDraft>,
703 draftKey: string,
704 snapshot: ComposerDraft,
705): Record<string, ComposerDraft> {
706 const next = { ...current };
707 if (isEmptyDraft(snapshot)) {
708 delete next[draftKey];
709 } else {
710 next[draftKey] = snapshot;
711 }
712 return next;
714​
715export function copyComposerDraftContentState(
716 current: Record<string, ComposerDraft>,
717 sourceDraftKey: string,
718 targetDraftKey: string,
719): Record<string, ComposerDraft> {
720 if (sourceDraftKey === targetDraftKey) {
721 return current;
722 }
723 const source = normalizeDraft(current[sourceDraftKey]);
724 const target = normalizeDraft(current[targetDraftKey]);
725 const sourceHasContent =
726 source.text.length > 0 ||
727 source.attachments.length > 0 ||
728 (source.importedShareIds?.length ?? 0) > 0;
729 const targetHasContent =
730 target.text.length > 0 ||
731 target.attachments.length > 0 ||
732 (target.importedShareIds?.length ?? 0) > 0;
733 if (!sourceHasContent || targetHasContent) {
734 return current;
735 }
736 return {
737 ...current,
738 [targetDraftKey]: {
739 ...target,
740 text: source.text,
741 attachments: source.attachments,
742 ...(source.importedShareIds ? { importedShareIds: source.importedShareIds } : {}),
743 },
744 };
746​
747export async function copyComposerDraftContentIfEmpty(
748 sourceDraftKey: string,
749 targetDraftKey: string,
750): Promise<void> {
751 ensureComposerDraftsLoaded();
752 if (loadPromise !== null) {
753 await loadPromise;
754 }
755 updateComposerDrafts((current) =>
756 copyComposerDraftContentState(current, sourceDraftKey, targetDraftKey),
757 );
759​
760function mergeComposerDraftText(existing: string, incoming: string): string {
761 if (incoming.length === 0) {
762 return existing;
763 }
764 if (existing.length === 0) {
765 return incoming;
766 }
767 // Import retries are possible after an interrupted native handoff. Keep the
768 // operation idempotent when the same shared text is already present.
769 if (existing === incoming || existing.endsWith(`\n\n${incoming}`)) {
770 return existing;
771 }
772 return `${existing}\n\n${incoming}`;
774​
775export function mergeComposerDraftContentState(
776 current: Record<string, ComposerDraft>,
777 draftKey: string,
778 content: ComposerDraftContent,
779): Record<string, ComposerDraft> {
780 const existing = normalizeDraft(current[draftKey]);
781 if (content.sourceShareId && existing.importedShareIds?.includes(content.sourceShareId)) {
782 return current;
783 }
784 const attachmentIds = new Set(existing.attachments.map((attachment) => attachment.id));
785 const incomingAttachments = content.attachments.filter((attachment) => {
786 if (attachmentIds.has(attachment.id)) {
787 return false;
788 }
789 attachmentIds.add(attachment.id);
790 return true;
791 });
792 const attachments = [...existing.attachments, ...incomingAttachments].slice(
793 0,
794 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
795 );
796 const text = mergeComposerDraftText(existing.text, content.text);
797 const importedShareIds = content.sourceShareId
798 ? [...(existing.importedShareIds ?? []), content.sourceShareId]
799 : existing.importedShareIds;
800 if (
801 text === existing.text &&
802 attachments.length === existing.attachments.length &&
803 importedShareIds === existing.importedShareIds
804 ) {
805 return current;
806 }
807 return {
808 ...current,
809 [draftKey]: {
810 ...existing,
811 text,
812 attachments,
813 ...(importedShareIds ? { importedShareIds } : {}),
814 },
815 };
817​
818/**
819 * Atomically moves an incoming share into a project-scoped composer draft.
820 * The durable write happens before the share inbox item can be acknowledged.
821 */
822export async function mergeComposerDraftContent(
823 draftKey: string,
824 content: ComposerDraftContent,
825): Promise<{ readonly skippedAttachmentCount: number }> {
826 ensureComposerDraftsLoaded();
827 if (loadPromise !== null) {
828 await loadPromise;
829 }
830 if (persistTimer !== null) {
831 clearTimeout(persistTimer);
832 persistTimer = null;
833 }
834 const current = appAtomRegistry.get(composerDraftsAtom);
835 const next = mergeComposerDraftContentState(current, draftKey, content);
836 const currentAttachmentIds = new Set(
837 normalizeDraft(current[draftKey]).attachments.map((attachment) => attachment.id),
838 );
839 const nextAttachmentIds = new Set(
840 normalizeDraft(next[draftKey]).attachments.map((attachment) => attachment.id),
841 );
842 const skippedAttachmentCount = content.attachments.filter(
843 (attachment) =>
844 !currentAttachmentIds.has(attachment.id) && !nextAttachmentIds.has(attachment.id),
845 ).length;
846 // Publish the content and its import receipt together before the filesystem
847 // await. Typing during persistence then builds on the receipt-bearing state,
848 // and its debounced write is serialized after this transaction.
849 if (next !== current) {
850 appAtomRegistry.set(composerDraftsAtom, next);
851 }
852 await persistenceQueue.run(() =>
853 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
854 );
855 return { skippedAttachmentCount };
857​
858/** Restores the exact content/settings captured before an interrupted import. */
859export async function restoreComposerDraftSnapshot(
860 draftKey: string,
861 snapshot: ComposerDraft,
862): Promise<void> {
863 ensureComposerDraftsLoaded();
864 if (loadPromise !== null) {
865 await loadPromise;
866 }
867 if (persistTimer !== null) {
868 clearTimeout(persistTimer);
869 persistTimer = null;
870 }
871 const next = restoreComposerDraftSnapshotState(
872 appAtomRegistry.get(composerDraftsAtom),
873 draftKey,
874 snapshot,
875 );
876 appAtomRegistry.set(composerDraftsAtom, next);
877 await persistenceQueue.run(() =>
878 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
879 );
881​
882export function sameComposerDraftState(a: ComposerDraft, b: ComposerDraft): boolean {
883 return (
884 a.text === b.text &&
885 a.attachments === b.attachments &&
886 a.importedShareIds === b.importedShareIds &&
887 a.modelSelection === b.modelSelection &&
888 a.runtimeMode === b.runtimeMode &&
889 a.interactionMode === b.interactionMode &&
890 a.workspaceSelection === b.workspaceSelection
891 );
893​
894/**
895 * Undoes an abandoned mergeComposerDraftContent. When the draft is untouched
896 * since `merged` (the state captured right after the merge), the pre-merge
897 * snapshot comes back exactly. When the user edited the draft during the
898 * merge's awaits, only what the merge inserted (the appended text and the new
899 * attachments) is taken back out, so the user's edits survive the rollback.
900 */
901export function undoComposerDraftMergeState(
902 current: Record<string, ComposerDraft>,
903 draftKey: string,
904 snapshot: ComposerDraft,
905 merged: ComposerDraft,
906): Record<string, ComposerDraft> {
907 const existing = normalizeDraft(current[draftKey]);
908 if (sameComposerDraftState(existing, merged)) {
909 return restoreComposerDraftSnapshotState(current, draftKey, snapshot);
910 }
911 const insertedText = merged.text.startsWith(snapshot.text)
912 ? merged.text.slice(snapshot.text.length)
913 : "";
914 const snapshotAttachmentIds = new Set(snapshot.attachments.map((attachment) => attachment.id));
915 const insertedAttachmentIds = new Set(
916 merged.attachments
917 .filter((attachment) => !snapshotAttachmentIds.has(attachment.id))
918 .map((attachment) => attachment.id),
919 );
920 // A setting still holding the merge's value is the merge's doing: restore
921 // the snapshot's. One the user changed since the merge stays theirs.
922 const undoSetting = <
923 K extends "modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection",
924 >(
925 key: K,
926 ): ComposerDraft[K] => (existing[key] === merged[key] ? snapshot[key] : existing[key]);
927 const text =
928 insertedText.length > 0 && existing.text.startsWith(merged.text)
929 ? snapshot.text + existing.text.slice(merged.text.length)
930 : insertedText.length > 0 && existing.text.endsWith(insertedText)
931 ? existing.text.slice(0, existing.text.length - insertedText.length)
932 : existing.text;
933 const draft = {
934 ...existing,
935 text,
936 attachments: existing.attachments.filter(
937 (attachment) => !insertedAttachmentIds.has(attachment.id),
938 ),
939 modelSelection: undoSetting("modelSelection"),
940 runtimeMode: undoSetting("runtimeMode"),
941 interactionMode: undoSetting("interactionMode"),
942 workspaceSelection: undoSetting("workspaceSelection"),
943 };
944 if (isEmptyDraft(draft)) {
945 const next = { ...current };
946 delete next[draftKey];
947 return next;
948 }
949 return {
950 ...current,
951 [draftKey]: draft,
952 };
954​
955/** Applies undoComposerDraftMergeState and lands it durably. */
956export async function undoComposerDraftMerge(
957 draftKey: string,
958 snapshot: ComposerDraft,
959 merged: ComposerDraft,
960): Promise<void> {
961 ensureComposerDraftsLoaded();
962 if (loadPromise !== null) {
963 await loadPromise;
964 }
965 if (persistTimer !== null) {
966 clearTimeout(persistTimer);
967 persistTimer = null;
968 }
969 const next = undoComposerDraftMergeState(
970 appAtomRegistry.get(composerDraftsAtom),
971 draftKey,
972 snapshot,
973 merged,
974 );
975 appAtomRegistry.set(composerDraftsAtom, next);
976 await persistenceQueue.run(() =>
977 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
978 );
980​
981export function clearComposerDraftContent(
982 draftKey: string,
983 options?: {
984 readonly clearModelSelection?: boolean;
985 readonly clearWorkspaceSelection?: boolean;
986 // Send clears the draft while the durable outbox write is still in
987 // flight. Sweeping then would race the write: a failed enqueue rolls the
988 // message out of the queue mid-sweep and its files get deleted right
989 // before the failure handler restores them. The sender re-schedules
990 // cleanup once the write settles.
991 readonly deferAttachmentCleanup?: boolean;
992 },
993): void {
994 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
995 updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options));
996 if (!options?.deferAttachmentCleanup) {
997 scheduleUnusedComposerAttachmentCleanup(previousAttachments);
998 }
1000​
1001export function clearComposerDraft(
1002 draftKey: string,
1003 options?: { readonly deferAttachmentCleanup?: boolean },
1004): void {
1005 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1006 updateComposerDrafts((current) => {
1007 if (!current[draftKey]) {
1008 return current;
1010 const next = { ...current };
1011 delete next[draftKey];
1012 return next;
1013 });
1014 if (!options?.deferAttachmentCleanup) {
1015 scheduleUnusedComposerAttachmentCleanup(previousAttachments);
1018​
1019export function removeComposerDraftsForEnvironment(
1020 drafts: Record<string, ComposerDraft>,
1021 environmentId: EnvironmentId,
1022): Record<string, ComposerDraft> {
1023 const environmentPrefix = `${environmentId}:`;
1024 const newTaskPrefix = `new-task:${environmentId}:`;
1025 return Object.fromEntries(
1026 Object.entries(drafts).filter(
1027 ([draftKey]) =>
1028 !draftKey.startsWith(environmentPrefix) && !draftKey.startsWith(newTaskPrefix),
1029 ),
1030 );
1032​
1033export async function clearComposerDraftsEnvironment(environmentId: EnvironmentId): Promise<void> {
1034 ensureComposerDraftsLoaded();
1035 if (loadPromise !== null) {
1036 await loadPromise;
1038​
1039 const current = appAtomRegistry.get(composerDraftsAtom);
1040 const next = removeComposerDraftsForEnvironment(current, environmentId);
1041 const removedAttachments = Object.entries(current)
1042 .filter(([draftKey]) => next[draftKey] === undefined)
1043 .flatMap(([, draft]) => draft.attachments);
1044​
1045 if (persistTimer !== null) {
1046 clearTimeout(persistTimer);
1047 persistTimer = null;
1049 appAtomRegistry.set(composerDraftsAtom, next);
1050 await persistenceQueue.run(() =>
1051 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1052 );
1053 await releaseUnusedComposerAttachmentFiles(removedAttachments);
1055​
1056export function useComposerDraft(draftKey: string | null): ComposerDraft {
1057 const drafts = useAtomValue(composerDraftsAtom);
1058 useEffect(() => {
1059 ensureComposerDraftsLoaded();
1060 }, []);
1061 return draftKey ? normalizeDraft(drafts[draftKey]) : EMPTY_DRAFT;
1063​
1064export function useStickyComposerModelSelection(): ModelSelection | null {
1065 const selection = useAtomValue(stickyComposerModelSelectionAtom);
1066 useEffect(() => {
1067 ensureComposerDraftsLoaded();
1068 }, []);
1069 return selection;