sailfork / t3code-github / apps/ mobile/ src/ state/ use-composer-drafts.test.ts

import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
import { createEnvironmentThreadShellAtoms } from "@t3tools/client-runtime/state/threads";
import {
  applyShellStreamEvent,
  createEnvironmentSnapshotAtom,
  EMPTY_SHELL_STATE,
  type EnvironmentShellState,
  type EnvironmentShellStatus,
} from "@t3tools/client-runtime/state/shell";
import {
  v2ShellSnapshot,
  v2ThreadShell,
} from "../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures";
import * as Option from "effect/Option";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
import { afterEach, describe, expect, it } from "@effect/vitest";
import {
  CommandId,
  ComposerContextId,
  EnvironmentId,
  MessageId,
  ProjectId,
  ProviderInstanceId,
  ThreadId,
  type OrchestrationV2ThreadShell,
  type OrchestrationV2ShellSnapshot,
  type ModelSelection,
} from "@t3tools/contracts";
import { onTestFinished, vi } from "vite-plus/test";

const composerDraftFileMocks = vi.hoisted(() => {
  let document = JSON.stringify({ schemaVersion: 1, drafts: {} });
  let readError: Error | null = null;
  let writeError: Error | null = null;
  let releaseRead: (() => void) | null = null;
  let readBarrier = Promise.resolve();
  let nextWriteBarrier: Promise<void> | null = null;
  let onWrite: (() => void) | null = null;
  const writes: string[] = [];
  const readImage = vi.fn(async () => "YWJj");

  return {
    readImage,
    blockRead() {
      readBarrier = new Promise<void>((resolve) => {
        releaseRead = resolve;
      });
    },
    releaseRead() {
      releaseRead?.();
      releaseRead = null;
    },
    getDocument() {
      return document;
    },
    setDocument(value: unknown) {
      document = JSON.stringify(value);
    },
    setReadError(error: Error | null) {
      readError = error;
    },
    setWriteError(error: Error | null) {
      writeError = error;
    },
    setNextWriteBarrier(barrier: Promise<void> | null) {
      nextWriteBarrier = barrier;
    },
    setOnWrite(callback: (() => void) | null) {
      onWrite = callback;
    },
    getWrites(): ReadonlyArray<string> {
      return writes;
    },
    resetWrites() {
      writes.length = 0;
    },
    Directory: class {
      create() {}

      list() {
        return [];
      }
    },
    File: class {
      exists = true;
      parentDirectory = null;

      create() {}

      moveSync() {}

      async text() {
        await readBarrier;
        if (readError) throw readError;
        return document;
      }

      async base64() {
        return readImage();
      }

      write(value: string) {
        if (writeError) {
          throw writeError;
        }
        if (nextWriteBarrier) {
          const barrier = nextWriteBarrier;
          nextWriteBarrier = null;
          return barrier.then(() => {
            document = value;
            writes.push(value);
            onWrite?.();
          });
        }
        document = value;
        writes.push(value);
        onWrite?.();
      }
    },
  };
});

const composerAttachmentCleanupMocks = vi.hoisted(() => ({
  remove: vi.fn(async () => undefined),
  releaseUploads: vi.fn(async () => undefined),
}));

const incomingShareStorageMocks = vi.hoisted(() => ({
  load: vi.fn<typeof import("../features/sharing/incoming-share-storage").loadIncomingShareDrafts>(
    async () => [],
  ),
}));

vi.mock("expo-file-system", () => ({
  Directory: composerDraftFileMocks.Directory,
  File: composerDraftFileMocks.File,
  Paths: { document: { uri: "file:///documents" } },
}));

vi.mock("../lib/composerImages", async (importOriginal) => ({
  ...(await importOriginal<typeof import("../lib/composerImages")>()),
  removePersistedComposerAttachmentFile: composerAttachmentCleanupMocks.remove,
}));

vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "0000" }));
vi.mock("./assets", () => ({ assetEnvironment: {} }));
vi.mock("./attachments", () => ({ attachmentEnvironment: {} }));
vi.mock("./session", () => ({ environmentSession: {} }));
vi.mock("@t3tools/client-runtime/state/runtime", () => ({
  createEnvironmentRpcCommand: () => Symbol("rpc-command"),
  executeAtomQuery: () => {
    throw new Error("Unexpected network query in the inline read test");
  },
  runAtomCommand: () => {
    throw new Error("Unexpected network command in the inline read test");
  },
  squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error,
}));

vi.mock("../lib/attachmentUpload", () => ({
  releasePendingAttachmentUploads: composerAttachmentCleanupMocks.releaseUploads,
}));

vi.mock("../features/sharing/incoming-share-storage", () => ({
  loadIncomingShareDrafts: incomingShareStorageMocks.load,
}));

import type { DraftComposerAttachment } from "../lib/composerImages";
import {
  collectComposerContextReferences,
  formatComposerContextReference,
} from "@t3tools/shared/composerContextReferences";
import { appAtomRegistry } from "./atom-registry";
import { startComposerDraftOperation } from "./composerDraftOperations";
import { threadOutboxManager } from "./thread-outbox";
import {
  appendComposerDraftAttachments,
  captureComposerDraftInsertion,
  countComposerDraftAttachmentsAfterSelection,
  getComposerDraftAfterSelection,
  archiveCloudComposerDrafts,
  clearComposerDraftContent,
  clearComposerDraftContentState,
  subscribeComposerDraftModelReconciliation,
  clearComposerDraftsEnvironment,
  ComposerDraftPersistenceError,
  composerDraftsAtom,
  composerCloudDraftsAtom,
  createNewTaskDraft,
  createComposerDraftContextHistory,
  setComposerDraftContext,
  decodePersistedComposerState,
  ensureComposerDraftsLoaded,
  type ComposerDraft,
  findNewTaskDraftKeys,
  flushComposerDrafts,
  getComposerDraftSnapshot,
  mergeComposerDraftContentState,
  migrateLegacyNewTaskDraft,
  modelOptionMemoryAtom,
  releaseUnusedComposerAttachmentFiles,
  removeComposerDraftsForEnvironment,
  replaceComposerDraftAttachments,
  resetComposerDraftsLoadState,
  restoreComposerDraftSnapshotState,
  restoreCloudComposerDrafts,
  retargetNewTaskDraft,
  setComposerDraftText,
  insertComposerDraftContext,
  insertComposerDraftText,
  rememberComposerDraftSelection,
  setComposerDraftAttachmentUpload,
  waitForComposerDraftsLoaded,
  setStickyComposerModelSelection,
  stickyComposerModelSelectionAtom,
  undoComposerDraftMergeState,
  updateComposerDraftSettings,
} from "./use-composer-drafts";
import { retainComposerAttachmentFileForPreview } from "../lib/composerAttachmentPreviewRetention";

const DRAFT: ComposerDraft = {
  text: "hello",
  attachments: [],
};

afterEach(() => {
  vi.useRealTimers();
  resetComposerDraftsLoadState();
  composerDraftFileMocks.setDocument({ schemaVersion: 1, drafts: {} });
  composerDraftFileMocks.setReadError(null);
  composerDraftFileMocks.setWriteError(null);
  composerDraftFileMocks.setNextWriteBarrier(null);
  composerDraftFileMocks.setOnWrite(null);
  composerDraftFileMocks.resetWrites();
  composerDraftFileMocks.readImage.mockReset();
  composerDraftFileMocks.readImage.mockResolvedValue("YWJj");
  appAtomRegistry.set(composerDraftsAtom, {});
  appAtomRegistry.set(composerCloudDraftsAtom, { accountId: null, signedOut: {} });
  appAtomRegistry.set(stickyComposerModelSelectionAtom, null);
  appAtomRegistry.set(modelOptionMemoryAtom, {});
  appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
  composerAttachmentCleanupMocks.remove.mockClear();
  composerAttachmentCleanupMocks.releaseUploads.mockReset();
  composerAttachmentCleanupMocks.releaseUploads.mockResolvedValue(undefined);
  incomingShareStorageMocks.load.mockReset();
  incomingShareStorageMocks.load.mockResolvedValue([]);
});

