import { useAtomValue } from "@effect/atom-react"; import { EnvironmentId as EnvironmentIdSchema, ModelSelection as ModelSelectionSchema, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, ProjectId as ProjectIdSchema, ProviderInteractionMode as ProviderInteractionModeSchema, RuntimeMode as RuntimeModeSchema, type EnvironmentId, type ModelSelection, type ProjectId, type ProviderInteractionMode, type RuntimeMode, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; import { useEffect } from "react"; import { Atom } from "effect/unstable/reactivity"; import { writeFileAtomically } from "../lib/atomic-file"; import { DraftComposerAttachmentSchema } from "../lib/composer-image-schema"; import { composerAttachmentFileReferenceKey, isComposerAttachmentFileRetained, retainComposerAttachmentFile, } from "../lib/composerAttachmentFiles"; import type { DraftComposerAttachment, FileBackedComposerAttachment } from "../lib/composerImages"; import { SerializedAsyncQueue } from "../lib/serialized-async-queue"; import { appAtomRegistry } from "./atom-registry"; import { isNewTaskDraftKey, newTaskDraftKey, parseLegacyNewTaskDraftKey, } from "./new-task-draft-key"; import { decodeQueuedThreadMessage, encodeQueuedThreadMessage, QueuedThreadMessageSchema, type QueuedThreadMessage, } from "./thread-outbox-model"; import { flushThreadOutbox, threadOutboxManager } from "./thread-outbox"; import { composerDraftEnvironmentId } from "../lib/composerAttachmentUploadQueue"; const COMPOSER_DRAFTS_SCHEMA_VERSION = 1; const COMPOSER_DRAFTS_DIRECTORY = "composer-drafts"; const COMPOSER_DRAFTS_FILE = "drafts.json"; const PERSIST_DEBOUNCE_MS = 200; export class ComposerDraftPersistenceError extends Schema.TaggedError()( "ComposerDraftPersistenceError", { operation: Schema.Literals(["open", "read", "decode", "encode", "write", "hydrate"]), directory: Schema.String, fileName: Schema.String, cause: Schema.Defect(), }, ) { override get message(): string { return `Composer draft persistence operation ${this.operation} failed for ${this.directory}/${this.fileName}.`; } } export interface ComposerDraft { readonly text: string; readonly attachments: ReadonlyArray; readonly importedShareIds?: ReadonlyArray; readonly modelSelection?: ModelSelection; readonly runtimeMode?: RuntimeMode; readonly interactionMode?: ProviderInteractionMode; readonly workspaceSelection?: ComposerDraftWorkspaceSelection; /** * Set on new-task drafts only. The project is stored here rather than in * the key so a project can hold any number of drafts and a draft can be * retargeted to another project without changing identity. */ readonly project?: ComposerDraftProject; } export interface ComposerDraftProject { readonly environmentId: EnvironmentId; readonly projectId: ProjectId; readonly createdAt: string; } export interface ComposerDraftContent { readonly text: string; readonly attachments: ReadonlyArray; readonly sourceShareId?: string; } export interface ComposerDraftWorkspaceSelection { readonly mode: "local" | "worktree"; readonly branch: string | null; readonly worktreePath: string | null; readonly startFromOrigin?: boolean; } export type ComposerDraftSettingsUpdate = Pick< ComposerDraft, "modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection" | "project" >; const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({ mode: Schema.Literals(["local", "worktree"]), branch: Schema.NullOr(Schema.String), worktreePath: Schema.NullOr(Schema.String), startFromOrigin: Schema.optional(Schema.Boolean), }); const ComposerDraftProjectSchema = Schema.Struct({ environmentId: EnvironmentIdSchema, projectId: ProjectIdSchema, createdAt: Schema.String, }); const ComposerDraftSchema = Schema.Struct({ text: Schema.String, attachments: Schema.Array(DraftComposerAttachmentSchema), importedShareIds: Schema.optional(Schema.Array(Schema.String)), modelSelection: Schema.optional(ModelSelectionSchema), runtimeMode: Schema.optional(RuntimeModeSchema), interactionMode: Schema.optional(ProviderInteractionModeSchema), workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema), project: Schema.optional(ComposerDraftProjectSchema), }); const PersistedComposerDraftsSchema = Schema.Struct({ schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION), drafts: Schema.Record(Schema.String, ComposerDraftSchema), stickyModelSelection: Schema.optional(ModelSelectionSchema), cloudAccountId: Schema.optional(Schema.String), signedOutDrafts: Schema.optional( Schema.Record( Schema.String, Schema.Struct({ drafts: Schema.Record(Schema.String, ComposerDraftSchema), queuedMessages: Schema.Array(QueuedThreadMessageSchema), }), ), ), }); const decodePersistedComposerDraftsDocument = Schema.decodeUnknownSync( PersistedComposerDraftsSchema, ); const EMPTY_DRAFT: ComposerDraft = { text: "", attachments: [], }; export const composerDraftsAtom = Atom.make>({}).pipe( Atom.keepAlive, Atom.withLabel("mobile:composer-drafts"), ); export const stickyComposerModelSelectionAtom = Atom.make(null).pipe( Atom.keepAlive, Atom.withLabel("mobile:sticky-composer-model-selection"), ); interface SignedOutDrafts { readonly drafts: Record; readonly queuedMessages: ReadonlyArray; } interface ComposerCloudDraftState { readonly accountId: string | null; readonly signedOut: Record; } export const composerCloudDraftsAtom = Atom.make({ accountId: null, signedOut: {}, }).pipe(Atom.keepAlive); let loadPromise: Promise | null = null; let persistTimer: ReturnType | null = null; let persistRetryNeeded = false; const persistenceQueue = new SerializedAsyncQueue(); /** Resets module-level state between test runs. */ export function resetComposerDraftsLoadState(): void { loadPromise = null; persistRetryNeeded = false; } function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft { if (!draft) { return EMPTY_DRAFT; } return { ...draft, text: draft.text, attachments: draft.attachments, }; } export function getComposerDraftSnapshot(draftKey: string): ComposerDraft { return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]); } export function isComposerDraftEmpty(draft: ComposerDraft): boolean { return isEmptyDraft(draft); } // The project stamp is identity, not content: a new-task draft with nothing // else in it is still empty and gets dropped like any other. function isEmptyDraft(draft: ComposerDraft): boolean { return ( draft.text.length === 0 && draft.attachments.length === 0 && draft.modelSelection === undefined && draft.runtimeMode === undefined && draft.interactionMode === undefined && draft.workspaceSelection === undefined ); } /** * Writes a draft back, dropping it once empty. A new-task draft keeps its * entry while the composer is bound to it (the project stamp is what the * composer binds to); the persist sweep still leaves empty ones off disk. */ function withComposerDraft( current: Record, draftKey: string, draft: ComposerDraft, ): Record { if (isEmptyDraft(draft) && draft.project === undefined) { const next = { ...current }; delete next[draftKey]; return next; } return { ...current, [draftKey]: draft }; } export { isNewTaskDraftKey, newTaskDraftKey } from "./new-task-draft-key"; // Draft ids only need to be unique within this device's draft file. Deriving // them from time plus randomness keeps this module free of native imports, // which the persistence tests rely on. function newDraftId(): string { return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`; } /** * Project-keyed new-task drafts from earlier builds are rewritten on load into * id-keyed drafts with the project stamped in, so existing drafts survive the * switch to many-per-project. */ export function migrateLegacyNewTaskDraft( key: string, draft: ComposerDraft, now: string, ): readonly [key: string, draft: ComposerDraft] { const legacy = draft.project === undefined ? parseLegacyNewTaskDraftKey(key) : null; if (legacy === null) { return [key, draft]; } return [ newTaskDraftKey(newDraftId()), { ...draft, project: { environmentId: EnvironmentIdSchema.make(legacy.environmentId), projectId: ProjectIdSchema.make(legacy.projectId), createdAt: now, }, }, ]; } export function decodePersistedComposerState(value: unknown): { readonly drafts: Record; readonly stickyModelSelection: ModelSelection | null; readonly cloudDrafts: ComposerCloudDraftState; } { const parsed = decodePersistedComposerDraftsDocument(value); const now = new Date().toISOString(); return { drafts: Object.fromEntries( Object.entries(parsed.drafts) .map(([key, draft]) => migrateLegacyNewTaskDraft( key, // Stale new-task drafts left on disk by builds before the // model-precedence fix carry a bare modelSelection with no // other selector settings. Strip it so the next compose pass // re-resolves project → sticky → provider defaults. Drafts // with runtime/interaction/workspace settings or actual text / // attachments were deliberately configured and are left alone. isNewTaskDraftKey(key) && draft.modelSelection && draft.text.length === 0 && draft.attachments.length === 0 && draft.runtimeMode === undefined && draft.interactionMode === undefined && draft.workspaceSelection === undefined ? { ...draft, modelSelection: undefined } : draft, now, ), ) // importedShareIds are share-import receipts: a contentless draft // carrying one is not empty, or the same native share would be // re-imported after restart. .filter(([, draft]) => !isEmptyDraft(draft) || (draft.importedShareIds?.length ?? 0) > 0), ), stickyModelSelection: parsed.stickyModelSelection ?? null, cloudDrafts: { accountId: parsed.cloudAccountId ?? null, signedOut: Object.fromEntries( Object.entries(parsed.signedOutDrafts ?? {}).map(([id, saved]) => [ id, { // Archived drafts come back through restoreCloudComposerDrafts // without another decode, so they get the same key migration. drafts: Object.fromEntries( Object.entries(saved.drafts).map(([key, draft]) => migrateLegacyNewTaskDraft(key, draft, now), ), ), queuedMessages: saved.queuedMessages.map(decodeQueuedThreadMessage), }, ]), ), }, }; } async function getComposerDraftsFile() { const { Directory, File, Paths } = await import("expo-file-system"); const directory = new Directory(Paths.document, COMPOSER_DRAFTS_DIRECTORY); directory.create({ idempotent: true, intermediates: true }); return new File(directory, COMPOSER_DRAFTS_FILE); } async function loadPersistedComposerState(): Promise< ReturnType > { let operation: ComposerDraftPersistenceError["operation"] = "open"; try { const file = await getComposerDraftsFile(); if (!file.exists) { return { drafts: {}, stickyModelSelection: null, cloudDrafts: { accountId: null, signedOut: {} }, }; } operation = "read"; const raw = await file.text(); operation = "decode"; return decodePersistedComposerState(JSON.parse(raw) as unknown); } catch (cause) { throw new ComposerDraftPersistenceError({ operation, directory: COMPOSER_DRAFTS_DIRECTORY, fileName: COMPOSER_DRAFTS_FILE, cause, }); } } async function writePersistedComposerState( drafts: Record, stickyModelSelection: ModelSelection | null, cloudDrafts = appAtomRegistry.get(composerCloudDraftsAtom), ): Promise { let operation: ComposerDraftPersistenceError["operation"] = "open"; try { const file = await getComposerDraftsFile(); operation = "encode"; const nonEmptyDrafts = Object.fromEntries( Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)), ); const document = { schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION, drafts: nonEmptyDrafts, ...(stickyModelSelection ? { stickyModelSelection } : {}), ...(cloudDrafts.accountId ? { cloudAccountId: cloudDrafts.accountId } : {}), ...(Object.keys(cloudDrafts.signedOut).length > 0 ? { signedOutDrafts: Object.fromEntries( Object.entries(cloudDrafts.signedOut).map(([id, saved]) => [ id, { drafts: saved.drafts, queuedMessages: saved.queuedMessages.map(encodeQueuedThreadMessage), }, ]), ), } : {}), } as const; const encoded = JSON.stringify(document); operation = "write"; await writeFileAtomically(file, encoded); } catch (cause) { throw new ComposerDraftPersistenceError({ operation, directory: COMPOSER_DRAFTS_DIRECTORY, fileName: COMPOSER_DRAFTS_FILE, cause, }); } } /** * Lands any debounced or in-flight draft write before the JS runtime is torn * down (app update restart), so the freshest draft state survives it. A write * failure propagates so the caller can decide whether the restart may proceed. */ export async function flushComposerDrafts(): Promise { // Never land a pre-hydration snapshot: persisted state must merge into the // atoms first, or this write would clobber disk with partial data. ensureComposerDraftsLoaded(); if (loadPromise !== null) { await loadPromise; } // An edit during an awaited write schedules another debounced write, so // keep landing snapshots until no debounce is pending after a queue drain. do { while (persistTimer !== null || persistRetryNeeded) { if (persistTimer !== null) clearTimeout(persistTimer); persistTimer = null; persistRetryNeeded = false; try { await persistenceQueue.run(() => writePersistedComposerState( appAtomRegistry.get(composerDraftsAtom), appAtomRegistry.get(stickyComposerModelSelectionAtom), ), ); } catch (error) { persistRetryNeeded = true; throw error; } } // Draining also waits for an already-fired debounce whose write is still // gated behind its own hydration await inside the queue. await persistenceQueue.run(() => Promise.resolve()); } while (persistTimer !== null || persistRetryNeeded); } function signedOutAttachmentOwners() { return Object.values(appAtomRegistry.get(composerCloudDraftsAtom).signedOut).flatMap((saved) => [ ...Object.values(saved.drafts), ...saved.queuedMessages, ]); } function isComposerAttachmentFileReferenced(fileUri: string): boolean { if (isComposerAttachmentFileRetained(fileUri)) { return true; } const referenceKey = composerAttachmentFileReferenceKey(fileUri); const drafts = Object.values(appAtomRegistry.get(composerDraftsAtom)); const queuedMessages = Object.values( appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), ).flat(); return [...drafts, ...queuedMessages, ...signedOutAttachmentOwners()].some((owner) => owner.attachments.some( (attachment) => attachment.fileUri !== undefined && composerAttachmentFileReferenceKey(attachment.fileUri) === referenceKey, ), ); } function isComposerAttachmentUploadReferenced( environmentId: EnvironmentId, attachmentId: string, ): boolean { const drafts = Object.values(appAtomRegistry.get(composerDraftsAtom)); const queuedMessages = Object.values( appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), ).flat(); return [...drafts, ...queuedMessages, ...signedOutAttachmentOwners()].some((owner) => owner.attachments.some( (attachment) => attachment.uploadEnvironmentId === environmentId && attachment.uploadedAttachmentId === attachmentId, ), ); } export async function releaseUnusedComposerAttachmentFiles( attachments: ReadonlyArray, ): Promise { const candidates = new Set( attachments.flatMap((attachment) => attachment.fileUri !== undefined ? [attachment.fileUri] : [], ), ); const uploadCandidates = new Map>(); for (const attachment of attachments) { if ( attachment.uploadEnvironmentId === undefined || attachment.uploadedAttachmentId === undefined ) { continue; } const ids = uploadCandidates.get(attachment.uploadEnvironmentId) ?? new Set(); ids.add(attachment.uploadedAttachmentId); uploadCandidates.set(attachment.uploadEnvironmentId, ids); } if (candidates.size === 0 && uploadCandidates.size === 0) { return; } // Persisted drafts must hydrate before the reference scan. On a cold start // the atom is still empty, and every file a persisted draft owns would look // unused. Hydrate before flushing so a pending pre-hydration write cannot // land an incomplete snapshot either. await waitForComposerDraftsLoaded(); await flushComposerDrafts(); if (!(await threadOutboxManager.load())) { // An unreadable outbox store must not look like an empty queue: deleting // now would take bytes a persisted queued message still needs. Skip the // sweep; the next one retries hydration. return; } await flushThreadOutbox(); const allFilesReferenced = [...candidates].every(isComposerAttachmentFileReferenced); const allUploadsReferenced = [...uploadCandidates].every(([environmentId, attachmentIds]) => [...attachmentIds].every((attachmentId) => isComposerAttachmentUploadReferenced(environmentId, attachmentId), ), ); if (allFilesReferenced && allUploadsReferenced) { return; } let incomingShareFileUris: ReadonlySet; try { const { loadIncomingShareDrafts } = await import("../features/sharing/incoming-share-storage"); const incomingShares = await loadIncomingShareDrafts({ strict: true }); incomingShareFileUris = new Set( incomingShares.flatMap((share) => share.attachments.flatMap((attachment) => attachment.fileUri !== undefined ? [composerAttachmentFileReferenceKey(attachment.fileUri)] : [], ), ), ); } catch (error) { console.warn("[composer-attachments] could not verify incoming share ownership", error); return; } const { removePersistedComposerAttachmentFile } = await import("../lib/composerImages"); for (const fileUri of candidates) { // Re-check ownership immediately before each deletion: a restore or edit // can re-own a file after an earlier scan decided it was unused. if ( isComposerAttachmentFileReferenced(fileUri) || incomingShareFileUris.has(composerAttachmentFileReferenceKey(fileUri)) ) { continue; } await removePersistedComposerAttachmentFile(fileUri); } if (uploadCandidates.size > 0) { const { releasePendingAttachmentUploads } = await import("../lib/attachmentUpload"); for (const [environmentId, attachmentIds] of uploadCandidates) { for (const attachmentId of attachmentIds) { // A different draft or queued message can reuse the same pending // upload with another local URI. Re-check the server-side ownership // key immediately before deletion. if (isComposerAttachmentUploadReferenced(environmentId, attachmentId)) { continue; } try { await releasePendingAttachmentUploads(environmentId, [attachmentId]); } catch (error) { // The server expires stale pending uploads. Local discard must still // complete when the environment is disconnected or deletion fails. console.warn("[composer-attachments] could not remove pending upload", { environmentId, attachmentId, error, }); } } } } } export function scheduleUnusedComposerAttachmentCleanup( attachments: ReadonlyArray, ): void { if ( !attachments.some( (attachment) => attachment.fileUri !== undefined || attachment.uploadedAttachmentId !== undefined, ) ) { return; } void releaseUnusedComposerAttachmentFiles(attachments).catch((error) => { console.warn("[composer-attachments] could not remove unused files", error); }); } /** Keeps a native preview or upload readable until it finishes, then retries ownership cleanup. */ export function retainComposerAttachmentFileForPreview( attachment: FileBackedComposerAttachment, ): () => void { return retainComposerAttachmentFile(attachment.fileUri, () => { scheduleUnusedComposerAttachmentCleanup([attachment]); }); } function schedulePersistComposerState(): void { if (persistTimer !== null) { clearTimeout(persistTimer); } persistTimer = setTimeout(() => { persistTimer = null; // The write enters the serialization queue before waiting on hydration, // so flushComposerDrafts' queue drain cannot resolve ahead of it. void persistenceQueue.run(async () => { try { await waitForComposerDraftsLoaded(); await writePersistedComposerState( appAtomRegistry.get(composerDraftsAtom), appAtomRegistry.get(stickyComposerModelSelectionAtom), ); persistRetryNeeded = false; } catch (error) { // A failed debounce has no timer left. A later final flush must retry // these edits after persisted ownership can be read safely. persistRetryNeeded = true; console.warn("[composer-drafts] failed to persist drafts", error); // Draft persistence is best-effort; in-memory drafts still keep working. } }); }, PERSIST_DEBOUNCE_MS); } export function ensureComposerDraftsLoaded(): void { if (loadPromise !== null) { return; } const loading = loadPersistedComposerState().then((persisted) => { appAtomRegistry.set(composerCloudDraftsAtom, persisted.cloudDrafts); if (Object.keys(persisted.drafts).length > 0) { const current = appAtomRegistry.get(composerDraftsAtom); appAtomRegistry.set(composerDraftsAtom, { ...persisted.drafts, ...current, }); } if ( persisted.stickyModelSelection !== null && appAtomRegistry.get(stickyComposerModelSelectionAtom) === null ) { appAtomRegistry.set(stickyComposerModelSelectionAtom, persisted.stickyModelSelection); } }); loadPromise = loading; // Handle fire-and-forget hook loads without swallowing failures from the // write and cleanup callers that await this same promise. A later call retries. void loading.catch((cause) => { if (loadPromise === loading) loadPromise = null; console.warn( "[composer-drafts] failed to hydrate drafts", cause instanceof ComposerDraftPersistenceError ? cause : new ComposerDraftPersistenceError({ operation: "hydrate", directory: COMPOSER_DRAFTS_DIRECTORY, fileName: COMPOSER_DRAFTS_FILE, cause, }), ); }); } /** Wait until persisted drafts have been merged into the in-memory composer state. */ export async function waitForComposerDraftsLoaded(): Promise { ensureComposerDraftsLoaded(); if (loadPromise !== null) { await loadPromise; } } export async function getComposerCloudAccountId(): Promise { await waitForComposerDraftsLoaded(); return appAtomRegistry.get(composerCloudDraftsAtom).accountId; } /** Save an account's local work before its relay environments are removed. */ export async function archiveCloudComposerDrafts( accountId: string | null, environmentIds: ReadonlySet, ): Promise { await waitForComposerDraftsLoaded(); if (!(await threadOutboxManager.load())) throw new Error("Could not preserve queued messages."); await flushThreadOutbox(); const cloud = appAtomRegistry.get(composerCloudDraftsAtom); const owner = accountId ?? cloud.accountId; if (owner === null) return; const queued = Object.values( appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), ).flat(); const current = appAtomRegistry.get(composerDraftsAtom); const remaining = { ...current }; const savedDrafts = { ...cloud.signedOut[owner]?.drafts }; for (const [key, draft] of Object.entries(current)) { const environmentId = composerDraftEnvironmentId(key, queued, draft); if (environmentId !== null && environmentIds.has(environmentId)) { savedDrafts[key] = draft; delete remaining[key]; } } const savedMessages = new Map( (cloud.signedOut[owner]?.queuedMessages ?? []).map((message) => [message.messageId, message]), ); for (const message of queued) { if (environmentIds.has(message.environmentId)) savedMessages.set(message.messageId, message); } appAtomRegistry.set(composerDraftsAtom, remaining); appAtomRegistry.set(composerCloudDraftsAtom, { // Keep the owner through removal. A crash or failed cleanup can retry it // on cold start before a different account activates. accountId: owner, signedOut: { ...cloud.signedOut, [owner]: { drafts: savedDrafts, queuedMessages: [...savedMessages.values()] }, }, }); schedulePersistComposerState(); await flushComposerDrafts(); } function sameDraftAttachmentIds( left: ReadonlyArray, right: ReadonlyArray, ): boolean { return ( left.length === right.length && left.every((attachment, index) => attachment.id === right[index]?.id) ); } /** An in-flight delivery can finish after sign-out took its snapshot. */ export async function removeDeliveredCloudQueuedMessage( message: QueuedThreadMessage, ): Promise { await waitForComposerDraftsLoaded(); const cloud = appAtomRegistry.get(composerCloudDraftsAtom); const signedOut = { ...cloud.signedOut }; let changed = false; for (const [accountId, saved] of Object.entries(signedOut)) { const archived = saved.queuedMessages.find( (candidate) => candidate.environmentId === message.environmentId && candidate.messageId === message.messageId, ); if ( !archived || archived.commandId !== message.commandId || archived.threadId !== message.threadId || archived.text !== message.text || !sameDraftAttachmentIds(archived.attachments, message.attachments) ) continue; // Upload ids may change during preparation; user edits must remain recoverable. if ( JSON.stringify([ archived.modelSelection, archived.runtimeMode, archived.interactionMode, archived.creation, ]) !== JSON.stringify([ message.modelSelection, message.runtimeMode, message.interactionMode, message.creation, ]) ) continue; const editorKey = `pending-task:${message.messageId}`; const editor = saved.drafts[editorKey]; if ( editor && (editor.text !== message.text || !sameDraftAttachmentIds(editor.attachments, message.attachments) || (editor.modelSelection !== undefined && JSON.stringify(editor.modelSelection) !== JSON.stringify(message.modelSelection)) || (editor.runtimeMode !== undefined && editor.runtimeMode !== message.runtimeMode) || (editor.interactionMode !== undefined && editor.interactionMode !== message.interactionMode) || (editor.workspaceSelection !== undefined && (editor.workspaceSelection.mode !== message.creation?.workspaceMode || editor.workspaceSelection.branch !== message.creation?.branch || editor.workspaceSelection.worktreePath !== message.creation?.worktreePath || (editor.workspaceSelection.startFromOrigin ?? false) !== (message.creation?.startFromOrigin ?? false)))) ) continue; const drafts = { ...saved.drafts }; delete drafts[editorKey]; signedOut[accountId] = { drafts, queuedMessages: saved.queuedMessages.filter((candidate) => candidate !== archived), }; changed = true; } if (!changed) return; appAtomRegistry.set(composerCloudDraftsAtom, { ...cloud, signedOut }); schedulePersistComposerState(); try { await flushComposerDrafts(); } catch (error) { // The live outbox can still remove this acknowledged message. Keep the // archive update pending so a later successful flush lands it too. schedulePersistComposerState(); throw error; } } /** Restores only this account, before its connections can deliver queued turns. */ export async function restoreCloudComposerDrafts(accountId: string): Promise { await waitForComposerDraftsLoaded(); const cloud = appAtomRegistry.get(composerCloudDraftsAtom); const saved = cloud.signedOut[accountId]; if (saved) { if (!(await threadOutboxManager.load())) throw new Error("Could not restore queued messages."); for (const message of saved.queuedMessages) { const alreadyQueued = Object.values( appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), ) .flat() .some((current) => current.messageId === message.messageId); if (!alreadyQueued) await threadOutboxManager.enqueue(message); } updateComposerDrafts((current) => { const restored = { ...current }; for (const [key, draft] of Object.entries(saved.drafts)) { const existing = current[key]; const attachmentIds = new Set(existing?.attachments.map((attachment) => attachment.id)); restored[key] = existing ? { ...draft, ...existing, text: mergeComposerDraftText(existing.text, draft.text), // A concurrent import must not lose files, even above the send limit. attachments: [ ...existing.attachments, ...draft.attachments.filter((attachment) => !attachmentIds.has(attachment.id)), ], importedShareIds: [ ...new Set([ ...(existing.importedShareIds ?? []), ...(draft.importedShareIds ?? []), ]), ], } : draft; } return restored; }); } const signedOut = { ...cloud.signedOut }; delete signedOut[accountId]; appAtomRegistry.set(composerCloudDraftsAtom, { accountId, signedOut }); schedulePersistComposerState(); await flushComposerDrafts(); } function updateComposerDrafts( update: (current: Record) => Record, ): void { const current = appAtomRegistry.get(composerDraftsAtom); const next = update(current); if (next === current) { return; } appAtomRegistry.set(composerDraftsAtom, next); schedulePersistComposerState(); } export function setStickyComposerModelSelection(modelSelection: ModelSelection): void { appAtomRegistry.set(stickyComposerModelSelectionAtom, modelSelection); schedulePersistComposerState(); } export function setComposerDraftText(draftKey: string, value: string): void { updateComposerDrafts((current) => { const draft = { ...normalizeDraft(current[draftKey]), text: value, }; return withComposerDraft(current, draftKey, draft); }); } export function appendComposerDraftText(draftKey: string, value: string): void { updateComposerDrafts((current) => { const existing = normalizeDraft(current[draftKey]); return { ...current, [draftKey]: { ...existing, text: `${existing.text}${value}`, }, }; }); } /** * Appends attachments to a draft, capped at the send limit against the draft's * live state (callers may have counted before an await; the picker can race * concurrent adds). Overflowed file attachments are released. Returns how many * were rejected. Restore paths pass allowOverflow so a failed send never drops * the message's own attachments. */ export function appendComposerDraftAttachments( draftKey: string, attachments: ReadonlyArray, options?: { readonly allowOverflow?: boolean; readonly maxAttachments?: number }, ): number { if (attachments.length === 0) { return 0; } let rejected: ReadonlyArray = []; updateComposerDrafts((current) => { const existing = normalizeDraft(current[draftKey]); const remaining = options?.allowOverflow ? attachments.length : Math.max( 0, Math.min( PROVIDER_SEND_TURN_MAX_ATTACHMENTS, options?.maxAttachments ?? PROVIDER_SEND_TURN_MAX_ATTACHMENTS, ) - existing.attachments.length, ); const accepted = attachments.slice(0, remaining); rejected = attachments.slice(remaining); if (accepted.length === 0) { return current; } return { ...current, [draftKey]: { ...existing, attachments: [...existing.attachments, ...accepted], }, }; }); scheduleUnusedComposerAttachmentCleanup(rejected); return rejected.length; } export function replaceComposerDraftAttachments( draftKey: string, attachments: ReadonlyArray, ): void { const previousAttachments = getComposerDraftSnapshot(draftKey).attachments; updateComposerDrafts((current) => { const draft = { ...normalizeDraft(current[draftKey]), attachments, }; return withComposerDraft(current, draftKey, draft); }); const retainedIds = new Set(attachments.map((attachment) => attachment.id)); scheduleUnusedComposerAttachmentCleanup( previousAttachments.filter((attachment) => !retainedIds.has(attachment.id)), ); } export function removeComposerDraftAttachment(draftKey: string, imageId: string): void { const previousAttachments = getComposerDraftSnapshot(draftKey).attachments; updateComposerDrafts((current) => { const existing = normalizeDraft(current[draftKey]); const draft = { ...existing, attachments: existing.attachments.filter((image) => image.id !== imageId), }; return withComposerDraft(current, draftKey, draft); }); scheduleUnusedComposerAttachmentCleanup( previousAttachments.filter((attachment) => attachment.id === imageId), ); } /** Stamps a finished upload without overwriting text, removals, or newer attachments. */ export function setComposerDraftAttachmentUpload( draftKey: string, attachment: DraftComposerAttachment, ): boolean { let previous: DraftComposerAttachment | undefined; updateComposerDrafts((current) => { const draft = current[draftKey]; previous = draft?.attachments.find((candidate) => candidate.id === attachment.id); if (!draft || !previous) return current; if ( previous.uploadedAttachmentId === attachment.uploadedAttachmentId && previous.uploadEnvironmentId === attachment.uploadEnvironmentId ) return current; return { ...current, [draftKey]: { ...draft, attachments: draft.attachments.map((candidate) => candidate.id === attachment.id ? { ...candidate, uploadedAttachmentId: attachment.uploadedAttachmentId, uploadEnvironmentId: attachment.uploadEnvironmentId, } : candidate, ), }, }; }); if (previous) scheduleUnusedComposerAttachmentCleanup([previous]); return previous !== undefined; } export function updateComposerDraftSettings( draftKey: string, settings: Partial, ): void { updateComposerDrafts((current) => { const draft = { ...normalizeDraft(current[draftKey]), ...settings, }; return withComposerDraft(current, draftKey, draft); }); } export function clearComposerDraftContentState( current: Record, draftKey: string, options?: { readonly clearModelSelection?: boolean; readonly clearWorkspaceSelection?: boolean; }, ): Record { const existing = current[draftKey]; if (!existing) { return current; } // Clearing content is the "this draft is done" moment (sent, queued, or // discarded), so the project stamp goes too and an otherwise-empty new-task // draft leaves the store rather than lingering as a blank row. const { importedShareIds: _importedShareIds, modelSelection, workspaceSelection, project: _project, ...retained } = existing; const draft = { ...retained, ...(options?.clearModelSelection || modelSelection === undefined ? {} : { modelSelection }), ...(options?.clearWorkspaceSelection || workspaceSelection === undefined ? {} : { workspaceSelection }), text: "", attachments: [], }; if (isEmptyDraft(draft)) { const next = { ...current }; delete next[draftKey]; return next; } return { ...current, [draftKey]: draft, }; } export function restoreComposerDraftSnapshotState( current: Record, draftKey: string, snapshot: ComposerDraft, ): Record { const next = { ...current }; if (isEmptyDraft(snapshot)) { delete next[draftKey]; } else { next[draftKey] = snapshot; } return next; } function stripAttachmentUploadReference( attachment: DraftComposerAttachment, ): DraftComposerAttachment { const { uploadedAttachmentId: _id, uploadEnvironmentId: _environmentId, ...rest } = attachment; return rest; } function mergeComposerDraftText(existing: string, incoming: string): string { if (incoming.length === 0) { return existing; } if (existing.length === 0) { return incoming; } // Import retries are possible after an interrupted native handoff. Keep the // operation idempotent when the same shared text is already present. if (existing === incoming || existing.endsWith(`\n\n${incoming}`)) { return existing; } return `${existing}\n\n${incoming}`; } export function mergeComposerDraftContentState( current: Record, draftKey: string, content: ComposerDraftContent, ): Record { const existing = normalizeDraft(current[draftKey]); if (content.sourceShareId && existing.importedShareIds?.includes(content.sourceShareId)) { return current; } const attachmentIds = new Set(existing.attachments.map((attachment) => attachment.id)); const incomingAttachments = content.attachments.filter((attachment) => { if (attachmentIds.has(attachment.id)) { return false; } attachmentIds.add(attachment.id); return true; }); const attachments = [...existing.attachments, ...incomingAttachments].slice( 0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, ); const text = mergeComposerDraftText(existing.text, content.text); const importedShareIds = content.sourceShareId ? [...(existing.importedShareIds ?? []), content.sourceShareId] : existing.importedShareIds; if ( text === existing.text && attachments.length === existing.attachments.length && importedShareIds === existing.importedShareIds ) { return current; } return { ...current, [draftKey]: { ...existing, text, attachments, ...(importedShareIds ? { importedShareIds } : {}), }, }; } /** * Atomically moves an incoming share into a project-scoped composer draft. * The durable write happens before the share inbox item can be acknowledged. */ export async function mergeComposerDraftContent( draftKey: string, content: ComposerDraftContent, ): Promise<{ readonly skippedAttachmentCount: number }> { ensureComposerDraftsLoaded(); if (loadPromise !== null) { await loadPromise; } if (persistTimer !== null) { clearTimeout(persistTimer); persistTimer = null; } const current = appAtomRegistry.get(composerDraftsAtom); const next = mergeComposerDraftContentState(current, draftKey, content); const currentAttachmentIds = new Set( normalizeDraft(current[draftKey]).attachments.map((attachment) => attachment.id), ); const nextAttachmentIds = new Set( normalizeDraft(next[draftKey]).attachments.map((attachment) => attachment.id), ); const skippedAttachmentCount = content.attachments.filter( (attachment) => !currentAttachmentIds.has(attachment.id) && !nextAttachmentIds.has(attachment.id), ).length; // Publish the content and its import receipt together before the filesystem // await. Typing during persistence then builds on the receipt-bearing state, // and its debounced write is serialized after this transaction. if (next !== current) { appAtomRegistry.set(composerDraftsAtom, next); } await persistenceQueue.run(() => writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)), ); return { skippedAttachmentCount }; } /** Restores the exact content/settings captured before an interrupted import. */ export async function restoreComposerDraftSnapshot( draftKey: string, snapshot: ComposerDraft, ): Promise { ensureComposerDraftsLoaded(); if (loadPromise !== null) { await loadPromise; } if (persistTimer !== null) { clearTimeout(persistTimer); persistTimer = null; } const next = restoreComposerDraftSnapshotState( appAtomRegistry.get(composerDraftsAtom), draftKey, snapshot, ); appAtomRegistry.set(composerDraftsAtom, next); await persistenceQueue.run(() => writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)), ); } export function sameComposerDraftState(a: ComposerDraft, b: ComposerDraft): boolean { return ( a.text === b.text && a.attachments === b.attachments && a.importedShareIds === b.importedShareIds && a.modelSelection === b.modelSelection && a.runtimeMode === b.runtimeMode && a.interactionMode === b.interactionMode && a.workspaceSelection === b.workspaceSelection ); } /** * Undoes an abandoned mergeComposerDraftContent. When the draft is untouched * since `merged` (the state captured right after the merge), the pre-merge * snapshot comes back exactly. When the user edited the draft during the * merge's awaits, only what the merge inserted (the appended text and the new * attachments) is taken back out, so the user's edits survive the rollback. */ export function undoComposerDraftMergeState( current: Record, draftKey: string, snapshot: ComposerDraft, merged: ComposerDraft, ): Record { const existing = normalizeDraft(current[draftKey]); if (sameComposerDraftState(existing, merged)) { return restoreComposerDraftSnapshotState(current, draftKey, snapshot); } const insertedText = merged.text.startsWith(snapshot.text) ? merged.text.slice(snapshot.text.length) : ""; const snapshotAttachmentIds = new Set(snapshot.attachments.map((attachment) => attachment.id)); const insertedAttachmentIds = new Set( merged.attachments .filter((attachment) => !snapshotAttachmentIds.has(attachment.id)) .map((attachment) => attachment.id), ); // A setting still holding the merge's value is the merge's doing: restore // the snapshot's. One the user changed since the merge stays theirs. const undoSetting = < K extends "modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection", >( key: K, ): ComposerDraft[K] => (existing[key] === merged[key] ? snapshot[key] : existing[key]); const text = insertedText.length > 0 && existing.text.startsWith(merged.text) ? snapshot.text + existing.text.slice(merged.text.length) : insertedText.length > 0 && existing.text.endsWith(insertedText) ? existing.text.slice(0, existing.text.length - insertedText.length) : existing.text; const draft = { ...existing, text, attachments: existing.attachments.filter( (attachment) => !insertedAttachmentIds.has(attachment.id), ), modelSelection: undoSetting("modelSelection"), runtimeMode: undoSetting("runtimeMode"), interactionMode: undoSetting("interactionMode"), workspaceSelection: undoSetting("workspaceSelection"), }; return withComposerDraft(current, draftKey, draft); } /** Applies undoComposerDraftMergeState and lands it durably. */ export async function undoComposerDraftMerge( draftKey: string, snapshot: ComposerDraft, merged: ComposerDraft, ): Promise { ensureComposerDraftsLoaded(); if (loadPromise !== null) { await loadPromise; } if (persistTimer !== null) { clearTimeout(persistTimer); persistTimer = null; } const next = undoComposerDraftMergeState( appAtomRegistry.get(composerDraftsAtom), draftKey, snapshot, merged, ); appAtomRegistry.set(composerDraftsAtom, next); await persistenceQueue.run(() => writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)), ); } export function clearComposerDraftContent( draftKey: string, options?: { readonly clearModelSelection?: boolean; readonly clearWorkspaceSelection?: boolean; // Send clears the draft while the durable outbox write is still in // flight. Sweeping then would race the write: a failed enqueue rolls the // message out of the queue mid-sweep and its files get deleted right // before the failure handler restores them. The sender re-schedules // cleanup once the write settles. readonly deferAttachmentCleanup?: boolean; }, ): void { const previousAttachments = getComposerDraftSnapshot(draftKey).attachments; updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options)); if (!options?.deferAttachmentCleanup) { scheduleUnusedComposerAttachmentCleanup(previousAttachments); } } export function clearComposerDraft( draftKey: string, options?: { readonly deferAttachmentCleanup?: boolean }, ): void { const previousAttachments = getComposerDraftSnapshot(draftKey).attachments; updateComposerDrafts((current) => { if (!current[draftKey]) { return current; } const next = { ...current }; delete next[draftKey]; return next; }); if (!options?.deferAttachmentCleanup) { scheduleUnusedComposerAttachmentCleanup(previousAttachments); } } export function removeComposerDraftsForEnvironment( drafts: Record, environmentId: EnvironmentId, ): Record { const environmentPrefix = `${environmentId}:`; return Object.fromEntries( Object.entries(drafts).filter( ([draftKey, draft]) => !draftKey.startsWith(environmentPrefix) && draft.project?.environmentId !== environmentId, ), ); } /** * Mints a new-task draft for a project. The entry is published immediately so * the composer can bind to its key before the user types; it stays out of the * list until it has content, and the empty-draft sweep drops it on persist if * nothing is ever written. */ export function createNewTaskDraft(project: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId; }): string { const draftKey = newTaskDraftKey(newDraftId()); const stamp: ComposerDraftProject = { environmentId: project.environmentId, projectId: project.projectId, createdAt: new Date().toISOString(), }; updateComposerDrafts((current) => ({ ...current, [draftKey]: { ...EMPTY_DRAFT, project: stamp }, })); return draftKey; } /** * Points an existing new-task draft at a different project, keeping its * content and identity. Workspace selection is project-specific (branch, * worktree), so it is cleared; model and mode choices carry over. */ export function retargetNewTaskDraft( draftKey: string, project: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }, ): void { updateComposerDrafts((current) => { const existing = current[draftKey]; const stamp = existing?.project; if ( stamp !== undefined && stamp.environmentId === project.environmentId && stamp.projectId === project.projectId ) { return current; } const { workspaceSelection: _workspaceSelection, ...retained } = normalizeDraft(existing); // Pending uploads live on one server. Crossing environments keeps the // local bytes (the upload worker re-sends them to the new environment) // but drops the old stamp, so it cannot pin the source environment's // pending upload alive from the moved draft. const attachments = retained.attachments.map((attachment) => attachment.uploadEnvironmentId !== undefined && attachment.uploadEnvironmentId !== project.environmentId ? stripAttachmentUploadReference(attachment) : attachment, ); return { ...current, [draftKey]: { ...retained, attachments, project: { environmentId: project.environmentId, projectId: project.projectId, createdAt: stamp?.createdAt ?? new Date().toISOString(), }, }, }; }); } /** New-task drafts for a project, newest first. */ export function findNewTaskDraftKeys( drafts: Readonly>, project: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }, ): ReadonlyArray { return Object.entries(drafts) .filter( ([key, draft]) => isNewTaskDraftKey(key) && draft.project?.environmentId === project.environmentId && draft.project.projectId === project.projectId, ) .sort(([, left], [, right]) => (right.project?.createdAt ?? "").localeCompare(left.project?.createdAt ?? ""), ) .map(([key]) => key); } export async function clearComposerDraftsEnvironment(environmentId: EnvironmentId): Promise { ensureComposerDraftsLoaded(); if (loadPromise !== null) { await loadPromise; } const current = appAtomRegistry.get(composerDraftsAtom); const next = removeComposerDraftsForEnvironment(current, environmentId); const removedAttachments = Object.entries(current) .filter(([draftKey]) => next[draftKey] === undefined) .flatMap(([, draft]) => draft.attachments); if (persistTimer !== null) { clearTimeout(persistTimer); persistTimer = null; } appAtomRegistry.set(composerDraftsAtom, next); await persistenceQueue.run(() => writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)), ); await releaseUnusedComposerAttachmentFiles(removedAttachments); } export function useComposerDraft(draftKey: string | null): ComposerDraft { const drafts = useAtomValue(composerDraftsAtom); useEffect(() => { ensureComposerDraftsLoaded(); }, []); return draftKey ? normalizeDraft(drafts[draftKey]) : EMPTY_DRAFT; } export function useStickyComposerModelSelection(): ModelSelection | null { const selection = useAtomValue(stickyComposerModelSelectionAtom); useEffect(() => { ensureComposerDraftsLoaded(); }, []); return selection; }