The best way to control Claude Code, Codex and more from any computer or phone

main
ts 2,240 lines 78.2 KB
Raw
1 import { useAtomValue } from "@effect/atom-react";
2 import { msg } from "gt-react-native";
3 import { m } from "../i18n/messages";
4 import {
5 EnvironmentId as EnvironmentIdSchema,
6 ModelSelection as ModelSelectionSchema,
7 ComposerContextId,
8 ComposerContextRecord,
9 COMPOSER_CONTEXT_MAX_RECORDS,
10 ForwardCompatibleArray,
11 OrchestrationMessageContext,
12 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
13 ProjectId as ProjectIdSchema,
14 ProviderInteractionMode as ProviderInteractionModeSchema,
15 ProviderOptionSelection as ProviderOptionSelectionSchema,
16 RuntimeMode as RuntimeModeSchema,
17 type EnvironmentId,
18 type ModelSelection,
19 type ProjectId,
20 type ProviderInteractionMode,
21 type ProviderOptionSelection,
22 type RuntimeMode,
23 type ScopedThreadRef,
24 type ThreadId,
25 } from "@t3tools/contracts";
26 import * as Schema from "effect/Schema";
27 import { useEffect, useState } from "react";
28 import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
29 import * as Option from "effect/Option";
30 import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment";
31 import type {
32 EnvironmentShellState,
33 EnvironmentThreadShell,
34 } from "@t3tools/client-runtime/state/shell";
35 import { draftModelPickMatchesThread } from "@t3tools/shared/model";
36
37 import { writeFileAtomically } from "../lib/atomic-file";
38 import { createComposerContextHistory, referencedComposerContext } from "../lib/composerContext";
39 import { isQueuedEditDraftKey } from "./queued-edit-draft-key";
40 import {
41 collectComposerContextReferences,
42 formatComposerContextReference,
43 sanitizeComposerContextLabel,
44 replaceComposerContextReferences,
45 } from "@t3tools/shared/composerContextReferences";
46 import { imageMimeType } from "@t3tools/shared/image";
47 import { videoMimeType } from "@t3tools/shared/video";
48 import { DraftComposerAttachmentSchema } from "../lib/composer-image-schema";
49 import {
50 composerAttachmentFileReferenceKey,
51 isComposerAttachmentFileRetained,
52 } from "../lib/composerAttachmentFiles";
53 import {
54 registerComposerAttachmentUnusedHandler,
55 retainComposerAttachmentFileForPreview,
56 } from "../lib/composerAttachmentPreviewRetention";
57 import type { DraftComposerAttachment, FileBackedComposerAttachment } from "../lib/composerImages";
58 import { SerializedAsyncQueue } from "../lib/serialized-async-queue";
59 import { appAtomRegistry } from "./atom-registry";
60 import {
61 abortComposerDraftOperations,
62 abortComposerDraftOperationsWhere,
63 } from "./composerDraftOperations";
64 import {
65 isNewTaskDraftKey,
66 newTaskDraftKey,
67 parseLegacyNewTaskDraftKey,
68 } from "./new-task-draft-key";
69 import {
70 decodeQueuedThreadMessage,
71 encodeQueuedThreadMessage,
72 QueuedThreadMessageSchema,
73 type QueuedThreadMessage,
74 } from "./thread-outbox-model";
75 import { flushThreadOutbox, threadOutboxManager } from "./thread-outbox";
76 import { composerDraftEnvironmentId } from "../lib/composerAttachmentUploadQueue";
77
78 const COMPOSER_DRAFTS_SCHEMA_VERSION = 1;
79 const COMPOSER_DRAFTS_DIRECTORY = "composer-drafts";
80 const COMPOSER_DRAFTS_FILE = "drafts.json";
81 const PERSIST_DEBOUNCE_MS = 200;
82
83 export const composerContextImportsAtom = Atom.make<Record<string, boolean>>({}).pipe(
84 Atom.keepAlive,
85 );
86
87 export function setComposerContextImporting(draftKey: string, importing: boolean): void {
88 const next = { ...appAtomRegistry.get(composerContextImportsAtom) };
89 if (importing) next[draftKey] = true;
90 else delete next[draftKey];
91 appAtomRegistry.set(composerContextImportsAtom, next);
92 }
93
94 interface ComposerDraftSelection {
95 readonly text: string;
96 readonly start: number;
97 readonly end: number;
98 }
99
100 // Keyed by draft so a caret move in one composer neither replaces another draft's caret
101 // nor notifies its readers. Kept alive so the caret survives the composer unmounting.
102 const composerDraftSelectionAtom = Atom.family((_draftKey: string) =>
103 Atom.make<ComposerDraftSelection | null>(null).pipe(
104 Atom.keepAlive,
105 Atom.withLabel("mobile:composer-draft-selection"),
106 ),
107 );
108 const NO_COMPOSER_DRAFT_SELECTION_ATOM = Atom.make<ComposerDraftSelection | null>(null);
109
110 // Never persisted. One counter across drafts, so an editor moved between drafts never
111 // sees a later reset numbered below one it already applied.
112 let lastComposerDraftReset = 0;
113 const composerDraftResetAtom = Atom.family((_draftKey: string) =>
114 Atom.make(0).pipe(Atom.withLabel("mobile:composer-draft-reset")),
115 );
116 const NO_COMPOSER_DRAFT_RESET_ATOM = Atom.make(0);
117
118 function nextComposerDraftReset(): number {
119 lastComposerDraftReset += 1;
120 return lastComposerDraftReset;
121 }
122
123 function markComposerDraftReset(draftKey: string): void {
124 appAtomRegistry.set(composerDraftResetAtom(draftKey), nextComposerDraftReset());
125 }
126
127 /**
128 * Raised when a draft's text is replaced outright (sent, discarded), or when the editor switches
129 * drafts. iOS editor events read it synchronously, so an edit the editor made before applying the
130 * reset cannot restore the text or land in the next draft. Android ignores it.
131 */
132 export function useComposerDraftResetGeneration(draftKey: string | null): () => number {
133 const atom = draftKey === null ? NO_COMPOSER_DRAFT_RESET_ATOM : composerDraftResetAtom(draftKey);
134 // Subscribing re-renders the editor so it sends the reset even when the text did not change.
135 useAtomValue(atom);
136 // The editor stays mounted across drafts (remounting drops the keyboard), so a switch takes a
137 // fresh generation; the selected draft's own, possibly older, stamp would move it backwards.
138 const [selected, setSelected] = useState({ draftKey, generation: 0 });
139 if (selected.draftKey !== draftKey) {
140 setSelected({ draftKey, generation: nextComposerDraftReset() });
141 }
142 return () => Math.max(selected.generation, appAtomRegistry.get(atom));
143 }
144
145 export function rememberComposerDraftSelection(
146 draftKey: string,
147 text: string,
148 selection: { start: number; end: number },
149 ): void {
150 appAtomRegistry.set(composerDraftSelectionAtom(draftKey), { text, ...selection });
151 }
152
153 function matchingComposerDraftSelection(
154 selection: ComposerDraftSelection | null,
155 text: string,
156 ): { start: number; end: number } | null {
157 if (selection?.text !== text) return null;
158 return { start: selection.start, end: selection.end };
159 }
160
161 /** Read the post-chip-insertion selection or the editor restores the pre-insert caret before the chip. */
162 function readComposerDraftSelection(
163 draftKey: string,
164 text: string,
165 ): { start: number; end: number } | null {
166 return matchingComposerDraftSelection(
167 appAtomRegistry.get(composerDraftSelectionAtom(draftKey)),
168 text,
169 );
170 }
171
172 export function useComposerDraftSelection(
173 draftKey: string | null,
174 text: string,
175 ): { start: number; end: number } | null {
176 const selection = useAtomValue(
177 draftKey === null ? NO_COMPOSER_DRAFT_SELECTION_ATOM : composerDraftSelectionAtom(draftKey),
178 );
179 return draftKey === null ? null : matchingComposerDraftSelection(selection, text);
180 }
181
182 export interface ComposerDraftInsertion {
183 readonly text: string;
184 readonly start: number;
185 readonly end: number;
186 }
187
188 export function captureComposerDraftInsertion(
189 draftKey: string,
190 selection?: { start: number; end: number },
191 ): ComposerDraftInsertion {
192 const { text } = getComposerDraftSnapshot(draftKey);
193 return {
194 text,
195 ...(selection ??
196 readComposerDraftSelection(draftKey, text) ?? { start: text.length, end: text.length }),
197 };
198 }
199
200 function mapCapturedRange(
201 captured: ComposerDraftInsertion,
202 text: string,
203 ): { start: number; end: number } | null {
204 if (captured.text === text) return captured;
205 // A replaced selection is not safe to delete after edits; only a caret follows them.
206 if (captured.start !== captured.end) return null;
207 const previous = captured.text;
208 const shared = Math.min(previous.length, text.length);
209 let prefix = 0;
210 while (prefix < shared && previous[prefix] === text[prefix]) prefix += 1;
211 let suffix = 0;
212 while (
213 suffix < shared - prefix &&
214 previous[previous.length - 1 - suffix] === text[text.length - 1 - suffix]
215 ) {
216 suffix += 1;
217 }
218 // Text typed at the caret lands after it, so the insertion stays before that text.
219 if (captured.start <= prefix) return captured;
220 if (captured.start < previous.length - suffix) return null;
221 const caret = captured.start + text.length - previous.length;
222 return { start: caret, end: caret };
223 }
224
225 /** Keep a caret after the insertion where it was, or the next keystroke lands before typed text. */
226 function caretAfterInsertion(
227 draftKey: string,
228 previousText: string,
229 range: { start: number; end: number },
230 inserted: number,
231 ): { start: number; end: number } {
232 const caret = readComposerDraftSelection(draftKey, previousText);
233 if (caret && caret.start > range.end) {
234 const delta = range.start + inserted - range.end;
235 return { start: caret.start + delta, end: caret.end + delta };
236 }
237 return { start: range.start + inserted, end: range.start + inserted };
238 }
239
240 function contextInsertionRange(
241 draftKey: string,
242 draft: ComposerDraft,
243 target?: ComposerDraftInsertion,
244 ) {
245 const captured = target ?? appAtomRegistry.get(composerDraftSelectionAtom(draftKey));
246 // Follow edits made during writes; append when an edit touched the captured range.
247 const selection = captured ? mapCapturedRange(captured, draft.text) : null;
248 const start = Math.max(0, Math.min(selection?.start ?? draft.text.length, draft.text.length));
249 return { start, end: Math.max(start, Math.min(selection?.end ?? start, draft.text.length)) };
250 }
251
252 function draftWithoutInsertionSelection(
253 draftKey: string,
254 draft: ComposerDraft,
255 target?: ComposerDraftInsertion,
256 ) {
257 const { start, end } = contextInsertionRange(draftKey, draft, target);
258 const text = `${draft.text.slice(0, start)} ${draft.text.slice(end)}`;
259 return withReferencedContextFiles(draft, text, referencedComposerContext(text, draft.context));
260 }
261
262 export function countComposerDraftAttachmentsAfterSelection(
263 draftKey: string,
264 target: ComposerDraftInsertion,
265 ): number {
266 return getComposerDraftAfterSelection(draftKey, target).attachments.length;
267 }
268
269 export function getComposerDraftAfterSelection(
270 draftKey: string,
271 target: ComposerDraftInsertion,
272 ): ComposerDraft {
273 return draftWithoutInsertionSelection(draftKey, getComposerDraftSnapshot(draftKey), target);
274 }
275
276 function withReferencedContextFiles(
277 draft: ComposerDraft,
278 text: string,
279 context: OrchestrationMessageContext | undefined,
280 ): ComposerDraft {
281 const previousIds = new Set(
282 draft.context?.records.flatMap((record) =>
283 "attachmentId" in record ? [record.attachmentId] : [],
284 ),
285 );
286 const retainedIds = new Set(
287 context?.records.flatMap((record) => ("attachmentId" in record ? [record.attachmentId] : [])),
288 );
289 const attachments = draft.attachments.filter(
290 (attachment) =>
291 attachment.type === "image" ||
292 !previousIds.has(attachment.id) ||
293 retainedIds.has(attachment.id),
294 );
295 // Keep the array identity on plain text edits so attachment readers see no change.
296 return {
297 ...draft,
298 text,
299 context,
300 attachments: attachments.length === draft.attachments.length ? draft.attachments : attachments,
301 };
302 }
303
304 /** Retains file bytes while native text undo can restore their references. */
305 export function createComposerDraftContextHistory() {
306 const restoreContext = createComposerContextHistory();
307 const files = new Map<
308 string,
309 { attachment: FileBackedComposerAttachment; release: () => void }
310 >();
311 return {
312 restore(text: string, draft: ComposerDraft) {
313 for (const attachment of draft.attachments) {
314 if (attachment.type !== "file") continue;
315 const previous = files.get(attachment.id);
316 files.delete(attachment.id);
317 if (previous?.attachment.fileUri === attachment.fileUri) {
318 previous.attachment = attachment;
319 files.set(attachment.id, previous);
320 } else {
321 previous?.release();
322 files.set(attachment.id, {
323 attachment,
324 release: retainComposerAttachmentFileForPreview(attachment),
325 });
326 }
327 }
328 const limit = Math.max(COMPOSER_CONTEXT_MAX_RECORDS, draft.attachments.length);
329 while (files.size > limit) {
330 const oldest = files.keys().next().value!;
331 files.get(oldest)!.release();
332 files.delete(oldest);
333 }
334 const context = restoreContext(text, draft.context);
335 const liveIds = new Set(draft.attachments.map((attachment) => attachment.id));
336 const attachments = (context?.records ?? []).flatMap((record) => {
337 if (
338 record.kind !== "file" ||
339 !("attachmentId" in record) ||
340 liveIds.has(record.attachmentId)
341 )
342 return [];
343 const saved = files.get(record.attachmentId)?.attachment;
344 liveIds.add(record.attachmentId);
345 return saved
346 ? [{ ...saved, uploadedAttachmentId: undefined, uploadEnvironmentId: undefined }]
347 : [];
348 });
349 return { context, attachments };
350 },
351 dispose() {
352 for (const file of files.values()) file.release();
353 files.clear();
354 },
355 };
356 }
357
358 export function setComposerDraftContext(
359 draftKey: string,
360 context: OrchestrationMessageContext | undefined,
361 ): void {
362 updateComposerDrafts((current) => ({
363 ...current,
364 [draftKey]: { ...normalizeDraft(current[draftKey]), context },
365 }));
366 }
367
368 export function insertComposerDraftContext(
369 draftKey: string,
370 content: {
371 text: string;
372 context: OrchestrationMessageContext;
373 attachments?: ReadonlyArray<DraftComposerAttachment>;
374 },
375 target?: ComposerDraftInsertion,
376 ): boolean {
377 let inserted = false;
378 let removed: ReadonlyArray<DraftComposerAttachment> = [];
379 updateComposerDrafts((current) => {
380 const draft = normalizeDraft(current[draftKey]);
381 const attachments = content.attachments ?? [];
382 const retained = draftWithoutInsertionSelection(draftKey, draft, target);
383 if (
384 attachments.length > 0 &&
385 retained.attachments.length + attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS
386 )
387 return current;
388 const nextDraft = draftWithInsertedContext(
389 draftKey,
390 { ...draft, attachments: [...draft.attachments, ...attachments] },
391 content,
392 target,
393 );
394 if (!nextDraft) return current;
395 inserted = true;
396 removed = draft.attachments.filter((attachment) => !nextDraft.attachments.includes(attachment));
397 return { ...current, [draftKey]: nextDraft };
398 });
399 scheduleUnusedComposerAttachmentCleanup(inserted ? removed : (content.attachments ?? []));
400 return inserted;
401 }
402
403 function draftWithInsertedContext(
404 draftKey: string,
405 draft: ComposerDraft,
406 content: { text: string; context: OrchestrationMessageContext },
407 target?: ComposerDraftInsertion,
408 maxContextRecords = COMPOSER_CONTEXT_MAX_RECORDS,
409 ): ComposerDraft | null {
410 const { start, end } = contextInsertionRange(draftKey, draft, target);
411 const before = draft.text.slice(0, start);
412 const after = draft.text.slice(end);
413 const insertion = `${before.length > 0 && !/\s$/.test(before) && !/^\s/.test(content.text) ? " " : ""}${content.text}${!/\s$/.test(content.text) && (after.length === 0 || !/^\s/.test(after)) ? " " : ""}`;
414 const text = before + insertion + after;
415 const records = new Map(draft.context?.records.map((record) => [record.contextId, record]));
416 for (const record of content.context.records) records.set(record.contextId, record);
417 const context = referencedComposerContext(text, { version: 1, records: [...records.values()] });
418 if ((context?.records.length ?? 0) > maxContextRecords) return null;
419 rememberComposerDraftSelection(
420 draftKey,
421 text,
422 caretAfterInsertion(draftKey, draft.text, { start, end }, insertion.length),
423 );
424 return withReferencedContextFiles(draft, text, context);
425 }
426
427 export class ComposerDraftPersistenceError extends Schema.TaggedError<ComposerDraftPersistenceError>()(
428 "ComposerDraftPersistenceError",
429 {
430 operation: Schema.Literals(["open", "read", "decode", "encode", "write", "hydrate"]),
431 directory: Schema.String,
432 fileName: Schema.String,
433 cause: Schema.Defect(),
434 },
435 ) {
436 override get message(): string {
437 return `Composer draft persistence operation ${this.operation} failed for ${this.directory}/${this.fileName}.`;
438 }
439 }
440
441 const isComposerDraftPersistenceError = Schema.is(ComposerDraftPersistenceError);
442
443 export interface ComposerDraft {
444 readonly text: string;
445 readonly context?: OrchestrationMessageContext;
446 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
447 readonly importedShareIds?: ReadonlyArray<string>;
448 readonly modelSelection?: ModelSelection;
449 readonly runtimeMode?: RuntimeMode;
450 readonly interactionMode?: ProviderInteractionMode;
451 /** `/clear` armed this draft: its next message starts a fresh provider session. */
452 readonly freshContext?: boolean;
453 readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
454 readonly project?: ComposerDraftProject;
455 }
456
457 export interface ComposerDraftProject {
458 readonly environmentId: EnvironmentId;
459 readonly projectId: ProjectId;
460 readonly createdAt: string;
461 }
462
463 export interface ComposerDraftContent {
464 readonly text: string;
465 readonly context?: OrchestrationMessageContext;
466 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
467 readonly sourceShareId?: string;
468 }
469
470 export interface ComposerDraftWorkspaceSelection {
471 readonly mode: "local" | "worktree";
472 readonly branch: string | null;
473 readonly worktreePath: string | null;
474 readonly startFromOrigin?: boolean;
475 readonly pullRequestReference?: string;
476 /**
477 * Local mode chosen before refs named the current branch. It is never cleared when refs load:
478 * a local task runs on the checkout, so the draft keeps following it (a later checkout change
479 * included) until the user picks a branch, rather than pinning the first name refs reported.
480 */
481 readonly followsCurrentCheckout?: boolean;
482 }
483
484 export type ComposerDraftSettingsUpdate = Pick<
485 ComposerDraft,
486 | "modelSelection"
487 | "runtimeMode"
488 | "interactionMode"
489 | "freshContext"
490 | "workspaceSelection"
491 | "project"
492 >;
493
494 const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
495 mode: Schema.Literals(["local", "worktree"]),
496 branch: Schema.NullOr(Schema.String),
497 worktreePath: Schema.NullOr(Schema.String),
498 startFromOrigin: Schema.optional(Schema.Boolean),
499 pullRequestReference: Schema.optional(Schema.String),
500 followsCurrentCheckout: Schema.optional(Schema.Boolean),
501 });
502
503 const ComposerDraftProjectSchema = Schema.Struct({
504 environmentId: EnvironmentIdSchema,
505 projectId: ProjectIdSchema,
506 createdAt: Schema.String,
507 });
508
509 // Recovery can exceed send limits; keep payloads reloadable and let send guards request trimming.
510 const PersistedComposerContextSchema = Schema.Struct({
511 version: Schema.Literal(1),
512 records: ForwardCompatibleArray(ComposerContextRecord),
513 });
514
515 const ComposerDraftSchema = Schema.Struct({
516 text: Schema.String,
517 context: Schema.optional(PersistedComposerContextSchema),
518 attachments: Schema.Array(DraftComposerAttachmentSchema),
519 importedShareIds: Schema.optional(Schema.Array(Schema.String)),
520 modelSelection: Schema.optional(ModelSelectionSchema),
521 runtimeMode: Schema.optional(RuntimeModeSchema),
522 interactionMode: Schema.optional(ProviderInteractionModeSchema),
523 freshContext: Schema.optional(Schema.Boolean),
524 workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema),
525 project: Schema.optional(ComposerDraftProjectSchema),
526 });
527
528 const PersistedComposerDraftsSchema = Schema.Struct({
529 schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION),
530 drafts: Schema.Record(Schema.String, ComposerDraftSchema),
531 stickyModelSelection: Schema.optional(ModelSelectionSchema),
532 modelOptionMemory: Schema.optional(
533 Schema.Record(
534 Schema.String,
535 Schema.Record(Schema.String, Schema.Array(ProviderOptionSelectionSchema)),
536 ),
537 ),
538 cloudAccountId: Schema.optional(Schema.String),
539 signedOutDrafts: Schema.optional(
540 Schema.Record(
541 Schema.String,
542 Schema.Struct({
543 drafts: Schema.Record(Schema.String, ComposerDraftSchema),
544 queuedMessages: Schema.Array(QueuedThreadMessageSchema),
545 }),
546 ),
547 ),
548 });
549
550 const decodePersistedComposerDraftsDocument = Schema.decodeUnknownSync(
551 PersistedComposerDraftsSchema,
552 );
553
554 const EMPTY_DRAFT: ComposerDraft = {
555 text: "",
556 attachments: [],
557 };
558
559 export const composerDraftsAtom = Atom.make<Record<string, ComposerDraft>>({}).pipe(
560 Atom.keepAlive,
561 Atom.withLabel("mobile:composer-drafts"),
562 );
563
564 /**
565 * Whether persisted drafts have merged in. Hydration starts with the app's
566 * attachment upload worker; a failed load stays false until the next
567 * `ensureComposerDraftsLoaded` caller retries it.
568 */
569 export const composerDraftsLoadedAtom = Atom.make(false).pipe(
570 Atom.keepAlive,
571 Atom.withLabel("mobile:composer-drafts-loaded"),
572 );
573
574 export const stickyComposerModelSelectionAtom = Atom.make<ModelSelection | null>(null).pipe(
575 Atom.keepAlive,
576 Atom.withLabel("mobile:sticky-composer-model-selection"),
577 );
578
579 export type ModelOptionMemoryState = Readonly<
580 Record<string, Readonly<Record<string, ReadonlyArray<ProviderOptionSelection>>>>
581 >;
582
583 export const modelOptionMemoryAtom = Atom.make<ModelOptionMemoryState>({}).pipe(
584 Atom.keepAlive,
585 Atom.withLabel("mobile:model-option-memory"),
586 );
587
588 interface SignedOutDrafts {
589 readonly drafts: Record<string, ComposerDraft>;
590 readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
591 }
592
593 interface ComposerCloudDraftState {
594 readonly accountId: string | null;
595 readonly signedOut: Record<string, SignedOutDrafts>;
596 }
597
598 export const composerCloudDraftsAtom = Atom.make<ComposerCloudDraftState>({
599 accountId: null,
600 signedOut: {},
601 }).pipe(Atom.keepAlive);
602
603 let loadPromise: Promise<void> | null = null;
604 let persistTimer: ReturnType<typeof setTimeout> | null = null;
605 let persistRetryNeeded = false;
606 const persistenceQueue = new SerializedAsyncQueue();
607
608 export function resetComposerDraftsLoadState(): void {
609 loadPromise = null;
610 appAtomRegistry.set(composerDraftsLoadedAtom, false);
611 persistRetryNeeded = false;
612 }
613
614 function attachmentContextRecord(
615 attachment: DraftComposerAttachment,
616 contextId = ComposerContextId.make(attachment.id),
617 ) {
618 const common = {
619 version: 1 as const,
620 contextId,
621 label: sanitizeComposerContextLabel(attachment.name, attachment.type),
622 attachmentId: attachment.id,
623 name: attachment.name,
624 mimeType: attachment.mimeType,
625 sizeBytes: attachment.sizeBytes,
626 };
627 // Document pickers label images as files; promote the record so every client can open them as images.
628 return attachment.type === "image" || imageMimeType(attachment) !== null
629 ? { ...common, kind: "image" as const }
630 : { ...common, kind: "file" as const };
631 }
632
633 function restoreMissingComposerFileReferences(
634 draft: ComposerDraft,
635 attachments = draft.attachments,
636 ): ComposerDraft {
637 const records = [...(draft.context?.records ?? [])];
638 const usedIds = new Set<string>(records.map((record) => record.contextId));
639 const referenced = new Set(
640 collectComposerContextReferences(draft.text).map(
641 (reference) => `${reference.kind}:${reference.contextId}`,
642 ),
643 );
644 let text = draft.text;
645 let changed = false;
646 for (const attachment of attachments) {
647 if (
648 attachment.type === "image" ||
649 imageMimeType(attachment) !== null ||
650 videoMimeType(attachment) !== null
651 )
652 continue;
653 let record = records.find(
654 (candidate) =>
655 candidate.kind === "file" &&
656 "attachmentId" in candidate &&
657 candidate.attachmentId === attachment.id,
658 );
659 if (!record) {
660 const baseId = attachment.id.replace(/[^a-z0-9_-]/gi, "_").slice(0, 110) || "file";
661 let contextId = baseId;
662 for (let suffix = 2; usedIds.has(contextId); suffix += 1) contextId = `${baseId}_${suffix}`;
663 usedIds.add(contextId);
664 record = attachmentContextRecord(attachment, ComposerContextId.make(contextId));
665 records.push(record);
666 changed = true;
667 }
668 const key = `${record.kind}:${record.contextId}`;
669 if (referenced.has(key)) continue;
670 text += `${text.length > 0 && !/\s$/.test(text) ? " " : ""}${formatComposerContextReference(record)} `;
671 referenced.add(key);
672 changed = true;
673 }
674 return changed ? { ...draft, text, context: { version: 1, records } } : draft;
675 }
676
677 function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
678 if (!draft) {
679 return EMPTY_DRAFT;
680 }
681 return {
682 ...draft,
683 text: draft.text,
684 attachments: draft.attachments,
685 };
686 }
687
688 export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
689 return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
690 }
691
692 export function isComposerDraftEmpty(draft: ComposerDraft): boolean {
693 return isEmptyDraft(draft);
694 }
695
696 function isEmptyDraft(draft: ComposerDraft): boolean {
697 return (
698 draft.text.length === 0 &&
699 draft.attachments.length === 0 &&
700 draft.modelSelection === undefined &&
701 draft.runtimeMode === undefined &&
702 draft.interactionMode === undefined &&
703 draft.freshContext !== true &&
704 draft.workspaceSelection === undefined
705 );
706 }
707
708 function withComposerDraft(
709 current: Record<string, ComposerDraft>,
710 draftKey: string,
711 draft: ComposerDraft,
712 ): Record<string, ComposerDraft> {
713 if (isEmptyDraft(draft) && draft.project === undefined) {
714 const next = { ...current };
715 delete next[draftKey];
716 return next;
717 }
718 return { ...current, [draftKey]: draft };
719 }
720
721 export { isNewTaskDraftKey, newTaskDraftKey } from "./new-task-draft-key";
722
723 function newDraftId(): string {
724 return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
725 }
726
727 export function migrateLegacyNewTaskDraft(
728 key: string,
729 draft: ComposerDraft,
730 now: string,
731 ): readonly [key: string, draft: ComposerDraft] {
732 const restored = restoreMissingComposerFileReferences(draft);
733 const legacy = draft.project === undefined ? parseLegacyNewTaskDraftKey(key) : null;
734 if (legacy === null) {
735 return [key, restored];
736 }
737 return [
738 newTaskDraftKey(newDraftId()),
739 {
740 ...restored,
741 project: {
742 environmentId: EnvironmentIdSchema.make(legacy.environmentId),
743 projectId: ProjectIdSchema.make(legacy.projectId),
744 createdAt: now,
745 },
746 },
747 ];
748 }
749
750 export function decodePersistedComposerState(value: unknown): {
751 readonly drafts: Record<string, ComposerDraft>;
752 readonly stickyModelSelection: ModelSelection | null;
753 readonly modelOptionMemory: ModelOptionMemoryState;
754 readonly cloudDrafts: ComposerCloudDraftState;
755 } {
756 const parsed = decodePersistedComposerDraftsDocument(value);
757 const now = new Date().toISOString();
758 return {
759 drafts: Object.fromEntries(
760 Object.entries(parsed.drafts)
761 .map(([key, draft]) =>
762 migrateLegacyNewTaskDraft(
763 key,
764 isNewTaskDraftKey(key) &&
765 draft.modelSelection &&
766 draft.text.length === 0 &&
767 draft.attachments.length === 0 &&
768 draft.runtimeMode === undefined &&
769 draft.interactionMode === undefined &&
770 draft.workspaceSelection === undefined
771 ? { ...draft, modelSelection: undefined }
772 : draft,
773 now,
774 ),
775 )
776 // Retain contentless drafts with import receipts to prevent re-importing native shares after restart.
777 .filter(([, draft]) => !isEmptyDraft(draft) || (draft.importedShareIds?.length ?? 0) > 0)
778 // Queued-edit sessions are memory-only; persisted drafts would outlive their run association and become unreachable.
779 .filter(([key]) => !isQueuedEditDraftKey(key)),
780 ),
781 stickyModelSelection: parsed.stickyModelSelection ?? null,
782 modelOptionMemory: parsed.modelOptionMemory ?? {},
783 cloudDrafts: {
784 accountId: parsed.cloudAccountId ?? null,
785 signedOut: Object.fromEntries(
786 Object.entries(parsed.signedOutDrafts ?? {}).map(([id, saved]) => [
787 id,
788 {
789 drafts: Object.fromEntries(
790 Object.entries(saved.drafts).map(([key, draft]) =>
791 migrateLegacyNewTaskDraft(key, draft, now),
792 ),
793 ),
794 queuedMessages: saved.queuedMessages.map(decodeQueuedThreadMessage),
795 },
796 ]),
797 ),
798 },
799 };
800 }
801
802 async function getComposerDraftsFile() {
803 const { Directory, File, Paths } = await import("expo-file-system");
804 const directory = new Directory(Paths.document, COMPOSER_DRAFTS_DIRECTORY);
805 directory.create({ idempotent: true, intermediates: true });
806 return new File(directory, COMPOSER_DRAFTS_FILE);
807 }
808
809 async function loadPersistedComposerState(): Promise<
810 ReturnType<typeof decodePersistedComposerState>
811 > {
812 let operation: ComposerDraftPersistenceError["operation"] = "open";
813 try {
814 const file = await getComposerDraftsFile();
815 if (!file.exists) {
816 return {
817 drafts: {},
818 stickyModelSelection: null,
819 modelOptionMemory: {},
820 cloudDrafts: { accountId: null, signedOut: {} },
821 };
822 }
823 operation = "read";
824 const raw = await file.text();
825 operation = "decode";
826 return decodePersistedComposerState(JSON.parse(raw) as unknown);
827 } catch (cause) {
828 throw new ComposerDraftPersistenceError({
829 operation,
830 directory: COMPOSER_DRAFTS_DIRECTORY,
831 fileName: COMPOSER_DRAFTS_FILE,
832 cause,
833 });
834 }
835 }
836
837 async function writePersistedComposerState(
838 drafts: Record<string, ComposerDraft>,
839 stickyModelSelection: ModelSelection | null,
840 cloudDrafts = appAtomRegistry.get(composerCloudDraftsAtom),
841 ): Promise<void> {
842 let operation: ComposerDraftPersistenceError["operation"] = "open";
843 try {
844 const file = await getComposerDraftsFile();
845 operation = "encode";
846 const nonEmptyDrafts = Object.fromEntries(
847 Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
848 );
849 const document = {
850 schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
851 drafts: nonEmptyDrafts,
852 ...(stickyModelSelection ? { stickyModelSelection } : {}),
853 ...(Object.keys(appAtomRegistry.get(modelOptionMemoryAtom)).length > 0
854 ? { modelOptionMemory: appAtomRegistry.get(modelOptionMemoryAtom) }
855 : {}),
856 ...(cloudDrafts.accountId ? { cloudAccountId: cloudDrafts.accountId } : {}),
857 ...(Object.keys(cloudDrafts.signedOut).length > 0
858 ? {
859 signedOutDrafts: Object.fromEntries(
860 Object.entries(cloudDrafts.signedOut).map(([id, saved]) => [
861 id,
862 {
863 drafts: saved.drafts,
864 queuedMessages: saved.queuedMessages.map(encodeQueuedThreadMessage),
865 },
866 ]),
867 ),
868 }
869 : {}),
870 } as const;
871 const encoded = JSON.stringify(document);
872 operation = "write";
873 await writeFileAtomically(file, encoded);
874 } catch (cause) {
875 throw new ComposerDraftPersistenceError({
876 operation,
877 directory: COMPOSER_DRAFTS_DIRECTORY,
878 fileName: COMPOSER_DRAFTS_FILE,
879 cause,
880 });
881 }
882 }
883
884 /** Propagates write failures so callers can decide whether to restart. */
885 export async function flushComposerDrafts(): Promise<void> {
886 // Hydrate before writing or partial atom state would clobber persisted drafts.
887 ensureComposerDraftsLoaded();
888 if (loadPromise !== null) {
889 await loadPromise;
890 }
891 // Edits during writes schedule more debounces; drain until none remain.
892 do {
893 while (persistTimer !== null || persistRetryNeeded) {
894 if (persistTimer !== null) clearTimeout(persistTimer);
895 persistTimer = null;
896 persistRetryNeeded = false;
897 try {
898 await persistenceQueue.run(() =>
899 writePersistedComposerState(
900 appAtomRegistry.get(composerDraftsAtom),
901 appAtomRegistry.get(stickyComposerModelSelectionAtom),
902 ),
903 );
904 } catch (error) {
905 persistRetryNeeded = true;
906 throw error;
907 }
908 }
909 // Draining includes fired debounce writes still awaiting hydration inside the queue.
910 await persistenceQueue.run(() => Promise.resolve());
911 } while (persistTimer !== null || persistRetryNeeded);
912 }
913
914 function signedOutAttachmentOwners() {
915 return Object.values(appAtomRegistry.get(composerCloudDraftsAtom).signedOut).flatMap((saved) => [
916 ...Object.values(saved.drafts),
917 ...saved.queuedMessages,
918 ]);
919 }
920
921 export function findLocalComposerClipboardAttachment(
922 knownEnvironmentIds: Iterable<EnvironmentId>,
923 environmentId: EnvironmentId,
924 id: string,
925 ): DraftComposerAttachment | undefined {
926 const queuedMessages = Object.values(
927 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
928 ).flat();
929 for (const [key, draft] of Object.entries(appAtomRegistry.get(composerDraftsAtom))) {
930 if (
931 composerDraftEnvironmentId(key, knownEnvironmentIds, queuedMessages, draft) !== environmentId
932 )
933 continue;
934 const attachment = draft.attachments.find((entry) => entry.id === id);
935 if (attachment) return attachment;
936 }
937 return queuedMessages
938 .filter((message) => message.environmentId === environmentId)
939 .flatMap((message) => message.attachments)
940 .find((attachment) => attachment.id === id);
941 }
942
943 function isComposerAttachmentFileReferenced(fileUri: string): boolean {
944 if (isComposerAttachmentFileRetained(fileUri)) {
945 return true;
946 }
947 const referenceKey = composerAttachmentFileReferenceKey(fileUri);
948 const drafts = Object.values(appAtomRegistry.get(composerDraftsAtom));
949 const queuedMessages = Object.values(
950 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
951 ).flat();
952 return [...drafts, ...queuedMessages, ...signedOutAttachmentOwners()].some((owner) =>
953 owner.attachments.some(
954 (attachment) =>
955 attachment.fileUri !== undefined &&
956 composerAttachmentFileReferenceKey(attachment.fileUri) === referenceKey,
957 ),
958 );
959 }
960
961 function isComposerAttachmentUploadReferenced(
962 environmentId: EnvironmentId,
963 attachmentId: string,
964 ): boolean {
965 const drafts = Object.values(appAtomRegistry.get(composerDraftsAtom));
966 const queuedMessages = Object.values(
967 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
968 ).flat();
969 return [...drafts, ...queuedMessages, ...signedOutAttachmentOwners()].some((owner) =>
970 owner.attachments.some(
971 (attachment) =>
972 attachment.uploadEnvironmentId === environmentId &&
973 attachment.uploadedAttachmentId === attachmentId,
974 ),
975 );
976 }
977
978 export async function releaseUnusedComposerAttachmentFiles(
979 attachments: ReadonlyArray<DraftComposerAttachment>,
980 ): Promise<void> {
981 const candidates = new Set(
982 attachments.flatMap((attachment) =>
983 attachment.fileUri !== undefined ? [attachment.fileUri] : [],
984 ),
985 );
986 const uploadCandidates = new Map<EnvironmentId, Set<string>>();
987 for (const attachment of attachments) {
988 if (
989 attachment.uploadEnvironmentId === undefined ||
990 attachment.uploadedAttachmentId === undefined
991 ) {
992 continue;
993 }
994 const ids = uploadCandidates.get(attachment.uploadEnvironmentId) ?? new Set<string>();
995 ids.add(attachment.uploadedAttachmentId);
996 uploadCandidates.set(attachment.uploadEnvironmentId, ids);
997 }
998 if (candidates.size === 0 && uploadCandidates.size === 0) {
999 return;
1000 }
1001
1002 // Hydrate before scanning references; cold-start atoms would otherwise mark owned files unused.
1003 await waitForComposerDraftsLoaded();
1004 await flushComposerDrafts();
1005 if (!(await threadOutboxManager.load())) {
1006 // Unreadable outbox stores may still own files; do not treat them as empty.
1007 return;
1008 }
1009 await flushThreadOutbox();
1010
1011 const allFilesReferenced = [...candidates].every(isComposerAttachmentFileReferenced);
1012 const allUploadsReferenced = [...uploadCandidates].every(([environmentId, attachmentIds]) =>
1013 [...attachmentIds].every((attachmentId) =>
1014 isComposerAttachmentUploadReferenced(environmentId, attachmentId),
1015 ),
1016 );
1017 if (allFilesReferenced && allUploadsReferenced) {
1018 return;
1019 }
1020
1021 let incomingShareFileUris: ReadonlySet<string>;
1022 try {
1023 const { loadIncomingShareDrafts } = await import("../features/sharing/incoming-share-storage");
1024 const incomingShares = await loadIncomingShareDrafts({ strict: true });
1025 incomingShareFileUris = new Set(
1026 incomingShares.flatMap((share) =>
1027 share.attachments.flatMap((attachment) =>
1028 attachment.fileUri !== undefined
1029 ? [composerAttachmentFileReferenceKey(attachment.fileUri)]
1030 : [],
1031 ),
1032 ),
1033 );
1034 } catch (error) {
1035 console.warn("[composer-attachments] could not verify incoming share ownership", error);
1036 return;
1037 }
1038
1039 const { removePersistedComposerAttachmentFile } = await import("../lib/composerImages");
1040 for (const fileUri of candidates) {
1041 // Re-check immediately before deletion; restores or edits can acquire ownership after scanning.
1042 if (
1043 isComposerAttachmentFileReferenced(fileUri) ||
1044 incomingShareFileUris.has(composerAttachmentFileReferenceKey(fileUri))
1045 ) {
1046 continue;
1047 }
1048 await removePersistedComposerAttachmentFile(fileUri);
1049 }
1050
1051 if (uploadCandidates.size > 0) {
1052 const { releasePendingAttachmentUploads } = await import("../lib/attachmentUpload");
1053 for (const [environmentId, attachmentIds] of uploadCandidates) {
1054 for (const attachmentId of attachmentIds) {
1055 if (isComposerAttachmentUploadReferenced(environmentId, attachmentId)) {
1056 continue;
1057 }
1058 try {
1059 await releasePendingAttachmentUploads(environmentId, [attachmentId]);
1060 } catch (error) {
1061 // The server expires pending uploads; local discard must survive disconnection or deletion failure.
1062 console.warn("[composer-attachments] could not remove pending upload", {
1063 environmentId,
1064 attachmentId,
1065 error,
1066 });
1067 }
1068 }
1069 }
1070 }
1071 }
1072
1073 export function scheduleUnusedComposerAttachmentCleanup(
1074 attachments: ReadonlyArray<DraftComposerAttachment>,
1075 ): void {
1076 if (
1077 !attachments.some(
1078 (attachment) =>
1079 attachment.fileUri !== undefined || attachment.uploadedAttachmentId !== undefined,
1080 )
1081 ) {
1082 return;
1083 }
1084 void releaseUnusedComposerAttachmentFiles(attachments).catch((error) => {
1085 console.warn("[composer-attachments] could not remove unused files", error);
1086 });
1087 }
1088
1089 registerComposerAttachmentUnusedHandler((attachment) => {
1090 scheduleUnusedComposerAttachmentCleanup([attachment]);
1091 });
1092
1093 export function schedulePersistComposerState(): void {
1094 if (persistTimer !== null) {
1095 clearTimeout(persistTimer);
1096 }
1097 persistTimer = setTimeout(() => {
1098 persistTimer = null;
1099 // Enqueue before awaiting hydration so flushComposerDrafts cannot drain ahead of this write.
1100 void persistenceQueue.run(async () => {
1101 try {
1102 await waitForComposerDraftsLoaded();
1103 await writePersistedComposerState(
1104 appAtomRegistry.get(composerDraftsAtom),
1105 appAtomRegistry.get(stickyComposerModelSelectionAtom),
1106 );
1107 persistRetryNeeded = false;
1108 } catch (error) {
1109 // Failed debounces leave no timer; final flush must retry after reading persisted ownership.
1110 persistRetryNeeded = true;
1111 console.warn("[composer-drafts] failed to persist drafts", error);
1112 }
1113 });
1114 }, PERSIST_DEBOUNCE_MS);
1115 }
1116
1117 export function ensureComposerDraftsLoaded(): void {
1118 if (loadPromise !== null) {
1119 return;
1120 }
1121 const loading = loadPersistedComposerState().then((persisted) => {
1122 appAtomRegistry.set(composerCloudDraftsAtom, persisted.cloudDrafts);
1123 if (Object.keys(persisted.drafts).length > 0) {
1124 const current = appAtomRegistry.get(composerDraftsAtom);
1125 appAtomRegistry.set(composerDraftsAtom, {
1126 ...persisted.drafts,
1127 ...current,
1128 });
1129 }
1130 if (
1131 persisted.stickyModelSelection !== null &&
1132 appAtomRegistry.get(stickyComposerModelSelectionAtom) === null
1133 ) {
1134 appAtomRegistry.set(stickyComposerModelSelectionAtom, persisted.stickyModelSelection);
1135 }
1136 if (Object.keys(persisted.modelOptionMemory).length > 0) {
1137 const current = appAtomRegistry.get(modelOptionMemoryAtom);
1138 appAtomRegistry.set(modelOptionMemoryAtom, {
1139 ...persisted.modelOptionMemory,
1140 ...Object.fromEntries(
1141 Object.entries(current).map(([instanceId, models]) => [
1142 instanceId,
1143 { ...persisted.modelOptionMemory[instanceId], ...models },
1144 ]),
1145 ),
1146 });
1147 }
1148 appAtomRegistry.set(composerDraftsLoadedAtom, true);
1149 });
1150 loadPromise = loading;
1151 void loading.catch((cause) => {
1152 if (loadPromise === loading) loadPromise = null;
1153 console.warn(
1154 "[composer-drafts] failed to hydrate drafts",
1155 isComposerDraftPersistenceError(cause)
1156 ? cause
1157 : new ComposerDraftPersistenceError({
1158 operation: "hydrate",
1159 directory: COMPOSER_DRAFTS_DIRECTORY,
1160 fileName: COMPOSER_DRAFTS_FILE,
1161 cause,
1162 }),
1163 );
1164 });
1165 }
1166
1167 export async function waitForComposerDraftsLoaded(): Promise<void> {
1168 ensureComposerDraftsLoaded();
1169 if (loadPromise !== null) {
1170 await loadPromise;
1171 }
1172 }
1173
1174 export async function getComposerCloudAccountId(): Promise<string | null> {
1175 await waitForComposerDraftsLoaded();
1176 return appAtomRegistry.get(composerCloudDraftsAtom).accountId;
1177 }
1178
1179 export async function archiveCloudComposerDrafts(
1180 accountId: string | null,
1181 environmentIds: ReadonlySet<EnvironmentId>,
1182 knownEnvironmentIds: Iterable<EnvironmentId>,
1183 ): Promise<void> {
1184 await waitForComposerDraftsLoaded();
1185 if (!(await threadOutboxManager.load()))
1186 throw new Error(m(msg("Could not preserve queued messages.")));
1187 await flushThreadOutbox();
1188 const cloud = appAtomRegistry.get(composerCloudDraftsAtom);
1189 const owner = accountId ?? cloud.accountId;
1190 if (owner === null) return;
1191 const queued = Object.values(
1192 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
1193 ).flat();
1194 const current = appAtomRegistry.get(composerDraftsAtom);
1195 const remaining = { ...current };
1196 const savedDrafts = { ...cloud.signedOut[owner]?.drafts };
1197 for (const [key, draft] of Object.entries(current)) {
1198 const environmentId = composerDraftEnvironmentId(key, knownEnvironmentIds, queued, draft);
1199 if (environmentId !== null && environmentIds.has(environmentId)) {
1200 savedDrafts[key] = draft;
1201 delete remaining[key];
1202 }
1203 }
1204 const savedMessages = new Map(
1205 (cloud.signedOut[owner]?.queuedMessages ?? []).map((message) => [message.messageId, message]),
1206 );
1207 for (const message of queued) {
1208 if (environmentIds.has(message.environmentId)) savedMessages.set(message.messageId, message);
1209 }
1210 appAtomRegistry.set(composerDraftsAtom, remaining);
1211 appAtomRegistry.set(composerCloudDraftsAtom, {
1212 // Retain the owner through removal so cold-start cleanup can retry before another account activates.
1213 accountId: owner,
1214 signedOut: {
1215 ...cloud.signedOut,
1216 [owner]: { drafts: savedDrafts, queuedMessages: [...savedMessages.values()] },
1217 },
1218 });
1219 schedulePersistComposerState();
1220 await flushComposerDrafts();
1221 }
1222
1223 function sameDraftAttachmentIds(
1224 left: ReadonlyArray<DraftComposerAttachment>,
1225 right: ReadonlyArray<DraftComposerAttachment>,
1226 ): boolean {
1227 return (
1228 left.length === right.length &&
1229 left.every((attachment, index) => attachment.id === right[index]?.id)
1230 );
1231 }
1232
1233 /** An in-flight delivery can finish after sign-out took its snapshot. */
1234 export async function removeDeliveredCloudQueuedMessage(
1235 message: QueuedThreadMessage,
1236 ): Promise<void> {
1237 await waitForComposerDraftsLoaded();
1238 const cloud = appAtomRegistry.get(composerCloudDraftsAtom);
1239 const signedOut = { ...cloud.signedOut };
1240 let changed = false;
1241 for (const [accountId, saved] of Object.entries(signedOut)) {
1242 const archived = saved.queuedMessages.find(
1243 (candidate) =>
1244 candidate.environmentId === message.environmentId &&
1245 candidate.messageId === message.messageId,
1246 );
1247 if (
1248 !archived ||
1249 archived.commandId !== message.commandId ||
1250 archived.threadId !== message.threadId ||
1251 archived.text !== message.text ||
1252 !sameDraftAttachmentIds(archived.attachments, message.attachments)
1253 )
1254 continue;
1255 if (
1256 JSON.stringify([
1257 archived.modelSelection,
1258 archived.runtimeMode,
1259 archived.interactionMode,
1260 archived.creation,
1261 ]) !==
1262 JSON.stringify([
1263 message.modelSelection,
1264 message.runtimeMode,
1265 message.interactionMode,
1266 message.creation,
1267 ])
1268 )
1269 continue;
1270 const editorKey = `pending-task:${message.messageId}`;
1271 const editor = saved.drafts[editorKey];
1272 if (
1273 editor &&
1274 (editor.text !== message.text ||
1275 !sameDraftAttachmentIds(editor.attachments, message.attachments) ||
1276 (editor.modelSelection !== undefined &&
1277 JSON.stringify(editor.modelSelection) !== JSON.stringify(message.modelSelection)) ||
1278 (editor.runtimeMode !== undefined && editor.runtimeMode !== message.runtimeMode) ||
1279 (editor.interactionMode !== undefined &&
1280 editor.interactionMode !== message.interactionMode) ||
1281 (editor.workspaceSelection !== undefined &&
1282 (editor.workspaceSelection.mode !== message.creation?.workspaceMode ||
1283 editor.workspaceSelection.branch !== message.creation?.branch ||
1284 editor.workspaceSelection.worktreePath !== message.creation?.worktreePath ||
1285 editor.workspaceSelection.pullRequestReference !==
1286 message.creation?.pullRequestReference ||
1287 (editor.workspaceSelection.startFromOrigin ?? false) !==
1288 (message.creation?.startFromOrigin ?? false))))
1289 )
1290 continue;
1291 const drafts = { ...saved.drafts };
1292 delete drafts[editorKey];
1293 signedOut[accountId] = {
1294 drafts,
1295 queuedMessages: saved.queuedMessages.filter((candidate) => candidate !== archived),
1296 };
1297 changed = true;
1298 }
1299 if (!changed) return;
1300 appAtomRegistry.set(composerCloudDraftsAtom, { ...cloud, signedOut });
1301 schedulePersistComposerState();
1302 try {
1303 await flushComposerDrafts();
1304 } catch (error) {
1305 // Keep archive updates pending after failure; live outbox removal can still require a later successful flush.
1306 schedulePersistComposerState();
1307 throw error;
1308 }
1309 }
1310
1311 export async function restoreCloudComposerDrafts(accountId: string): Promise<void> {
1312 await waitForComposerDraftsLoaded();
1313 const cloud = appAtomRegistry.get(composerCloudDraftsAtom);
1314 const saved = cloud.signedOut[accountId];
1315 if (saved) {
1316 if (!(await threadOutboxManager.load()))
1317 throw new Error(m(msg("Could not restore queued messages.")));
1318 for (const message of saved.queuedMessages) {
1319 const alreadyQueued = Object.values(
1320 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
1321 )
1322 .flat()
1323 .some((current) => current.messageId === message.messageId);
1324 if (!alreadyQueued) await threadOutboxManager.enqueue(message);
1325 }
1326 updateComposerDrafts((current) => {
1327 const restored = { ...current };
1328 for (const [key, draft] of Object.entries(saved.drafts)) {
1329 const existing = current[key];
1330 const attachmentIds = new Set(existing?.attachments.map((attachment) => attachment.id));
1331 restored[key] = existing
1332 ? {
1333 ...draft,
1334 ...existing,
1335 text: mergeComposerDraftText(existing.text, draft.text),
1336 context: mergeReferencedComposerContext(
1337 mergeComposerDraftText(existing.text, draft.text),
1338 draft.context,
1339 existing.context,
1340 ),
1341 // A concurrent import must not lose files, even above the send limit.
1342 attachments: [
1343 ...existing.attachments,
1344 ...draft.attachments.filter((attachment) => !attachmentIds.has(attachment.id)),
1345 ],
1346 importedShareIds: [
1347 ...new Set([
1348 ...(existing.importedShareIds ?? []),
1349 ...(draft.importedShareIds ?? []),
1350 ]),
1351 ],
1352 }
1353 : draft;
1354 }
1355 return restored;
1356 });
1357 }
1358 const signedOut = { ...cloud.signedOut };
1359 delete signedOut[accountId];
1360 appAtomRegistry.set(composerCloudDraftsAtom, { accountId, signedOut });
1361 schedulePersistComposerState();
1362 await flushComposerDrafts();
1363 }
1364
1365 function updateComposerDrafts(
1366 update: (current: Record<string, ComposerDraft>) => Record<string, ComposerDraft>,
1367 ): void {
1368 const current = appAtomRegistry.get(composerDraftsAtom);
1369 const next = update(current);
1370 if (next === current) {
1371 return;
1372 }
1373 appAtomRegistry.set(composerDraftsAtom, next);
1374 schedulePersistComposerState();
1375 }
1376
1377 export function setStickyComposerModelSelection(modelSelection: ModelSelection): void {
1378 appAtomRegistry.set(stickyComposerModelSelectionAtom, modelSelection);
1379 schedulePersistComposerState();
1380 }
1381
1382 export function setComposerDraftText(draftKey: string, value: string): void {
1383 let removed: ReadonlyArray<DraftComposerAttachment> = [];
1384 updateComposerDrafts((current) => {
1385 const existing = normalizeDraft(current[draftKey]);
1386 const context = referencedComposerContext(value, existing.context);
1387 const draft = withReferencedContextFiles(existing, value, context);
1388 removed = existing.attachments.filter((attachment) => !draft.attachments.includes(attachment));
1389 return withComposerDraft(current, draftKey, draft);
1390 });
1391 scheduleUnusedComposerAttachmentCleanup(removed);
1392 }
1393
1394 export function insertComposerDraftText(
1395 draftKey: string,
1396 value: string,
1397 target: ComposerDraftInsertion,
1398 ): void {
1399 const draft = getComposerDraftSnapshot(draftKey);
1400 const { start, end } = contextInsertionRange(draftKey, draft, target);
1401 const text = draft.text.slice(0, start) + value + draft.text.slice(end);
1402 const caret = caretAfterInsertion(draftKey, draft.text, { start, end }, value.length);
1403 setComposerDraftText(draftKey, text);
1404 rememberComposerDraftSelection(draftKey, text, caret);
1405 }
1406
1407 export function appendComposerDraftText(draftKey: string, value: string): void {
1408 updateComposerDrafts((current) => {
1409 const existing = normalizeDraft(current[draftKey]);
1410 return {
1411 ...current,
1412 [draftKey]: {
1413 ...existing,
1414 text: `${existing.text}${value}`,
1415 },
1416 };
1417 });
1418 }
1419
1420 // Pasted images all share one name, so an image's inline bytes decide whether it is a repeat.
1421 function isSameAttachment(a: DraftComposerAttachment, b: DraftComposerAttachment): boolean {
1422 return (
1423 a.mimeType === b.mimeType &&
1424 a.sizeBytes === b.sizeBytes &&
1425 a.name === b.name &&
1426 (a.type !== "image" || b.type !== "image" || a.dataUrl === b.dataUrl)
1427 );
1428 }
1429
1430 /**
1431 * Restore puts back attachments after failed sends, so it skips the duplicate check and the caps.
1432 * Returns how many attachments the caps rejected.
1433 */
1434 export function appendComposerDraftAttachments(
1435 draftKey: string,
1436 incoming: ReadonlyArray<DraftComposerAttachment>,
1437 options?: {
1438 readonly restore?: boolean;
1439 readonly appendReference?: boolean;
1440 readonly insertion?: ComposerDraftInsertion;
1441 readonly maxAttachments?: number;
1442 },
1443 ): number {
1444 if (incoming.length === 0) {
1445 return 0;
1446 }
1447 let rejected: ReadonlyArray<DraftComposerAttachment> = [];
1448 let removed: ReadonlyArray<DraftComposerAttachment> = [];
1449 let duplicates: ReadonlyArray<DraftComposerAttachment> = [];
1450 updateComposerDrafts((current) => {
1451 const existing = normalizeDraft(current[draftKey]);
1452 const retained = options?.appendReference
1453 ? draftWithoutInsertionSelection(draftKey, existing, options.insertion)
1454 : existing;
1455 const seen = [...retained.attachments];
1456 const attachments = options?.restore
1457 ? incoming
1458 : incoming.filter((attachment) => {
1459 if (seen.some((other) => isSameAttachment(other, attachment))) return false;
1460 seen.push(attachment);
1461 return true;
1462 });
1463 duplicates = incoming.filter((attachment) => !attachments.includes(attachment));
1464 const remaining = options?.restore
1465 ? attachments.length
1466 : Math.max(
1467 0,
1468 Math.min(
1469 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
1470 options?.maxAttachments ?? PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
1471 ) - retained.attachments.length,
1472 );
1473 const contextCapacity =
1474 options?.appendReference && !options.restore
1475 ? Math.max(0, COMPOSER_CONTEXT_MAX_RECORDS - (retained.context?.records.length ?? 0))
1476 : attachments.length;
1477 const accepted = attachments.slice(0, Math.min(remaining, contextCapacity));
1478 rejected = attachments.slice(accepted.length);
1479 if (accepted.length === 0) {
1480 return current;
1481 }
1482 let draft = { ...existing, attachments: [...existing.attachments, ...accepted] };
1483 if (options?.appendReference) {
1484 const records = accepted.map((attachment) => attachmentContextRecord(attachment));
1485 const inserted = draftWithInsertedContext(
1486 draftKey,
1487 draft,
1488 {
1489 text: records.map(formatComposerContextReference).join(" "),
1490 context: { version: 1, records },
1491 },
1492 options.insertion,
1493 options.restore ? Infinity : COMPOSER_CONTEXT_MAX_RECORDS,
1494 );
1495 if (!inserted) {
1496 rejected = attachments;
1497 return current;
1498 }
1499 draft = { ...inserted, attachments: [...inserted.attachments] };
1500 removed = existing.attachments.filter(
1501 (attachment) => !draft.attachments.includes(attachment),
1502 );
1503 }
1504 return {
1505 ...current,
1506 [draftKey]: draft,
1507 };
1508 });
1509 scheduleUnusedComposerAttachmentCleanup([...rejected, ...removed, ...duplicates]);
1510 return rejected.length;
1511 }
1512
1513 export function replaceComposerDraftAttachments(
1514 draftKey: string,
1515 attachments: ReadonlyArray<DraftComposerAttachment>,
1516 ): void {
1517 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1518 const retainedIds = new Set(attachments.map((attachment) => attachment.id));
1519 updateComposerDrafts((current) => {
1520 const existing = normalizeDraft(current[draftKey]);
1521 const droppedContextIds = new Set(
1522 existing.context?.records
1523 .filter((record) => "attachmentId" in record && !retainedIds.has(record.attachmentId))
1524 .map((record) => record.contextId),
1525 );
1526 const text = replaceComposerContextReferences(existing.text, (ref) =>
1527 droppedContextIds.has(ref.contextId) ? "" : ref.source,
1528 );
1529 const draft = {
1530 ...existing,
1531 text,
1532 context: referencedComposerContext(text, existing.context),
1533 attachments,
1534 };
1535 return withComposerDraft(current, draftKey, draft);
1536 });
1537 scheduleUnusedComposerAttachmentCleanup(
1538 previousAttachments.filter((attachment) => !retainedIds.has(attachment.id)),
1539 );
1540 }
1541
1542 export function removeComposerDraftAttachment(draftKey: string, imageId: string): void {
1543 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1544 updateComposerDrafts((current) => {
1545 const existing = normalizeDraft(current[draftKey]);
1546 const removedIds = new Set(
1547 existing.context?.records
1548 .filter((record) => "attachmentId" in record && record.attachmentId === imageId)
1549 .map((record) => record.contextId),
1550 );
1551 const text = replaceComposerContextReferences(existing.text, (ref) =>
1552 removedIds.has(ref.contextId) ? "" : ref.source,
1553 );
1554 const draft = {
1555 ...existing,
1556 text,
1557 context: referencedComposerContext(text, existing.context),
1558 attachments: existing.attachments.filter((image) => image.id !== imageId),
1559 };
1560 return withComposerDraft(current, draftKey, draft);
1561 });
1562 scheduleUnusedComposerAttachmentCleanup(
1563 previousAttachments.filter((attachment) => attachment.id === imageId),
1564 );
1565 }
1566
1567 export function setComposerDraftAttachmentUpload(
1568 draftKey: string,
1569 attachment: DraftComposerAttachment,
1570 ): boolean {
1571 let previous: DraftComposerAttachment | undefined;
1572 updateComposerDrafts((current) => {
1573 const draft = current[draftKey];
1574 previous = draft?.attachments.find((candidate) => candidate.id === attachment.id);
1575 if (!draft || !previous) return current;
1576 if (
1577 previous.uploadedAttachmentId === attachment.uploadedAttachmentId &&
1578 previous.uploadEnvironmentId === attachment.uploadEnvironmentId
1579 )
1580 return current;
1581 return {
1582 ...current,
1583 [draftKey]: {
1584 ...draft,
1585 attachments: draft.attachments.map((candidate) =>
1586 candidate.id === attachment.id
1587 ? {
1588 ...candidate,
1589 uploadedAttachmentId: attachment.uploadedAttachmentId,
1590 uploadEnvironmentId: attachment.uploadEnvironmentId,
1591 }
1592 : candidate,
1593 ),
1594 },
1595 };
1596 });
1597 if (previous) scheduleUnusedComposerAttachmentCleanup([previous]);
1598 return previous !== undefined;
1599 }
1600
1601 export function updateComposerDraftSettings(
1602 draftKey: string,
1603 settings: Partial<ComposerDraftSettingsUpdate>,
1604 ): void {
1605 updateComposerDrafts((current) => {
1606 const draft = {
1607 ...normalizeDraft(current[draftKey]),
1608 ...settings,
1609 };
1610 return withComposerDraft(current, draftKey, draft);
1611 });
1612 }
1613
1614 /** Lets the thread's model show again once the server accepted this exact pick. */
1615 export function releaseComposerDraftModelSelection(
1616 draftKey: string,
1617 modelSelection: ModelSelection,
1618 ): void {
1619 updateComposerDrafts((current) => {
1620 const existing = current[draftKey];
1621 // A newer pick, even of the same model, is still waiting for its own reply.
1622 if (existing?.modelSelection !== modelSelection) return current;
1623 const { modelSelection: _modelSelection, ...draft } = existing;
1624 return withComposerDraft(current, draftKey, draft);
1625 });
1626 }
1627
1628 export function setFreshSessionPending(draftKey: string, pending: boolean): void {
1629 if ((getComposerDraftSnapshot(draftKey).freshContext === true) === pending) return;
1630 updateComposerDraftSettings(draftKey, { freshContext: pending ? true : undefined });
1631 }
1632
1633 export function isFreshSessionPending(draftKey: string): boolean {
1634 return getComposerDraftSnapshot(draftKey).freshContext === true;
1635 }
1636
1637 export function subscribeComposerDraftModelReconciliation(input: {
1638 readonly registry: AtomRegistry.AtomRegistry;
1639 readonly threadRefsAtom: Atom.Atom<ReadonlyArray<ScopedThreadRef>>;
1640 readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom<EnvironmentThreadShell | null>;
1641 readonly shellStateAtom: (
1642 environmentId: EnvironmentId,
1643 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, unknown>>;
1644 readonly pendingThreadIdsAtom: (environmentId: EnvironmentId) => Atom.Atom<ReadonlySet<ThreadId>>;
1645 }): () => void {
1646 const draftsAtom = Atom.make(appAtomRegistry.get(composerDraftsAtom));
1647 const unsubscribeDrafts = appAtomRegistry.subscribe(composerDraftsAtom, (drafts) =>
1648 input.registry.set(draftsAtom, drafts),
1649 );
1650 const threadKeysAtom = Atom.map(
1651 input.threadRefsAtom,
1652 (refs) => new Set(refs.map(scopedThreadKey)),
1653 );
1654 const matchesAtom = Atom.make((get) => {
1655 const threadKeys = get(threadKeysAtom);
1656 const matches: Array<readonly [string, ComposerDraft]> = [];
1657 for (const [key, draft] of Object.entries(get(draftsAtom))) {
1658 if (!draft.modelSelection || isNewTaskDraftKey(key) || isQueuedEditDraftKey(key)) continue;
1659 const ref = parseScopedThreadKey(key);
1660 if (!ref || !threadKeys.has(key)) continue;
1661 const thread = get(input.threadShellAtom(ref));
1662 if (!thread || !draftModelPickMatchesThread(draft.modelSelection, thread.modelSelection))
1663 continue;
1664 // The pick can match an old model while an earlier pick in flight still replaces it.
1665 if (get(input.pendingThreadIdsAtom(ref.environmentId)).has(ref.threadId)) continue;
1666 // Status and selection must come from the same emission; derived atoms can update apart.
1667 const shell = AsyncResult.getOrElse(get(input.shellStateAtom(ref.environmentId)), () => null);
1668 if (shell?.status !== "live") continue;
1669 const authoritativeThread = Option.getOrNull(shell.snapshot)?.threads.find(
1670 (candidate) => candidate.id === ref.threadId,
1671 );
1672 if (
1673 authoritativeThread &&
1674 draftModelPickMatchesThread(draft.modelSelection, authoritativeThread.modelSelection)
1675 ) {
1676 matches.push([key, draft]);
1677 }
1678 }
1679 return matches;
1680 });
1681 const unsubscribeMatches = input.registry.subscribe(
1682 matchesAtom,
1683 (matches) => {
1684 if (matches.length === 0) return;
1685 updateComposerDrafts((current) => {
1686 let next = current;
1687 for (const [key, matchedDraft] of matches) {
1688 if (next[key] !== matchedDraft) continue;
1689 const { modelSelection: _modelSelection, ...draft } = matchedDraft;
1690 next = withComposerDraft(next, key, draft);
1691 }
1692 return next;
1693 });
1694 },
1695 { immediate: true },
1696 );
1697 return () => {
1698 unsubscribeMatches();
1699 unsubscribeDrafts();
1700 };
1701 }
1702
1703 export function clearComposerDraftContentState(
1704 current: Record<string, ComposerDraft>,
1705 draftKey: string,
1706 options?: {
1707 readonly clearModelSelection?: boolean;
1708 readonly clearWorkspaceSelection?: boolean;
1709 },
1710 ): Record<string, ComposerDraft> {
1711 const existing = current[draftKey];
1712 if (!existing) {
1713 return current;
1714 }
1715 const {
1716 importedShareIds: _importedShareIds,
1717 context: _context,
1718 modelSelection,
1719 workspaceSelection,
1720 project: _project,
1721 ...retained
1722 } = existing;
1723 const draft = {
1724 ...retained,
1725 ...(options?.clearModelSelection || modelSelection === undefined ? {} : { modelSelection }),
1726 ...(options?.clearWorkspaceSelection || workspaceSelection === undefined
1727 ? {}
1728 : { workspaceSelection }),
1729 text: "",
1730 attachments: [],
1731 };
1732 if (isEmptyDraft(draft)) {
1733 const next = { ...current };
1734 delete next[draftKey];
1735 return next;
1736 }
1737 return {
1738 ...current,
1739 [draftKey]: draft,
1740 };
1741 }
1742
1743 export function restoreComposerDraftSnapshotState(
1744 current: Record<string, ComposerDraft>,
1745 draftKey: string,
1746 snapshot: ComposerDraft,
1747 ): Record<string, ComposerDraft> {
1748 const next = { ...current };
1749 if (isEmptyDraft(snapshot)) {
1750 delete next[draftKey];
1751 } else {
1752 next[draftKey] = snapshot;
1753 }
1754 return next;
1755 }
1756
1757 function stripAttachmentUploadReference(
1758 attachment: DraftComposerAttachment,
1759 ): DraftComposerAttachment {
1760 const { uploadedAttachmentId: _id, uploadEnvironmentId: _environmentId, ...rest } = attachment;
1761 return rest;
1762 }
1763
1764 function mergeComposerDraftText(existing: string, incoming: string): string {
1765 if (incoming.length === 0) {
1766 return existing;
1767 }
1768 if (existing.length === 0) {
1769 return incoming;
1770 }
1771 if (existing === incoming || existing.endsWith(`\n\n${incoming}`)) {
1772 return existing;
1773 }
1774 return `${existing}\n\n${incoming}`;
1775 }
1776
1777 function mergeReferencedComposerContext(
1778 text: string,
1779 first?: OrchestrationMessageContext,
1780 second?: OrchestrationMessageContext,
1781 ) {
1782 const records = new Map((first?.records ?? []).map((record) => [record.contextId, record]));
1783 for (const record of second?.records ?? []) records.set(record.contextId, record);
1784 if (records.size === 0) return undefined;
1785 return referencedComposerContext(text, { version: 1, records: [...records.values()] });
1786 }
1787
1788 export function mergeComposerDraftContentState(
1789 current: Record<string, ComposerDraft>,
1790 draftKey: string,
1791 content: ComposerDraftContent,
1792 ): Record<string, ComposerDraft> {
1793 const existing = normalizeDraft(current[draftKey]);
1794 if (content.sourceShareId && existing.importedShareIds?.includes(content.sourceShareId)) {
1795 return current;
1796 }
1797 const attachmentIds = new Set(existing.attachments.map((attachment) => attachment.id));
1798 const incomingAttachments = content.attachments.filter((attachment) => {
1799 if (attachmentIds.has(attachment.id)) {
1800 return false;
1801 }
1802 attachmentIds.add(attachment.id);
1803 return true;
1804 });
1805 const attachments = [...existing.attachments, ...incomingAttachments].slice(
1806 0,
1807 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
1808 );
1809 const text = mergeComposerDraftText(existing.text, content.text);
1810 const context = mergeReferencedComposerContext(text, existing.context, content.context);
1811 const importedShareIds = content.sourceShareId
1812 ? [...(existing.importedShareIds ?? []), content.sourceShareId]
1813 : existing.importedShareIds;
1814 if (
1815 text === existing.text &&
1816 attachments.length === existing.attachments.length &&
1817 content.context === undefined &&
1818 importedShareIds === existing.importedShareIds
1819 ) {
1820 return current;
1821 }
1822 return {
1823 ...current,
1824 // The composer shows non-image files only as inline chips, so a shared file
1825 // merged without one would be attached but invisible until sent. Other
1826 // merges carry their own text, and appending chips to it would defeat
1827 // mergeComposerDraftText's duplicate check on a retried merge.
1828 [draftKey]: restoreMissingComposerFileReferences(
1829 {
1830 ...existing,
1831 text,
1832 attachments,
1833 context,
1834 ...(importedShareIds ? { importedShareIds } : {}),
1835 },
1836 content.sourceShareId ? attachments.slice(existing.attachments.length) : [],
1837 ),
1838 };
1839 }
1840
1841 /** Persists before the share inbox item can be acknowledged. */
1842 export async function mergeComposerDraftContent(
1843 draftKey: string,
1844 content: ComposerDraftContent,
1845 ): Promise<{ readonly skippedAttachmentCount: number }> {
1846 ensureComposerDraftsLoaded();
1847 if (loadPromise !== null) {
1848 await loadPromise;
1849 }
1850 if (persistTimer !== null) {
1851 clearTimeout(persistTimer);
1852 persistTimer = null;
1853 }
1854 const current = appAtomRegistry.get(composerDraftsAtom);
1855 const next = mergeComposerDraftContentState(current, draftKey, content);
1856 const currentAttachmentIds = new Set(
1857 normalizeDraft(current[draftKey]).attachments.map((attachment) => attachment.id),
1858 );
1859 const nextAttachmentIds = new Set(
1860 normalizeDraft(next[draftKey]).attachments.map((attachment) => attachment.id),
1861 );
1862 const skippedAttachmentCount = content.attachments.filter(
1863 (attachment) =>
1864 !currentAttachmentIds.has(attachment.id) && !nextAttachmentIds.has(attachment.id),
1865 ).length;
1866 // Publish content and receipt before awaiting disk; concurrent typing then preserves the receipt in later serialized writes.
1867 if (next !== current) {
1868 appAtomRegistry.set(composerDraftsAtom, next);
1869 }
1870 await persistenceQueue.run(() =>
1871 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1872 );
1873 return { skippedAttachmentCount };
1874 }
1875
1876 export function sameComposerDraftState(a: ComposerDraft, b: ComposerDraft): boolean {
1877 return (
1878 a.text === b.text &&
1879 a.attachments === b.attachments &&
1880 a.context === b.context &&
1881 a.importedShareIds === b.importedShareIds &&
1882 a.modelSelection === b.modelSelection &&
1883 a.runtimeMode === b.runtimeMode &&
1884 a.interactionMode === b.interactionMode &&
1885 a.freshContext === b.freshContext &&
1886 a.workspaceSelection === b.workspaceSelection
1887 );
1888 }
1889
1890 /** Restore untouched drafts exactly; after concurrent edits, remove only merged text and attachments. */
1891 export function undoComposerDraftMergeState(
1892 current: Record<string, ComposerDraft>,
1893 draftKey: string,
1894 snapshot: ComposerDraft,
1895 merged: ComposerDraft,
1896 ): Record<string, ComposerDraft> {
1897 const existing = normalizeDraft(current[draftKey]);
1898 if (sameComposerDraftState(existing, merged)) {
1899 return restoreComposerDraftSnapshotState(current, draftKey, snapshot);
1900 }
1901 const insertedText = merged.text.startsWith(snapshot.text)
1902 ? merged.text.slice(snapshot.text.length)
1903 : "";
1904 const snapshotAttachmentIds = new Set(snapshot.attachments.map((attachment) => attachment.id));
1905 const insertedAttachmentIds = new Set(
1906 merged.attachments
1907 .filter((attachment) => !snapshotAttachmentIds.has(attachment.id))
1908 .map((attachment) => attachment.id),
1909 );
1910 const undoSetting = <
1911 K extends
1912 | "modelSelection"
1913 | "runtimeMode"
1914 | "interactionMode"
1915 | "freshContext"
1916 | "workspaceSelection",
1917 >(
1918 key: K,
1919 ): ComposerDraft[K] => (existing[key] === merged[key] ? snapshot[key] : existing[key]);
1920 const text =
1921 insertedText.length > 0 && existing.text.startsWith(merged.text)
1922 ? snapshot.text + existing.text.slice(merged.text.length)
1923 : insertedText.length > 0 && existing.text.endsWith(insertedText)
1924 ? existing.text.slice(0, existing.text.length - insertedText.length)
1925 : existing.text;
1926 const draft = {
1927 ...existing,
1928 text,
1929 context: referencedComposerContext(text, existing.context),
1930 attachments: existing.attachments.filter(
1931 (attachment) => !insertedAttachmentIds.has(attachment.id),
1932 ),
1933 modelSelection: undoSetting("modelSelection"),
1934 runtimeMode: undoSetting("runtimeMode"),
1935 interactionMode: undoSetting("interactionMode"),
1936 freshContext: undoSetting("freshContext"),
1937 workspaceSelection: undoSetting("workspaceSelection"),
1938 };
1939 return withComposerDraft(current, draftKey, draft);
1940 }
1941
1942 export async function undoComposerDraftMerge(
1943 draftKey: string,
1944 snapshot: ComposerDraft,
1945 merged: ComposerDraft,
1946 ): Promise<void> {
1947 ensureComposerDraftsLoaded();
1948 if (loadPromise !== null) {
1949 await loadPromise;
1950 }
1951 if (persistTimer !== null) {
1952 clearTimeout(persistTimer);
1953 persistTimer = null;
1954 }
1955 const next = undoComposerDraftMergeState(
1956 appAtomRegistry.get(composerDraftsAtom),
1957 draftKey,
1958 snapshot,
1959 merged,
1960 );
1961 appAtomRegistry.set(composerDraftsAtom, next);
1962 await persistenceQueue.run(() =>
1963 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
1964 );
1965 }
1966
1967 export function clearComposerDraftContent(
1968 draftKey: string,
1969 options?: {
1970 readonly clearModelSelection?: boolean;
1971 readonly clearWorkspaceSelection?: boolean;
1972 // Defer sweeping during enqueue; rollback can briefly remove ownership before restoring attachments.
1973 readonly deferAttachmentCleanup?: boolean;
1974 },
1975 ): void {
1976 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1977 markComposerDraftReset(draftKey);
1978 updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options));
1979 if (!options?.deferAttachmentCleanup) {
1980 scheduleUnusedComposerAttachmentCleanup(previousAttachments);
1981 }
1982 }
1983
1984 export function clearComposerDraft(
1985 draftKey: string,
1986 options?: { readonly deferAttachmentCleanup?: boolean },
1987 ): void {
1988 abortComposerDraftOperations(draftKey);
1989 markComposerDraftReset(draftKey);
1990 const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1991 updateComposerDrafts((current) => {
1992 if (!current[draftKey]) {
1993 return current;
1994 }
1995 const next = { ...current };
1996 delete next[draftKey];
1997 return next;
1998 });
1999 if (!options?.deferAttachmentCleanup) {
2000 scheduleUnusedComposerAttachmentCleanup(previousAttachments);
2001 }
2002 }
2003
2004 export function removeComposerDraftsForEnvironment(
2005 drafts: Record<string, ComposerDraft>,
2006 environmentId: EnvironmentId,
2007 ): Record<string, ComposerDraft> {
2008 const environmentPrefix = `${environmentId}:`;
2009 return Object.fromEntries(
2010 Object.entries(drafts).filter(
2011 ([draftKey, draft]) =>
2012 !draftKey.startsWith(environmentPrefix) && draft.project?.environmentId !== environmentId,
2013 ),
2014 );
2015 }
2016
2017 export function createNewTaskDraft(project: {
2018 readonly environmentId: EnvironmentId;
2019 readonly projectId: ProjectId;
2020 }): string {
2021 const draftKey = newTaskDraftKey(newDraftId());
2022 const stamp: ComposerDraftProject = {
2023 environmentId: project.environmentId,
2024 projectId: project.projectId,
2025 createdAt: new Date().toISOString(),
2026 };
2027 updateComposerDrafts((current) => ({
2028 ...current,
2029 [draftKey]: { ...EMPTY_DRAFT, project: stamp },
2030 }));
2031 return draftKey;
2032 }
2033
2034 export function retargetNewTaskDraft(
2035 draftKey: string,
2036 project: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId },
2037 options?: { readonly keepPullRequestWorkspace?: boolean },
2038 ): void {
2039 updateComposerDrafts((current) => {
2040 const existing = current[draftKey];
2041 const stamp = existing?.project;
2042 if (
2043 stamp !== undefined &&
2044 stamp.environmentId === project.environmentId &&
2045 stamp.projectId === project.projectId
2046 ) {
2047 return current;
2048 }
2049 const { workspaceSelection, ...retained } = normalizeDraft(existing);
2050 // The PR checkout is recreated on the target machine, so only the old local path is dropped.
2051 const keptWorkspaceSelection =
2052 options?.keepPullRequestWorkspace && workspaceSelection?.pullRequestReference !== undefined
2053 ? { ...workspaceSelection, worktreePath: null }
2054 : undefined;
2055 // Keep bytes across environment moves but drop server-specific upload stamps.
2056 const attachments = retained.attachments.map((attachment) =>
2057 attachment.uploadEnvironmentId !== undefined &&
2058 attachment.uploadEnvironmentId !== project.environmentId
2059 ? stripAttachmentUploadReference(attachment)
2060 : attachment,
2061 );
2062 return {
2063 ...current,
2064 [draftKey]: {
2065 ...retained,
2066 ...(keptWorkspaceSelection ? { workspaceSelection: keptWorkspaceSelection } : {}),
2067 attachments,
2068 project: {
2069 environmentId: project.environmentId,
2070 projectId: project.projectId,
2071 createdAt: stamp?.createdAt ?? new Date().toISOString(),
2072 },
2073 },
2074 };
2075 });
2076 }
2077
2078 /** Retargets a saved draft after loading. Returns false if absent or cancelled before the write. */
2079 export async function retargetSavedNewTaskDraft(
2080 draftKey: string,
2081 project: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId },
2082 signal?: AbortSignal,
2083 ): Promise<boolean> {
2084 await waitForComposerDraftsLoaded();
2085 if (signal?.aborted || appAtomRegistry.get(composerDraftsAtom)[draftKey] === undefined)
2086 return false;
2087 retargetNewTaskDraft(draftKey, project);
2088 return true;
2089 }
2090
2091 export function findNewTaskDraftKeys(
2092 drafts: Readonly<Record<string, ComposerDraft>>,
2093 project: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId },
2094 ): ReadonlyArray<string> {
2095 return Object.entries(drafts)
2096 .filter(
2097 ([key, draft]) =>
2098 isNewTaskDraftKey(key) &&
2099 draft.project?.environmentId === project.environmentId &&
2100 draft.project.projectId === project.projectId,
2101 )
2102 .sort(([, left], [, right]) =>
2103 (right.project?.createdAt ?? "").localeCompare(left.project?.createdAt ?? ""),
2104 )
2105 .map(([key]) => key);
2106 }
2107
2108 export async function clearComposerDraftsEnvironment(environmentId: EnvironmentId): Promise<void> {
2109 ensureComposerDraftsLoaded();
2110 if (loadPromise !== null) {
2111 await loadPromise;
2112 }
2113
2114 const current = appAtomRegistry.get(composerDraftsAtom);
2115 const next = removeComposerDraftsForEnvironment(current, environmentId);
2116 const removedAttachments = Object.entries(current)
2117 .filter(([draftKey]) => next[draftKey] === undefined)
2118 .flatMap(([, draft]) => draft.attachments);
2119 // Keys with no stored draft yet (an empty thread composer) can still have a pick running.
2120 const environmentPrefix = `${environmentId}:`;
2121 abortComposerDraftOperationsWhere(
2122 (draftKey) =>
2123 draftKey.startsWith(environmentPrefix) ||
2124 (current[draftKey] !== undefined && next[draftKey] === undefined),
2125 );
2126
2127 if (persistTimer !== null) {
2128 clearTimeout(persistTimer);
2129 persistTimer = null;
2130 }
2131 appAtomRegistry.set(composerDraftsAtom, next);
2132 await persistenceQueue.run(() =>
2133 writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
2134 );
2135 await releaseUnusedComposerAttachmentFiles(removedAttachments);
2136 }
2137
2138 const composerDraftAtom = Atom.family((draftKey: string) =>
2139 Atom.make((get) => get(composerDraftsAtom)[draftKey] ?? EMPTY_DRAFT),
2140 );
2141 const EMPTY_DRAFT_ATOM = Atom.make(EMPTY_DRAFT);
2142
2143 type ComposerDraftsByKey = Readonly<Record<string, ComposerDraft>>;
2144 const EMPTY_DRAFTS: ComposerDraftsByKey = {};
2145 function sameDrafts(a: ComposerDraftsByKey, b: ComposerDraftsByKey): boolean {
2146 const keys = Object.keys(a);
2147 return keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key]);
2148 }
2149 export const questionAttachmentDraftsAtom = Atom.family((prefix: string) =>
2150 Atom.make((get): ComposerDraftsByKey => {
2151 if (prefix === "") return EMPTY_DRAFTS;
2152 const matching = Object.entries(get(composerDraftsAtom)).filter(([key]) =>
2153 key.startsWith(prefix),
2154 );
2155 return matching.length === 0 ? EMPTY_DRAFTS : Object.fromEntries(matching);
2156 }).pipe(Atom.withEquality(sameDrafts)),
2157 );
2158
2159 export const newTaskComposerDraftsAtom = Atom.make((get): ComposerDraftsByKey => {
2160 const matching = Object.entries(get(composerDraftsAtom)).filter(([key]) =>
2161 isNewTaskDraftKey(key),
2162 );
2163 return matching.length === 0 ? EMPTY_DRAFTS : Object.fromEntries(matching);
2164 }).pipe(Atom.withEquality(sameDrafts));
2165
2166 type ComposerDraftUploadSource = Pick<ComposerDraft, "attachments" | "project">;
2167 type ComposerDraftUploadSources = Readonly<Record<string, ComposerDraftUploadSource>>;
2168 export const composerDraftUploadSourcesAtom = Atom.make((get): ComposerDraftUploadSources =>
2169 Object.fromEntries(
2170 Object.entries(get(composerDraftsAtom)).map(([key, draft]) => [
2171 key,
2172 { attachments: draft.attachments, project: draft.project },
2173 ]),
2174 ),
2175 ).pipe(
2176 Atom.withEquality((a: ComposerDraftUploadSources, b: ComposerDraftUploadSources) => {
2177 const keys = Object.keys(a);
2178 return (
2179 keys.length === Object.keys(b).length &&
2180 keys.every(
2181 (key) => a[key]?.attachments === b[key]?.attachments && a[key]?.project === b[key]?.project,
2182 )
2183 );
2184 }),
2185 );
2186
2187 type ComposerDraftSettings = Pick<
2188 ComposerDraft,
2189 "modelSelection" | "runtimeMode" | "interactionMode" | "freshContext"
2190 >;
2191 const EMPTY_DRAFT_SETTINGS: ComposerDraftSettings = {};
2192 const composerDraftSettingsAtom = Atom.family((draftKey: string) =>
2193 Atom.make((get): ComposerDraftSettings => {
2194 const draft = get(composerDraftAtom(draftKey));
2195 return {
2196 modelSelection: draft.modelSelection,
2197 runtimeMode: draft.runtimeMode,
2198 interactionMode: draft.interactionMode,
2199 freshContext: draft.freshContext,
2200 };
2201 }).pipe(
2202 Atom.withEquality(
2203 (a: ComposerDraftSettings, b: ComposerDraftSettings) =>
2204 a.modelSelection === b.modelSelection &&
2205 a.runtimeMode === b.runtimeMode &&
2206 a.interactionMode === b.interactionMode &&
2207 a.freshContext === b.freshContext,
2208 ),
2209 ),
2210 );
2211 const EMPTY_DRAFT_SETTINGS_ATOM = Atom.make(EMPTY_DRAFT_SETTINGS);
2212
2213 export function useComposerDraftSettings(draftKey: string | null): ComposerDraftSettings {
2214 const settings = useAtomValue(
2215 draftKey ? composerDraftSettingsAtom(draftKey) : EMPTY_DRAFT_SETTINGS_ATOM,
2216 );
2217 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts loading persisted composer drafts from native storage on first use
2218 useEffect(() => {
2219 ensureComposerDraftsLoaded();
2220 }, []);
2221 return settings;
2222 }
2223
2224 export function useComposerDraft(draftKey: string | null): ComposerDraft {
2225 const draft = useAtomValue(draftKey ? composerDraftAtom(draftKey) : EMPTY_DRAFT_ATOM);
2226 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts loading persisted composer drafts from native storage on first use
2227 useEffect(() => {
2228 ensureComposerDraftsLoaded();
2229 }, []);
2230 return draft;
2231 }
2232
2233 export function useStickyComposerModelSelection(): ModelSelection | null {
2234 const selection = useAtomValue(stickyComposerModelSelectionAtom);
2235 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts loading persisted composer drafts from native storage on first use
2236 useEffect(() => {
2237 ensureComposerDraftsLoaded();
2238 }, []);
2239 return selection;
2240 }