function contextDraft(start: number, count: number): ComposerDraft {
  const records = Array.from({ length: count }, (_, index) => ({
    version: 1 as const,
    contextId: ComposerContextId.make(`skill-${start + index}`),
    kind: "skill" as const,
    label: "Skill",
    name: "skill",
  }));
  return {
    text: records.map((record) => `[Skill](t3-context://v1/skill/${record.contextId})`).join(" "),
    context: { version: 1, records },
    attachments: [],
  };
}

function modelReconciliationHarness(
  environmentId: EnvironmentId,
  threadId: ThreadId,
  initialStatus: EnvironmentShellStatus = "live",
) {
  const tasks: Array<() => void> = [];
  const registry = AtomRegistry.make({
    scheduleTask: (task) => {
      tasks.push(task);
      return () => {};
    },
  });
  onTestFinished(() => registry.dispose());
  const flush = () => {
    for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task();
  };
  const selectedThreadId = ThreadId.make("another-selected-thread");
  const initialSnapshot: OrchestrationV2ShellSnapshot = {
    ...v2ShellSnapshot,
    threads: [
      { ...v2ThreadShell, id: threadId },
      { ...v2ThreadShell, id: selectedThreadId },
    ],
  };
  const shellStateAtom = Atom.make<EnvironmentShellState>({
    ...EMPTY_SHELL_STATE,
    snapshot: Option.some(initialSnapshot),
    status: initialStatus,
  });
  const shellResultAtom = Atom.map(shellStateAtom, AsyncResult.success);
  const snapshotAtom = createEnvironmentSnapshotAtom(() => shellResultAtom)(environmentId);
  const catalogValueAtom = Atom.make({
    isReady: true,
    entries: new Map([
      [
        environmentId,
        {
          target: new PrimaryConnectionTarget({
            environmentId,
            label: "Environment",
            httpBaseUrl: "https://example.test",
            wsBaseUrl: "wss://example.test",
          }),
          profile: Option.none(),
          enabled: true,
        },
      ],
    ]),
  });
  const shells = createEnvironmentThreadShellAtoms({
    catalogValueAtom,
    snapshotAtom: () => snapshotAtom,
    hiddenThreadTagsAtom: () => Atom.make(null),
  });
  const selectedShell = shells.threadShellAtom({ environmentId, threadId: selectedThreadId });
  onTestFinished(registry.mount(selectedShell));
  onTestFinished(
    subscribeComposerDraftModelReconciliation({
      registry,
      threadShellAtom: shells.threadShellAtom,
      threadRefsAtom: shells.threadRefsAtom,
      shellStateAtom: () => shellResultAtom,
    }),
  );
  flush();
  return {
    flush,
    setStatus(status: EnvironmentShellStatus) {
      registry.set(shellStateAtom, { ...registry.get(shellStateAtom), status });
      flush();
    },
    update(changes: Partial<OrchestrationV2ThreadShell>, status?: EnvironmentShellStatus) {
      const state = registry.get(shellStateAtom);
      const snapshot = Option.getOrThrow(state.snapshot);
      registry.set(shellStateAtom, {
        ...state,
        status: status ?? state.status,
        snapshot: Option.some(
          applyShellStreamEvent(snapshot, {
            kind: "thread.updated",
            location: "active",
            sequence: snapshot.snapshotSequence + 1,
            thread: { ...snapshot.threads[0]!, ...changes },
          }),
        ),
      });
      flush();
      expect(registry.get(selectedShell)?.id).toBe(selectedThreadId);
    },
    model: () => registry.get(shells.threadShellAtom({ environmentId, threadId }))!.modelSelection,
  };
}

