TypeScript
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);
incomingShareStorageMocks.load.mockResolvedValue([]);
await releaseUnusedComposerAttachmentFiles([currentFile]);
expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(currentFile.fileUri);
},
);
it("does not delete attachment files when the draft removal cannot be saved", async () => {
const file = {
id: "file-unsaved",
type: "file" as const,
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 42,
fileUri: "file:///documents/t3-composer-attachments/report.pdf",
};
setComposerDraftText("environment-1:thread-1", "Unsaved draft");
composerDraftFileMocks.setWriteError(new Error("storage unavailable"));
try {
await expect(releaseUnusedComposerAttachmentFiles([file])).rejects.toBeInstanceOf(
ComposerDraftPersistenceError,
);
expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
} finally {
composerDraftFileMocks.setWriteError(null);
}
});
it("hydrates selector state even when the message content is empty", () => {
const hydrated = Object.entries(
decodePersistedComposerState({
schemaVersion: 1,
drafts: {
"new-task:environment-1:project-1": {
text: "",
attachments: [],
modelSelection: {
instanceId: "codex",
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
runtimeMode: "approval-required",
interactionMode: "plan",
workspaceSelection: {
mode: "worktree",
branch: "main",
worktreePath: null,
},
},
},
}).drafts,
);
expect(hydrated).toHaveLength(1);
const [key, draft] = hydrated[0]!;
expect(key).toMatch(/^new-task:[0-9a-z-]+$/);
expect(draft).toEqual({
text: "",
attachments: [],
modelSelection: {
instanceId: "codex",
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
runtimeMode: "approval-required",
interactionMode: "plan",
workspaceSelection: {
mode: "worktree",
branch: "main",
worktreePath: null,
},
project: {
environmentId: "environment-1",
projectId: "project-1",
createdAt: expect.any(String),
},
});
});
it("keeps share-import receipts on otherwise contentless new-task drafts", () => {
const receiptDraft: ComposerDraft = {
text: "",
attachments: [],
importedShareIds: ["share-1"],
};
const stripped = Object.values(
decodePersistedComposerState({
schemaVersion: 1,
drafts: {
"new-task:environment-1:project-1": {
...receiptDraft,
modelSelection: {
instanceId: "codex",
model: "gpt-5.4",
},
},
},
}).drafts,
);
expect(stripped).toHaveLength(1);
expect(stripped[0]).toMatchObject({
text: "",
attachments: [],
importedShareIds: ["share-1"],
project: { environmentId: "environment-1", projectId: "project-1" },
});
expect(stripped[0]?.modelSelection).toBeUndefined();
const kept = Object.values(
decodePersistedComposerState({
schemaVersion: 1,
drafts: { "new-task:environment-1:project-1": receiptDraft },
}).drafts,
);
expect(kept).toHaveLength(1);
expect(kept[0]).toMatchObject(receiptDraft);
});
it("migrates project-keyed new-task drafts to id keys with the project stamped in", () => {
const now = "2026-09-05T12:00:00.000Z";
const [key, draft] = migrateLegacyNewTaskDraft(
"new-task:environment-1:project-1",
{ text: "keep me", attachments: [] },
now,
);
expect(key).toMatch(/^new-task:[0-9a-z-]+$/);
expect(draft).toEqual({
text: "keep me",
attachments: [],
project: {
environmentId: EnvironmentId.make("environment-1"),
projectId: ProjectId.make("project-1"),
createdAt: now,
},
});
const stamped: ComposerDraft = {
text: "x",
attachments: [],
project: {
environmentId: EnvironmentId.make("environment-1"),
projectId: ProjectId.make("project-1"),
createdAt: now,
},
};
expect(migrateLegacyNewTaskDraft("new-task:some-id", stamped, now)).toEqual([
"new-task:some-id",
stamped,
]);
expect(migrateLegacyNewTaskDraft("environment-1:thread-1", DRAFT, now)).toEqual([
"environment-1:thread-1",
DRAFT,
]);
expect(migrateLegacyNewTaskDraft("pending-task:message-1", DRAFT, now)).toEqual([
"pending-task:message-1",
DRAFT,
]);
});
it("keeps a freshly minted new-task draft bound until content arrives, then lists it per project", () => {
const project = {
environmentId: EnvironmentId.make("environment-1"),
projectId: ProjectId.make("project-1"),
};
const first = createNewTaskDraft(project);
const second = createNewTaskDraft(project);
expect(first).not.toBe(second);
expect(appAtomRegistry.get(composerDraftsAtom)[first]?.project).toMatchObject(project);
setComposerDraftText(first, "first idea");
setComposerDraftText(second, "second idea");
expect(findNewTaskDraftKeys(appAtomRegistry.get(composerDraftsAtom), project)).toEqual(
expect.arrayContaining([first, second]),
);
clearComposerDraftContent(first, { clearModelSelection: true, clearWorkspaceSelection: true });
expect(appAtomRegistry.get(composerDraftsAtom)[first]).toBeUndefined();
expect(getComposerDraftSnapshot(second).text).toBe("second idea");
});
it("retargets a new-task draft to another project without losing its text", () => {
const from = {
environmentId: EnvironmentId.make("environment-1"),
projectId: ProjectId.make("project-1"),
};
const to = {
environmentId: EnvironmentId.make("environment-2"),
projectId: ProjectId.make("project-2"),
};
const key = createNewTaskDraft(from);
setComposerDraftText(key, "moving house");
appAtomRegistry.set(composerDraftsAtom, {
...appAtomRegistry.get(composerDraftsAtom),
[key]: {
...getComposerDraftSnapshot(key),
runtimeMode: "approval-required",
workspaceSelection: { mode: "worktree", branch: "feature/a", worktreePath: null },
},
});
const createdAt = getComposerDraftSnapshot(key).project?.createdAt;
retargetNewTaskDraft(key, to);
const moved = getComposerDraftSnapshot(key);
expect(moved.text).toBe("moving house");
expect(moved.runtimeMode).toBe("approval-required");
expect(moved.workspaceSelection).toBeUndefined();
expect(moved.project).toEqual({ ...to, createdAt });
expect(findNewTaskDraftKeys(appAtomRegistry.get(composerDraftsAtom), from)).toEqual([]);
expect(findNewTaskDraftKeys(appAtomRegistry.get(composerDraftsAtom), to)).toEqual([key]);
});
it("merges persisted option memory without replacing newer choices", async () => {
composerDraftFileMocks.setDocument({
schemaVersion: 1,
drafts: {},
modelOptionMemory: {
pi: {
"xai/grok-4.6": [{ id: "thinking", value: "high" }],
"openai/gpt-5.4": [{ id: "thinking", value: "medium" }],
},
},
});
appAtomRegistry.set(modelOptionMemoryAtom, {
pi: { "xai/grok-4.6": [{ id: "thinking", value: "xhigh" }] },
});
ensureComposerDraftsLoaded();
await waitForComposerDraftsLoaded();
expect(appAtomRegistry.get(modelOptionMemoryAtom)).toEqual({
pi: {
"xai/grok-4.6": [{ id: "thinking", value: "xhigh" }],
"openai/gpt-5.4": [{ id: "thinking", value: "medium" }],
},
});
});
it("flush waits for pending hydration instead of clobbering disk", async () => {
vi.useFakeTimers();
composerDraftFileMocks.setDocument({
schemaVersion: 1,
drafts: {
"environment-1:thread-1": DRAFT,
},
stickyModelSelection: {
instanceId: "codex",
model: "gpt-5.6-sol",
},
});
composerDraftFileMocks.blockRead();
composerDraftFileMocks.resetWrites();
ensureComposerDraftsLoaded();
await Promise.resolve();
setComposerDraftText("new-task:environment-1:project-1", "New prompt");
const flush = flushComposerDrafts();
await vi.advanceTimersByTimeAsync(200);
expect(composerDraftFileMocks.getWrites()).toHaveLength(0);
composerDraftFileMocks.releaseRead();
await flush;
const written = JSON.parse(composerDraftFileMocks.getDocument());
expect(written.drafts["environment-1:thread-1"]).toEqual(DRAFT);
expect(written.drafts["new-task:environment-1:project-1"]).toEqual({
text: "New prompt",
attachments: [],
});
expect(written.stickyModelSelection).toEqual({
instanceId: "codex",
model: "gpt-5.6-sol",
});
});
it.each(["read", "decode"] as const)(
"preserves saved drafts and attachment files when the draft %s fails",
async (failure) => {
vi.useFakeTimers();
const file = {
id: "saved-file",
type: "file" as const,
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 42,
fileUri: "file:///documents/t3-composer-attachments/report.pdf",
};
composerDraftFileMocks.setDocument({
schemaVersion: failure === "decode" ? 999 : 1,
drafts: { "environment-1:saved": { text: "Saved draft", attachments: [file] } },
});
const original = composerDraftFileMocks.getDocument();
if (failure === "read") {
composerDraftFileMocks.setReadError(new Error("storage unavailable"));
}
await expect(releaseUnusedComposerAttachmentFiles([file])).rejects.toMatchObject({
operation: failure,
});
setComposerDraftText("environment-1:new", "Keep my new edits too");
await expect(flushComposerDrafts()).rejects.toMatchObject({ operation: failure });
expect(composerDraftFileMocks.getDocument()).toBe(original);
expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
},
);
it("serializes environment cleanup after an older queued write", async () => {
vi.useFakeTimers();
composerDraftFileMocks.setDocument({ schemaVersion: 1, drafts: {} });
composerDraftFileMocks.resetWrites();
let releaseFirstWrite!: () => void;
const firstWriteBarrier = new Promise<void>((resolve) => {
releaseFirstWrite = resolve;
});
composerDraftFileMocks.setNextWriteBarrier(firstWriteBarrier);
let writeCount = 0;
const bothWritesCommitted = new Promise<void>((resolve) => {
composerDraftFileMocks.setOnWrite(() => {
writeCount += 1;
if (writeCount === 2) {
resolve();
}
});
});
appAtomRegistry.set(composerDraftsAtom, {
"environment-1:thread-1": DRAFT,
"environment-2:thread-2": { text: "keep", attachments: [] },
});
setStickyComposerModelSelection({
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.6-sol",
});
await vi.advanceTimersByTimeAsync(200);
const clear = clearComposerDraftsEnvironment(EnvironmentId.make("environment-1"));
await Promise.resolve();
expect(composerDraftFileMocks.getWrites()).toHaveLength(0);
releaseFirstWrite();
await clear;
await bothWritesCommitted;
expect(JSON.parse(composerDraftFileMocks.getDocument())).toEqual({
schemaVersion: 1,
drafts: {
"environment-2:thread-2": { text: "keep", attachments: [] },
},
stickyModelSelection: {
instanceId: "codex",
model: "gpt-5.6-sol",
},
});
});
it("clears sent content without clearing the selected model or workspace", () => {
const draftKey = "environment-1:thread-1";
const draft: ComposerDraft = {
text: "send this",
attachments: [],
importedShareIds: ["share-1"],
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
workspaceSelection: {
mode: "worktree",
branch: "main",
worktreePath: null,
},
};
expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({
[draftKey]: {
modelSelection: draft.modelSelection,
workspaceSelection: draft.workspaceSelection,
text: "",
attachments: [],
},
});
});
it("drops another environment's upload stamp when a draft moves across machines", () => {
const uploadedElsewhere: DraftComposerAttachment = {
id: "image-1",
type: "image",
name: "screen.png",
mimeType: "image/png",
sizeBytes: 1,
previewUri: "file:///drafts/screen.png",
fileUri: "file:///drafts/screen.png",
uploadedAttachmentId: "upload-1",
uploadEnvironmentId: EnvironmentId.make("environment-1"),
};
const uploadedOnTarget: DraftComposerAttachment = {
...uploadedElsewhere,
id: "image-2",
uploadedAttachmentId: "upload-2",
uploadEnvironmentId: EnvironmentId.make("environment-2"),
};
const key = createNewTaskDraft({
environmentId: EnvironmentId.make("environment-1"),
projectId: ProjectId.make("project-1"),
});
appAtomRegistry.set(composerDraftsAtom, {
...appAtomRegistry.get(composerDraftsAtom),
[key]: {
...getComposerDraftSnapshot(key),
text: "Ship it",
attachments: [uploadedElsewhere, uploadedOnTarget],
},
});
retargetNewTaskDraft(key, {
environmentId: EnvironmentId.make("environment-2"),
projectId: ProjectId.make("project-2"),
});
expect(getComposerDraftSnapshot(key).attachments).toEqual([
{
id: "image-1",
type: "image",
name: "screen.png",
mimeType: "image/png",
sizeBytes: 1,
previewUri: "file:///drafts/screen.png",
fileUri: "file:///drafts/screen.png",
},
uploadedOnTarget,
]);
});
it("merges shared content into a project draft without duplicating retries", () => {
const draftKey = "new-task:environment-1:project-1";
const sharedAttachment = {
id: "share-1:image:0",
type: "image" as const,
name: "Screenshot.png",
mimeType: "image/png",
sizeBytes: 3,
dataUrl: "data:image/png;base64,YWJj",
previewUri: "data:image/png;base64,YWJj",
};
const existing: Record<string, ComposerDraft> = {
[draftKey]: { text: "Existing context", attachments: [] },
};
const content = {
text: "Shared note",
attachments: [sharedAttachment],
sourceShareId: "share-1",
};
const merged = mergeComposerDraftContentState(existing, draftKey, content);
expect(merged[draftKey]).toMatchObject({
text: "Existing context\n\nShared note",
attachments: [sharedAttachment],
importedShareIds: ["share-1"],
});
expect(mergeComposerDraftContentState(merged, draftKey, content)).toBe(merged);
const edited = {
...merged,
[draftKey]: { ...merged[draftKey]!, text: "User edited the imported context" },
};
expect(mergeComposerDraftContentState(edited, draftKey, content)).toBe(edited);
});
it("shows a shared non-image file as a composer chip", () => {
const draftKey = "new-task:environment-1:project-1";
const sharedFile = {
id: "share-1:file:0",
type: "file" as const,
name: "backup.json",
mimeType: "application/json",
sizeBytes: 41,
fileUri: "file:///documents/backup.json",
};
const existingFile = { ...sharedFile, id: "existing-file", name: "notes.txt" };
const merged = mergeComposerDraftContentState(
{ [draftKey]: { text: "", attachments: [existingFile] } },
draftKey,
{ text: "", attachments: [sharedFile], sourceShareId: "share-1" },
)[draftKey]!;
expect(merged.attachments).toEqual([existingFile, sharedFile]);
const references = collectComposerContextReferences(merged.text);
expect(references).toHaveLength(1);
expect(merged.context?.records).toEqual([
expect.objectContaining({
kind: "file",
contextId: references[0]!.contextId,
attachmentId: sharedFile.id,
}),
]);
// A recovery merge carries its own text; a chip appended to it would
// break the duplicate-text check when the merge is retried.
const recovered = { text: "Retry this", attachments: [sharedFile] };
const once = mergeComposerDraftContentState({}, draftKey, recovered);
expect(once[draftKey]?.text).toBe("Retry this");
expect(mergeComposerDraftContentState(once, draftKey, recovered)).toBe(once);
});
it("preserves existing images when shared content exceeds the draft attachment limit", () => {
const draftKey = "new-task:environment-1:project-1";
const image = (id: string) => ({
id,
type: "image" as const,
name: `${id}.png`,
mimeType: "image/png",
sizeBytes: 3,
dataUrl: "data:image/png;base64,YWJj",
previewUri: "data:image/png;base64,YWJj",
});
const existingImage = image("existing");
const sharedImages = Array.from({ length: 100 }, (_, index) => image(`shared-${index}`));
const merged = mergeComposerDraftContentState(
{ [draftKey]: { text: "", attachments: [existingImage] } },
draftKey,
{ text: "", attachments: sharedImages },
);
expect(merged[draftKey]?.attachments).toHaveLength(100);
expect(merged[draftKey]?.attachments[0]).toEqual(existingImage);
expect(merged[draftKey]?.attachments.at(-1)?.id).toBe("shared-98");
});
it("restores the exact draft captured before an interrupted share import", () => {
const draftKey = "new-task:environment-1:project-1";
const beforeImport: ComposerDraft = {
text: "Existing context",
attachments: [],
runtimeMode: "approval-required",
};
const imported: ComposerDraft = {
...beforeImport,
text: "Existing context\n\nShared note",
importedShareIds: ["share-1"],
};
expect(
restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, beforeImport),
).toEqual({ [draftKey]: beforeImport });
expect(
restoreComposerDraftSnapshotState({ [draftKey]: imported }, draftKey, {
text: "",
attachments: [],
}),
).toEqual({});
});
it("removes only drafts owned by the selected environment", () => {
const environmentId = EnvironmentId.make("environment-cloud");
const retainedEnvironmentId = EnvironmentId.make("environment-local");
const cloudDraft: ComposerDraft = {
...DRAFT,
project: {
environmentId,
projectId: ProjectId.make("project-cloud"),
createdAt: "2026-09-05T00:00:00.000Z",
},
};
const localDraft: ComposerDraft = {
...DRAFT,
project: {
environmentId: retainedEnvironmentId,
projectId: ProjectId.make("project-local"),
createdAt: "2026-09-05T00:00:00.000Z",
},
};
expect(
removeComposerDraftsForEnvironment(
{
[`${environmentId}:thread-cloud`]: DRAFT,
"new-task:cloud-draft": cloudDraft,
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
"new-task:local-draft": localDraft,
},
environmentId,
),
).toEqual({
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
"new-task:local-draft": localDraft,
});
});
it("aborts operations running for drafts an environment removal drops", async () => {
const environmentId = EnvironmentId.make("environment-removed");
composerDraftFileMocks.setDocument({ schemaVersion: 1, drafts: {} });
appAtomRegistry.set(composerDraftsAtom, {
"new-task:removed-draft": {
...DRAFT,
project: {
environmentId,
projectId: ProjectId.make("project-removed"),
createdAt: "2026-09-05T00:00:00.000Z",
},
},
"environment-kept:thread-kept": DRAFT,
});
const newTask = startComposerDraftOperation("new-task:removed-draft");
const emptyThread = startComposerDraftOperation(`${environmentId}:thread-empty`);
const kept = startComposerDraftOperation("environment-kept:thread-kept");
await clearComposerDraftsEnvironment(environmentId);
expect(newTask.signal.aborted).toBe(true);
expect(emptyThread.signal.aborted).toBe(true);
expect(kept.signal.aborted).toBe(false);
kept.finish();
});
it("lands a still-debounced draft write when flushed", async () => {
const draftKey = "environment-1:thread-1";
setComposerDraftText(draftKey, "typed right before the restart");
await flushComposerDrafts();
expect(JSON.parse(composerDraftFileMocks.getDocument())).toMatchObject({
drafts: { [draftKey]: { text: "typed right before the restart" } },
});
});
it("propagates a flush write failure instead of resolving as saved", async () => {
const draftKey = "environment-1:thread-1";
setComposerDraftText(draftKey, "unsaved");
composerDraftFileMocks.setWriteError(new Error("storage unavailable"));
try {
await expect(flushComposerDrafts()).rejects.toBeInstanceOf(ComposerDraftPersistenceError);
} finally {
composerDraftFileMocks.setWriteError(null);
}
});
it("restores the pre-merge snapshot when the draft is untouched since the merge", () => {
const draftKey = "environment-1:thread-1";
const snapshot: ComposerDraft = { text: "typed before", attachments: [] };
const merged: ComposerDraft = {
text: "typed before\n\nqueued text",
attachments: [],
runtimeMode: "approval-required",
};
expect(undoComposerDraftMergeState({ [draftKey]: merged }, draftKey, snapshot, merged)).toEqual(
{ [draftKey]: snapshot },
);
expect(
undoComposerDraftMergeState(
{ [draftKey]: merged },
draftKey,
{ text: "", attachments: [] },
merged,
),
).toEqual({});
});
it("returns merge-written settings to the snapshot but keeps user-edited ones", () => {
const draftKey = "environment-1:thread-1";
const snapshot: ComposerDraft = {
text: "typed before",
attachments: [],
runtimeMode: "approval-required",
interactionMode: "default",
};
const merged: ComposerDraft = {
text: "typed before\n\nqueued text",
attachments: [],
runtimeMode: "full-access",
interactionMode: "default",
};
const edited: ComposerDraft = {
text: "typed EDITED before\n\nqueued text",
attachments: [],
runtimeMode: "full-access",
interactionMode: "plan",
};
expect(undoComposerDraftMergeState({ [draftKey]: edited }, draftKey, snapshot, merged)).toEqual(
{
[draftKey]: {
text: "typed EDITED before",
attachments: [],
runtimeMode: "approval-required",
interactionMode: "plan",
},
},
);
});
it("takes out only what the merge inserted when the user edited during it", () => {
const draftKey = "environment-1:thread-1";
const keptAttachment = {
id: "kept",
type: "file" as const,
name: "kept.pdf",
mimeType: "application/pdf",
sizeBytes: 1,
fileUri: "file:///documents/t3-composer-attachments/kept.pdf",
};
const insertedAttachment = {
id: "inserted",
type: "file" as const,
name: "inserted.pdf",
mimeType: "application/pdf",
sizeBytes: 1,
fileUri: "file:///documents/t3-composer-attachments/inserted.pdf",
};
const userAttachment = { ...keptAttachment, id: "user-added" };
const snapshot: ComposerDraft = { text: "typed before", attachments: [keptAttachment] };
const merged: ComposerDraft = {
text: "typed before\n\nqueued text",
attachments: [keptAttachment, insertedAttachment],
};
const edited: ComposerDraft = {
text: "typed EDITED before\n\nqueued text",
attachments: [keptAttachment, insertedAttachment, userAttachment],
};
expect(undoComposerDraftMergeState({ [draftKey]: edited }, draftKey, snapshot, merged)).toEqual(
{
[draftKey]: {
text: "typed EDITED before",
attachments: [keptAttachment, userAttachment],
},
},
);
const rewritten: ComposerDraft = {
text: "totally rewritten",
attachments: [insertedAttachment],
};
expect(
undoComposerDraftMergeState({ [draftKey]: rewritten }, draftKey, snapshot, merged),
).toEqual({
[draftKey]: { text: "totally rewritten", attachments: [] },
});
});
it("keeps text appended after a merge when rolling it back", () => {
const draftKey = "environment-1:thread-1";
const snapshot: ComposerDraft = { text: "typed before", attachments: [] };
const content = { text: "queued text", attachments: [] };
const merged = mergeComposerDraftContentState({ [draftKey]: snapshot }, draftKey, content)[
draftKey
]!;
const edited: ComposerDraft = {
...merged,
text: `${merged.text}\n\nuser follow-up`,
};
const rolledBack = undoComposerDraftMergeState(
{ [draftKey]: edited },
draftKey,
snapshot,
merged,
);
expect(rolledBack[draftKey]?.text).toBe("typed before\n\nuser follow-up");
const retried = mergeComposerDraftContentState(rolledBack, draftKey, content);
expect(retried[draftKey]?.text.match(/queued text/g)).toHaveLength(1);
});
it("spares a file re-owned between the sweep's scan and its deletion", async () => {
const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
onTestFinished(() => outboxLoad.mockRestore());
const fileFor = (id: string) => ({
id,
type: "file" as const,
name: `${id}.pdf`,
mimeType: "application/pdf",
sizeBytes: 42,
fileUri: `file:///documents/t3-composer-attachments/${id}.pdf`,
});
const first = fileFor("file-first");
const reowned = fileFor("file-reowned");
composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => {
appAtomRegistry.set(composerDraftsAtom, {
"environment-1:thread-1": { text: "restored", attachments: [reowned] },
});
});
await releaseUnusedComposerAttachmentFiles([first, reowned]);
expect(composerAttachmentCleanupMocks.remove.mock.calls).toEqual([[first.fileUri]]);
});
it("keeps attachment files and uploads after a recovered message leaves an incomplete outbox", async () => {
vi.resetModules();
const drafts = await import("./use-composer-drafts");
const { threadOutboxManager: manager } = await import("./thread-outbox");
const { expoThreadOutboxStorage: storage, ThreadOutboxStorageError } =
await import("./thread-outbox-storage");
const { removeThreadOutboxMessage } = await import("./thread-outbox-removal");
const { appAtomRegistry: registry } = await import("./atom-registry");
onTestFinished(() => registry.dispose());
const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
onTestFinished(() => warning.mockRestore());
const file = {
id: "file-partial-outbox",
type: "file" as const,
name: "shared.pdf",
mimeType: "application/pdf",
sizeBytes: 42,
fileUri: "file:///documents/t3-composer-attachments/shared.pdf",
uploadEnvironmentId: EnvironmentId.make("environment-1"),
uploadedAttachmentId: "pending-partial-outbox",
};
const readable = {
environmentId: EnvironmentId.make("environment-1"),
threadId: ThreadId.make("thread-1"),
messageId: MessageId.make("message-readable"),
commandId: CommandId.make("command-readable"),
text: "Send the readable message",
attachments: [file],
createdAt: "2026-09-04T00:00:00.000Z",
};
const saved = new Map([[readable.messageId, readable]]);
let unreadable = true;
const load = vi.spyOn(storage, "load").mockImplementation(async () => ({
messages: [...saved.values()],
errors: unreadable
? [
new ThreadOutboxStorageError({
operation: "read-message",
environmentId: null,
threadId: null,
messageId: null,
fileName: "unreadable.json",
cause: new Error("unreadable record"),
}),
]
: [],
}));
const remove = vi.spyOn(storage, "remove").mockImplementation(async (message) => {
saved.delete(message.messageId);
});
onTestFinished(() => {
load.mockRestore();
remove.mockRestore();
});
await expect(manager.load()).resolves.toBe(false);
await expect(manager.confirmQueued(readable)).resolves.toBe(true);
await expect(removeThreadOutboxMessage(readable)).resolves.toBe(true);
await drafts.releaseUnusedComposerAttachmentFiles([file]);
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({});
expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled();
const recovered = {
...readable,
environmentId: EnvironmentId.make("environment-2"),
messageId: MessageId.make("message-recovered"),
commandId: CommandId.make("command-recovered"),
};
saved.set(recovered.messageId, recovered);
unreadable = false;
await expect(manager.load()).resolves.toBe(true);
await drafts.releaseUnusedComposerAttachmentFiles([file]);
expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled();
await removeThreadOutboxMessage(recovered);
await drafts.releaseUnusedComposerAttachmentFiles([file]);
expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri);
expect(composerAttachmentCleanupMocks.releaseUploads).toHaveBeenCalledWith(
file.uploadEnvironmentId,
[file.uploadedAttachmentId],
);
});
it("hydrates persisted drafts before a cold-start sweep deletes their files", async () => {
const file = {
id: "file-cold-start",
type: "file" as const,
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 42,
fileUri: "file:///documents/t3-composer-attachments/report.pdf",
};
composerDraftFileMocks.setDocument({
schemaVersion: 1,
drafts: {
"environment-1:thread-1": { text: "Persisted draft", attachments: [file] },
},
});
vi.resetModules();
const fresh = await import("./use-composer-drafts");
const freshRegistry = (await import("./atom-registry")).appAtomRegistry;
await fresh.releaseUnusedComposerAttachmentFiles([file]);
expect(freshRegistry.get(fresh.composerDraftsAtom)).toEqual({
"environment-1:thread-1": {
text: "Persisted draft [report.pdf](t3-context://v1/file/file-cold-start) ",
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(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
});
});