describe("mobile composer drafts", () => {
  it.each([false, true])(
    "restores visible file chips from legacy drafts (archived: %s)",
    async (archived) => {
      const file = {
        type: "file" as const,
        id: "legacy-file",
        name: "notes.txt",
        mimeType: "text/plain",
        sizeBytes: 10,
        fileUri: "file:///notes.txt",
      };
      const image = { ...file, id: "photo", name: "photo.png", mimeType: "image/png" };
      const video = { ...file, id: "video", name: "clip.mp4", mimeType: "video/mp4" };
      const legacy = { text: "Review these", attachments: [file, image, video] };
      const document = {
        schemaVersion: 1,
        drafts: archived ? {} : { thread: legacy },
        ...(archived
          ? { signedOutDrafts: { account: { drafts: { thread: legacy }, queuedMessages: [] } } }
          : {}),
      };
      const decoded = decodePersistedComposerState(document);
      const restored = archived
        ? decoded.cloudDrafts.signedOut.account?.drafts.thread
        : decoded.drafts.thread;
      expect(restored?.text).toBe("Review these [notes.txt](t3-context://v1/file/legacy-file) ");
      expect(restored?.attachments).toEqual(legacy.attachments);
      expect(restored?.context?.records).toEqual([
        expect.objectContaining({ kind: "file", attachmentId: file.id }),
      ]);
      expect(
        decodePersistedComposerState({ schemaVersion: 1, drafts: { thread: restored } }).drafts
          .thread,
      ).toEqual(restored);
      appAtomRegistry.set(composerDraftsAtom, { thread: restored! });
      setComposerDraftText("thread", "Review these");
      expect(getComposerDraftSnapshot("thread").attachments).toEqual([image, video]);
      await releaseUnusedComposerAttachmentFiles([file]);
    },
  );

  it("restores a missing file reference without duplicating its record or replacing another record's id", () => {
    const file = {
      type: "file" as const,
      id: "file",
      name: "notes.txt",
      mimeType: "text/plain",
      sizeBytes: 10,
      fileUri: "file:///notes.txt",
    };
    const existing = {
      version: 1,
      contextId: "original",
      kind: "file",
      label: file.name,
      attachmentId: file.id,
      name: file.name,
      mimeType: file.mimeType,
      sizeBytes: file.sizeBytes,
    };
    const skill = { version: 1, contextId: "file", kind: "skill", label: "Skill", name: "skill" };
    for (const records of [[existing, skill], [skill]]) {
      const restored = decodePersistedComposerState({
        schemaVersion: 1,
        drafts: {
          thread: { text: "", attachments: [file], context: { version: 1, records } },
        },
      }).drafts.thread;
      expect(restored?.context?.records).toHaveLength(2);
      expect(restored?.context?.records).toContainEqual(skill);
      expect(restored?.text).toBe(
        `[notes.txt](t3-context://v1/file/${records.length === 2 ? "original" : "file_2"}) `,
      );
    }
  });
  it.each([false, true])(
    "restores deleted file chips and releases undo history (uploaded: %s)",
    async (uploaded) => {
      const key = "environment:undo-file";
      const file = {
        type: "file" as const,
        id: "undo-file",
        name: "notes.txt",
        mimeType: "text/plain",
        sizeBytes: 1,
        fileUri: "file:///documents/t3-composer-attachments/undo-file.txt",
        ...(uploaded
          ? {
              uploadedAttachmentId: "pending-upload",
              uploadEnvironmentId: EnvironmentId.make("environment"),
            }
          : {}),
      };
      appendComposerDraftAttachments(key, [file], { appendReference: true });
      const original = getComposerDraftSnapshot(key);
      const history = createComposerDraftContextHistory();
      const changeText = (text: string) => {
        const restored = history.restore(text, getComposerDraftSnapshot(key));
        setComposerDraftText(key, text);
        setComposerDraftContext(key, restored.context);
        appendComposerDraftAttachments(key, restored.attachments, { allowOverflow: true });
      };
      try {
        changeText("");
        expect(getComposerDraftSnapshot(key).attachments).toEqual([]);
        await releaseUnusedComposerAttachmentFiles([file]);
        expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalledWith(file.fileUri);
        changeText(original.text);
        expect(getComposerDraftSnapshot(key).context).toEqual(original.context);
        expect(getComposerDraftSnapshot(key).attachments).toEqual([
          { ...file, uploadedAttachmentId: undefined, uploadEnvironmentId: undefined },
        ]);
        changeText("");
      } finally {
        history.dispose();
      }
      await releaseUnusedComposerAttachmentFiles([file]);
      expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri);
    },
  );

  it("retains a pick matching cached state until the live shell confirms it", () => {
    const environmentId = EnvironmentId.make("environment-1");
    const threadId = ThreadId.make("thread-1");
    const key = `${environmentId}:${threadId}`;
    const h = modelReconciliationHarness(environmentId, threadId, "cached");
    const pick = h.model();
    updateComposerDraftSettings(key, { modelSelection: pick });
    h.flush();
    const before = getComposerDraftSnapshot(key);
    expect(before.modelSelection).toEqual(pick);

    for (const status of ["empty", "synchronizing", "cached"] as const) {
      h.setStatus(status);
      expect(getComposerDraftSnapshot(key)).toEqual(before);
    }
    h.update({ modelSelection: { ...pick, model: "remote-model" } }, "live");
    expect(getComposerDraftSnapshot(key)).toEqual(before);
    h.update({ modelSelection: pick }, "synchronizing");
    expect(getComposerDraftSnapshot(key)).toEqual(before);
    h.setStatus("live");
    expect(appAtomRegistry.get(composerDraftsAtom)[key]).toBeUndefined();
  });

  it("releases an inactive thread pick only after its queued model becomes durable", () => {
    const environmentId = EnvironmentId.make("environment-1");
    const threadId = ThreadId.make("thread-1");
    const key = `${environmentId}:${threadId}`;
    const pick = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.5" };
    setComposerDraftText(key, "keep this unsent follow-up");
    appendComposerDraftAttachments(
      key,
      [
        {
          type: "file",
          id: "file",
          name: "notes.txt",
          mimeType: "text/plain",
          sizeBytes: 4,
          fileUri: "file:///notes.txt",
        },
      ],
      { appendReference: true },
    );
    updateComposerDraftSettings(key, {
      modelSelection: pick,
      runtimeMode: "approval-required",
      interactionMode: "plan",
    });
    const before = getComposerDraftSnapshot(key);
    const remoteKey = `environment-remote:${threadId}`;
    updateComposerDraftSettings(remoteKey, { modelSelection: pick });
    const remoteBefore = getComposerDraftSnapshot(remoteKey);
    const h = modelReconciliationHarness(environmentId, threadId);

    h.update({ status: "queued" });
    expect(getComposerDraftSnapshot(key)).toEqual(before);
    h.update({
      status: "running",
      modelSelection: { ...pick, options: [{ id: "fastMode", value: false }] },
    });
    expect(getComposerDraftSnapshot(key)).toEqual({ ...before, modelSelection: undefined });
    expect(getComposerDraftSnapshot(remoteKey)).toEqual(remoteBefore);

    h.update({
      modelSelection: {
        instanceId: ProviderInstanceId.make("claudeAgent"),
        model: "claude-opus-5-5",
      },
    });
    expect(getComposerDraftSnapshot(key).modelSelection ?? h.model()).toEqual(h.model());
    expect(getComposerDraftSnapshot(key)).toEqual({ ...before, modelSelection: undefined });
  });

  it("retains an unavailable provider pick through differing durable model updates", () => {
    const environmentId = EnvironmentId.make("environment-1");
    const threadId = ThreadId.make("thread-1");
    const key = `${environmentId}:${threadId}`;
    const pick: ModelSelection = {
      instanceId: ProviderInstanceId.make("codex-secondary"),
      model: "gpt-5.5",
      options: [
        { id: "reasoningEffort", value: "high" },
        { id: "fastMode", value: true },
      ],
    };
    updateComposerDraftSettings(key, { modelSelection: pick });
    const before = getComposerDraftSnapshot(key);
    const h = modelReconciliationHarness(environmentId, threadId);
    expect(getComposerDraftSnapshot(key)).toEqual(before);
    for (const modelSelection of [
      { ...pick, instanceId: ProviderInstanceId.make("codex") },
      { ...pick, model: "gpt-5.4" },
      { ...pick, options: [{ id: "reasoningEffort", value: "high" }] },
      {
        ...pick,
        options: [
          { id: "reasoningEffort", value: "low" },
          { id: "fastMode", value: true },
        ],
      },
    ]) {
      h.update({ modelSelection });
      expect(getComposerDraftSnapshot(key)).toEqual(before);
    }
    h.update({ modelSelection: { ...pick, options: pick.options!.toReversed() } });
    expect(appAtomRegistry.get(composerDraftsAtom)[key]).toBeUndefined();
  });

  it("drops chips and records for attachments a replace no longer keeps", () => {
    const key = "new-task:draft-1";
    const kept = {
      type: "file" as const,
      id: "kept-file",
      name: "kept.txt",
      mimeType: "text/plain",
      sizeBytes: 1,
      fileUri: "file:///kept.txt",
    };
    const dropped = {
      type: "file" as const,
      id: "dropped-file",
      name: "dropped.txt",
      mimeType: "text/plain",
      sizeBytes: 1,
      fileUri: "file:///dropped.txt",
    };
    appendComposerDraftAttachments(key, [kept, dropped], { appendReference: true });

    const before = getComposerDraftSnapshot(key);
    expect(before.text).toContain("dropped.txt");
    expect(before.context?.records).toHaveLength(2);

    replaceComposerDraftAttachments(key, [kept]);

    const after = getComposerDraftSnapshot(key);
    expect(after.attachments.map((attachment) => attachment.id)).toEqual([kept.id]);
    expect(after.text).not.toContain("dropped.txt");
    expect(after.context?.records.map((record) => record.contextId)).toEqual([
      before.context?.records[0]?.contextId,
    ]);
  });

  it("keeps over-limit recovery context reloadable without losing other drafts", () => {
    const key = "environment-1:recovery";
    const merged = mergeComposerDraftContentState(
      { [key]: contextDraft(0, 200), other: DRAFT },
      key,
      contextDraft(200, 200),
    );
    expect(merged[key]?.context?.records).toHaveLength(400);
    const reloaded = decodePersistedComposerState(
      JSON.parse(JSON.stringify({ schemaVersion: 1, drafts: merged })),
    ).drafts;
    expect(reloaded[key]).toEqual(merged[key]);
    expect(reloaded.other).toEqual(DRAFT);
  });

  it("prunes unreferenced context during a content merge", () => {
    const existing = contextDraft(0, 2);
    const incoming = contextDraft(2, 2);
    const merged = mergeComposerDraftContentState(
      { key: { ...existing, text: "[Skill](t3-context://v1/skill/skill-0)" } },
      "key",
      { ...incoming, text: "[Skill](t3-context://v1/skill/skill-2)" },
    );
    expect(merged.key?.context?.records.map((record) => record.contextId)).toEqual([
      "skill-0",
      "skill-2",
    ]);
  });

  it("restores and persists both full cloud and live context drafts", async () => {
    const load = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
    onTestFinished(() => load.mockRestore());
    await waitForComposerDraftsLoaded();
    const key = "environment-1:restored";
    appAtomRegistry.set(composerDraftsAtom, { [key]: contextDraft(0, 200) });
    appAtomRegistry.set(composerCloudDraftsAtom, {
      accountId: null,
      signedOut: { account: { drafts: { [key]: contextDraft(200, 200) }, queuedMessages: [] } },
    });
    await restoreCloudComposerDrafts("account");
    expect(getComposerDraftSnapshot(key).context?.records).toHaveLength(400);
    const reloaded = decodePersistedComposerState(JSON.parse(composerDraftFileMocks.getDocument()));
    expect(reloaded.drafts[key]?.context?.records).toHaveLength(400);
    expect(reloaded.cloudDrafts.signedOut).toEqual({});
  });

  it.each([
    { name: "notes.txt", mimeType: "text/plain" },
    { name: "document-photo.png", mimeType: "image/png" },
    { name: "recording.mp4", mimeType: "video/mp4" },
  ])(
    "removes $name after its last reference is deleted, while retaining native images",
    async ({ name, mimeType }) => {
      const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
      onTestFinished(() => outboxLoad.mockRestore());
      const cleanup = Promise.withResolvers<void>();
      composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
        cleanup.resolve();
      });
      const key = "environment-1:remove-context-files";
      const file = {
        id: "file-1",
        type: "file" as const,
        name,
        mimeType,
        sizeBytes: 4,
        fileUri: `file:///${name}`,
      };
      const image = {
        ...file,
        id: "image-1",
        type: "image" as const,
        name: "image.png",
        mimeType: "image/png",
        fileUri: "file:///image.png",
        previewUri: "file:///image.png",
      };
      appendComposerDraftAttachments(key, [file, image], { appendReference: true });
      const fileLink = formatComposerContextReference(
        getComposerDraftSnapshot(key).context!.records[0]!,
      );
      setComposerDraftText(key, `${fileLink} ${fileLink}`);
      expect(getComposerDraftSnapshot(key).attachments).toEqual([file, image]);
      setComposerDraftText(key, fileLink);
      expect(getComposerDraftSnapshot(key).attachments).toEqual([file, image]);
      expect(
        countComposerDraftAttachmentsAfterSelection(key, {
          text: fileLink,
          start: 0,
          end: fileLink.length,
        }),
      ).toBe(1);
      setComposerDraftText(key, "plain text");
      expect(getComposerDraftSnapshot(key).attachments).toEqual([image]);
      await cleanup.promise;
    },
  );

  it("rejects attachments atomically when no context slots remain", async () => {
    const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
    onTestFinished(() => outboxLoad.mockRestore());
    const cleanup = Promise.withResolvers<void>();
    composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
      cleanup.resolve();
    });
    const key = "environment-1:full-context";
    const records = Array.from({ length: 200 }, (_, index) => ({
      version: 1 as const,
      contextId: `ctx-${index}` as never,
      kind: "skill" as const,
      label: "Skill",
      name: "skill",
    }));
    appAtomRegistry.set(composerDraftsAtom, {
      [key]: {
        text: records
          .map((record) => `[Skill](t3-context://v1/skill/${record.contextId})`)
          .join(" "),
        context: { version: 1, records },
        attachments: [],
      },
    });
    const before = getComposerDraftSnapshot(key);
    expect(
      appendComposerDraftAttachments(
        key,
        [
          {
            id: "overflow",
            type: "file",
            name: "notes.txt",
            mimeType: "text/plain",
            sizeBytes: 4,
            fileUri: "file:///overflow.txt",
          },
        ],
        { appendReference: true },
      ),
    ).toBe(1);
    expect(getComposerDraftSnapshot(key)).toEqual(before);
    await cleanup.promise;
  });
  it.each(["environment-1:thread", "environment-1:new-task:draft"])(
    "preserves the captured paste selection across async writes in %s",
    async (key) => {
      const file = {
        id: "paste",
        type: "file" as const,
        name: "pasted-text.txt",
        mimeType: "text/plain",
        sizeBytes: 40_000,
        fileUri: "file:///paste.txt",
      };
      setComposerDraftText(key, "before selected after");
      const insertion = captureComposerDraftInsertion(key, { start: 7, end: 15 });
      const write = Promise.withResolvers<typeof file>();
      const pending = write.promise.then((attachment) =>
        appendComposerDraftAttachments(key, [attachment], { appendReference: true, insertion }),
      );
      rememberComposerDraftSelection(key, insertion.text, { start: 0, end: 6 });
      rememberComposerDraftSelection("another-draft", "unrelated", { start: 0, end: 9 });
      write.resolve(file);
      expect(await pending).toBe(0);
      const draft = getComposerDraftSnapshot(key);
      expect(draft.text).toBe("before [pasted-text.txt](t3-context://v1/file/paste) after");
      expect(draft.attachments).toEqual([file]);
    },
  );

  it("preserves edits made while a paste is pending instead of deleting stale offsets", async () => {
    const key = "environment-1:typing-during-paste";
    setComposerDraftText(key, "old selection");
    const insertion = captureComposerDraftInsertion(key, { start: 0, end: 13 });
    const write = Promise.withResolvers<void>();
    const pending = write.promise.then(() => insertComposerDraftText(key, " pasted", insertion));
    setComposerDraftText(key, "keep newly typed text");
    write.resolve();
    await pending;
    expect(getComposerDraftSnapshot(key).text).toBe("keep newly typed text pasted");
  });

  it.each(["attachment", "context", "imported context"])(
    "releases a selected file when replaced by %s",
    async (kind) => {
      const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
      onTestFinished(() => outboxLoad.mockRestore());
      const cleanup = Promise.withResolvers<void>();
      composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
        cleanup.resolve();
        return undefined;
      });
      const key = "environment-1:replace-file";
      const files = Array.from({ length: 100 }, (_, index) => ({
        id: `file-${index}`,
        type: "file" as const,
        name: `notes-${index}.txt`,
        mimeType: "text/plain",
        sizeBytes: 4,
        fileUri: `file:///notes-${index}.txt`,
      }));
      appendComposerDraftAttachments(key, files, { appendReference: true });
      const firstLink = "[notes-0.txt](t3-context://v1/file/file-0)";
      const insertion = captureComposerDraftInsertion(key, { start: 0, end: firstLink.length });
      expect(countComposerDraftAttachmentsAfterSelection(key, insertion)).toBe(99);
      expect(getComposerDraftAfterSelection(key, insertion).context?.records).toHaveLength(99);
      const replacement = { ...files[0]!, id: "replacement", fileUri: "file:///replacement.txt" };
      if (kind === "attachment") {
        expect(
          appendComposerDraftAttachments(key, [replacement], { appendReference: true, insertion }),
        ).toBe(0);
      } else if (kind === "imported context") {
        const record = {
          version: 1 as const,
          kind: "file" as const,
          contextId: ComposerContextId.make("replacement"),
          attachmentId: replacement.id,
          label: replacement.name,
          name: replacement.name,
          mimeType: replacement.mimeType,
          sizeBytes: replacement.sizeBytes,
        };
        expect(
          insertComposerDraftContext(
            key,
            {
              text: formatComposerContextReference(record),
              context: { version: 1, records: [record] },
              attachments: [replacement],
            },
            insertion,
          ),
        ).toBe(true);
        expect(getComposerDraftSnapshot(key).attachments).toHaveLength(100);
        expect(getComposerDraftSnapshot(key).context?.records).toContainEqual(record);
        expect(getComposerDraftSnapshot(key).text).toBe(
          `${formatComposerContextReference(record)}${insertion.text.slice(firstLink.length)}`,
        );
      } else {
        insertComposerDraftContext(
          key,
          { text: "replacement", context: { version: 1, records: [] } },
          insertion,
        );
      }
      const draft = getComposerDraftSnapshot(key);
      expect(draft.attachments.map((file) => file.id)).not.toContain("file-0");
      expect(draft.attachments.slice(0, 99)).toEqual(files.slice(1));
      expect(draft.context?.records.some((record) => record.contextId === "file-0")).toBe(false);
      await cleanup.promise;
      expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(files[0]!.fileUri);
    },
  );

  it("rejects an imported file atomically when edits during import use up its replacement slot", async () => {
    const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
    onTestFinished(() => outboxLoad.mockRestore());
    const cleanup = Promise.withResolvers<void>();
    composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
      cleanup.resolve();
      return undefined;
    });
    const key = "environment-1:concurrent-import";
    const files = Array.from({ length: 100 }, (_, index) => ({
      id: `existing-${index}`,
      type: "file" as const,
      name: `notes-${index}.txt`,
      mimeType: "text/plain",
      sizeBytes: 4,
      fileUri: `file:///notes-${index}.txt`,
    }));
    appendComposerDraftAttachments(key, files, { appendReference: true });
    const firstLink = "[notes-0.txt](t3-context://v1/file/existing-0)";
    const insertion = captureComposerDraftInsertion(key, { start: 0, end: firstLink.length });
    setComposerDraftText(key, `New edit ${insertion.text}`);
    const edited = getComposerDraftSnapshot(key);
    const imported = { ...files[0]!, id: "imported", fileUri: "file:///imported.txt" };
    const record = {
      version: 1 as const,
      kind: "file" as const,
      contextId: ComposerContextId.make("imported"),
      attachmentId: imported.id,
      label: imported.name,
      name: imported.name,
      mimeType: imported.mimeType,
      sizeBytes: imported.sizeBytes,
    };
    expect(
      insertComposerDraftContext(
        key,
        {
          text: formatComposerContextReference(record),
          context: { version: 1, records: [record] },
          attachments: [imported],
        },
        insertion,
      ),
    ).toBe(false);
    expect(getComposerDraftSnapshot(key)).toEqual(edited);
    await cleanup.promise;
    expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(imported.fileUri);
  });

  it("retains a file when replacing only one of its repeated references", () => {
    const key = "environment-1:repeat-reference";
    const file = {
      id: "repeat",
      type: "file" as const,
      name: "notes.txt",
      mimeType: "text/plain",
      sizeBytes: 4,
      fileUri: "file:///repeat.txt",
    };
    appendComposerDraftAttachments(key, [file], { appendReference: true });
    const link = getComposerDraftSnapshot(key).text;
    setComposerDraftText(key, `${link} ${link}`);
    const insertion = captureComposerDraftInsertion(key, { start: 0, end: link.length });
    expect(countComposerDraftAttachmentsAfterSelection(key, insertion)).toBe(1);
    insertComposerDraftContext(
      key,
      { text: "replaced", context: { version: 1, records: [] } },
      insertion,
    );
    expect(getComposerDraftSnapshot(key).attachments).toEqual([file]);
    expect(getComposerDraftSnapshot(key).text).toBe(`replaced ${link}`);
  });

  it("inserts context at the saved caret and retains its payload through persistence and restore", () => {
    const draftKey = "context-environment:context-thread";
    const record = {
      version: 1 as const,
      kind: "terminal" as const,
      contextId: ComposerContextId.make("context-terminal"),
      label: "Build output",
      terminalId: "main",
      terminalLabel: "Terminal",
      lineStart: 1,
      lineEnd: 1,
      text: "Build failed",
    };
    const reference = "[Build output](t3-context://v1/terminal/context-terminal)";
    setComposerDraftText(draftKey, "Fix this next");
    rememberComposerDraftSelection(draftKey, "Fix this next", { start: 4, end: 8 });
    insertComposerDraftContext(draftKey, {
      text: reference,
      context: { version: 1, records: [record] },
    });
    const draft = getComposerDraftSnapshot(draftKey);
    expect(draft.text).toBe(`Fix ${reference} next`);
    const decoded = decodePersistedComposerState(
      JSON.parse(JSON.stringify({ schemaVersion: 1, drafts: { [draftKey]: draft } })),
    ).drafts[draftKey];
    expect(decoded?.context?.records).toEqual([record]);
    const restored = mergeComposerDraftContentState(
      { [draftKey]: { text: "Additional work", attachments: [] } },
      draftKey,
      decoded!,
    );
    expect(restored[draftKey]?.text).toContain(reference);
    expect(restored[draftKey]?.context?.records).toEqual([record]);
    expect(clearComposerDraftContentState(restored, draftKey)[draftKey]?.context).toBeUndefined();
    setComposerDraftText(draftKey, "Fix next");
    expect(getComposerDraftSnapshot(draftKey).context).toBeUndefined();
  });

  it("keeps each draft's caret when another composer moves its own caret", () => {
    const threadKey = "caret-environment:caret-thread";
    const newTaskKey = "caret-environment:new-task:caret-draft";
    setComposerDraftText(threadKey, "Fix this next");
    setComposerDraftText(newTaskKey, "Another task");
    rememberComposerDraftSelection(threadKey, "Fix this next", { start: 4, end: 8 });
    rememberComposerDraftSelection(newTaskKey, "Another task", { start: 2, end: 2 });
    insertComposerDraftContext(threadKey, {
      text: "[Build output](t3-context://v1/terminal/caret-terminal)",
      context: {
        version: 1,
        records: [
          {
            version: 1,
            kind: "terminal",
            contextId: ComposerContextId.make("caret-terminal"),
            label: "Build output",
            terminalId: "main",
            terminalLabel: "Terminal",
            lineStart: 1,
            lineEnd: 1,
            text: "Build failed",
          },
        ],
      },
    });
    expect(getComposerDraftSnapshot(threadKey).text).toBe(
      "Fix [Build output](t3-context://v1/terminal/caret-terminal) next",
    );
  });

  it("releases videos rejected by the live draft limit and keeps accepted files", async () => {
    const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
    onTestFinished(() => outboxLoad.mockRestore());
    const cleanup = Promise.withResolvers<void>();
    composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
      cleanup.resolve();
    });
    const makeAttachment = (id: string) => ({
      id,
      type: "file" as const,
      name: `${id}.mov`,
      mimeType: "video/quicktime",
      sizeBytes: 42,
      fileUri: `file:///documents/t3-composer-attachments/${id}.mov`,
    });
    const draftKey = "new-task:environment-1:project-cap";
    const existing = Array.from({ length: 99 }, (_, index) => makeAttachment(`held-${index}`));
    appAtomRegistry.set(composerDraftsAtom, {
      [draftKey]: { text: "send this", attachments: existing },
    });

    const rejected = appendComposerDraftAttachments(draftKey, [
      makeAttachment("incoming-1"),
      makeAttachment("incoming-2"),
    ]);

    expect(rejected).toBe(1);
    const draft = appAtomRegistry.get(composerDraftsAtom)[draftKey];
    expect(draft?.attachments).toHaveLength(100);
    expect(draft?.attachments.at(-1)?.id).toBe("incoming-1");
    await cleanup.promise;
    expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledExactlyOnceWith(
      makeAttachment("incoming-2").fileUri,
    );

    const overflowRejected = appendComposerDraftAttachments(
      draftKey,
      [makeAttachment("restored-1")],
      { allowOverflow: true },
    );
    expect(overflowRejected).toBe(0);
    expect(appAtomRegistry.get(composerDraftsAtom)[draftKey]?.attachments).toHaveLength(101);
  });

  it("keeps shared attachment files until every draft releases them", async () => {
    const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
    onTestFinished(() => outboxLoad.mockRestore());
    const file = {
      id: "file-1",
      type: "file" as const,
      name: "report.pdf",
      mimeType: "application/pdf",
      sizeBytes: 42,
      fileUri: "file:///documents/t3-composer-attachments/report.pdf",
    };
    appAtomRegistry.set(composerDraftsAtom, {
      source: { text: "First draft", attachments: [file] },
      copied: { text: "Second draft", attachments: [file] },
    });

    await releaseUnusedComposerAttachmentFiles([file]);
    expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();

    appAtomRegistry.set(composerDraftsAtom, {
      copied: { text: "Second draft", attachments: [file] },
    });
    await releaseUnusedComposerAttachmentFiles([file]);
    expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();

    appAtomRegistry.set(composerDraftsAtom, {});
    await releaseUnusedComposerAttachmentFiles([file]);
    expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri);
  });

  it("retains a referenced file-backed image and releases it once unreferenced", async () => {
    const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
    onTestFinished(() => outboxLoad.mockRestore());
    const image = {
      id: "image-1",
      type: "image" as const,
      name: "photo.png",
      mimeType: "image/png",
      sizeBytes: 3,
      fileUri: "file:///documents/t3-composer-attachments/photo.png",
      previewUri: "file:///documents/t3-composer-attachments/photo.png",
    };
    appAtomRegistry.set(composerDraftsAtom, {
      "environment-1:thread-1": { text: "look at this", attachments: [image] },
    });

    await releaseUnusedComposerAttachmentFiles([image]);
    expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();

    appAtomRegistry.set(composerDraftsAtom, {});
    appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {
      "environment-1:thread-1": [
        {
          environmentId: EnvironmentId.make("environment-1"),
          threadId: ThreadId.make("thread-1"),
          messageId: MessageId.make("queued-image"),
          commandId: CommandId.make("command-image"),
          text: "look at this",
          attachments: [image],
          createdAt: "2026-08-31T12:00:00.000Z",
        },
      ],
    });
    await releaseUnusedComposerAttachmentFiles([image]);
    expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();

    appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
    await releaseUnusedComposerAttachmentFiles([image]);
    expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledExactlyOnceWith(image.fileUri);
  });

  it("keeps an image through an inline read after its draft is removed", async () => {
    const { prepareTurnAttachments } =
      await vi.importActual<typeof import("../lib/attachmentUpload")>("../lib/attachmentUpload");
    const image = {
      id: "image-reading",
      type: "image" as const,
      name: "photo.png",
      mimeType: "image/png",
      sizeBytes: 3,
      fileUri: "file:///documents/t3-composer-attachments/photo.png",
      previewUri: "file:///documents/t3-composer-attachments/photo.png",
    };
    const readStarted = Promise.withResolvers<void>();
    const read = Promise.withResolvers<void>();
    const removed = Promise.withResolvers<void>();
    let imageExists = true;
    composerDraftFileMocks.readImage.mockImplementation(async () => {
      readStarted.resolve();
      await read.promise;
      if (!imageExists) throw new Error("The image was deleted during its read");
      return "YWJj";
    });
    composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
      imageExists = false;
      removed.resolve();
    });
    appendComposerDraftAttachments("environment-1:thread-1", [image]);
    await flushComposerDrafts();
    const preparing = prepareTurnAttachments({
      environmentId: EnvironmentId.make("environment-1"),
      attachments: [image],
    });
    onTestFinished(async () => {
      read.resolve();
      await preparing.catch(() => undefined);
    });
    await readStarted.promise;
    clearComposerDraftContent("environment-1:thread-1", { deferAttachmentCleanup: true });
    await releaseUnusedComposerAttachmentFiles([image]);
    expect(imageExists).toBe(true);

    read.resolve();
    const prepared = await preparing;
    expect(prepared.status).toBe("ready");
    if (prepared.status !== "ready") return;
    expect(prepared.attachments).toEqual([
      {
        type: "image",
        name: "photo.png",
        mimeType: "image/png",
        sizeBytes: 3,
        dataUrl: "data:image/png;base64,YWJj",
      },
    ]);
    await removed.promise;
    expect(imageExists).toBe(false);
  });

  it("keeps a failed-send draft's pending upload for retry", async () => {
    const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
    onTestFinished(() => outboxLoad.mockRestore());
    const file = {
      id: "file-failed-send",
      type: "file" as const,
      name: "report.pdf",
      mimeType: "application/pdf",
      sizeBytes: 42,
      fileUri: "file:///documents/t3-composer-attachments/failed-send.pdf",
      uploadedAttachmentId: "pending-failed-send",
      uploadEnvironmentId: EnvironmentId.make("environment-1"),
    };
    appAtomRegistry.set(composerDraftsAtom, {
      "environment-1:thread-1": { text: "Retry this send", attachments: [file] },
    });

    await releaseUnusedComposerAttachmentFiles([file]);

    expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
    expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled();
  });

  it("retains offline image bytes and newer edits when an early upload finishes", async () => {
    const key = "environment-1:thread-1";
    const image = {
      id: "photo",
      type: "image" as const,
      name: "photo.png",
      mimeType: "image/png",
      sizeBytes: 3,
      dataUrl: "data:image/png;base64,YWJj",
      previewUri: "file:///photo.png",
    };
    const second = { ...image, id: "second", name: "second.png" };
    const uploaded = {
      ...image,
      uploadedAttachmentId: "pending-photo",
      uploadEnvironmentId: EnvironmentId.make("environment-1"),
    };
    composerDraftFileMocks.setDocument({ schemaVersion: 1, drafts: {} });
    appendComposerDraftAttachments(key, [image]);
    setComposerDraftText(key, "Edited while uploading");
    appendComposerDraftAttachments(key, [second]);
    expect(setComposerDraftAttachmentUpload(key, uploaded)).toBe(true);
    await flushComposerDrafts();

    appAtomRegistry.set(composerDraftsAtom, {});
    resetComposerDraftsLoadState();
    await waitForComposerDraftsLoaded();
    expect(getComposerDraftSnapshot(key)).toMatchObject({
      text: "Edited while uploading",
      attachments: [uploaded, second],
    });
    expect(setComposerDraftAttachmentUpload(key, { ...uploaded, id: "removed-photo" })).toBe(false);
    expect(getComposerDraftSnapshot(key).attachments).toHaveLength(2);
  });

  it.each(["file", "image"] as const)(
    "keeps signed-out %s attachments through cleanup and restart, and restores only the owning account",
    async (type) => {
      const load = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
      onTestFinished(() => load.mockRestore());
      await waitForComposerDraftsLoaded();
      const environmentId = EnvironmentId.make("cloud-environment");
      const key = `${environmentId}:thread-1`;
      const name = type === "image" ? "notes.png" : "notes.pdf";
      const metadata = {
        id: "local-notes",
        name,
        mimeType: type === "image" ? "image/png" : "application/pdf",
        sizeBytes: 42,
        fileUri: `file:///documents/t3-composer-attachments/${name}`,
        uploadEnvironmentId: environmentId,
        uploadedAttachmentId: "pending-notes",
      };
      const file =
        type === "image"
          ? { ...metadata, type, previewUri: metadata.fileUri }
          : { ...metadata, type };
      const queued = {
        environmentId,
        threadId: ThreadId.make("thread-2"),
        messageId: MessageId.make("queued-1"),
        commandId: CommandId.make("command-1"),
        text: "Send later",
        attachments: [file],
        createdAt: "2026-08-31T12:00:00.000Z",
      };
      appAtomRegistry.set(composerDraftsAtom, {
        [key]: { text: "Unsent notes", attachments: [file] },
        "direct-environment:thread-1": DRAFT,
        "pending-task:queued-1": { text: "Edited queued task", attachments: [file] },
      });
      appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, { queued: [queued] });
      await archiveCloudComposerDrafts("account-a", new Set([environmentId]), [
        environmentId,
        EnvironmentId.make("direct-environment"),
      ]);
      expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({
        "direct-environment:thread-1": DRAFT,
      });

      appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
      await clearComposerDraftsEnvironment(environmentId);
      await releaseUnusedComposerAttachmentFiles([file]);
      expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
      expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled();

      appAtomRegistry.set(composerDraftsAtom, {});
      appAtomRegistry.set(composerCloudDraftsAtom, { accountId: null, signedOut: {} });
      resetComposerDraftsLoadState();
      await waitForComposerDraftsLoaded();
      await restoreCloudComposerDrafts("account-b");
      expect(getComposerDraftSnapshot(key).attachments).toEqual([]);
      expect(appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom)).toEqual({});
      const enqueue = vi.spyOn(threadOutboxManager, "enqueue").mockResolvedValue();
      onTestFinished(() => enqueue.mockRestore());
      await restoreCloudComposerDrafts("account-a");
      expect(getComposerDraftSnapshot(key)).toEqual(
        type === "image"
          ? { text: "Unsent notes", attachments: [file] }
          : {
              text: "Unsent notes [notes.pdf](t3-context://v1/file/local-notes) ",
              attachments: [file],
              context: {
                version: 1,
                records: [
                  {
                    version: 1,
                    contextId: file.id,
                    kind: "file",
                    label: file.name,
                    attachmentId: file.id,
                    name: file.name,
                    mimeType: file.mimeType,
                    sizeBytes: file.sizeBytes,
                  },
                ],
              },
            },
      );
      expect(getComposerDraftSnapshot("pending-task:queued-1").text).toBe(
        type === "image"
          ? "Edited queued task"
          : "Edited queued task [notes.pdf](t3-context://v1/file/local-notes) ",
      );
      expect(enqueue).toHaveBeenCalledExactlyOnceWith(queued);
      expect(appAtomRegistry.get(composerCloudDraftsAtom).signedOut).toEqual({});
      const persisted = decodePersistedComposerState(
        JSON.parse(composerDraftFileMocks.getDocument()),
      );
      expect(persisted.drafts[key]?.attachments).toEqual([file]);
      expect(persisted.cloudDrafts.accountId).toBe("account-a");
    },
  );

  it("fails sign-out preservation before cleanup if a durable backup cannot be written", async () => {
    const load = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
    onTestFinished(() => load.mockRestore());
    await waitForComposerDraftsLoaded();
    appAtomRegistry.set(composerDraftsAtom, { "environment-1:thread-1": DRAFT });
    composerDraftFileMocks.setWriteError(new Error("Storage is full"));
    await expect(
      archiveCloudComposerDrafts("account-a", new Set([EnvironmentId.make("environment-1")]), [
        EnvironmentId.make("environment-1"),
      ]),
    ).rejects.toThrow();
    expect(
      appAtomRegistry.get(composerCloudDraftsAtom).signedOut["account-a"]?.drafts[
        "environment-1:thread-1"
      ],
    ).toEqual(DRAFT);
    expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
    composerDraftFileMocks.setWriteError(null);
    await archiveCloudComposerDrafts(null, new Set([EnvironmentId.make("environment-1")]), [
      EnvironmentId.make("environment-1"),
    ]);
    expect(
      decodePersistedComposerState(JSON.parse(composerDraftFileMocks.getDocument())).cloudDrafts
        .signedOut["account-a"]?.drafts["environment-1:thread-1"],
    ).toEqual(DRAFT);
  });

  it.each(["file", "image"] as const)(
    "keeps a removed %s until both preview and a share copy finish",
    async (type) => {
      const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
      onTestFinished(() => outboxLoad.mockRestore());
      const name = type === "image" ? "photo.png" : "recording.mp4";
      const fileName = `33333333-3333-4333-8333-333333333333-${name}`;
      const metadata = {
        id: "file-preview",
        name,
        mimeType: type === "image" ? "image/png" : "video/mp4",
        sizeBytes: 42,
        fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,
      };
      const file =
        type === "image"
          ? { ...metadata, type, previewUri: metadata.fileUri }
          : { ...metadata, type };
      const currentFile = {
        ...file,
        fileUri: `file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents/t3-composer-attachments/${fileName}`,
      };
      const releasePlayback = retainComposerAttachmentFileForPreview(file);
      const releaseShareCopy = retainComposerAttachmentFileForPreview(currentFile);
      onTestFinished(releasePlayback);
      onTestFinished(releaseShareCopy);

      await releaseUnusedComposerAttachmentFiles([currentFile]);
      expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();

      releasePlayback();
      releasePlayback();
      await releaseUnusedComposerAttachmentFiles([file]);
      expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();

      const deleted = Promise.withResolvers<void>();
      composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
        deleted.resolve();
        return undefined;
      });
      releaseShareCopy();
      await deleted.promise;

      expect(composerAttachmentCleanupMocks.remove.mock.calls).toEqual([[currentFile.fileUri]]);
    },
  );

  it("preserves a preview opened while cleanup is checking the incoming inbox", async () => {
    const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
    onTestFinished(() => outboxLoad.mockRestore());
    const file = {
      id: "file-opening-preview",
      type: "file" as const,
      name: "recording.mp4",
      mimeType: "video/mp4",
      sizeBytes: 42,
      fileUri: "file:///documents/t3-composer-attachments/recording.mp4",
    };
    const ownershipReadStarted = Promise.withResolvers<void>();
    const ownershipRead = Promise.withResolvers<[]>();
    incomingShareStorageMocks.load.mockImplementationOnce(() => {
      ownershipReadStarted.resolve();
      return ownershipRead.promise;
    });

    const cleanup = releaseUnusedComposerAttachmentFiles([file]);
    await ownershipReadStarted.promise;
    const release = retainComposerAttachmentFileForPreview(file);
    onTestFinished(release);
    ownershipRead.resolve([]);
    await cleanup;
    expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();

    const deleted = Promise.withResolvers<void>();
    composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
      deleted.resolve();
      return undefined;
    });
    release();
    await deleted.promise;
    expect(composerAttachmentCleanupMocks.remove.mock.calls).toEqual([[file.fileUri]]);
  });

  it("removes an unreferenced local file and its pending upload", async () => {
    const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
    onTestFinished(() => outboxLoad.mockRestore());
    const environmentId = EnvironmentId.make("environment-1");
    const file = {
      id: "file-discarded",
      type: "file" as const,
      name: "report.pdf",
      mimeType: "application/pdf",
      sizeBytes: 42,
      fileUri: "file:///documents/t3-composer-attachments/discarded.pdf",
      uploadedAttachmentId: "pending-discarded",
      uploadEnvironmentId: environmentId,
    };

    await releaseUnusedComposerAttachmentFiles([file]);

    expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri);
    expect(composerAttachmentCleanupMocks.releaseUploads).toHaveBeenCalledWith(environmentId, [
      "pending-discarded",
    ]);
  });

  it("keeps a pending upload referenced through another local file", async () => {
    const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
    onTestFinished(() => outboxLoad.mockRestore());
    const environmentId = EnvironmentId.make("environment-1");
    const discarded = {
      id: "file-discarded-copy",
      type: "file" as const,
      name: "report.pdf",
      mimeType: "application/pdf",
      sizeBytes: 42,
      fileUri: "file:///documents/t3-composer-attachments/discarded-copy.pdf",
      uploadedAttachmentId: "pending-shared",
      uploadEnvironmentId: environmentId,
    };
    const retained = {
      ...discarded,
      id: "file-retained-copy",
      fileUri: "file:///documents/t3-composer-attachments/retained-copy.pdf",
    };
    appAtomRegistry.set(composerDraftsAtom, {
      "environment-1:thread-1": { text: "Keep this copy", attachments: [retained] },
    });

    await releaseUnusedComposerAttachmentFiles([discarded]);

    expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(discarded.fileUri);
    expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled();
  });

  it("completes local cleanup when pending upload deletion fails", async () => {
    const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
    onTestFinished(() => outboxLoad.mockRestore());
    const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined);
    onTestFinished(() => warning.mockRestore());
    composerAttachmentCleanupMocks.releaseUploads.mockRejectedValueOnce(
      new Error("environment disconnected"),
    );
    const file = {
      id: "file-delete-failed",
      type: "file" as const,
      name: "report.pdf",
      mimeType: "application/pdf",
      sizeBytes: 42,
      fileUri: "file:///documents/t3-composer-attachments/delete-failed.pdf",
      uploadedAttachmentId: "pending-delete-failed",
      uploadEnvironmentId: EnvironmentId.make("environment-1"),
    };

    await expect(releaseUnusedComposerAttachmentFiles([file])).resolves.toBeUndefined();

    expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri);
    expect(warning).toHaveBeenCalledWith(
      "[composer-attachments] could not remove pending upload",
      expect.objectContaining({ attachmentId: "pending-delete-failed" }),
    );
  });

  it("keeps local attachment files while an outbox message still needs them", async () => {
    const file = {
      id: "file-queued",
      type: "file" as const,
      name: "report.pdf",
      mimeType: "application/pdf",
      sizeBytes: 42,
      fileUri: "file:///documents/t3-composer-attachments/report.pdf",
    };
    appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {
      "environment-1:thread-1": [
        {
          environmentId: EnvironmentId.make("environment-1"),
          threadId: ThreadId.make("thread-1"),
          messageId: MessageId.make("message-1"),
          commandId: CommandId.make("command-1"),
          text: "Review the report",
          attachments: [file],
          createdAt: "2026-08-24T12:00:00.000Z",
        },
      ],
    });

    await releaseUnusedComposerAttachmentFiles([file]);

    expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
  });

  it("loads persisted outbox messages before deciding an attachment file is unused", async () => {
    const file = {
      id: "file-persisted",
      type: "file" as const,
      name: "report.pdf",
      mimeType: "application/pdf",
      sizeBytes: 42,
      fileUri: "file:///documents/t3-composer-attachments/report.pdf",
    };
    const load = vi.spyOn(threadOutboxManager, "load").mockImplementation(async () => {
      appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {
        "environment-1:thread-1": [
          {
            environmentId: EnvironmentId.make("environment-1"),
            threadId: ThreadId.make("thread-1"),
            messageId: MessageId.make("message-persisted"),
            commandId: CommandId.make("command-persisted"),
            text: "Review the report",
            attachments: [file],
            createdAt: "2026-08-24T12:00:00.000Z",
          },
        ],
      });
      return true;
    });

    try {
      await releaseUnusedComposerAttachmentFiles([file]);

      expect(load).toHaveBeenCalledOnce();
      expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
    } finally {
      load.mockRestore();
    }
  });

  it("keeps a file until its incoming share is consumed", async () => {
    const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
    onTestFinished(() => outboxLoad.mockRestore());
    const file = {
      id: "file-incoming",
      type: "file" as const,
      name: "report.pdf",
      mimeType: "application/pdf",
      sizeBytes: 42,
      fileUri: "file:///documents/t3-composer-attachments/incoming.pdf",
    };
    incomingShareStorageMocks.load
      .mockResolvedValueOnce([
        {
          schemaVersion: 1,
          id: "share-1",
          createdAt: "2026-08-28T12:00:00.000Z",
          text: "Review this file",
          attachments: [file],
          warnings: [],
        },
      ])
      .mockResolvedValueOnce([]);

    await releaseUnusedComposerAttachmentFiles([file]);

    expect(incomingShareStorageMocks.load).toHaveBeenLastCalledWith({ strict: true });
    expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();

    await releaseUnusedComposerAttachmentFiles([file]);

    expect(incomingShareStorageMocks.load).toHaveBeenCalledTimes(2);
    expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri);
  });

  it("does not delete files when incoming share ownership cannot be loaded", async () => {
    const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
    onTestFinished(() => outboxLoad.mockRestore());
    const file = {
      id: "file-incoming-unknown",
      type: "file" as const,
      name: "report.pdf",
      mimeType: "application/pdf",
      sizeBytes: 42,
      fileUri: "file:///documents/t3-composer-attachments/incoming-unknown.pdf",
    };
    const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined);
    incomingShareStorageMocks.load.mockRejectedValueOnce(new Error("inbox unavailable"));
    onTestFinished(() => warning.mockRestore());

    await releaseUnusedComposerAttachmentFiles([file]);

    expect(incomingShareStorageMocks.load).toHaveBeenCalledWith({ strict: true });
    expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
  });

  it.each(["draft", "outbox", "inbox"] as const)(
    "preserves relocated files still referenced by a persisted %s",
    async (owner) => {
      const fileName = "33333333-3333-4333-8333-333333333333-report.pdf";
      const oldFile = {
        id: "file-relocated",
        type: "file" as const,
        name: "report.pdf",
        mimeType: "application/pdf",
        sizeBytes: 42,
        fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,
      };
      const currentFile = {
        ...oldFile,
        fileUri: `file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents/t3-composer-attachments/${fileName}`,
      };
      const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
      onTestFinished(() => outboxLoad.mockRestore());
      if (owner === "draft") {
        composerDraftFileMocks.setDocument({
          schemaVersion: 1,
          drafts: { "environment-1:thread-1": { text: "Saved draft", attachments: [oldFile] } },
        });
        resetComposerDraftsLoadState();
      } else if (owner === "outbox") {
        outboxLoad.mockImplementation(async () => {
          appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {
            "environment-1:thread-1": [
              {
                environmentId: EnvironmentId.make("environment-1"),
                threadId: ThreadId.make("thread-1"),
                messageId: MessageId.make("message-relocated"),
                commandId: CommandId.make("command-relocated"),
                text: "Queued draft",
                attachments: [oldFile],
                createdAt: "2026-08-28T12:00:00.000Z",
              },
            ],
          });
          return true;
        });
      } else {
        incomingShareStorageMocks.load.mockResolvedValue([
          {
            schemaVersion: 1,
            id: "share-relocated",
            createdAt: "2026-08-28T12:00:00.000Z",
            text: "Incoming file",
            attachments: [oldFile],
            warnings: [],
          },
        ]);
      }

      await releaseUnusedComposerAttachmentFiles([currentFile]);

      expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();

      appAtomRegistry.set(composerDraftsAtom, {});
      appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
      outboxLoad.mockResolvedValue(true);