feat(mobile): pick, share, and receive files in threads (#8237)
Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
47 files changed
+7460
-298
No files matched your search
@@ -148,12 +148,13 @@ const sharingPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
|
||||
supportsText: true,
|
||||
supportsWebUrlWithMaxCount: 1,
|
||||
supportsImageWithMaxCount: 8,
|
||||
supportsFileWithMaxCount: 8,
|
||||
},
|
||||
},
|
||||
android: {
|
||||
enabled: true,
|
||||
singleShareMimeTypes: ["text/plain", "image/*"],
|
||||
multipleShareMimeTypes: ["image/*"],
|
||||
singleShareMimeTypes: ["*/*"],
|
||||
multipleShareMimeTypes: ["*/*"],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { SymbolView } from "../components/AppSymbol";
|
||||
import { Image, Pressable, ScrollView, View } from "react-native";
|
||||
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { AppText as Text } from "./AppText";
|
||||
import type { DraftComposerAttachment } from "../lib/composerImages";
|
||||
|
||||
export interface ComposerAttachmentStripProps {
|
||||
/** Attachment images to display. */
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
/** Called when the user taps the remove button on an image. */
|
||||
/** Attachments to display. */
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
/** Called when the user removes an attachment. */
|
||||
readonly onRemove: (imageId: string) => void;
|
||||
/** Called when the user taps on an image thumbnail to preview it. */
|
||||
readonly onPressImage?: (previewUri: string) => void;
|
||||
@@ -19,8 +20,7 @@ export interface ComposerAttachmentStripProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* A horizontally-scrollable strip of image attachment thumbnails with remove
|
||||
* buttons. Used by both the thread composer and the new-task draft screen.
|
||||
* Attachment thumbnails used by the thread composer and the new-task draft screen.
|
||||
*/
|
||||
export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
|
||||
const size = props.imageSize ?? 72;
|
||||
@@ -40,29 +40,47 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
|
||||
className="grow-0"
|
||||
>
|
||||
<View className="flex-row gap-2.5">
|
||||
{props.attachments.map((image) => (
|
||||
{props.attachments.map((attachment) => (
|
||||
<View
|
||||
key={image.id}
|
||||
key={attachment.id}
|
||||
className="relative"
|
||||
style={{
|
||||
paddingTop: removeButtonGutter,
|
||||
paddingRight: removeButtonGutter,
|
||||
}}
|
||||
>
|
||||
<Pressable
|
||||
onPress={props.onPressImage ? () => props.onPressImage!(image.previewUri) : undefined}
|
||||
>
|
||||
<Image
|
||||
source={{ uri: image.previewUri }}
|
||||
className="bg-subtle"
|
||||
{attachment.type === "image" ? (
|
||||
<Pressable
|
||||
onPress={
|
||||
props.onPressImage ? () => props.onPressImage!(attachment.previewUri) : undefined
|
||||
}
|
||||
>
|
||||
<Image
|
||||
source={{ uri: attachment.previewUri }}
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
borderRadius: radius,
|
||||
}}
|
||||
className="bg-subtle"
|
||||
resizeMode="cover"
|
||||
/>
|
||||
</Pressable>
|
||||
) : (
|
||||
<View
|
||||
className="items-center justify-center gap-1 bg-subtle px-2"
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
borderRadius: radius,
|
||||
}}
|
||||
resizeMode="cover"
|
||||
/>
|
||||
</Pressable>
|
||||
>
|
||||
<SymbolView name="doc.text" size={22} tintColor="#a3a3a3" type="monochrome" />
|
||||
<Text className="w-full text-center text-2xs text-foreground" numberOfLines={1}>
|
||||
{attachment.name}
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
<Pressable
|
||||
className="absolute h-[22px] w-[22px] items-center justify-center rounded-[11px] bg-black/55"
|
||||
style={{
|
||||
@@ -70,7 +88,7 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
|
||||
right: removeButtonPlacement === "gutter" ? 0 : 4,
|
||||
}}
|
||||
hitSlop={6}
|
||||
onPress={() => props.onRemove(image.id)}
|
||||
onPress={() => props.onRemove(attachment.id)}
|
||||
>
|
||||
<SymbolView
|
||||
name="xmark"
|
||||
|
||||
@@ -29,7 +29,7 @@ import { authClientMetadata } from "../lib/authClientMetadata";
|
||||
import * as Runtime from "../lib/runtime";
|
||||
import * as MobileStorage from "../persistence/mobile-storage";
|
||||
import { appAtomRegistry } from "../state/atom-registry";
|
||||
import { clearThreadOutboxEnvironment } from "../state/thread-outbox";
|
||||
import { clearThreadOutboxEnvironment } from "../state/thread-outbox-removal";
|
||||
import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
|
||||
import { mobileApplicationActiveWakeup } from "./app-state-wakeups";
|
||||
import { connectionStorageLayer } from "./storage";
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useNavigation } from "@react-navigation/native";
|
||||
import { useCallback } from "react";
|
||||
import { Alert } from "react-native";
|
||||
|
||||
import { removeThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
import { removeThreadOutboxMessage } from "../../state/thread-outbox-removal";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { releaseEditingQueuedMessage } from "../../state/use-thread-outbox";
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import Constants from "expo-constants";
|
||||
import * as Crypto from "expo-crypto";
|
||||
import { PROVIDER_SEND_TURN_MAX_FILE_BYTES } from "@t3tools/contracts";
|
||||
import {
|
||||
clearSharedPayloads,
|
||||
getResolvedSharedPayloadsAsync,
|
||||
@@ -12,11 +13,13 @@ import { Alert, AppState, Platform } from "react-native";
|
||||
|
||||
import {
|
||||
buildIncomingShareDraft,
|
||||
isShareFileUriUnderOwnedRoots,
|
||||
type IncomingShareDestination,
|
||||
type IncomingShareDraft,
|
||||
} from "./incoming-share-model";
|
||||
import { createIncomingSharePayloadReader } from "./incoming-share-native";
|
||||
import { IncomingShareInbox } from "./incoming-share-inbox";
|
||||
import { persistComposerAttachmentFile } from "../../lib/composerImages";
|
||||
import {
|
||||
loadIncomingShareDrafts,
|
||||
removeIncomingShareDraft,
|
||||
@@ -54,7 +57,7 @@ const getIncomingSharePayloads = createIncomingSharePayloadReader({
|
||||
readPayloads: getSharedPayloads,
|
||||
});
|
||||
|
||||
async function resolvedPayloadsForImages(): Promise<ReadonlyArray<ResolvedSharePayload>> {
|
||||
async function resolvedPayloadsForFiles(): Promise<ReadonlyArray<ResolvedSharePayload>> {
|
||||
try {
|
||||
return await getResolvedSharedPayloadsAsync();
|
||||
} catch (error) {
|
||||
@@ -84,12 +87,29 @@ async function readBase64(uri: string): Promise<string> {
|
||||
return new File(uri).base64();
|
||||
}
|
||||
|
||||
async function readFileSize(uri: string): Promise<number | null> {
|
||||
const { File } = await import("expo-file-system");
|
||||
return new File(uri).size ?? null;
|
||||
}
|
||||
|
||||
async function removeOwnedFile(uri: string): Promise<void> {
|
||||
if (!uri.startsWith("file:")) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { File } = await import("expo-file-system");
|
||||
const { File, Paths } = await import("expo-file-system");
|
||||
// Only delete files in directories this app owns: its documents and cache
|
||||
// sandbox and its share-extension App Group container. An iOS
|
||||
// open-in-place share points at the sender's own storage; deleting that
|
||||
// URI would destroy the user's document.
|
||||
const ownedRootUris = [
|
||||
Paths.document.uri,
|
||||
Paths.cache.uri,
|
||||
...Object.values(Paths.appleSharedContainers ?? {}).map((directory) => directory.uri),
|
||||
];
|
||||
if (!isShareFileUriUnderOwnedRoots(uri, ownedRootUris)) {
|
||||
return;
|
||||
}
|
||||
const file = new File(uri);
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
@@ -99,21 +119,23 @@ async function removeOwnedFile(uri: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function removeReplayedImagePayloadFiles(
|
||||
payloads: ReadonlyArray<SharePayload>,
|
||||
): Promise<void> {
|
||||
async function removeReplayedPayloadFiles(payloads: ReadonlyArray<SharePayload>): Promise<void> {
|
||||
const uris = new Set<string>();
|
||||
for (const payload of payloads) {
|
||||
if (payload.shareType === "image") {
|
||||
if (["image", "file", "audio", "video"].includes(payload.shareType)) {
|
||||
uris.add(payload.value);
|
||||
}
|
||||
}
|
||||
if (uris.size === 0) {
|
||||
return;
|
||||
}
|
||||
const resolvedPayloads = await resolvedPayloadsForImages();
|
||||
const resolvedPayloads = payloads.some((payload) =>
|
||||
["file", "audio", "video"].includes(payload.shareType),
|
||||
)
|
||||
? []
|
||||
: await resolvedPayloadsForFiles();
|
||||
for (const payload of resolvedPayloads) {
|
||||
if (payload.shareType === "image" && payload.contentUri) {
|
||||
if (["image", "file", "audio", "video"].includes(payload.shareType) && payload.contentUri) {
|
||||
uris.add(payload.contentUri);
|
||||
}
|
||||
}
|
||||
@@ -131,14 +153,29 @@ const incomingShareInbox = new IncomingShareInbox({
|
||||
clearPayloads: clearSharedPayloads,
|
||||
buildDraft: async ({ payloads, id, createdAt }) => {
|
||||
const cleanupUris = new Set<string>();
|
||||
const resolvedPayloads = payloads.some((payload) => payload.shareType === "image")
|
||||
? await resolvedPayloadsForImages()
|
||||
: [];
|
||||
const persistedUris = new Set<string>();
|
||||
const hasGenericFilePayload = payloads.some((payload) =>
|
||||
["file", "audio", "video"].includes(payload.shareType),
|
||||
);
|
||||
const resolvedPayloads =
|
||||
!hasGenericFilePayload && payloads.some((payload) => payload.shareType === "image")
|
||||
? await resolvedPayloadsForFiles()
|
||||
: [];
|
||||
const draft = await buildIncomingShareDraft({
|
||||
payloads,
|
||||
resolvedPayloads,
|
||||
fileReader: {
|
||||
readBase64,
|
||||
persistFile: async (uri, name) => {
|
||||
const persistedUri = await persistComposerAttachmentFile(
|
||||
uri,
|
||||
name,
|
||||
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
|
||||
);
|
||||
persistedUris.add(persistedUri);
|
||||
return persistedUri;
|
||||
},
|
||||
readSize: readFileSize,
|
||||
removeOwnedFile: (uri) => {
|
||||
cleanupUris.add(uri);
|
||||
},
|
||||
@@ -151,9 +188,12 @@ const incomingShareInbox = new IncomingShareInbox({
|
||||
cleanup: async () => {
|
||||
await Promise.all([...cleanupUris].map(removeOwnedFile));
|
||||
},
|
||||
rollback: async () => {
|
||||
await Promise.all([...persistedUris].map(removeOwnedFile));
|
||||
},
|
||||
};
|
||||
},
|
||||
cleanupReplayedPayloads: removeReplayedImagePayloadFiles,
|
||||
cleanupReplayedPayloads: removeReplayedPayloadFiles,
|
||||
idForPayloads: incomingShareIdForPayloads,
|
||||
now: () => new Date().toISOString(),
|
||||
onClearError: (error) => {
|
||||
|
||||
@@ -136,11 +136,13 @@ describe("IncomingShareInbox", () => {
|
||||
it("does not acknowledge a supported payload when its durable write fails", async () => {
|
||||
const clearPayloads = vi.fn();
|
||||
const cleanup = vi.fn(async () => undefined);
|
||||
const rollback = vi.fn(async () => undefined);
|
||||
const { inbox } = createHarness({
|
||||
clearPayloads,
|
||||
buildDraft: async ({ id, createdAt }) => ({
|
||||
draft: draft(id, createdAt),
|
||||
cleanup,
|
||||
rollback,
|
||||
}),
|
||||
writeDraft: async () => {
|
||||
throw new Error("disk full");
|
||||
@@ -150,6 +152,7 @@ describe("IncomingShareInbox", () => {
|
||||
await expect(inbox.refresh({ ingestNative: true })).rejects.toThrow("disk full");
|
||||
expect(clearPayloads).not.toHaveBeenCalled();
|
||||
expect(cleanup).not.toHaveBeenCalled();
|
||||
expect(rollback).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("durably reserves a share for one project before draft import", async () => {
|
||||
|
||||
@@ -20,6 +20,7 @@ export interface IncomingShareInboxDependencies {
|
||||
}) => Promise<{
|
||||
readonly draft: IncomingShareDraft;
|
||||
readonly cleanup: () => Promise<void>;
|
||||
readonly rollback?: () => Promise<void>;
|
||||
}>;
|
||||
readonly cleanupReplayedPayloads?: (payloads: ReadonlyArray<SharePayload>) => Promise<void>;
|
||||
readonly idForPayloads: (payloads: ReadonlyArray<SharePayload>) => Promise<string>;
|
||||
@@ -116,7 +117,14 @@ export class IncomingShareInbox {
|
||||
// The durable inbox write is the transaction boundary. Never clear the
|
||||
// native handoff first: a process termination must leave one recoverable
|
||||
// copy on one side of the boundary.
|
||||
await this.dependencies.writeDraft(draft);
|
||||
try {
|
||||
await this.dependencies.writeDraft(draft);
|
||||
} catch (error) {
|
||||
if (built.rollback) {
|
||||
await this.cleanup(built.rollback);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
await this.cleanup(built.cleanup);
|
||||
this.clearNativePayloads();
|
||||
return sortAndDedupeIncomingShares([draft, ...persisted]);
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import { describe, expect, it, vi } from "@effect/vitest";
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ResolvedSharePayload, SharePayload } from "expo-sharing";
|
||||
|
||||
import { buildIncomingShareDraft, hasIncomingShareContent } from "./incoming-share-model";
|
||||
import {
|
||||
buildIncomingShareDraft,
|
||||
hasIncomingShareContent,
|
||||
isShareFileUriUnderOwnedRoots,
|
||||
selectIncomingShareAttachments,
|
||||
selectIncomingShareAttachmentsForServer,
|
||||
} from "./incoming-share-model";
|
||||
|
||||
describe("incoming native shares", () => {
|
||||
it("converts shared text, URLs, and images into a durable composer draft", async () => {
|
||||
@@ -96,6 +103,411 @@ describe("incoming native shares", () => {
|
||||
expect(hasIncomingShareContent(result)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps a shared PDF on disk without converting its contents to base64", async () => {
|
||||
const file: SharePayload = {
|
||||
shareType: "file",
|
||||
value: "file:///shared/report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
};
|
||||
const readBase64 = vi.fn(async () => "unused");
|
||||
const persistFile = vi.fn(async () => "file:///documents/report.pdf");
|
||||
const removeOwnedFile = vi.fn(async (_uri: string) => undefined);
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-report",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads: [file],
|
||||
resolvedPayloads: [
|
||||
{
|
||||
...file,
|
||||
contentUri: file.value,
|
||||
contentType: "file",
|
||||
contentMimeType: "application/pdf",
|
||||
contentSize: 42,
|
||||
originalName: "report.pdf",
|
||||
},
|
||||
],
|
||||
fileReader: { readBase64, persistFile, removeOwnedFile },
|
||||
});
|
||||
|
||||
expect(result.attachments).toEqual([
|
||||
{
|
||||
id: "share-report:file:0",
|
||||
type: "file",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
fileUri: "file:///documents/report.pdf",
|
||||
},
|
||||
]);
|
||||
expect(readBase64).not.toHaveBeenCalled();
|
||||
expect(persistFile).toHaveBeenCalledWith(file.value, "report.pdf");
|
||||
expect(removeOwnedFile).toHaveBeenCalledWith(file.value);
|
||||
});
|
||||
|
||||
it("rejects shared files that exceed the generic attachment limit", async () => {
|
||||
const file: SharePayload = {
|
||||
shareType: "file",
|
||||
value: "file:///shared/huge.zip",
|
||||
mimeType: "application/zip",
|
||||
};
|
||||
const persistFile = vi.fn(async () => "file:///documents/huge.zip");
|
||||
const removeOwnedFile = vi.fn(async () => undefined);
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-huge",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads: [file],
|
||||
resolvedPayloads: [
|
||||
{
|
||||
...file,
|
||||
contentUri: file.value,
|
||||
contentType: "file",
|
||||
contentMimeType: "application/zip",
|
||||
contentSize: PROVIDER_SEND_TURN_MAX_FILE_BYTES + 1,
|
||||
originalName: "huge.zip",
|
||||
},
|
||||
],
|
||||
fileReader: {
|
||||
readBase64: async () => "unused",
|
||||
persistFile,
|
||||
removeOwnedFile,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.attachments).toEqual([]);
|
||||
expect(result.warnings).toEqual(["'huge.zip' exceeds the 50 MB attachment limit."]);
|
||||
expect(persistFile).not.toHaveBeenCalled();
|
||||
expect(removeOwnedFile).toHaveBeenCalledWith(file.value);
|
||||
});
|
||||
|
||||
it("reports an unreadable shared file without calling it oversized", async () => {
|
||||
const file: SharePayload = {
|
||||
shareType: "file",
|
||||
value: "file:///shared/empty.txt",
|
||||
mimeType: "text/plain",
|
||||
};
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-empty",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads: [file],
|
||||
resolvedPayloads: [],
|
||||
fileReader: {
|
||||
readBase64: async () => "unused",
|
||||
readSize: async () => 0,
|
||||
removeOwnedFile: async () => undefined,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.attachments).toEqual([]);
|
||||
expect(result.warnings).toEqual(["'empty.txt' is empty or could not be read."]);
|
||||
});
|
||||
|
||||
it("reads an Android content URI's size after copying it into app-owned storage", async () => {
|
||||
const file: SharePayload = {
|
||||
shareType: "file",
|
||||
value: "content://shared/report",
|
||||
mimeType: "application/pdf",
|
||||
};
|
||||
const persistFile = vi.fn(async () => "file:///documents/report.pdf");
|
||||
const readSize = vi.fn(async (uri: string) => (uri.startsWith("content:") ? null : 42));
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-android-report",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads: [file],
|
||||
resolvedPayloads: [],
|
||||
fileReader: {
|
||||
readBase64: async () => "unused",
|
||||
persistFile,
|
||||
readSize,
|
||||
removeOwnedFile: async () => undefined,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.attachments).toEqual([
|
||||
{
|
||||
id: "share-android-report:file:0",
|
||||
type: "file",
|
||||
name: "report",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
fileUri: "file:///documents/report.pdf",
|
||||
},
|
||||
]);
|
||||
expect(readSize.mock.calls).toEqual([
|
||||
["content://shared/report"],
|
||||
["file:///documents/report.pdf"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("records the stored copy's measured size when a content URI under-reports", async () => {
|
||||
const file: SharePayload = {
|
||||
shareType: "file",
|
||||
value: "content://shared/report",
|
||||
mimeType: "application/pdf",
|
||||
};
|
||||
// The source claims 42 bytes but the stored copy measures 4200.
|
||||
const persistFile = vi.fn(async () => "file:///documents/report.pdf");
|
||||
const readSize = vi.fn(async (uri: string) => (uri.startsWith("content:") ? 42 : 4200));
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-android-report",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads: [file],
|
||||
resolvedPayloads: [],
|
||||
fileReader: {
|
||||
readBase64: async () => "unused",
|
||||
persistFile,
|
||||
readSize,
|
||||
removeOwnedFile: async () => undefined,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.attachments).toHaveLength(1);
|
||||
expect(result.attachments[0]?.sizeBytes).toBe(4200);
|
||||
});
|
||||
|
||||
it("treats a zero-length Android content URI as unknown until its copy is measured", async () => {
|
||||
const file: SharePayload = {
|
||||
shareType: "file",
|
||||
value: "content://shared/report",
|
||||
mimeType: "application/pdf",
|
||||
};
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-zero-metadata",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads: [file],
|
||||
resolvedPayloads: [],
|
||||
fileReader: {
|
||||
readBase64: async () => "unused",
|
||||
persistFile: async () => "file:///documents/report.pdf",
|
||||
readSize: async (uri) => (uri.startsWith("content:") ? 0 : 42),
|
||||
removeOwnedFile: async () => undefined,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.attachments[0]?.sizeBytes).toBe(42);
|
||||
expect(result.warnings).toEqual([]);
|
||||
});
|
||||
|
||||
it("rejects a shared file whose persisted copy measures empty and releases the copy", async () => {
|
||||
const file: SharePayload = {
|
||||
shareType: "file",
|
||||
value: "content://shared/report",
|
||||
mimeType: "application/pdf",
|
||||
};
|
||||
const persistedUri = "file:///documents/report.pdf";
|
||||
const removeOwnedFile = vi.fn(async (_uri: string) => undefined);
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-empty-copy",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads: [file],
|
||||
resolvedPayloads: [],
|
||||
fileReader: {
|
||||
readBase64: async () => "unused",
|
||||
persistFile: async () => persistedUri,
|
||||
// The source claims 42 bytes but the stored copy measures zero: the
|
||||
// copy is what uploads, so its measured size wins and the empty file
|
||||
// is rejected instead of shipped with a made-up size.
|
||||
readSize: async (uri) => (uri.startsWith("content:") ? 42 : 0),
|
||||
removeOwnedFile,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.attachments).toEqual([]);
|
||||
expect(result.warnings).toEqual(["'report' is empty or could not be read."]);
|
||||
expect(removeOwnedFile.mock.calls.map(([uri]) => uri)).toContain(persistedUri);
|
||||
});
|
||||
|
||||
it("keeps the Android display name without copying the file into the Expo cache", async () => {
|
||||
const file = {
|
||||
shareType: "file" as const,
|
||||
value: "content://shared/12345",
|
||||
mimeType: "application/pdf",
|
||||
originalName: "quarterly-report.pdf",
|
||||
};
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-named-report",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads: [file],
|
||||
resolvedPayloads: [],
|
||||
fileReader: {
|
||||
readBase64: async () => "unused",
|
||||
readSize: async () => 42,
|
||||
persistFile: async (_uri, name) => `file:///documents/${name}`,
|
||||
removeOwnedFile: async () => undefined,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.attachments).toEqual([
|
||||
{
|
||||
id: "share-named-report:file:0",
|
||||
type: "file",
|
||||
name: "quarterly-report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
fileUri: "file:///documents/quarterly-report.pdf",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps a no-copy file source that the returned attachment still owns", async () => {
|
||||
const sourceUri = "file:///documents/report.pdf";
|
||||
const removeOwnedFile = vi.fn(async () => undefined);
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-no-copy",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads: [{ shareType: "file", value: sourceUri, mimeType: "application/pdf" }],
|
||||
resolvedPayloads: [],
|
||||
fileReader: {
|
||||
readBase64: async () => "unused",
|
||||
readSize: async () => 42,
|
||||
removeOwnedFile,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.attachments[0]).toMatchObject({ type: "file", fileUri: sourceUri });
|
||||
expect(removeOwnedFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a persisted copy and releases distinct temporary source URIs", async () => {
|
||||
const payloadUri = "content://shared/report";
|
||||
const resolvedUri = "file:///cache/report.pdf";
|
||||
const persistedUri = "file:///documents/report.pdf";
|
||||
const removeOwnedFile = vi.fn(async (_uri: string) => undefined);
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-copy",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
payloads: [{ shareType: "file", value: payloadUri, mimeType: "application/pdf" }],
|
||||
resolvedPayloads: [
|
||||
{
|
||||
shareType: "file",
|
||||
value: payloadUri,
|
||||
mimeType: "application/pdf",
|
||||
contentUri: resolvedUri,
|
||||
contentType: "file",
|
||||
contentMimeType: "application/pdf",
|
||||
contentSize: 42,
|
||||
originalName: "report.pdf",
|
||||
},
|
||||
],
|
||||
fileReader: {
|
||||
readBase64: async () => "unused",
|
||||
readSize: async () => 42,
|
||||
persistFile: async () => persistedUri,
|
||||
removeOwnedFile,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.attachments[0]).toMatchObject({ type: "file", fileUri: persistedUri });
|
||||
expect(removeOwnedFile.mock.calls.map(([uri]) => uri)).toEqual([resolvedUri, payloadUri]);
|
||||
});
|
||||
|
||||
it("keeps images and rejects shared files on servers without file support", () => {
|
||||
const image = {
|
||||
id: "image-1",
|
||||
type: "image" as const,
|
||||
name: "image.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 3,
|
||||
dataUrl: "data:image/png;base64,YWJj",
|
||||
previewUri: "data:image/png;base64,YWJj",
|
||||
};
|
||||
const file = {
|
||||
id: "file-1",
|
||||
type: "file" as const,
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
fileUri: "file:///documents/report.pdf",
|
||||
};
|
||||
|
||||
expect(
|
||||
selectIncomingShareAttachments({
|
||||
attachments: [image, file],
|
||||
maxFileAttachmentBytes: null,
|
||||
}),
|
||||
).toEqual({
|
||||
attachments: [image],
|
||||
warnings: ["'report.pdf' was skipped because this server does not support files."],
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the destination server's attachment limit in share warnings", () => {
|
||||
const file = {
|
||||
id: "file-1",
|
||||
type: "file" as const,
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 6 * 1024 * 1024,
|
||||
fileUri: "file:///documents/report.pdf",
|
||||
};
|
||||
|
||||
expect(
|
||||
selectIncomingShareAttachments({
|
||||
attachments: [file],
|
||||
maxFileAttachmentBytes: 5 * 1024 * 1024,
|
||||
}),
|
||||
).toEqual({
|
||||
attachments: [],
|
||||
warnings: ["'report.pdf' exceeds the 5 MB attachment limit."],
|
||||
});
|
||||
});
|
||||
|
||||
it("uses current server support and limits when selecting a reserved share", () => {
|
||||
const file = {
|
||||
id: "file-1",
|
||||
type: "file" as const,
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 6 * 1024 * 1024,
|
||||
fileUri: "file:///documents/report.pdf",
|
||||
};
|
||||
|
||||
expect(
|
||||
selectIncomingShareAttachmentsForServer({ attachments: [file], serverConfig: null }),
|
||||
).toEqual({ status: "pending" });
|
||||
expect(
|
||||
selectIncomingShareAttachmentsForServer({
|
||||
attachments: [file],
|
||||
serverConfig: { environment: { capabilities: { attachmentUploads: true } } },
|
||||
}),
|
||||
).toMatchObject({ status: "ready", attachments: [] });
|
||||
expect(
|
||||
selectIncomingShareAttachmentsForServer({
|
||||
attachments: [file],
|
||||
serverConfig: {
|
||||
environment: {
|
||||
capabilities: {
|
||||
attachmentUploads: true,
|
||||
fileAttachments: { maxUploadBytes: 5 * 1024 * 1024 },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toMatchObject({ status: "ready", attachments: [] });
|
||||
expect(
|
||||
selectIncomingShareAttachmentsForServer({
|
||||
attachments: [file],
|
||||
serverConfig: {
|
||||
environment: {
|
||||
capabilities: {
|
||||
attachmentUploads: true,
|
||||
fileAttachments: { maxUploadBytes: 10 * 1024 * 1024 },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toMatchObject({ status: "ready", attachments: [file] });
|
||||
});
|
||||
|
||||
it("releases every temporary file when a share exceeds the attachment limit", async () => {
|
||||
const payloads = Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS + 1 }, (_, index) => ({
|
||||
shareType: "image" as const,
|
||||
@@ -193,4 +605,109 @@ describe("incoming native shares", () => {
|
||||
expect(result.attachments).toHaveLength(1);
|
||||
expect(result.warnings).toEqual([]);
|
||||
});
|
||||
|
||||
it("releases a persisted copy when a later step fails to read it", async () => {
|
||||
const file: SharePayload = {
|
||||
shareType: "file",
|
||||
value: "content://shared/report",
|
||||
mimeType: "application/pdf",
|
||||
};
|
||||
const persistedUri = "file:///documents/t3-composer-attachments/report.pdf";
|
||||
const removeOwnedFile = vi.fn(async (_uri: string) => undefined);
|
||||
|
||||
const result = await buildIncomingShareDraft({
|
||||
id: "share-persist-leak",
|
||||
createdAt: "2026-07-16T08:00:00.000Z",
|
||||
payloads: [file],
|
||||
resolvedPayloads: [],
|
||||
fileReader: {
|
||||
readBase64: async () => "unused",
|
||||
persistFile: async () => persistedUri,
|
||||
readSize: async (uri) => {
|
||||
if (uri === persistedUri) {
|
||||
throw new Error("read failed");
|
||||
}
|
||||
return null;
|
||||
},
|
||||
removeOwnedFile,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.attachments).toEqual([]);
|
||||
expect(result.warnings).toEqual(["read failed"]);
|
||||
expect(removeOwnedFile.mock.calls.map(([uri]) => uri)).toContain(persistedUri);
|
||||
});
|
||||
});
|
||||
|
||||
describe("share cleanup ownership", () => {
|
||||
const ownedRoots = [
|
||||
"file:///var/mobile/Containers/Data/Application/APP/Documents/",
|
||||
"file:///var/mobile/Containers/Shared/AppGroup/GROUP",
|
||||
];
|
||||
|
||||
it("allows deleting files inside the app's own directories", () => {
|
||||
expect(
|
||||
isShareFileUriUnderOwnedRoots(
|
||||
"file:///var/mobile/Containers/Shared/AppGroup/GROUP/shared.pdf",
|
||||
ownedRoots,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("treats /private/var and /var as the same iOS location", () => {
|
||||
expect(
|
||||
isShareFileUriUnderOwnedRoots(
|
||||
"file:///private/var/mobile/Containers/Shared/AppGroup/GROUP/shared.pdf",
|
||||
ownedRoots,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isShareFileUriUnderOwnedRoots(
|
||||
"file:///var/mobile/Containers/Data/Application/APP/Documents/t3-composer-attachments/a.pdf",
|
||||
["file:///private/var/mobile/Containers/Data/Application/APP/Documents/"],
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses to delete a sender-owned open-in-place document", () => {
|
||||
expect(
|
||||
isShareFileUriUnderOwnedRoots(
|
||||
"file:///private/var/mobile/Containers/Shared/FileProvider/OTHER/File%20Provider%20Storage/taxes.pdf",
|
||||
ownedRoots,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses traversal segments that escape an owned root", () => {
|
||||
// An encoded separator survives URL normalization: "..%2F.." decodes to
|
||||
// "../..", so the lexical check must reject it before containment.
|
||||
expect(
|
||||
isShareFileUriUnderOwnedRoots(
|
||||
"file:///var/mobile/Containers/Shared/AppGroup/GROUP/..%2F..%2FsenderDoc.pdf",
|
||||
ownedRoots,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isShareFileUriUnderOwnedRoots(
|
||||
"file:///var/mobile/Containers/Shared/AppGroup/GROUP/../senderDoc.pdf",
|
||||
ownedRoots,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isShareFileUriUnderOwnedRoots(
|
||||
"file:///var/mobile/Containers/Shared/AppGroup/GROUP/%2e%2e/senderDoc.pdf",
|
||||
ownedRoots,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses non-file URIs and the owned root itself", () => {
|
||||
expect(isShareFileUriUnderOwnedRoots("content://shared/report", ownedRoots)).toBe(false);
|
||||
expect(
|
||||
isShareFileUriUnderOwnedRoots(
|
||||
"file:///var/mobile/Containers/Shared/AppGroup/GROUP",
|
||||
ownedRoots,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,18 @@
|
||||
import {
|
||||
clampFileAttachmentUploadBytes,
|
||||
fileAttachmentTooLargeMessage,
|
||||
} from "@t3tools/client-runtime/state/attachments";
|
||||
import {
|
||||
isProviderSendTurnSupportedImageMimeType,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type { ResolvedSharePayload, SharePayload } from "expo-sharing";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { DraftComposerAttachmentSchema } from "../../lib/composer-image-schema";
|
||||
import type { DraftComposerAttachment } from "../../lib/composerImages";
|
||||
import { estimateBase64ByteSize } from "../../lib/base64";
|
||||
|
||||
export interface IncomingShareDraft {
|
||||
@@ -16,7 +21,7 @@ export interface IncomingShareDraft {
|
||||
readonly createdAt: string;
|
||||
readonly destination?: IncomingShareDestination;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly warnings: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
@@ -36,7 +41,7 @@ export const IncomingShareDraftSchema = Schema.Struct({
|
||||
createdAt: Schema.String,
|
||||
destination: Schema.optional(IncomingShareDestinationSchema),
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
attachments: Schema.Array(DraftComposerAttachmentSchema),
|
||||
warnings: Schema.Array(Schema.String),
|
||||
});
|
||||
|
||||
@@ -46,9 +51,126 @@ export function decodeIncomingShareDraft(value: unknown): IncomingShareDraft {
|
||||
return decodeIncomingShareDraftSync(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* `file:` path with the iOS `/private` prefix stripped, so URIs that reach the
|
||||
* same file through the `/var` symlink and through `/private/var` compare
|
||||
* equal. Null for anything that is not a `file:` URI.
|
||||
*/
|
||||
function normalizedFileUriPath(uri: string): string | null {
|
||||
try {
|
||||
const url = new URL(uri);
|
||||
if (url.protocol !== "file:") {
|
||||
return null;
|
||||
}
|
||||
const path = decodeURIComponent(url.pathname);
|
||||
// URL parsing collapses literal ".." segments, but an encoded separator
|
||||
// survives it: "..%2F.." decodes to "../..", which the filesystem would
|
||||
// resolve outside the root the lexical containment check accepted.
|
||||
if (path.split("/").includes("..")) {
|
||||
return null;
|
||||
}
|
||||
return path.startsWith("/private/var/") ? path.slice("/private".length) : path;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a shared `file:` URI points strictly inside one of the directories
|
||||
* this app owns (its sandbox and its share-extension App Group container).
|
||||
* Share cleanup must never delete anything else: an iOS open-in-place share
|
||||
* hands over the sender's own file URL, and deleting it destroys the user's
|
||||
* document.
|
||||
*/
|
||||
export function isShareFileUriUnderOwnedRoots(
|
||||
uri: string,
|
||||
ownedRootUris: ReadonlyArray<string>,
|
||||
): boolean {
|
||||
const path = normalizedFileUriPath(uri);
|
||||
if (path === null) {
|
||||
return false;
|
||||
}
|
||||
return ownedRootUris.some((rootUri) => {
|
||||
const rootPath = normalizedFileUriPath(rootUri);
|
||||
if (rootPath === null) {
|
||||
return false;
|
||||
}
|
||||
const root = rootPath.endsWith("/") ? rootPath : `${rootPath}/`;
|
||||
return path.startsWith(root) && path.length > root.length;
|
||||
});
|
||||
}
|
||||
|
||||
export interface IncomingShareFileReader {
|
||||
readonly readBase64: (uri: string) => Promise<string>;
|
||||
readonly removeOwnedFile: (uri: string) => Promise<void> | void;
|
||||
readonly persistFile?: (uri: string, name: string) => Promise<string>;
|
||||
readonly readSize?: (uri: string) => Promise<number | null>;
|
||||
}
|
||||
|
||||
/** Apply the destination server's file support after the user chooses a project. */
|
||||
export function selectIncomingShareAttachments(input: {
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly maxFileAttachmentBytes: number | null;
|
||||
}): {
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly warnings: ReadonlyArray<string>;
|
||||
} {
|
||||
const attachments: DraftComposerAttachment[] = [];
|
||||
const warnings: string[] = [];
|
||||
|
||||
for (const attachment of input.attachments) {
|
||||
if (attachment.type === "image") {
|
||||
attachments.push(attachment);
|
||||
continue;
|
||||
}
|
||||
if (input.maxFileAttachmentBytes === null) {
|
||||
warnings.push(`'${attachment.name}' was skipped because this server does not support files.`);
|
||||
continue;
|
||||
}
|
||||
const maxFileAttachmentBytes = clampFileAttachmentUploadBytes(input.maxFileAttachmentBytes);
|
||||
if (attachment.sizeBytes > maxFileAttachmentBytes) {
|
||||
warnings.push(fileAttachmentTooLargeMessage(attachment.name, maxFileAttachmentBytes));
|
||||
continue;
|
||||
}
|
||||
attachments.push(attachment);
|
||||
}
|
||||
|
||||
return { attachments, warnings };
|
||||
}
|
||||
|
||||
export function selectIncomingShareAttachmentsForServer(input: {
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly serverConfig: {
|
||||
readonly environment: {
|
||||
readonly capabilities: {
|
||||
readonly attachmentUploads?: boolean;
|
||||
readonly fileAttachments?: { readonly maxUploadBytes: number };
|
||||
};
|
||||
};
|
||||
} | null;
|
||||
}):
|
||||
| { readonly status: "pending" }
|
||||
| {
|
||||
readonly status: "ready";
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly warnings: ReadonlyArray<string>;
|
||||
} {
|
||||
const hasFiles = input.attachments.some((attachment) => attachment.type === "file");
|
||||
if (hasFiles && input.serverConfig === null) {
|
||||
return { status: "pending" };
|
||||
}
|
||||
const capabilities = input.serverConfig?.environment.capabilities;
|
||||
const maxFileAttachmentBytes =
|
||||
capabilities?.attachmentUploads === true
|
||||
? (capabilities.fileAttachments?.maxUploadBytes ?? null)
|
||||
: null;
|
||||
return {
|
||||
status: "ready",
|
||||
...selectIncomingShareAttachments({
|
||||
attachments: input.attachments,
|
||||
maxFileAttachmentBytes,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function sharedText(payloads: ReadonlyArray<SharePayload>): string {
|
||||
@@ -119,8 +241,11 @@ function fallbackName(uri: string, index: number, mimeType: string): string {
|
||||
} catch {
|
||||
// Fall through to a deterministic attachment name.
|
||||
}
|
||||
const extension = mimeType.split("/")[1]?.replace(/[^a-z0-9.+-]/gi, "") || "png";
|
||||
return `shared-image-${index + 1}.${extension}`;
|
||||
const family = mimeType.split("/")[0]?.toLowerCase();
|
||||
const kind = family === "image" || family === "audio" || family === "video" ? family : "file";
|
||||
const extension =
|
||||
mimeType.split("/")[1]?.replace(/[^a-z0-9.+-]/gi, "") || (kind === "image" ? "png" : "bin");
|
||||
return `shared-${kind}-${index + 1}.${extension}`;
|
||||
}
|
||||
|
||||
export async function buildIncomingShareDraft(input: {
|
||||
@@ -130,13 +255,18 @@ export async function buildIncomingShareDraft(input: {
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
}): Promise<IncomingShareDraft> {
|
||||
const attachments: DraftComposerImageAttachment[] = [];
|
||||
const attachments: DraftComposerAttachment[] = [];
|
||||
const warnings: string[] = [];
|
||||
const consumedResolvedPayloadIndexes = new Set<number>();
|
||||
let warnedAttachmentLimit = false;
|
||||
|
||||
for (const [index, payload] of input.payloads.entries()) {
|
||||
if (payload.shareType !== "image") {
|
||||
if (
|
||||
payload.shareType !== "image" &&
|
||||
payload.shareType !== "file" &&
|
||||
payload.shareType !== "audio" &&
|
||||
payload.shareType !== "video"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const resolved = resolvedImageFor(
|
||||
@@ -149,7 +279,7 @@ export async function buildIncomingShareDraft(input: {
|
||||
if (attachments.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
|
||||
if (!warnedAttachmentLimit) {
|
||||
warnings.push(
|
||||
`Only the first ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} shared images were attached.`,
|
||||
`Only the first ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} shared ${payload.shareType === "image" ? "images" : "files"} were attached.`,
|
||||
);
|
||||
warnedAttachmentLimit = true;
|
||||
}
|
||||
@@ -157,7 +287,100 @@ export async function buildIncomingShareDraft(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
const mimeType = (resolved?.contentMimeType ?? payload.mimeType ?? "image/png").toLowerCase();
|
||||
const mimeType = (
|
||||
resolved?.contentMimeType ??
|
||||
payload.mimeType ??
|
||||
(payload.shareType === "image" ? "image/png" : "application/octet-stream")
|
||||
).toLowerCase();
|
||||
if (payload.shareType !== "image") {
|
||||
// The patched native module never emits a blank display name, but keep
|
||||
// the guard: an empty name would fail the attachment name contract.
|
||||
const sharedFileName =
|
||||
typeof payload.originalName === "string" && payload.originalName.trim().length > 0
|
||||
? payload.originalName
|
||||
: undefined;
|
||||
const name = resolved?.originalName ?? sharedFileName ?? fallbackName(uri, index, mimeType);
|
||||
if (!uri) {
|
||||
warnings.push("One shared file could not be read.");
|
||||
continue;
|
||||
}
|
||||
let persistedFileUri: string | undefined;
|
||||
let retainedFileUri: string | undefined;
|
||||
try {
|
||||
let sizeBytes = resolved?.contentSize ?? (await input.fileReader.readSize?.(uri)) ?? null;
|
||||
if (
|
||||
(sizeBytes === null || (sizeBytes === 0 && uri.startsWith("content:"))) &&
|
||||
input.fileReader.persistFile
|
||||
) {
|
||||
persistedFileUri = await input.fileReader.persistFile(uri, name);
|
||||
sizeBytes = (await input.fileReader.readSize?.(persistedFileUri)) ?? null;
|
||||
}
|
||||
if (sizeBytes === null) {
|
||||
warnings.push(`The size of '${name}' could not be determined.`);
|
||||
if (persistedFileUri) {
|
||||
await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (sizeBytes <= 0) {
|
||||
warnings.push(`'${name}' is empty or could not be read.`);
|
||||
if (persistedFileUri) {
|
||||
await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
|
||||
warnings.push(fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_FILE_BYTES));
|
||||
if (persistedFileUri) {
|
||||
await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (persistedFileUri === undefined && input.fileReader.persistFile) {
|
||||
persistedFileUri = await input.fileReader.persistFile(uri, name);
|
||||
// An Android content: source can misreport its size while the
|
||||
// stored copy is what uploads, so the copy's measured size is what
|
||||
// the attachment must record. A measured zero means the copy holds
|
||||
// no bytes: reject it, whatever the source claimed.
|
||||
const storedSize = (await input.fileReader.readSize?.(persistedFileUri)) ?? null;
|
||||
if (storedSize !== null) {
|
||||
sizeBytes = storedSize;
|
||||
}
|
||||
if (sizeBytes <= 0) {
|
||||
warnings.push(`'${name}' is empty or could not be read.`);
|
||||
await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
|
||||
continue;
|
||||
}
|
||||
if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
|
||||
warnings.push(fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_FILE_BYTES));
|
||||
await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
attachments.push({
|
||||
id: `${input.id}:file:${index}`,
|
||||
type: "file",
|
||||
name,
|
||||
mimeType,
|
||||
sizeBytes,
|
||||
fileUri: persistedFileUri ?? uri,
|
||||
});
|
||||
retainedFileUri = persistedFileUri ?? uri;
|
||||
} catch (error) {
|
||||
warnings.push(error instanceof Error ? error.message : `Could not read '${name}'.`);
|
||||
// A copy persisted before the failure has no attachment referencing
|
||||
// it; release it or it leaks in the app's attachment directory.
|
||||
if (persistedFileUri !== undefined) {
|
||||
await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
|
||||
}
|
||||
} finally {
|
||||
await releaseOwnedFiles(
|
||||
input.fileReader,
|
||||
[uri, payload.value].filter((candidate) => candidate !== retainedFileUri),
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!uri || !mimeType.startsWith("image/")) {
|
||||
warnings.push("One shared item was not a supported image.");
|
||||
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
const fileSystemMocks = vi.hoisted(() => {
|
||||
let entries: File[] = [];
|
||||
|
||||
class File {
|
||||
readonly exists = true;
|
||||
|
||||
constructor(
|
||||
readonly name: string,
|
||||
private readonly contents: string,
|
||||
) {}
|
||||
|
||||
async text(): Promise<string> {
|
||||
return this.contents;
|
||||
}
|
||||
}
|
||||
|
||||
class Directory {
|
||||
create(): void {}
|
||||
|
||||
list(): ReadonlyArray<File> {
|
||||
return entries;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
Directory,
|
||||
File,
|
||||
setEntries(next: File[]) {
|
||||
entries = next;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("expo-file-system", () => ({
|
||||
Directory: fileSystemMocks.Directory,
|
||||
File: fileSystemMocks.File,
|
||||
Paths: { document: "/documents" },
|
||||
}));
|
||||
|
||||
import { IncomingShareStorageError, loadIncomingShareDrafts } from "./incoming-share-storage";
|
||||
|
||||
const VALID_DRAFT = {
|
||||
schemaVersion: 1,
|
||||
id: "share-valid",
|
||||
createdAt: "2026-08-28T12:00:00.000Z",
|
||||
text: "Review this file",
|
||||
attachments: [],
|
||||
warnings: [],
|
||||
} as const;
|
||||
|
||||
afterEach(() => {
|
||||
fileSystemMocks.setEntries([]);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("incoming share storage", () => {
|
||||
it("skips an invalid persisted share by default", async () => {
|
||||
fileSystemMocks.setEntries([
|
||||
new fileSystemMocks.File("valid.json", JSON.stringify(VALID_DRAFT)),
|
||||
new fileSystemMocks.File("invalid.json", "{"),
|
||||
]);
|
||||
const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
||||
|
||||
await expect(loadIncomingShareDrafts()).resolves.toEqual([VALID_DRAFT]);
|
||||
expect(warning).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("rejects an invalid persisted share in strict mode", async () => {
|
||||
fileSystemMocks.setEntries([new fileSystemMocks.File("invalid.json", "{")]);
|
||||
|
||||
await expect(loadIncomingShareDrafts({ strict: true })).rejects.toBeInstanceOf(
|
||||
IncomingShareStorageError,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -33,7 +33,9 @@ async function getFile(shareId: string) {
|
||||
return new File(await getDirectory(), fileName(shareId));
|
||||
}
|
||||
|
||||
export async function loadIncomingShareDrafts(): Promise<ReadonlyArray<IncomingShareDraft>> {
|
||||
export async function loadIncomingShareDrafts(options?: {
|
||||
readonly strict?: boolean;
|
||||
}): Promise<ReadonlyArray<IncomingShareDraft>> {
|
||||
try {
|
||||
const { File } = await import("expo-file-system");
|
||||
const drafts: IncomingShareDraft[] = [];
|
||||
@@ -44,14 +46,18 @@ export async function loadIncomingShareDrafts(): Promise<ReadonlyArray<IncomingS
|
||||
try {
|
||||
drafts.push(decodeIncomingShareDraft(JSON.parse(await entry.text()) as unknown));
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[incoming-share] ignored invalid persisted share",
|
||||
new IncomingShareStorageError({ operation: "load", shareId: null, cause }),
|
||||
);
|
||||
const error = new IncomingShareStorageError({ operation: "load", shareId: null, cause });
|
||||
if (options?.strict) {
|
||||
throw error;
|
||||
}
|
||||
console.warn("[incoming-share] ignored invalid persisted share", error);
|
||||
}
|
||||
}
|
||||
return drafts.sort((left, right) => right.createdAt.localeCompare(left.createdAt));
|
||||
} catch (cause) {
|
||||
if (cause instanceof IncomingShareStorageError) {
|
||||
throw cause;
|
||||
}
|
||||
throw new IncomingShareStorageError({ operation: "load", shareId: null, cause });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
|
||||
|
||||
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import {
|
||||
@@ -42,20 +43,27 @@ import {
|
||||
} from "./use-thread-settings-sheet-presentation";
|
||||
|
||||
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
|
||||
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
|
||||
import {
|
||||
convertPastedImagesToAttachments,
|
||||
pickComposerFiles,
|
||||
pickComposerImages,
|
||||
} from "../../lib/composerImages";
|
||||
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
|
||||
import {
|
||||
clearComposerDraftContent,
|
||||
flushComposerDrafts,
|
||||
getComposerDraftSnapshot,
|
||||
mergeComposerDraftContent,
|
||||
restoreComposerDraftSnapshot,
|
||||
scheduleUnusedComposerAttachmentCleanup,
|
||||
type ComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
|
||||
import { resolveSelectableModelSelection } from "../../lib/modelOptions";
|
||||
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
|
||||
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
|
||||
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
import { removeThreadOutboxMessage } from "../../state/thread-outbox-removal";
|
||||
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
|
||||
import { useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
|
||||
@@ -66,6 +74,9 @@ import {
|
||||
resolveNewTaskWorkspaceLabel,
|
||||
} from "./new-task-context-presentation";
|
||||
import { useIncomingShare } from "../sharing/IncomingShareProvider";
|
||||
import { selectIncomingShareAttachmentsForServer } from "../sharing/incoming-share-model";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { serverEnvironment } from "../../state/server";
|
||||
|
||||
function NewTaskWorkspaceIcon(props: {
|
||||
readonly workspaceMode: "local" | "worktree";
|
||||
@@ -215,9 +226,18 @@ export function NewTaskDraftScreen(props: {
|
||||
);
|
||||
const isProjectPickerReturnActive =
|
||||
isReturningToProjectPicker && !requestedInitialProjectAvailable;
|
||||
const isIncomingShareTransferPending = Boolean(
|
||||
incomingShare && cancelledIncomingShareId !== props.incomingShareId,
|
||||
const isIncomingShareAwaitingServerConfig = Boolean(
|
||||
incomingShare?.attachments.some((attachment) => attachment.type === "file") &&
|
||||
selectedEnvironmentServerConfig === null,
|
||||
);
|
||||
const isIncomingShareTransferPending = Boolean(
|
||||
incomingShare &&
|
||||
cancelledIncomingShareId !== props.incomingShareId &&
|
||||
!isIncomingShareAwaitingServerConfig,
|
||||
);
|
||||
const isComposerInteractionLocked = isIncomingShareTransferPending || flow.submitting;
|
||||
// Also guard while a submit is in flight: an Android back press or iOS
|
||||
// Cancel would otherwise abandon the screen while the task still starts.
|
||||
const composerMenu = useComposerCommandMenu({
|
||||
draftMessage: flow.prompt,
|
||||
environmentId: selectedProject?.environmentId ?? null,
|
||||
@@ -227,12 +247,14 @@ export function NewTaskDraftScreen(props: {
|
||||
: (flow.selectedWorktreePath ?? selectedProject?.workspaceRoot)) || null,
|
||||
selectedProviderStatus: flow.selectedProviderStatus,
|
||||
hasThread: false,
|
||||
enabled: isComposerFocused && !isIncomingShareTransferPending,
|
||||
enabled: isComposerFocused && !isComposerInteractionLocked,
|
||||
onChangeDraftMessage: flow.setPrompt,
|
||||
onUpdateInteractionMode: flow.planModeEnabled ? flow.setInteractionMode : undefined,
|
||||
});
|
||||
usePreventRemove(
|
||||
(isIncomingShareTransferPending && !isProjectPickerReturnActive) || isCancellingShareImport,
|
||||
(isIncomingShareTransferPending && !isProjectPickerReturnActive) ||
|
||||
isCancellingShareImport ||
|
||||
flow.submitting,
|
||||
() => undefined,
|
||||
);
|
||||
const hasImportedIncomingShare = Boolean(
|
||||
@@ -446,6 +468,13 @@ export function NewTaskDraftScreen(props: {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
incomingShare.attachments.some((attachment) => attachment.type === "file") &&
|
||||
selectedEnvironmentServerConfig === null
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (alertedUnavailableIncomingShareIdRef.current === shareId) {
|
||||
alertedUnavailableIncomingShareIdRef.current = null;
|
||||
}
|
||||
@@ -455,6 +484,7 @@ export function NewTaskDraftScreen(props: {
|
||||
shareImportDraftBackupRef.current.set(importKey, draftBackup);
|
||||
const importToken = Symbol(importKey);
|
||||
let didReserveShare = false;
|
||||
let didConsumeShare = false;
|
||||
let needsDraftRestore = false;
|
||||
activeShareImportTokenRef.current = importToken;
|
||||
setImportingShareKey(importKey);
|
||||
@@ -472,10 +502,19 @@ export function NewTaskDraftScreen(props: {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const selectedAttachments = selectIncomingShareAttachmentsForServer({
|
||||
attachments: incomingShare.attachments,
|
||||
serverConfig: appAtomRegistry.get(
|
||||
serverEnvironment.configValueAtom(destinationProject.environmentId),
|
||||
),
|
||||
});
|
||||
if (selectedAttachments.status === "pending") {
|
||||
throw new Error("Server attachment support is still loading.");
|
||||
}
|
||||
needsDraftRestore = true;
|
||||
const { skippedAttachmentCount } = await mergeComposerDraftContent(draftKey, {
|
||||
text: incomingShare.text,
|
||||
attachments: incomingShare.attachments,
|
||||
attachments: selectedAttachments.attachments,
|
||||
sourceShareId: shareId,
|
||||
});
|
||||
if (
|
||||
@@ -489,13 +528,25 @@ export function NewTaskDraftScreen(props: {
|
||||
return;
|
||||
}
|
||||
await consumeShare(shareId);
|
||||
didConsumeShare = true;
|
||||
// The consumed inbox draft was the last owner of files that never made
|
||||
// it into the composer draft (unsupported server, oversize, limit
|
||||
// skips). Release them before any early return: an unmount or a
|
||||
// superseding import must not leak them, and the sweep re-checks
|
||||
// ownership so it cannot delete a file another draft picked up.
|
||||
const retainedAttachmentIds = new Set(
|
||||
getComposerDraftSnapshot(draftKey).attachments.map((attachment) => attachment.id),
|
||||
);
|
||||
scheduleUnusedComposerAttachmentCleanup(
|
||||
incomingShare.attachments.filter((attachment) => !retainedAttachmentIds.has(attachment.id)),
|
||||
);
|
||||
if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
|
||||
return;
|
||||
}
|
||||
const warnings = [...incomingShare.warnings];
|
||||
const warnings = [...incomingShare.warnings, ...selectedAttachments.warnings];
|
||||
if (skippedAttachmentCount > 0) {
|
||||
warnings.push(
|
||||
`${skippedAttachmentCount} shared image${skippedAttachmentCount === 1 ? " was" : "s were"} skipped because this draft reached the attachment limit.`,
|
||||
`${skippedAttachmentCount} shared file${skippedAttachmentCount === 1 ? " was" : "s were"} skipped because this draft reached the attachment limit.`,
|
||||
);
|
||||
}
|
||||
if (warnings.length > 0) {
|
||||
@@ -526,8 +577,16 @@ export function NewTaskDraftScreen(props: {
|
||||
setIsCancellingShareImport(true);
|
||||
try {
|
||||
if (needsDraftRestore) {
|
||||
// The restore drops the share's merged-in attachments
|
||||
// from the draft. Sweep them only when the inbox entry
|
||||
// was consumed: before that, the inbox still references
|
||||
// these files and must keep them for a later import.
|
||||
const mergedAttachments = getComposerDraftSnapshot(draftKey).attachments;
|
||||
await restoreComposerDraftSnapshot(draftKey, draftBackup);
|
||||
needsDraftRestore = false;
|
||||
if (didConsumeShare) {
|
||||
scheduleUnusedComposerAttachmentCleanup(mergedAttachments);
|
||||
}
|
||||
}
|
||||
if (didReserveShare) {
|
||||
await releaseShareReservation(shareId, {
|
||||
@@ -602,6 +661,7 @@ export function NewTaskDraftScreen(props: {
|
||||
props.initialProjectRef?.projectId,
|
||||
releaseShareReservation,
|
||||
reserveShare,
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProject,
|
||||
shareImportAttempt,
|
||||
]);
|
||||
@@ -633,12 +693,47 @@ export function NewTaskDraftScreen(props: {
|
||||
const showBranchLoading = flow.branchesLoading && flow.availableBranches.length === 0;
|
||||
|
||||
async function handlePickImages(): Promise<void> {
|
||||
if (isIncomingShareTransferPending) {
|
||||
if (isComposerInteractionLocked) {
|
||||
return;
|
||||
}
|
||||
const result = await pickComposerImages({ existingCount: flow.attachments.length });
|
||||
if (result.images.length > 0) {
|
||||
flow.appendAttachments(result.images);
|
||||
const rejectedCount = result.images.length > 0 ? flow.appendAttachments(result.images) : 0;
|
||||
const problems = [
|
||||
...(result.error ? [result.error] : []),
|
||||
...(rejectedCount > 0
|
||||
? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`]
|
||||
: []),
|
||||
];
|
||||
if (problems.length > 0) {
|
||||
Alert.alert("Could not attach photo", problems.join("\n\n"));
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePickFiles(): Promise<void> {
|
||||
if (isComposerInteractionLocked) {
|
||||
return;
|
||||
}
|
||||
const maxBytes =
|
||||
selectedEnvironmentServerConfig?.environment.capabilities.fileAttachments?.maxUploadBytes;
|
||||
if (maxBytes === undefined) {
|
||||
Alert.alert("File attachments are not available on this server.");
|
||||
return;
|
||||
}
|
||||
const result = await pickComposerFiles({
|
||||
existingCount: flow.attachments.length,
|
||||
maxBytes,
|
||||
});
|
||||
const rejectedCount = result.files.length > 0 ? flow.appendAttachments(result.files) : 0;
|
||||
// The picker error and the live-cap rejection can both happen in one
|
||||
// pick; report both in a single alert.
|
||||
const problems = [
|
||||
...(result.error ? [result.error] : []),
|
||||
...(rejectedCount > 0
|
||||
? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`]
|
||||
: []),
|
||||
];
|
||||
if (problems.length > 0) {
|
||||
Alert.alert("Could not attach file", problems.join("\n\n"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -693,6 +788,16 @@ export function NewTaskDraftScreen(props: {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
// A failed-send restore can leave the draft over the cap on purpose (it
|
||||
// never drops the user's files); starting anyway would upload everything
|
||||
// and have the server reject the turn.
|
||||
if (draft.attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
|
||||
Alert.alert(
|
||||
"Too many attachments",
|
||||
`Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const editingPendingTask = flow.editingPendingTask;
|
||||
|
||||
@@ -764,6 +869,10 @@ export function NewTaskDraftScreen(props: {
|
||||
interactionMode,
|
||||
initialMessageText,
|
||||
initialAttachments: draft.attachments,
|
||||
onAttachmentsUploaded: async (attachments) => {
|
||||
flow.replaceAttachments(attachments);
|
||||
await flushComposerDrafts();
|
||||
},
|
||||
...(editingPendingTask
|
||||
? {
|
||||
turnMetadata: {
|
||||
@@ -839,7 +948,7 @@ export function NewTaskDraftScreen(props: {
|
||||
// The context-first screen intentionally opens with the keyboard closed.
|
||||
// Focusing is a user action, so presenting the form sheet has one motion.
|
||||
autoFocus={false}
|
||||
editable={!isIncomingShareTransferPending}
|
||||
editable={!isComposerInteractionLocked}
|
||||
multiline
|
||||
scrollEnabled
|
||||
value={flow.prompt}
|
||||
@@ -873,7 +982,7 @@ export function NewTaskDraftScreen(props: {
|
||||
navigation.goBack();
|
||||
};
|
||||
const chooseProject = () => {
|
||||
if (isIncomingShareTransferPending) {
|
||||
if (isComposerInteractionLocked) {
|
||||
return;
|
||||
}
|
||||
promptInputRef.current?.blur();
|
||||
@@ -881,7 +990,7 @@ export function NewTaskDraftScreen(props: {
|
||||
navigation.dispatch(StackActions.push("NewTask", { incomingShareId: props.incomingShareId }));
|
||||
};
|
||||
const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {
|
||||
if (isIncomingShareTransferPending) {
|
||||
if (isComposerInteractionLocked) {
|
||||
return;
|
||||
}
|
||||
promptInputRef.current?.blur();
|
||||
@@ -901,7 +1010,7 @@ export function NewTaskDraftScreen(props: {
|
||||
accessibilityHint="Opens the project picker"
|
||||
accessibilityLabel={`Change project from ${selectedProject.title}`}
|
||||
accessibilityRole="button"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
disabled={isComposerInteractionLocked}
|
||||
onPress={chooseProject}
|
||||
className="min-w-0 max-w-[250px] border-b border-foreground-muted active:opacity-65"
|
||||
>
|
||||
@@ -919,7 +1028,7 @@ export function NewTaskDraftScreen(props: {
|
||||
<ComposerInlineControl
|
||||
accessibilityLabel={`Environment: ${selectedEnvironmentLabel}`}
|
||||
chevronDirection="right"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
disabled={isComposerInteractionLocked}
|
||||
icon="desktopcomputer"
|
||||
label={`on ${selectedEnvironmentLabel}`}
|
||||
maxWidth={260}
|
||||
@@ -954,7 +1063,7 @@ export function NewTaskDraftScreen(props: {
|
||||
<ComposerInlineControl
|
||||
accessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}
|
||||
accessibilityLabel={workspaceLabel}
|
||||
disabled={isIncomingShareTransferPending}
|
||||
disabled={isComposerInteractionLocked}
|
||||
iconNode={
|
||||
<NewTaskWorkspaceIcon
|
||||
workspaceMode={flow.workspaceMode}
|
||||
@@ -970,7 +1079,7 @@ export function NewTaskDraftScreen(props: {
|
||||
<ComposerInlineControl
|
||||
accessibilityLabel={`${flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}: ${selectedBranchLabel}`}
|
||||
chevronDirection="right"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
disabled={isComposerInteractionLocked}
|
||||
icon="arrow.triangle.branch"
|
||||
label={showBranchLoading ? "Loading branches…" : selectedBranchLabel}
|
||||
maxWidth={190}
|
||||
@@ -1010,7 +1119,7 @@ export function NewTaskDraftScreen(props: {
|
||||
attachments={flow.attachments}
|
||||
imageBorderRadius={16}
|
||||
imageSize={72}
|
||||
onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}
|
||||
onRemove={isComposerInteractionLocked ? () => undefined : flow.removeAttachment}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
@@ -1021,14 +1130,24 @@ export function NewTaskDraftScreen(props: {
|
||||
<ComposerToolbarScroller contentPaddingRight={8} fadeSurface="sheet">
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Add attachment"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
disabled={isComposerInteractionLocked}
|
||||
icon="plus"
|
||||
onPress={() => void handlePickImages()}
|
||||
onPress={() => {
|
||||
if (selectedEnvironmentServerConfig?.environment.capabilities.fileAttachments) {
|
||||
Alert.alert("Add attachment", undefined, [
|
||||
{ text: "Photos", onPress: () => void handlePickImages() },
|
||||
{ text: "Files", onPress: () => void handlePickFiles() },
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
]);
|
||||
return;
|
||||
}
|
||||
void handlePickImages();
|
||||
}}
|
||||
showChevron={false}
|
||||
/>
|
||||
<ComposerInlineControl
|
||||
accessibilityLabel="Model and reasoning settings"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
disabled={isComposerInteractionLocked}
|
||||
emphasized
|
||||
iconNode={
|
||||
<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
|
||||
@@ -1041,7 +1160,7 @@ export function NewTaskDraftScreen(props: {
|
||||
<ComposerInlineControl
|
||||
accessibilityHint={`Switches to ${flow.interactionMode === "plan" ? "Build" : "Plan"} mode`}
|
||||
accessibilityLabel={`Interaction mode: ${flow.interactionMode === "plan" ? "Plan" : "Build"}`}
|
||||
disabled={isIncomingShareTransferPending}
|
||||
disabled={isComposerInteractionLocked}
|
||||
emphasized
|
||||
icon={
|
||||
flow.interactionMode === "plan"
|
||||
|
||||
@@ -99,8 +99,8 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
? incomingShare.attachments.length === 0
|
||||
? "Choose a project for what you shared"
|
||||
: incomingShare.attachments.length === 1
|
||||
? "Choose a project for the image you shared"
|
||||
: `Choose a project for the ${incomingShare.attachments.length} images you shared`
|
||||
? `Choose a project for the ${incomingShare.attachments[0]?.type === "image" ? "image" : "file"} you shared`
|
||||
: `Choose a project for the ${incomingShare.attachments.length} ${incomingShare.attachments.every((attachment) => attachment.type === "image") ? "images" : "files"} you shared`
|
||||
: null;
|
||||
const screenTitle = incomingShare ? "Start a task" : "Choose project";
|
||||
const projectEmptyState = deriveProjectEmptyState(catalogState);
|
||||
|
||||
@@ -19,7 +19,15 @@ import {
|
||||
useState,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import { ActivityIndicator, Image, Platform, Pressable, View, type ViewStyle } from "react-native";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Alert,
|
||||
Image,
|
||||
Platform,
|
||||
Pressable,
|
||||
View,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import Animated, {
|
||||
FadeIn,
|
||||
@@ -36,6 +44,7 @@ import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/re
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
|
||||
import { GlassSurface } from "../../components/GlassSurface";
|
||||
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
@@ -46,7 +55,7 @@ import {
|
||||
} from "../../components/ComposerToolbar";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import type { DraftComposerAttachment } from "../../lib/composerImages";
|
||||
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
|
||||
import type { RemoteClientConnectionState } from "../../lib/connection";
|
||||
@@ -76,7 +85,7 @@ export const COMPOSER_EXPANDED_CHROME = 156;
|
||||
|
||||
export interface ThreadComposerProps {
|
||||
readonly draftMessage: string;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly placeholder: string;
|
||||
readonly contentMaxWidth?: number;
|
||||
readonly bottomInset?: number;
|
||||
@@ -97,6 +106,7 @@ export interface ThreadComposerProps {
|
||||
readonly editorRef?: RefObject<ComposerEditorHandle | null>;
|
||||
readonly onChangeDraftMessage: (value: string) => void;
|
||||
readonly onPickDraftImages: () => Promise<void>;
|
||||
readonly onPickDraftFiles: () => Promise<void>;
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly onRemoveDraftImage: (imageId: string) => void;
|
||||
readonly onStopThread: () => void;
|
||||
@@ -597,15 +607,27 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
</View>
|
||||
{!isExpanded && props.draftAttachments.length > 0 ? (
|
||||
<View className="flex-row gap-1 pl-1">
|
||||
{props.draftAttachments.slice(0, 3).map((image) => (
|
||||
<Pressable key={image.id} onPress={() => onPressImage(image.previewUri)}>
|
||||
<Image
|
||||
source={{ uri: image.previewUri }}
|
||||
className="size-[30px] rounded-lg bg-subtle"
|
||||
resizeMode="cover"
|
||||
/>
|
||||
</Pressable>
|
||||
))}
|
||||
{props.draftAttachments.slice(0, 3).map((attachment) =>
|
||||
attachment.type === "image" ? (
|
||||
<Pressable
|
||||
key={attachment.id}
|
||||
onPress={() => onPressImage(attachment.previewUri)}
|
||||
>
|
||||
<Image
|
||||
source={{ uri: attachment.previewUri }}
|
||||
className="size-[30px] rounded-lg bg-subtle"
|
||||
resizeMode="cover"
|
||||
/>
|
||||
</Pressable>
|
||||
) : (
|
||||
<View
|
||||
key={attachment.id}
|
||||
className="size-[30px] items-center justify-center rounded-lg bg-subtle"
|
||||
>
|
||||
<SymbolView name="doc.text" size={15} tintColor="#a3a3a3" type="monochrome" />
|
||||
</View>
|
||||
),
|
||||
)}
|
||||
{props.draftAttachments.length > 3 ? (
|
||||
<View className="size-[30px] items-center justify-center rounded-lg bg-subtle-strong">
|
||||
<Text className="text-foreground-muted text-2xs font-t3-bold">
|
||||
@@ -650,7 +672,17 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Add attachment"
|
||||
icon="plus"
|
||||
onPress={() => void props.onPickDraftImages()}
|
||||
onPress={() => {
|
||||
if (props.serverConfig?.environment.capabilities.fileAttachments) {
|
||||
Alert.alert("Add attachment", undefined, [
|
||||
{ text: "Photos", onPress: () => void props.onPickDraftImages() },
|
||||
{ text: "Files", onPress: () => void props.onPickDraftFiles() },
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
]);
|
||||
return;
|
||||
}
|
||||
void props.onPickDraftImages();
|
||||
}}
|
||||
showChevron={false}
|
||||
/>
|
||||
<View className="min-w-0 flex-1" style={{ maxWidth: 152 }}>
|
||||
|
||||
@@ -54,7 +54,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
|
||||
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import type { DraftComposerAttachment } from "../../lib/composerImages";
|
||||
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
|
||||
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
@@ -101,7 +101,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly draftMessage: string;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly connectionStateLabel: EnvironmentConnectionPhase;
|
||||
/** Message sync status for the selected thread (drives the composer status pill). */
|
||||
readonly threadSyncStatus?: EnvironmentThreadStatus;
|
||||
@@ -118,6 +118,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly onOpenConnectionEditor: () => void;
|
||||
readonly onChangeDraftMessage: (value: string) => void;
|
||||
readonly onPickDraftImages: () => Promise<void>;
|
||||
readonly onPickDraftFiles: () => Promise<void>;
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly onRemoveDraftImage: (imageId: string) => void;
|
||||
readonly onStopThread: () => void;
|
||||
@@ -776,6 +777,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
bottomInset={composerBottomInset}
|
||||
onChangeDraftMessage={props.onChangeDraftMessage}
|
||||
onPickDraftImages={props.onPickDraftImages}
|
||||
onPickDraftFiles={props.onPickDraftFiles}
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
|
||||
@@ -1,12 +1,23 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import type {
|
||||
ChatAttachment,
|
||||
ChatFileAttachment,
|
||||
ChatImageAttachment,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
|
||||
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
|
||||
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { HeaderHeightContext } from "@react-navigation/elements";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useFocusEffect, useNavigation } from "@react-navigation/native";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
@@ -27,6 +38,7 @@ import {
|
||||
} from "react-native-nitro-markdown";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Alert,
|
||||
Image,
|
||||
Platform,
|
||||
type LayoutChangeEvent,
|
||||
@@ -57,6 +69,7 @@ import { useFontFamily } from "../../lib/useFontFamily";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
|
||||
import { downloadAndShareAttachment } from "../../lib/attachmentDownload";
|
||||
import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks";
|
||||
import {
|
||||
hasNativeSelectableMarkdownText,
|
||||
@@ -112,7 +125,10 @@ import {
|
||||
WORK_GROUP_TOGGLE_HEIGHT,
|
||||
} from "./thread-work-log";
|
||||
import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
|
||||
import { useAssetUrl, useAssetUrlState } from "../../state/assets";
|
||||
import { assetEnvironment, useAssetUrl, useAssetUrlState } from "../../state/assets";
|
||||
import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
|
||||
import { usePreparedConnection } from "../../state/session";
|
||||
import * as Option from "effect/Option";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
import { MARKDOWN_IMAGE_MAX_WIDTH, resolveMarkdownImageDisplaySize } from "./markdownImageSize";
|
||||
|
||||
@@ -207,6 +223,122 @@ function MessageAttachmentImage(props: {
|
||||
);
|
||||
}
|
||||
|
||||
// The attachment union has an open member (`type: string` for attachment
|
||||
// types from newer servers), so literal comparisons do not narrow it. Split
|
||||
// with guards and render unknown types as inert rows, never crash.
|
||||
function isImageAttachment(attachment: ChatAttachment): attachment is ChatImageAttachment {
|
||||
return attachment.type === "image";
|
||||
}
|
||||
|
||||
function isFileAttachment(attachment: ChatAttachment): attachment is ChatFileAttachment {
|
||||
return attachment.type === "file";
|
||||
}
|
||||
|
||||
function MessageAttachmentFile(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly attachment: ChatFileAttachment;
|
||||
}) {
|
||||
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const preparedConnection = usePreparedConnection(props.environmentId);
|
||||
const { attachment } = props;
|
||||
const httpBaseUrl = Option.isSome(preparedConnection)
|
||||
? preparedConnection.value.httpBaseUrl
|
||||
: null;
|
||||
const openingRef = useRef<AbortController | null>(null);
|
||||
const [opening, setOpening] = useState(false);
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
setOpening(false);
|
||||
return () => {
|
||||
openingRef.current?.abort();
|
||||
openingRef.current = null;
|
||||
};
|
||||
}, [props.environmentId, attachment.id, httpBaseUrl]),
|
||||
);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Open ${attachment.name}`}
|
||||
accessibilityState={{ disabled: opening || httpBaseUrl === null, busy: opening }}
|
||||
disabled={opening || httpBaseUrl === null}
|
||||
className="flex-row items-center gap-2 py-1"
|
||||
onPress={() => {
|
||||
if (httpBaseUrl === null || openingRef.current) return;
|
||||
const controller = new AbortController();
|
||||
openingRef.current = controller;
|
||||
setOpening(true);
|
||||
void (async () => {
|
||||
try {
|
||||
const result = await createAssetUrl({
|
||||
environmentId: props.environmentId,
|
||||
input: {
|
||||
resource: {
|
||||
_tag: "attachment",
|
||||
attachmentId: attachment.id,
|
||||
fileName: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
},
|
||||
},
|
||||
});
|
||||
if (controller.signal.aborted) return;
|
||||
if (result._tag === "Failure") {
|
||||
throw squashAtomCommandFailure(result);
|
||||
}
|
||||
const url = resolveAssetUrl(httpBaseUrl, result.value.relativeUrl);
|
||||
if (url === null) {
|
||||
throw new Error("The attachment could not be opened.");
|
||||
}
|
||||
await downloadAndShareAttachment({ url, attachment, signal: controller.signal });
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted) {
|
||||
Alert.alert(
|
||||
"Could not open attachment",
|
||||
error instanceof Error ? error.message : "The attachment is unavailable.",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (openingRef.current === controller) {
|
||||
openingRef.current = null;
|
||||
setOpening(false);
|
||||
}
|
||||
}
|
||||
})();
|
||||
}}
|
||||
>
|
||||
{opening ? (
|
||||
<ActivityIndicator size="small" />
|
||||
) : (
|
||||
<SymbolView name="doc.text" size={16} tintColor="#a3a3a3" type="monochrome" />
|
||||
)}
|
||||
<Text className="min-w-0 flex-1 text-sm text-foreground" numberOfLines={1}>
|
||||
{attachment.name}
|
||||
</Text>
|
||||
<Text className="text-xs text-foreground-muted">
|
||||
{formatAttachmentSize(attachment.sizeBytes)}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* An attachment type this build does not know (newer server). Rendered as an
|
||||
* inert row: the name is still useful, but there is nothing to open.
|
||||
*/
|
||||
function MessageAttachmentUnknown(props: { readonly name: string }) {
|
||||
return (
|
||||
<View className="flex-row items-center gap-2 py-1">
|
||||
<SymbolView name="doc.text" size={16} tintColor="#a3a3a3" type="monochrome" />
|
||||
<Text className="min-w-0 flex-1 text-sm text-foreground" numberOfLines={1}>
|
||||
{props.name}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ThreadMarkdownImageView(props: {
|
||||
readonly uri: string | null;
|
||||
readonly sourceKey: string;
|
||||
@@ -1032,9 +1164,7 @@ function renderFeedEntry(
|
||||
const isUser = message.role === "user";
|
||||
const styles = isUser ? markdownStyles.user : markdownStyles.assistant;
|
||||
const timestampLabel = formatMessageTime(isUser ? message.createdAt : message.updatedAt);
|
||||
const attachments = (message.attachments ?? []).filter(
|
||||
(attachment) => attachment.type === "image",
|
||||
);
|
||||
const attachments = message.attachments ?? [];
|
||||
const hasReviewCommentContext = message.text.includes("<review_comment");
|
||||
// A bubble that sizes itself from its content cannot lay out a block whose
|
||||
// intrinsic width overflows `maxWidth`: Android positions the bubble's
|
||||
@@ -1082,7 +1212,7 @@ function renderFeedEntry(
|
||||
/>
|
||||
) : null}
|
||||
{attachments.map((attachment) => {
|
||||
return (
|
||||
return isImageAttachment(attachment) ? (
|
||||
<MessageAttachmentImage
|
||||
key={attachment.id}
|
||||
environmentId={props.environmentId}
|
||||
@@ -1090,6 +1220,14 @@ function renderFeedEntry(
|
||||
className="aspect-[1.3] w-full rounded-[14px] bg-white/15"
|
||||
onPressImage={props.onPressImage}
|
||||
/>
|
||||
) : isFileAttachment(attachment) ? (
|
||||
<MessageAttachmentFile
|
||||
key={attachment.id}
|
||||
environmentId={props.environmentId}
|
||||
attachment={attachment}
|
||||
/>
|
||||
) : (
|
||||
<MessageAttachmentUnknown key={attachment.id} name={attachment.name} />
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
@@ -1144,7 +1282,7 @@ function renderFeedEntry(
|
||||
)
|
||||
) : null}
|
||||
{attachments.map((attachment) => {
|
||||
return (
|
||||
return isImageAttachment(attachment) ? (
|
||||
<MessageAttachmentImage
|
||||
key={attachment.id}
|
||||
environmentId={props.environmentId}
|
||||
@@ -1152,6 +1290,14 @@ function renderFeedEntry(
|
||||
className="mt-1.5 aspect-[1.3] w-full rounded-[18px] bg-adaptive-neutral-200-800"
|
||||
onPressImage={props.onPressImage}
|
||||
/>
|
||||
) : isFileAttachment(attachment) ? (
|
||||
<MessageAttachmentFile
|
||||
key={attachment.id}
|
||||
environmentId={props.environmentId}
|
||||
attachment={attachment}
|
||||
/>
|
||||
) : (
|
||||
<MessageAttachmentUnknown key={attachment.id} name={attachment.name} />
|
||||
);
|
||||
})}
|
||||
{showAssistantMeta ? (
|
||||
|
||||
@@ -794,6 +794,7 @@ function ThreadRouteContent(
|
||||
onOpenConnectionEditor={handleOpenConnectionEditor}
|
||||
onChangeDraftMessage={composer.onChangeDraftMessage}
|
||||
onPickDraftImages={composer.onPickDraftImages}
|
||||
onPickDraftFiles={composer.onPickDraftFiles}
|
||||
onNativePasteImages={composer.onNativePasteImages}
|
||||
onRemoveDraftImage={composer.onRemoveDraftImage}
|
||||
serverConfig={serverConfig}
|
||||
|
||||
@@ -27,7 +27,7 @@ import { pipe } from "effect/Function";
|
||||
|
||||
import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../state/entities";
|
||||
import type { TurnCommandMetadata } from "../../lib/commandMetadata";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import type { DraftComposerAttachment } from "../../lib/composerImages";
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
import {
|
||||
buildModelOptions,
|
||||
@@ -48,18 +48,22 @@ import {
|
||||
isComposerDraftEmpty,
|
||||
removeComposerDraftAttachment,
|
||||
replaceComposerDraftAttachments,
|
||||
scheduleUnusedComposerAttachmentCleanup,
|
||||
setComposerDraftText,
|
||||
setStickyComposerModelSelection,
|
||||
updateComposerDraftSettings,
|
||||
useComposerDraft,
|
||||
useStickyComposerModelSelection,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import {
|
||||
capturePendingTaskEditorWriteBaseline,
|
||||
flushPendingTaskEditorWrite,
|
||||
} from "../../state/pending-task-editor-writes";
|
||||
import { useDebouncedValue, usePaginatedBranches } from "../../state/queries";
|
||||
import { vcsEnvironment } from "../../state/vcs";
|
||||
import {
|
||||
flattenQueuedThreadMessages,
|
||||
threadOutboxManager,
|
||||
updateThreadOutboxMessage,
|
||||
type QueuedThreadMessage,
|
||||
} from "../../state/thread-outbox";
|
||||
import {
|
||||
@@ -135,7 +139,7 @@ type NewTaskFlowContextValue = {
|
||||
readonly draftKey: string | null;
|
||||
readonly editingPendingTask: QueuedThreadMessage | null;
|
||||
readonly prompt: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly submitting: boolean;
|
||||
readonly branchQuery: string;
|
||||
readonly branchesLoading: boolean;
|
||||
@@ -174,8 +178,9 @@ type NewTaskFlowContextValue = {
|
||||
readonly cancelEditingPendingTask: () => void;
|
||||
readonly buildPendingTaskMessage: (metadata: TurnCommandMetadata) => QueuedThreadMessage | null;
|
||||
readonly setPrompt: (value: string) => void;
|
||||
readonly replaceAttachments: (attachments: ReadonlyArray<DraftComposerImageAttachment>) => void;
|
||||
readonly appendAttachments: (attachments: ReadonlyArray<DraftComposerImageAttachment>) => void;
|
||||
readonly replaceAttachments: (attachments: ReadonlyArray<DraftComposerAttachment>) => void;
|
||||
/** Appends draft attachments; returns how many the live cap rejected. */
|
||||
readonly appendAttachments: (attachments: ReadonlyArray<DraftComposerAttachment>) => number;
|
||||
readonly removeAttachment: (imageId: string) => void;
|
||||
readonly clearAttachments: () => void;
|
||||
readonly setSubmitting: (value: boolean) => void;
|
||||
@@ -230,6 +235,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
// Mirrors `editingPendingTask` synchronously so the unmount flush cannot act
|
||||
// on a task whose editing session already ended this render.
|
||||
const editingPendingTaskRef = useRef<QueuedThreadMessage | null>(null);
|
||||
// Outbox revision this editor session may write after its predecessor save.
|
||||
// Unrelated accepted writes still beat the dismissed session's CAS.
|
||||
const editingRevisionRef = useRef(Promise.resolve(0));
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setSelectedEnvironmentId(null);
|
||||
@@ -513,7 +521,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
const replaceAttachments = useCallback(
|
||||
(nextAttachments: ReadonlyArray<DraftComposerImageAttachment>) => {
|
||||
(nextAttachments: ReadonlyArray<DraftComposerAttachment>) => {
|
||||
if (!selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
@@ -521,12 +529,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
// Returns how many attachments the live cap rejected so the caller can
|
||||
// tell the user (a concurrent add can fill the draft mid-pick).
|
||||
const appendAttachments = useCallback(
|
||||
(nextAttachments: ReadonlyArray<DraftComposerImageAttachment>) => {
|
||||
(nextAttachments: ReadonlyArray<DraftComposerAttachment>): number => {
|
||||
if (!selectedProjectDraftKey) {
|
||||
return;
|
||||
return 0;
|
||||
}
|
||||
appendComposerDraftAttachments(selectedProjectDraftKey, nextAttachments);
|
||||
return appendComposerDraftAttachments(selectedProjectDraftKey, nextAttachments);
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
@@ -835,6 +845,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
setSelectedProjectKey(scopedProjectKey(message.environmentId, message.creation.projectId));
|
||||
activeEditingMessageId = message.messageId;
|
||||
editingPendingTaskRef.current = message;
|
||||
editingRevisionRef.current = capturePendingTaskEditorWriteBaseline(message.messageId);
|
||||
setEditingPendingTask(message);
|
||||
// Hold the outbox drain off this task while it is open in the editor.
|
||||
holdEditingQueuedMessage(message.messageId);
|
||||
@@ -932,6 +943,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
}
|
||||
clearComposerDraft(pendingTaskDraftKey(editing.messageId));
|
||||
releaseEditingQueuedMessage(editing.messageId);
|
||||
scheduleUnusedComposerAttachmentCleanup(editing.attachments);
|
||||
}
|
||||
setEditingPendingTask(null);
|
||||
}, []);
|
||||
@@ -984,17 +996,28 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
return;
|
||||
}
|
||||
|
||||
// update() rewrites the task only if it is still queued — a concurrent
|
||||
// delete or delivery wins, so the flush cannot resurrect it.
|
||||
void updateThreadOutboxMessage(message)
|
||||
.then(() => {
|
||||
// The write handoff lets a reopened editor follow this editor's pending
|
||||
// save. Its CAS still rejects unrelated queue edits, deletes, and
|
||||
// deliveries, so the flush cannot resurrect or overwrite them.
|
||||
void flushPendingTaskEditorWrite({
|
||||
message,
|
||||
baseline: editingRevisionRef.current,
|
||||
draftKey: pendingTaskDraftKey(editing.messageId),
|
||||
})
|
||||
.then((savedDraftStillCurrent) => {
|
||||
// If this task was reopened (possibly in a fresh provider) while
|
||||
// the save was in flight, that session owns the draft and the lock.
|
||||
if (activeEditingMessageId === editing.messageId) {
|
||||
return;
|
||||
}
|
||||
if (!savedDraftStillCurrent) {
|
||||
// A newer queue write won the CAS, or a newer editor changed this
|
||||
// draft. Keep the draft and drain lock so reopening can retry it.
|
||||
return;
|
||||
}
|
||||
clearComposerDraft(pendingTaskDraftKey(editing.messageId));
|
||||
releaseEditingQueuedMessage(editing.messageId);
|
||||
scheduleUnusedComposerAttachmentCleanup(editing.attachments);
|
||||
})
|
||||
.catch((error) => {
|
||||
// Keep the drain lock and the draft: delivering the stale payload
|
||||
|
||||
@@ -14,13 +14,17 @@ import * as Cause from "effect/Cause";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import type { DraftComposerAttachment } from "../../lib/composerImages";
|
||||
import { prepareTurnAttachments, validateDraftFileAttachments } from "../../lib/attachmentUpload";
|
||||
import { makeTurnCommandMetadata, type TurnCommandMetadata } from "../../lib/commandMetadata";
|
||||
import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn";
|
||||
import { randomHex } from "../../lib/uuid";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { scheduleUnusedComposerAttachmentCleanup } from "../../state/use-composer-drafts";
|
||||
import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
|
||||
import { validateProjectThreadCreation } from "./projectThreadCreationValidation";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { serverEnvironment } from "../../state/server";
|
||||
|
||||
export function useCreateProjectThread() {
|
||||
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
|
||||
@@ -36,7 +40,10 @@ export function useCreateProjectThread() {
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly interactionMode: ProviderInteractionMode;
|
||||
readonly initialMessageText: string;
|
||||
readonly initialAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly initialAttachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly onAttachmentsUploaded: (
|
||||
attachments: ReadonlyArray<DraftComposerAttachment>,
|
||||
) => Promise<void>;
|
||||
/** Reuse identifiers from a queued pending task instead of minting new ones. */
|
||||
readonly turnMetadata?: TurnCommandMetadata;
|
||||
}) => {
|
||||
@@ -56,6 +63,50 @@ export function useCreateProjectThread() {
|
||||
return AsyncResult.failure(Cause.fail(validationError));
|
||||
}
|
||||
|
||||
const validateLiveFileAttachments = (
|
||||
attachments: ReadonlyArray<DraftComposerAttachment>,
|
||||
): string | null =>
|
||||
validateDraftFileAttachments({
|
||||
attachments,
|
||||
serverConfig: appAtomRegistry.get(
|
||||
serverEnvironment.configValueAtom(input.project.environmentId),
|
||||
),
|
||||
});
|
||||
const initialAttachmentError = validateLiveFileAttachments(input.initialAttachments);
|
||||
if (initialAttachmentError !== null) {
|
||||
setPendingConnectionError(initialAttachmentError);
|
||||
return AsyncResult.failure(Cause.fail(new Error(initialAttachmentError)));
|
||||
}
|
||||
|
||||
let prepared: Awaited<ReturnType<typeof prepareTurnAttachments>>;
|
||||
try {
|
||||
// If persisting the references into the draft throws, the owner call
|
||||
// deletes the pending uploads it minted before rethrowing.
|
||||
prepared = await prepareTurnAttachments({
|
||||
environmentId: input.project.environmentId,
|
||||
attachments: input.initialAttachments,
|
||||
persistUploadedReferences: async (draftAttachments) => {
|
||||
await input.onAttachmentsUploaded(draftAttachments);
|
||||
return "persisted";
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "An attachment could not upload.";
|
||||
setPendingConnectionError(message);
|
||||
return AsyncResult.failure(Cause.fail(new Error(message)));
|
||||
}
|
||||
if (prepared.status !== "ready") {
|
||||
const message = "The attachments are no longer available.";
|
||||
setPendingConnectionError(message);
|
||||
return AsyncResult.failure(Cause.fail(new Error(message)));
|
||||
}
|
||||
|
||||
const preparedAttachmentError = validateLiveFileAttachments(prepared.draftAttachments);
|
||||
if (preparedAttachmentError !== null) {
|
||||
setPendingConnectionError(preparedAttachmentError);
|
||||
return AsyncResult.failure(Cause.fail(new Error(preparedAttachmentError)));
|
||||
}
|
||||
|
||||
const result = await startTurn({
|
||||
environmentId: input.project.environmentId,
|
||||
input: buildProjectThreadStartTurnInput({
|
||||
@@ -67,6 +118,7 @@ export function useCreateProjectThread() {
|
||||
createdAt: metadata.createdAt,
|
||||
text: initialMessageText,
|
||||
attachments: input.initialAttachments,
|
||||
uploadedAttachments: prepared.attachments,
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
@@ -84,7 +136,13 @@ export function useCreateProjectThread() {
|
||||
);
|
||||
return AsyncResult.failure(result.cause);
|
||||
}
|
||||
// The started turn holds its own copy of the bytes; a failed delete is
|
||||
// surfaced without failing the started task.
|
||||
await prepared.releaseUploads().catch((error) => {
|
||||
console.warn("[project-thread] could not delete consumed pending uploads", error);
|
||||
});
|
||||
setPendingConnectionError(null);
|
||||
scheduleUnusedComposerAttachmentCleanup(input.initialAttachments);
|
||||
|
||||
return mapAtomCommandResult(result, () =>
|
||||
scopeThreadRef(input.project.environmentId, threadId),
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
directories: new Set<string>(),
|
||||
deleted: vi.fn(),
|
||||
download: vi.fn(),
|
||||
share: vi.fn(),
|
||||
available: vi.fn(),
|
||||
uuid: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("expo-file-system", () => {
|
||||
class Directory {
|
||||
readonly uri: string;
|
||||
|
||||
constructor(...parts: Array<string | Directory>) {
|
||||
this.uri = parts.map((part) => (typeof part === "string" ? part : part.uri)).join("/");
|
||||
}
|
||||
|
||||
get name(): string {
|
||||
return this.uri.split("/").at(-1)!;
|
||||
}
|
||||
|
||||
get exists(): boolean {
|
||||
return mocks.directories.has(this.uri);
|
||||
}
|
||||
|
||||
create(): void {
|
||||
mocks.directories.add(this.uri);
|
||||
}
|
||||
|
||||
list(): Directory[] {
|
||||
const prefix = `${this.uri}/`;
|
||||
return [...mocks.directories]
|
||||
.filter((uri) => uri.startsWith(prefix) && !uri.slice(prefix.length).includes("/"))
|
||||
.map((uri) => new Directory(uri));
|
||||
}
|
||||
|
||||
delete(): void {
|
||||
mocks.deleted(this.uri);
|
||||
mocks.directories.delete(this.uri);
|
||||
}
|
||||
}
|
||||
|
||||
class File {
|
||||
static downloadFileAsync = mocks.download;
|
||||
readonly uri: string;
|
||||
|
||||
constructor(directory: Directory, name: string) {
|
||||
this.uri = `${directory.uri}/${encodeURIComponent(name)}`;
|
||||
}
|
||||
}
|
||||
|
||||
return { Directory, File, Paths: { cache: "file:///cache" } };
|
||||
});
|
||||
|
||||
vi.mock("expo-sharing", () => ({
|
||||
isAvailableAsync: mocks.available,
|
||||
shareAsync: mocks.share,
|
||||
}));
|
||||
|
||||
vi.mock("./uuid", () => ({ uuidv4: mocks.uuid }));
|
||||
|
||||
import { downloadAndShareAttachment } from "./attachmentDownload";
|
||||
import { isForegroundHandoffActive } from "./foreground-handoff";
|
||||
|
||||
const NOW = 1_787_990_400_000;
|
||||
const DAY_MS = 24 * 60 * 60_000;
|
||||
const CACHE = "file:///cache/t3-attachment-downloads";
|
||||
const input = {
|
||||
url: "https://chosen-environment.example/api/assets/signed-token/report.pdf",
|
||||
attachment: { name: "report.pdf", mimeType: "application/pdf" },
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.directories.clear();
|
||||
mocks.deleted.mockReset();
|
||||
mocks.download.mockReset();
|
||||
mocks.share.mockReset();
|
||||
mocks.available.mockReset();
|
||||
mocks.uuid.mockReset();
|
||||
mocks.download.mockImplementation(async (_url: string, file: { uri: string }) => file);
|
||||
mocks.share.mockResolvedValue(undefined);
|
||||
mocks.available.mockResolvedValue(true);
|
||||
let sequence = 0;
|
||||
mocks.uuid.mockImplementation(
|
||||
() => `00000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}`,
|
||||
);
|
||||
vi.spyOn(Date, "now").mockReturnValue(NOW);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
expect(isForegroundHandoffActive()).toBe(false);
|
||||
});
|
||||
|
||||
describe("downloadAndShareAttachment", () => {
|
||||
it("downloads the chosen environment's signed URL and shares the local file", async () => {
|
||||
const controller = new AbortController();
|
||||
await downloadAndShareAttachment({ ...input, signal: controller.signal });
|
||||
|
||||
expect(mocks.download).toHaveBeenCalledWith(
|
||||
input.url,
|
||||
expect.objectContaining({ uri: expect.stringMatching(/\/report\.pdf$/) }),
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(mocks.share).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/^file:\/\/\/cache\/.+\/report\.pdf$/),
|
||||
{
|
||||
mimeType: "application/pdf",
|
||||
dialogTitle: "report.pdf",
|
||||
},
|
||||
);
|
||||
expect(mocks.deleted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shares videos even when the server serves their bytes inline", async () => {
|
||||
await downloadAndShareAttachment({
|
||||
url: "https://relay-environment.example/api/assets/signed-video/clip.mp4",
|
||||
attachment: { name: "clip.mp4", mimeType: 'video/mp4; codecs="avc1"' },
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
|
||||
expect(mocks.share).toHaveBeenCalledWith(expect.stringMatching(/\/clip\.mp4$/), {
|
||||
mimeType: "video/mp4",
|
||||
dialogTitle: "clip.mp4",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["../../résumé.pdf", "résumé.pdf"],
|
||||
["C:\\folder\\clip.mp4", "clip.mp4"],
|
||||
["a?query#part%2F.txt", "a?query#part%2F.txt"],
|
||||
["Report #5 - 100%.pdf", "Report #5 - 100%.pdf"],
|
||||
["..", "attachment"],
|
||||
[" ", "attachment"],
|
||||
["\ud800file\u0000.txt", "_file_.txt"],
|
||||
[".env", ".env"],
|
||||
])("uses a safe basename for %j", async (name, expected) => {
|
||||
await downloadAndShareAttachment({
|
||||
...input,
|
||||
attachment: { ...input.attachment, name },
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
const file = mocks.download.mock.calls[0]![1] as { uri: string };
|
||||
expect(decodeURIComponent(file.uri.split("/").at(-1)!)).toBe(expected);
|
||||
});
|
||||
|
||||
it("preserves ordinary long filenames that fit within the filesystem limit", async () => {
|
||||
const name =
|
||||
"Project quarterly report with detailed implementation and delivery notes for August 2026.pdf";
|
||||
await downloadAndShareAttachment({
|
||||
...input,
|
||||
attachment: { ...input.attachment, name },
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
const file = mocks.download.mock.calls[0]![1] as { uri: string };
|
||||
expect(decodeURIComponent(file.uri.split("/").at(-1)!)).toBe(name);
|
||||
});
|
||||
|
||||
it("bounds the UTF-8 filename length while preserving its extension", async () => {
|
||||
await downloadAndShareAttachment({
|
||||
...input,
|
||||
attachment: { name: `${"🙂".repeat(80)}.mp4`, mimeType: "video/mp4" },
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
const file = mocks.download.mock.calls[0]![1] as { uri: string };
|
||||
const name = decodeURIComponent(file.uri.split("/").at(-1)!);
|
||||
expect(name.endsWith(".mp4")).toBe(true);
|
||||
expect(new TextEncoder().encode(name).length).toBeLessThanOrEqual(255);
|
||||
});
|
||||
|
||||
it("reports unavailable sharing before downloading or creating files", async () => {
|
||||
mocks.available.mockResolvedValue(false);
|
||||
await expect(
|
||||
downloadAndShareAttachment({ ...input, signal: new AbortController().signal }),
|
||||
).rejects.toThrow("Saving and sharing files is unavailable on this device.");
|
||||
expect(mocks.download).not.toHaveBeenCalled();
|
||||
expect(mocks.directories.size).toBe(0);
|
||||
});
|
||||
|
||||
it("cleans an interrupted download only after the native request settles", async () => {
|
||||
const started = Promise.withResolvers<void>();
|
||||
const download = Promise.withResolvers<{ uri: string }>();
|
||||
mocks.download.mockImplementation(() => {
|
||||
started.resolve();
|
||||
return download.promise;
|
||||
});
|
||||
const controller = new AbortController();
|
||||
const task = downloadAndShareAttachment({ ...input, signal: controller.signal });
|
||||
await started.promise;
|
||||
controller.abort();
|
||||
expect(mocks.deleted).not.toHaveBeenCalled();
|
||||
download.reject(new Error("Canceled native request"));
|
||||
await task;
|
||||
expect(mocks.deleted).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.share).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not open a late download after cancellation", async () => {
|
||||
const started = Promise.withResolvers<{ uri: string }>();
|
||||
const download = Promise.withResolvers<{ uri: string }>();
|
||||
mocks.download.mockImplementation((_url: string, file: { uri: string }) => {
|
||||
started.resolve(file);
|
||||
return download.promise;
|
||||
});
|
||||
const controller = new AbortController();
|
||||
const task = downloadAndShareAttachment({ ...input, signal: controller.signal });
|
||||
const file = await started.promise;
|
||||
controller.abort();
|
||||
download.resolve(file);
|
||||
await task;
|
||||
expect(mocks.share).not.toHaveBeenCalled();
|
||||
expect(mocks.deleted).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("retains an export when its row unmounts during the native handoff", async () => {
|
||||
const opened = Promise.withResolvers<void>();
|
||||
const share = Promise.withResolvers<void>();
|
||||
mocks.share.mockImplementation(() => {
|
||||
expect(isForegroundHandoffActive()).toBe(true);
|
||||
opened.resolve();
|
||||
return share.promise;
|
||||
});
|
||||
const controller = new AbortController();
|
||||
const task = downloadAndShareAttachment({ ...input, signal: controller.signal });
|
||||
await opened.promise;
|
||||
controller.abort();
|
||||
share.resolve();
|
||||
await task;
|
||||
expect(mocks.deleted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cleans failed exports and releases the foreground handoff", async () => {
|
||||
mocks.share.mockRejectedValue(new Error("No activity can open this file"));
|
||||
await expect(
|
||||
downloadAndShareAttachment({ ...input, signal: new AbortController().signal }),
|
||||
).rejects.toThrow("Could not open the share sheet. Try again.");
|
||||
expect(mocks.deleted).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("removes expired exports while leaving recent and unrelated cache entries alone", async () => {
|
||||
const old = `${CACHE}/${NOW - DAY_MS - 1}-00000000-0000-4000-8000-000000000010`;
|
||||
const recent = `${CACHE}/${NOW - DAY_MS + 1}-00000000-0000-4000-8000-000000000011`;
|
||||
const unrelated = `${CACHE}/unrelated`;
|
||||
mocks.directories.add(old).add(recent).add(unrelated);
|
||||
|
||||
await downloadAndShareAttachment({ ...input, signal: new AbortController().signal });
|
||||
expect(mocks.deleted.mock.calls).toEqual([[old]]);
|
||||
expect(mocks.directories.has(recent)).toBe(true);
|
||||
expect(mocks.directories.has(unrelated)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not prune an active export even if it passes the cache expiry", async () => {
|
||||
const opened = Promise.withResolvers<void>();
|
||||
const share = Promise.withResolvers<void>();
|
||||
mocks.share.mockImplementationOnce(() => {
|
||||
opened.resolve();
|
||||
return share.promise;
|
||||
});
|
||||
const first = downloadAndShareAttachment({ ...input, signal: new AbortController().signal });
|
||||
await opened.promise;
|
||||
vi.mocked(Date.now).mockReturnValue(NOW + DAY_MS + 1);
|
||||
|
||||
await downloadAndShareAttachment({ ...input, signal: new AbortController().signal });
|
||||
expect(mocks.deleted).not.toHaveBeenCalled();
|
||||
share.resolve();
|
||||
await first;
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import type { ChatFileAttachment } from "@t3tools/contracts";
|
||||
import type { Directory } from "expo-file-system";
|
||||
|
||||
import { beginForegroundHandoff } from "./foreground-handoff";
|
||||
import { uuidv4 } from "./uuid";
|
||||
|
||||
const ATTACHMENT_DOWNLOAD_DIRECTORY = "t3-attachment-downloads";
|
||||
const DOWNLOAD_RETENTION_MS = 24 * 60 * 60_000;
|
||||
const DOWNLOAD_DIRECTORY_NAME = /^(\d+)-[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;
|
||||
const activeDirectories = new Set<string>();
|
||||
|
||||
function downloadFileName(name: string): string {
|
||||
const basename = name.split(/[\\/]/).at(-1) ?? "";
|
||||
const sanitized = Array.from(basename, (character) => {
|
||||
const codePoint = character.codePointAt(0)!;
|
||||
return codePoint < 32 ||
|
||||
(codePoint >= 127 && codePoint <= 159) ||
|
||||
(codePoint >= 0xd800 && codePoint <= 0xdfff)
|
||||
? "_"
|
||||
: character;
|
||||
})
|
||||
.join("")
|
||||
.trim();
|
||||
if (!sanitized || /^\.+$/.test(sanitized)) {
|
||||
return "attachment";
|
||||
}
|
||||
const encoder = new TextEncoder();
|
||||
if (encoder.encode(sanitized).byteLength <= 255) {
|
||||
return sanitized;
|
||||
}
|
||||
const extensionMatch = /\.[a-z0-9]{1,16}$/i.exec(sanitized);
|
||||
const extension = extensionMatch && extensionMatch.index > 0 ? extensionMatch[0] : "";
|
||||
const stem = extension ? sanitized.slice(0, -extension.length) : sanitized;
|
||||
let remainingBytes = 255 - encoder.encode(extension).byteLength;
|
||||
let shortStem = "";
|
||||
for (const character of stem) {
|
||||
const bytes = encoder.encode(character).byteLength;
|
||||
if (bytes > remainingBytes) break;
|
||||
shortStem += character;
|
||||
remainingBytes -= bytes;
|
||||
}
|
||||
return `${shortStem || "attachment"}${extension}`;
|
||||
}
|
||||
|
||||
function removeDownloadDirectory(directory: Directory): void {
|
||||
try {
|
||||
if (directory.exists) {
|
||||
directory.delete();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("[attachment-downloads] could not remove a cached file", error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Downloads original bytes for the native save/share sheet, including inline video responses. */
|
||||
export async function downloadAndShareAttachment(input: {
|
||||
readonly url: string;
|
||||
readonly attachment: Pick<ChatFileAttachment, "name" | "mimeType">;
|
||||
readonly signal: AbortSignal;
|
||||
}): Promise<void> {
|
||||
const [{ Directory, File, Paths }, Sharing] = await Promise.all([
|
||||
import("expo-file-system"),
|
||||
import("expo-sharing"),
|
||||
]);
|
||||
if (input.signal.aborted) return;
|
||||
const canShare = await Sharing.isAvailableAsync();
|
||||
if (input.signal.aborted) return;
|
||||
if (!canShare) {
|
||||
throw new Error("Saving and sharing files is unavailable on this device.");
|
||||
}
|
||||
|
||||
const cache = new Directory(Paths.cache, ATTACHMENT_DOWNLOAD_DIRECTORY);
|
||||
cache.create({ idempotent: true, intermediates: true });
|
||||
const now = Date.now();
|
||||
try {
|
||||
for (const entry of cache.list()) {
|
||||
const match = DOWNLOAD_DIRECTORY_NAME.exec(entry.name);
|
||||
if (
|
||||
entry instanceof Directory &&
|
||||
match &&
|
||||
Number(match[1]) < now - DOWNLOAD_RETENTION_MS &&
|
||||
!activeDirectories.has(entry.uri)
|
||||
) {
|
||||
removeDownloadDirectory(entry);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("[attachment-downloads] could not inspect cached files", error);
|
||||
}
|
||||
|
||||
const directory = new Directory(cache, `${now}-${uuidv4()}`);
|
||||
activeDirectories.add(directory.uri);
|
||||
let shared = false;
|
||||
let openingShareSheet = false;
|
||||
try {
|
||||
directory.create();
|
||||
const destination = new File(directory, downloadFileName(input.attachment.name));
|
||||
const file = await File.downloadFileAsync(input.url, destination, { signal: input.signal });
|
||||
if (input.signal.aborted) return;
|
||||
|
||||
openingShareSheet = true;
|
||||
const endHandoff = beginForegroundHandoff();
|
||||
try {
|
||||
await Sharing.shareAsync(file.uri, {
|
||||
mimeType: input.attachment.mimeType.split(";", 1)[0]?.trim() || "application/octet-stream",
|
||||
dialogTitle: input.attachment.name,
|
||||
});
|
||||
shared = true;
|
||||
} finally {
|
||||
endHandoff();
|
||||
}
|
||||
} catch (cause) {
|
||||
if (input.signal.aborted) return;
|
||||
throw new Error(
|
||||
openingShareSheet
|
||||
? "Could not open the share sheet. Try again."
|
||||
: "Could not download the attachment. Check the connection and try again.",
|
||||
{ cause },
|
||||
);
|
||||
} finally {
|
||||
activeDirectories.delete(directory.uri);
|
||||
// A receiver can still be reading after Android's chooser returns.
|
||||
// Successful exports expire on a later open; partial downloads do not.
|
||||
if (!shared) {
|
||||
removeDownloadDirectory(directory);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
documentUri: "file:///documents",
|
||||
createAssetUrl: vi.fn(),
|
||||
createUploadUrl: Symbol("create-upload-url"),
|
||||
executeAtomQuery: vi.fn(),
|
||||
removeUpload: Symbol("remove-upload"),
|
||||
preparedConnection: Symbol("prepared-connection"),
|
||||
runAtomCommand: vi.fn(),
|
||||
readAtom: vi.fn(),
|
||||
upload: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@t3tools/client-runtime/state/runtime", () => ({
|
||||
// The client-runtime attachments module resolves the same file through its
|
||||
// relative import, so these fakes also feed runAttachmentUploadCycle and
|
||||
// verifyPersistedAttachmentUpload.
|
||||
createEnvironmentRpcCommand: () => Symbol("rpc-command"),
|
||||
executeAtomQuery: mocks.executeAtomQuery,
|
||||
runAtomCommand: mocks.runAtomCommand,
|
||||
squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error,
|
||||
}));
|
||||
|
||||
vi.mock("../state/atom-registry", () => ({
|
||||
appAtomRegistry: { get: mocks.readAtom },
|
||||
}));
|
||||
|
||||
vi.mock("../state/assets", () => ({
|
||||
assetEnvironment: { createUrl: mocks.createAssetUrl },
|
||||
}));
|
||||
|
||||
vi.mock("../state/attachments", () => ({
|
||||
attachmentEnvironment: {
|
||||
createUploadUrl: mocks.createUploadUrl,
|
||||
remove: mocks.removeUpload,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../state/session", () => ({
|
||||
environmentSession: {
|
||||
preparedConnectionValueAtom: () => mocks.preparedConnection,
|
||||
},
|
||||
}));
|
||||
|
||||
// Cuts the expo-crypto -> react-native import chain out of the test graph.
|
||||
vi.mock("./uuid", () => ({
|
||||
uuidv4: () => "uuid",
|
||||
randomHex: () => "0000",
|
||||
}));
|
||||
|
||||
vi.mock("expo-file-system", () => ({
|
||||
File: class {
|
||||
constructor(readonly uri: string) {}
|
||||
|
||||
upload(url: string, options: unknown) {
|
||||
return mocks.upload(this.uri, url, options);
|
||||
}
|
||||
},
|
||||
Paths: {
|
||||
get document() {
|
||||
return { uri: mocks.documentUri };
|
||||
},
|
||||
},
|
||||
UploadType: { BINARY_CONTENT: 0 },
|
||||
}));
|
||||
|
||||
import {
|
||||
prepareTurnAttachments,
|
||||
releasePendingAttachmentUploads,
|
||||
withUploadedMobileAttachmentReferences,
|
||||
validateDraftFileAttachments,
|
||||
} from "./attachmentUpload";
|
||||
import type { DraftComposerAttachment } from "./composerImages";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const MINTED_ID = "pending-00000000-0000-4000-8000-000000000001-pdf";
|
||||
|
||||
const image = {
|
||||
id: "image-1",
|
||||
type: "image",
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 3,
|
||||
dataUrl: "data:image/png;base64,YWJj",
|
||||
previewUri: "file:///images/screenshot.png",
|
||||
} as const satisfies DraftComposerAttachment;
|
||||
|
||||
const file = {
|
||||
id: "file-1",
|
||||
type: "file",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
fileUri: "file:///documents/report.pdf",
|
||||
} as const satisfies DraftComposerAttachment;
|
||||
|
||||
describe("validateDraftFileAttachments", () => {
|
||||
it("allows legacy image-only sends without server config", () => {
|
||||
expect(validateDraftFileAttachments({ attachments: [image], serverConfig: null })).toBeNull();
|
||||
});
|
||||
|
||||
it("blocks files while config is unknown or file uploads are unsupported", () => {
|
||||
expect(validateDraftFileAttachments({ attachments: [file], serverConfig: null })).toBe(
|
||||
"Server attachment support is still loading.",
|
||||
);
|
||||
expect(
|
||||
validateDraftFileAttachments({
|
||||
attachments: [file],
|
||||
serverConfig: { environment: { capabilities: { attachmentUploads: true } } },
|
||||
}),
|
||||
).toBe("This server does not support file attachments.");
|
||||
});
|
||||
|
||||
it("uses the current clamped limit and allows valid mixed attachments", () => {
|
||||
const lowerLimit = {
|
||||
environment: {
|
||||
capabilities: {
|
||||
attachmentUploads: true,
|
||||
fileAttachments: { maxUploadBytes: 20 },
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(validateDraftFileAttachments({ attachments: [file], serverConfig: lowerLimit })).toBe(
|
||||
"'report.pdf' exceeds the 20 bytes attachment limit.",
|
||||
);
|
||||
const allowed = {
|
||||
environment: {
|
||||
capabilities: {
|
||||
attachmentUploads: true,
|
||||
fileAttachments: { maxUploadBytes: 100 },
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(
|
||||
validateDraftFileAttachments({ attachments: [image, file], serverConfig: allowed }),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
function removeCallsFor(attachmentId: string): number {
|
||||
return mocks.runAtomCommand.mock.calls.filter(
|
||||
([, command, target]) =>
|
||||
command === mocks.removeUpload &&
|
||||
(target as { input: { attachmentId: string } }).input.attachmentId === attachmentId,
|
||||
).length;
|
||||
}
|
||||
|
||||
describe("prepareTurnAttachments", () => {
|
||||
beforeEach(() => {
|
||||
mocks.documentUri = "file:///documents";
|
||||
mocks.createAssetUrl.mockReset();
|
||||
mocks.createAssetUrl.mockImplementation((target: unknown) => target);
|
||||
mocks.executeAtomQuery.mockReset();
|
||||
mocks.executeAtomQuery.mockResolvedValue({ _tag: "Success", value: {} });
|
||||
mocks.runAtomCommand.mockReset();
|
||||
mocks.readAtom.mockReset();
|
||||
mocks.upload.mockReset();
|
||||
mocks.readAtom.mockReturnValue(Option.some({ httpBaseUrl: "https://environment.example/" }));
|
||||
mocks.runAtomCommand.mockImplementation(async (_registry: unknown, command: unknown) =>
|
||||
command === mocks.createUploadUrl
|
||||
? {
|
||||
_tag: "Success",
|
||||
value: {
|
||||
attachmentId: MINTED_ID,
|
||||
relativeUrl: "/api/attachments/upload/signed",
|
||||
expiresAt: 1,
|
||||
},
|
||||
}
|
||||
: { _tag: "Success", value: undefined },
|
||||
);
|
||||
mocks.upload.mockResolvedValue({ status: 204, body: "", headers: {} });
|
||||
});
|
||||
|
||||
it("keeps existing image attachments on the legacy wire path", async () => {
|
||||
const prepared = await prepareTurnAttachments({ environmentId, attachments: [image] });
|
||||
|
||||
expect(prepared.status).toBe("ready");
|
||||
if (prepared.status !== "ready") return;
|
||||
expect(prepared.attachments).toEqual([
|
||||
{
|
||||
type: "image",
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 3,
|
||||
dataUrl: "data:image/png;base64,YWJj",
|
||||
},
|
||||
]);
|
||||
expect(prepared.pendingAttachmentIds).toEqual([]);
|
||||
expect(mocks.upload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uploads generic file bytes directly and keeps mixed attachment order", async () => {
|
||||
const prepared = await prepareTurnAttachments({ environmentId, attachments: [file, image] });
|
||||
|
||||
expect(mocks.upload).toHaveBeenCalledWith(
|
||||
"file:///documents/report.pdf",
|
||||
"https://environment.example/api/attachments/upload/signed",
|
||||
{
|
||||
httpMethod: "POST",
|
||||
uploadType: 0,
|
||||
headers: { "Content-Type": "application/pdf" },
|
||||
},
|
||||
);
|
||||
expect(prepared.status).toBe("ready");
|
||||
if (prepared.status !== "ready") return;
|
||||
expect(prepared.attachments[0]).toEqual({
|
||||
type: "file",
|
||||
id: MINTED_ID,
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
});
|
||||
expect(prepared.attachments[1]?.type).toBe("image");
|
||||
expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
|
||||
expect(prepared.draftAttachments[0]).toEqual({
|
||||
...file,
|
||||
uploadedAttachmentId: MINTED_ID,
|
||||
uploadEnvironmentId: environmentId,
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the current connection when an environment reconnects during URL creation", async () => {
|
||||
mocks.readAtom
|
||||
.mockReturnValueOnce(Option.some({ httpBaseUrl: "https://old-environment.example/" }))
|
||||
.mockReturnValueOnce(Option.some({ httpBaseUrl: "https://new-environment.example/" }));
|
||||
|
||||
await prepareTurnAttachments({ environmentId, attachments: [file] });
|
||||
|
||||
expect(mocks.upload).toHaveBeenCalledWith(
|
||||
file.fileUri,
|
||||
"https://new-environment.example/api/attachments/upload/signed",
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it("uploads a restored draft file from the current iOS document container", async () => {
|
||||
const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf";
|
||||
const restoredFile = {
|
||||
...file,
|
||||
fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,
|
||||
};
|
||||
mocks.documentUri =
|
||||
"file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
|
||||
const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`;
|
||||
mocks.upload.mockImplementation(async (uri: string) => {
|
||||
if (uri !== currentUri) {
|
||||
throw new Error("File does not exist in the previous application container.");
|
||||
}
|
||||
return { status: 204, body: "", headers: {} };
|
||||
});
|
||||
|
||||
const prepared = await prepareTurnAttachments({
|
||||
environmentId,
|
||||
attachments: [restoredFile],
|
||||
});
|
||||
|
||||
expect(prepared.status).toBe("ready");
|
||||
expect(mocks.upload).toHaveBeenCalledWith(
|
||||
currentUri,
|
||||
"https://environment.example/api/attachments/upload/signed",
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it("adds uploaded file references to durable drafts without changing images", () => {
|
||||
expect(
|
||||
withUploadedMobileAttachmentReferences({
|
||||
environmentId,
|
||||
attachments: [file, image],
|
||||
uploadedAttachments: [
|
||||
{
|
||||
type: "file",
|
||||
id: "pending-existing-pdf",
|
||||
name: file.name,
|
||||
mimeType: file.mimeType,
|
||||
sizeBytes: file.sizeBytes,
|
||||
},
|
||||
{
|
||||
type: "image",
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
dataUrl: image.dataUrl,
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
...file,
|
||||
uploadedAttachmentId: "pending-existing-pdf",
|
||||
uploadEnvironmentId: environmentId,
|
||||
},
|
||||
image,
|
||||
]);
|
||||
});
|
||||
|
||||
it("reuses a pending file upload from a previous outbox attempt", async () => {
|
||||
const previouslyUploaded = {
|
||||
...file,
|
||||
uploadedAttachmentId: "pending-existing-pdf",
|
||||
uploadEnvironmentId: environmentId,
|
||||
};
|
||||
|
||||
const prepared = await prepareTurnAttachments({
|
||||
environmentId,
|
||||
attachments: [previouslyUploaded, image],
|
||||
});
|
||||
|
||||
expect(prepared.status).toBe("ready");
|
||||
if (prepared.status !== "ready") return;
|
||||
expect(prepared.attachments).toEqual([
|
||||
{
|
||||
type: "file",
|
||||
id: "pending-existing-pdf",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
},
|
||||
{
|
||||
type: "image",
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 3,
|
||||
dataUrl: "data:image/png;base64,YWJj",
|
||||
},
|
||||
]);
|
||||
expect(prepared.pendingAttachmentIds).toEqual(["pending-existing-pdf"]);
|
||||
expect(mocks.upload).not.toHaveBeenCalled();
|
||||
expect(mocks.runAtomCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uploads a file again when its saved pending upload has expired", async () => {
|
||||
mocks.executeAtomQuery.mockResolvedValueOnce({
|
||||
_tag: "Failure",
|
||||
error: { _tag: "AssetAttachmentNotFoundError" },
|
||||
});
|
||||
const previouslyUploaded = {
|
||||
...file,
|
||||
uploadedAttachmentId: "pending-expired-pdf",
|
||||
uploadEnvironmentId: environmentId,
|
||||
};
|
||||
|
||||
const prepared = await prepareTurnAttachments({
|
||||
environmentId,
|
||||
attachments: [previouslyUploaded],
|
||||
});
|
||||
|
||||
expect(mocks.upload).toHaveBeenCalledOnce();
|
||||
expect(prepared.status).toBe("ready");
|
||||
if (prepared.status !== "ready") return;
|
||||
expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
|
||||
});
|
||||
|
||||
it("removes pending uploads when the native HTTP request fails", async () => {
|
||||
mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
|
||||
|
||||
await expect(prepareTurnAttachments({ environmentId, attachments: [file] })).rejects.toThrow(
|
||||
"Upload failed for 'report.pdf' (500).",
|
||||
);
|
||||
expect(removeCallsFor(MINTED_ID)).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps a previously persisted upload when a later attachment fails", async () => {
|
||||
const previouslyUploaded = {
|
||||
...file,
|
||||
id: "file-existing",
|
||||
uploadedAttachmentId: "pending-existing-pdf",
|
||||
uploadEnvironmentId: environmentId,
|
||||
};
|
||||
mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
|
||||
|
||||
await expect(
|
||||
prepareTurnAttachments({ environmentId, attachments: [previouslyUploaded, file] }),
|
||||
).rejects.toThrow("Upload failed for 'report.pdf' (500).");
|
||||
|
||||
expect(removeCallsFor("pending-existing-pdf")).toBe(0);
|
||||
});
|
||||
|
||||
it("deletes the minted uploads when the owner abandons the send", async () => {
|
||||
const result = await prepareTurnAttachments({
|
||||
environmentId,
|
||||
attachments: [file],
|
||||
persistUploadedReferences: async () => "abandon",
|
||||
});
|
||||
|
||||
expect(result.status).toBe("abandoned");
|
||||
expect(removeCallsFor(MINTED_ID)).toBe(1);
|
||||
});
|
||||
|
||||
it("deletes the minted uploads when persisting the references throws", async () => {
|
||||
await expect(
|
||||
prepareTurnAttachments({
|
||||
environmentId,
|
||||
attachments: [file],
|
||||
persistUploadedReferences: async () => {
|
||||
throw new Error("draft write failed");
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("draft write failed");
|
||||
|
||||
expect(removeCallsFor(MINTED_ID)).toBe(1);
|
||||
});
|
||||
|
||||
it("skips persisting when every reference is already stored", async () => {
|
||||
const previouslyUploaded = {
|
||||
...file,
|
||||
uploadedAttachmentId: "pending-existing-pdf",
|
||||
uploadEnvironmentId: environmentId,
|
||||
};
|
||||
const persist = vi.fn(async () => "persisted" as const);
|
||||
|
||||
const prepared = await prepareTurnAttachments({
|
||||
environmentId,
|
||||
attachments: [previouslyUploaded],
|
||||
persistUploadedReferences: persist,
|
||||
});
|
||||
|
||||
expect(prepared.status).toBe("ready");
|
||||
expect(persist).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("releasePendingAttachmentUploads", () => {
|
||||
beforeEach(() => {
|
||||
mocks.runAtomCommand.mockReset();
|
||||
});
|
||||
|
||||
it("retries a failed delete once before reporting it", async () => {
|
||||
mocks.runAtomCommand
|
||||
.mockResolvedValueOnce({ _tag: "Failure", error: new Error("offline") })
|
||||
.mockResolvedValue({ _tag: "Success", value: undefined });
|
||||
|
||||
await expect(
|
||||
releasePendingAttachmentUploads(environmentId, ["pending-a"]),
|
||||
).resolves.toBeUndefined();
|
||||
expect(mocks.runAtomCommand).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("throws when a delete keeps failing so the caller sees the leak", async () => {
|
||||
mocks.runAtomCommand.mockResolvedValue({ _tag: "Failure", error: new Error("offline") });
|
||||
|
||||
await expect(releasePendingAttachmentUploads(environmentId, ["pending-a"])).rejects.toThrow(
|
||||
"pending-a",
|
||||
);
|
||||
});
|
||||
|
||||
it("treats an already-deleted pending upload as released", async () => {
|
||||
mocks.runAtomCommand.mockResolvedValue({
|
||||
_tag: "Failure",
|
||||
error: { _tag: "AssetAttachmentNotFoundError" },
|
||||
});
|
||||
|
||||
await expect(
|
||||
releasePendingAttachmentUploads(environmentId, ["pending-a"]),
|
||||
).resolves.toBeUndefined();
|
||||
expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,318 @@
|
||||
import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
|
||||
import {
|
||||
clampFileAttachmentUploadBytes,
|
||||
fileAttachmentTooLargeMessage,
|
||||
isAssetAttachmentNotFoundFailure,
|
||||
runAttachmentUploadCycle,
|
||||
verifyPersistedAttachmentUpload,
|
||||
} from "@t3tools/client-runtime/state/attachments";
|
||||
import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import type {
|
||||
ChatFileAttachment,
|
||||
EnvironmentId,
|
||||
UploadChatImageAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import { appAtomRegistry } from "../state/atom-registry";
|
||||
import { assetEnvironment } from "../state/assets";
|
||||
import { attachmentEnvironment } from "../state/attachments";
|
||||
import { environmentSession } from "../state/session";
|
||||
import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";
|
||||
import { toUploadChatImageAttachments, type DraftComposerAttachment } from "./composerImages";
|
||||
|
||||
/**
|
||||
* This module owns the server side of a composer attachment's lifecycle.
|
||||
* `prepareTurnAttachments` acquires pending uploads (verifying and reusing
|
||||
* persisted ones), hands the uploaded ids back to the attachment's durable
|
||||
* owner (queued outbox message or composer draft), and returns a release
|
||||
* handle for after the turn consumed the bytes. Nothing outside this module
|
||||
* mints or deletes pending uploads. The local-file side of the lifecycle is
|
||||
* owned by `removeThreadOutboxMessage` / the composer draft mutators, which
|
||||
* release files through `releaseUnusedComposerAttachmentFiles`.
|
||||
*/
|
||||
export type UploadedMobileAttachment = UploadChatImageAttachment | ChatFileAttachment;
|
||||
|
||||
export function validateDraftFileAttachments(input: {
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly serverConfig: {
|
||||
readonly environment: {
|
||||
readonly capabilities: {
|
||||
readonly attachmentUploads?: boolean;
|
||||
readonly fileAttachments?: { readonly maxUploadBytes: number };
|
||||
};
|
||||
};
|
||||
} | null;
|
||||
}): string | null {
|
||||
const files = input.attachments.filter((attachment) => attachment.type === "file");
|
||||
if (files.length === 0) return null;
|
||||
if (input.serverConfig === null) return "Server attachment support is still loading.";
|
||||
const capabilities = input.serverConfig.environment.capabilities;
|
||||
if (capabilities.attachmentUploads !== true || capabilities.fileAttachments === undefined) {
|
||||
return "This server does not support file attachments.";
|
||||
}
|
||||
const maxBytes = clampFileAttachmentUploadBytes(capabilities.fileAttachments.maxUploadBytes);
|
||||
const oversized = files.find((attachment) => attachment.sizeBytes > maxBytes);
|
||||
return oversized ? fileAttachmentTooLargeMessage(oversized.name, maxBytes) : null;
|
||||
}
|
||||
|
||||
/** Keep uploaded file ids on durable drafts so a later send can reuse their bytes. */
|
||||
export function withUploadedMobileAttachmentReferences(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly uploadedAttachments: ReadonlyArray<UploadedMobileAttachment>;
|
||||
}): ReadonlyArray<DraftComposerAttachment> {
|
||||
return input.attachments.map((attachment, index) => {
|
||||
const uploaded = input.uploadedAttachments[index];
|
||||
if (
|
||||
attachment.type !== "file" ||
|
||||
uploaded?.type !== "file" ||
|
||||
(attachment.uploadedAttachmentId === uploaded.id &&
|
||||
attachment.uploadEnvironmentId === input.environmentId)
|
||||
) {
|
||||
return attachment;
|
||||
}
|
||||
return {
|
||||
...attachment,
|
||||
uploadedAttachmentId: uploaded.id,
|
||||
uploadEnvironmentId: input.environmentId,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes pending uploads the client no longer references. Every delete result
|
||||
* is inspected; failed deletes are retried once and a persistent failure
|
||||
* throws, so a caller can never silently leak the outcome. (The server also
|
||||
* expires pending uploads, so a leaked id self-heals eventually.)
|
||||
*/
|
||||
export async function releasePendingAttachmentUploads(
|
||||
environmentId: EnvironmentId,
|
||||
attachmentIds: ReadonlyArray<string>,
|
||||
): Promise<void> {
|
||||
const deleteOnce = async (attachmentId: string): Promise<boolean> => {
|
||||
const result = await runAtomCommand(
|
||||
appAtomRegistry,
|
||||
attachmentEnvironment.remove,
|
||||
{ environmentId, input: { attachmentId } },
|
||||
{ reportFailure: false, reportDefect: false },
|
||||
);
|
||||
return (
|
||||
result._tag === "Success" ||
|
||||
isAssetAttachmentNotFoundFailure(squashAtomCommandFailure(result))
|
||||
);
|
||||
};
|
||||
|
||||
const failedAttachmentIds: string[] = [];
|
||||
for (const attachmentId of attachmentIds) {
|
||||
if (!(await deleteOnce(attachmentId)) && !(await deleteOnce(attachmentId))) {
|
||||
failedAttachmentIds.push(attachmentId);
|
||||
}
|
||||
}
|
||||
if (failedAttachmentIds.length > 0) {
|
||||
throw new Error(
|
||||
`Could not delete ${failedAttachmentIds.length} pending attachment upload(s): ${failedAttachmentIds.join(", ")}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function releaseCreatedUploadsQuietly(
|
||||
environmentId: EnvironmentId,
|
||||
attachmentIds: ReadonlyArray<string>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await releasePendingAttachmentUploads(environmentId, attachmentIds);
|
||||
} catch (error) {
|
||||
// The original failure must propagate; the leaked pending uploads expire
|
||||
// on the server.
|
||||
console.warn("[attachments] could not delete abandoned pending uploads", error);
|
||||
}
|
||||
}
|
||||
|
||||
export interface PreparedTurnAttachments {
|
||||
readonly status: "ready";
|
||||
/** Wire attachments for `startTurn`, in the original composer order. */
|
||||
readonly attachments: ReadonlyArray<UploadedMobileAttachment>;
|
||||
/** Composer attachments annotated with the uploaded pending ids. */
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
/** Every pending upload backing this turn (reused and newly minted). */
|
||||
readonly pendingAttachmentIds: ReadonlyArray<string>;
|
||||
/** Deletes all pending uploads once the delivered turn holds the bytes. */
|
||||
readonly releaseUploads: () => Promise<void>;
|
||||
}
|
||||
|
||||
export type PrepareTurnAttachmentsResult =
|
||||
| PreparedTurnAttachments
|
||||
| { readonly status: "abandoned" };
|
||||
|
||||
async function uploadFileBytes(
|
||||
attachment: Extract<DraftComposerAttachment, { readonly type: "file" }>,
|
||||
url: string,
|
||||
): Promise<void> {
|
||||
const { File, Paths, UploadType } = await import("expo-file-system");
|
||||
const fileUri =
|
||||
resolveOwnedComposerAttachmentFileUri(attachment.fileUri, Paths.document.uri) ??
|
||||
attachment.fileUri;
|
||||
const result = await new File(fileUri).upload(url, {
|
||||
httpMethod: "POST",
|
||||
uploadType: UploadType.BINARY_CONTENT,
|
||||
headers: { "Content-Type": attachment.mimeType },
|
||||
});
|
||||
if (result.status < 200 || result.status >= 300) {
|
||||
throw new Error(`Upload failed for '${attachment.name}' (${result.status}).`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Acquires server-side uploads for one turn's attachments and persists the
|
||||
* uploaded ids into the attachments' durable owner.
|
||||
*
|
||||
* `persistUploadedReferences` runs once the bytes are on the server and only
|
||||
* when new ids appeared. It must write the annotated attachments into the
|
||||
* owner (queued message or draft) so a retry after a crash reuses the bytes.
|
||||
* Returning `"abandon"` (owner no longer wants the send) or throwing deletes
|
||||
* the pending uploads this call minted, so the owner cannot leak them.
|
||||
*/
|
||||
export async function prepareTurnAttachments(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly persistUploadedReferences?: (
|
||||
draftAttachments: ReadonlyArray<DraftComposerAttachment>,
|
||||
) => Promise<"persisted" | "abandon">;
|
||||
}): Promise<PrepareTurnAttachmentsResult> {
|
||||
const { environmentId } = input;
|
||||
const files = input.attachments.filter((attachment) => attachment.type === "file");
|
||||
const ready = (
|
||||
attachments: ReadonlyArray<UploadedMobileAttachment>,
|
||||
pendingAttachmentIds: ReadonlyArray<string>,
|
||||
draftAttachments: ReadonlyArray<DraftComposerAttachment>,
|
||||
): PreparedTurnAttachments => ({
|
||||
status: "ready",
|
||||
attachments,
|
||||
draftAttachments,
|
||||
pendingAttachmentIds,
|
||||
releaseUploads: () => releasePendingAttachmentUploads(environmentId, pendingAttachmentIds),
|
||||
});
|
||||
|
||||
if (files.length === 0) {
|
||||
return ready(
|
||||
toUploadChatImageAttachments(
|
||||
input.attachments.filter((attachment) => attachment.type === "image"),
|
||||
),
|
||||
[],
|
||||
input.attachments,
|
||||
);
|
||||
}
|
||||
|
||||
const connection = appAtomRegistry.get(
|
||||
environmentSession.preparedConnectionValueAtom(environmentId),
|
||||
);
|
||||
if (Option.isNone(connection)) {
|
||||
throw new Error("The environment is not connected.");
|
||||
}
|
||||
|
||||
const uploadedAttachments: UploadedMobileAttachment[] = [];
|
||||
const pendingAttachmentIds: string[] = [];
|
||||
const createdAttachmentIds: string[] = [];
|
||||
try {
|
||||
for (const attachment of input.attachments) {
|
||||
if (attachment.type === "image") {
|
||||
uploadedAttachments.push(...toUploadChatImageAttachments([attachment]));
|
||||
continue;
|
||||
}
|
||||
|
||||
// Reuse the bytes from a previous attempt when their pending upload is
|
||||
// still alive on this environment.
|
||||
if (
|
||||
attachment.uploadEnvironmentId === environmentId &&
|
||||
attachment.uploadedAttachmentId !== undefined
|
||||
) {
|
||||
const verification = await verifyPersistedAttachmentUpload({
|
||||
registry: appAtomRegistry,
|
||||
createAssetUrl: assetEnvironment.createUrl,
|
||||
environmentId,
|
||||
attachmentId: attachment.uploadedAttachmentId,
|
||||
});
|
||||
if (verification.status === "failed") {
|
||||
throw verification.error;
|
||||
}
|
||||
if (verification.status === "verified") {
|
||||
pendingAttachmentIds.push(attachment.uploadedAttachmentId);
|
||||
uploadedAttachments.push({
|
||||
type: "file",
|
||||
id: attachment.uploadedAttachmentId,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
// "missing": the pending upload expired, upload the bytes again.
|
||||
}
|
||||
|
||||
const result = await runAttachmentUploadCycle({
|
||||
registry: appAtomRegistry,
|
||||
createUploadUrl: attachmentEnvironment.createUploadUrl,
|
||||
remove: attachmentEnvironment.remove,
|
||||
environmentId,
|
||||
upload: {
|
||||
type: "file",
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
},
|
||||
// Read the connection at transfer time: the environment may have
|
||||
// reconnected on a new base URL since this cycle started.
|
||||
resolveUploadUrl: (relativeUrl) => {
|
||||
const currentConnection = appAtomRegistry.get(
|
||||
environmentSession.preparedConnectionValueAtom(environmentId),
|
||||
);
|
||||
return Option.isNone(currentConnection)
|
||||
? null
|
||||
: resolveAssetUrl(currentConnection.value.httpBaseUrl, relativeUrl);
|
||||
},
|
||||
transport: (url) => ({
|
||||
done: uploadFileBytes(attachment, url),
|
||||
// expo-file-system uploads cannot abort mid-flight.
|
||||
abort: () => {},
|
||||
}),
|
||||
onMinted: (attachmentId) => {
|
||||
pendingAttachmentIds.push(attachmentId);
|
||||
createdAttachmentIds.push(attachmentId);
|
||||
return "continue";
|
||||
},
|
||||
});
|
||||
if (result.status !== "uploaded") {
|
||||
throw result.status === "failed" && result.error !== undefined
|
||||
? result.error
|
||||
: new Error(`Upload failed for '${attachment.name}'.`);
|
||||
}
|
||||
uploadedAttachments.push({
|
||||
type: "file",
|
||||
id: result.attachmentId,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
});
|
||||
}
|
||||
|
||||
const draftAttachments = withUploadedMobileAttachmentReferences({
|
||||
environmentId,
|
||||
attachments: input.attachments,
|
||||
uploadedAttachments,
|
||||
});
|
||||
const referencesChanged = draftAttachments.some(
|
||||
(attachment, index) => attachment !== input.attachments[index],
|
||||
);
|
||||
if (referencesChanged && input.persistUploadedReferences) {
|
||||
if ((await input.persistUploadedReferences(draftAttachments)) === "abandon") {
|
||||
await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
|
||||
return { status: "abandoned" };
|
||||
}
|
||||
}
|
||||
return ready(uploadedAttachments, pendingAttachmentIds, draftAttachments);
|
||||
} catch (error) {
|
||||
await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
export const DraftComposerImageAttachmentSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
@@ -9,3 +10,19 @@ export const DraftComposerImageAttachmentSchema = Schema.Struct({
|
||||
sizeBytes: Schema.Number,
|
||||
dataUrl: Schema.String,
|
||||
});
|
||||
|
||||
export const DraftComposerFileAttachmentSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
type: Schema.Literal("file"),
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
fileUri: Schema.String,
|
||||
uploadedAttachmentId: Schema.optional(Schema.String),
|
||||
uploadEnvironmentId: Schema.optional(EnvironmentId),
|
||||
});
|
||||
|
||||
export const DraftComposerAttachmentSchema = Schema.Union([
|
||||
DraftComposerImageAttachmentSchema,
|
||||
DraftComposerFileAttachmentSchema,
|
||||
]);
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
composerAttachmentFileReferenceKey,
|
||||
resolveOwnedComposerAttachmentFileUri,
|
||||
} from "./composerAttachmentFiles";
|
||||
|
||||
const OLD_CONTAINER = "11111111-1111-4111-8111-111111111111";
|
||||
const CURRENT_CONTAINER = "22222222-2222-4222-8222-222222222222";
|
||||
const FILE_NAME = "33333333-3333-4333-8333-333333333333-report%20%252F%20%23.pdf";
|
||||
|
||||
describe("owned attachment paths", () => {
|
||||
it.each([
|
||||
"file:///var/mobile/Containers/Data/Application/",
|
||||
"file:///Users/dev/Library/Developer/CoreSimulator/Devices/device/data/Containers/Data/Application/",
|
||||
])("resolves saved files after an iOS container move under %s", (prefix) => {
|
||||
const oldUri = `${prefix}${OLD_CONTAINER}/Documents/t3-composer-attachments/${FILE_NAME}`;
|
||||
const documentUri = `${prefix}${CURRENT_CONTAINER}/Documents/`;
|
||||
const currentUri = `${documentUri}t3-composer-attachments/${FILE_NAME}`;
|
||||
|
||||
expect(resolveOwnedComposerAttachmentFileUri(oldUri, documentUri)).toBe(currentUri);
|
||||
expect(composerAttachmentFileReferenceKey(oldUri)).toBe(
|
||||
composerAttachmentFileReferenceKey(currentUri),
|
||||
);
|
||||
});
|
||||
|
||||
it("recognizes the private/var alias without changing the stored filename", () => {
|
||||
const oldUri = `file:///private/var/mobile/Containers/Data/Application/${OLD_CONTAINER}/Documents/t3-composer-attachments/${FILE_NAME}`;
|
||||
const documentUri = `file:///var/mobile/Containers/Data/Application/${CURRENT_CONTAINER}/Documents/`;
|
||||
const currentUri = `${documentUri}t3-composer-attachments/${FILE_NAME}`;
|
||||
|
||||
expect(resolveOwnedComposerAttachmentFileUri(oldUri, documentUri)).toBe(currentUri);
|
||||
expect(composerAttachmentFileReferenceKey(oldUri)).toBe(
|
||||
composerAttachmentFileReferenceKey(currentUri),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
`file:///private/var/mobile/Containers/Shared/FileProvider/other/Documents/t3-composer-attachments/${FILE_NAME}`,
|
||||
`file:///var/mobile/Containers/Shared/AppGroup/other/t3-composer-attachments/${FILE_NAME}`,
|
||||
`file:///var/mobile/Containers/Data/Application/${OLD_CONTAINER}/Documents/report.pdf`,
|
||||
`file:///var/mobile/Containers/Data/Application/${OLD_CONTAINER}/Documents/t3-composer-attachments/report.pdf`,
|
||||
`file:///downloads/t3-composer-attachments/${FILE_NAME}`,
|
||||
`content://shared/t3-composer-attachments/${FILE_NAME}`,
|
||||
`https://example.com/t3-composer-attachments/${FILE_NAME}`,
|
||||
`file:///var/mobile/Containers/Data/Application/${OLD_CONTAINER}/Documents/t3-composer-attachments/..%2F..%2Fsender.pdf`,
|
||||
`file:///var/mobile/Containers/Data/Application/${OLD_CONTAINER}/Documents/t3-composer-attachments/${FILE_NAME}%2Fnested.pdf`,
|
||||
])("does not rebase an external or escaped path: %s", (uri) => {
|
||||
expect(
|
||||
resolveOwnedComposerAttachmentFileUri(
|
||||
uri,
|
||||
`file:///var/mobile/Containers/Data/Application/${CURRENT_CONTAINER}/Documents/`,
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
export const COMPOSER_ATTACHMENT_DIRECTORY = "t3-composer-attachments";
|
||||
|
||||
const UUID_PATTERN = "[a-f\\d]{8}-[a-f\\d]{4}-[a-f\\d]{4}-[a-f\\d]{4}-[a-f\\d]{12}";
|
||||
const GENERATED_FILE_NAME = new RegExp(`^${UUID_PATTERN}-`, "i");
|
||||
const IOS_DOCUMENTS_PATH = new RegExp(
|
||||
`^(.*/Containers/Data/Application/)${UUID_PATTERN}/Documents$`,
|
||||
"i",
|
||||
);
|
||||
|
||||
function fileUriPath(uri: string): string | null {
|
||||
try {
|
||||
const url = new URL(uri);
|
||||
if (url.protocol !== "file:" || url.hostname || url.search || url.hash) {
|
||||
return null;
|
||||
}
|
||||
const path = decodeURIComponent(url.pathname);
|
||||
if (path.includes("\\") || path.includes("\0") || path.split("/").includes("..")) {
|
||||
return null;
|
||||
}
|
||||
return path.startsWith("/private/var/") ? path.slice("/private".length) : path;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function ownedFileLocation(uri: string) {
|
||||
const path = fileUriPath(uri);
|
||||
if (path === null) {
|
||||
return null;
|
||||
}
|
||||
const separator = `/${COMPOSER_ATTACHMENT_DIRECTORY}/`;
|
||||
const index = path.lastIndexOf(separator);
|
||||
const name = index < 0 ? "" : path.slice(index + separator.length);
|
||||
if (!name || name === "." || name.includes("/")) {
|
||||
return null;
|
||||
}
|
||||
return { documentPath: path.slice(0, index), name };
|
||||
}
|
||||
|
||||
/** Compares references across iOS data-container moves without rewriting saved drafts. */
|
||||
export function composerAttachmentFileReferenceKey(uri: string): string {
|
||||
const location = ownedFileLocation(uri);
|
||||
if (!location) {
|
||||
return uri;
|
||||
}
|
||||
const containerPrefix = GENERATED_FILE_NAME.test(location.name)
|
||||
? IOS_DOCUMENTS_PATH.exec(location.documentPath)?.[1]
|
||||
: undefined;
|
||||
const documentPath = containerPrefix
|
||||
? `${containerPrefix}<app>/Documents`
|
||||
: location.documentPath;
|
||||
return `file://${documentPath}/${COMPOSER_ATTACHMENT_DIRECTORY}/${encodeURIComponent(location.name)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves only our saved attachment copies. iOS preserves Documents on updates
|
||||
* but can change its container UUID. Picker and open-in-place source URIs must
|
||||
* bypass this resolver so another app's document keeps its original location.
|
||||
*/
|
||||
export function resolveOwnedComposerAttachmentFileUri(
|
||||
uri: string,
|
||||
documentDirectoryUri: string,
|
||||
): string | null {
|
||||
const location = ownedFileLocation(uri);
|
||||
const documentPath = fileUriPath(documentDirectoryUri)?.replace(/\/+$/, "");
|
||||
if (!location || !documentPath) {
|
||||
return null;
|
||||
}
|
||||
if (location.documentPath !== documentPath) {
|
||||
const currentContainerPrefix = IOS_DOCUMENTS_PATH.exec(documentPath)?.[1];
|
||||
if (
|
||||
!currentContainerPrefix ||
|
||||
currentContainerPrefix !== IOS_DOCUMENTS_PATH.exec(location.documentPath)?.[1] ||
|
||||
!GENERATED_FILE_NAME.test(location.name)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const resolved = new URL(documentDirectoryUri);
|
||||
resolved.pathname = `${resolved.pathname.replace(/\/+$/, "")}/${COMPOSER_ATTACHMENT_DIRECTORY}/${encodeURIComponent(location.name)}`;
|
||||
return resolved.href;
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
documentUri: "file:///documents",
|
||||
pickFile: vi.fn(),
|
||||
copy: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
open: vi.fn(),
|
||||
size: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("expo-file-system", () => {
|
||||
class Directory {
|
||||
readonly uri: string;
|
||||
|
||||
constructor(root: string | { readonly uri: string }, name: string) {
|
||||
this.uri = `${typeof root === "string" ? root : root.uri}/${name}`;
|
||||
}
|
||||
|
||||
create(): void {}
|
||||
}
|
||||
|
||||
class File {
|
||||
static pickFileAsync = mocks.pickFile;
|
||||
|
||||
readonly uri: string;
|
||||
|
||||
constructor(source: string | Directory, name?: string) {
|
||||
this.uri = source instanceof Directory ? `${source.uri}/${name}` : source;
|
||||
}
|
||||
|
||||
get exists(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
get size(): number | null {
|
||||
return mocks.size(this.uri) ?? null;
|
||||
}
|
||||
|
||||
create(): void {}
|
||||
|
||||
open(mode: string) {
|
||||
return mocks.open(this.uri, mode);
|
||||
}
|
||||
|
||||
async copy(destination: File): Promise<void> {
|
||||
mocks.copy(this.uri, destination.uri);
|
||||
}
|
||||
|
||||
delete(): void {
|
||||
mocks.delete(this.uri);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
Directory,
|
||||
File,
|
||||
FileMode: { ReadOnly: "r", WriteOnly: "w" },
|
||||
Paths: {
|
||||
get document() {
|
||||
return { uri: mocks.documentUri };
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("./uuid", () => ({ uuidv4: () => "attachment-id" }));
|
||||
|
||||
import {
|
||||
persistComposerAttachmentFile,
|
||||
pickComposerFiles,
|
||||
removePersistedComposerAttachmentFile,
|
||||
} from "./composerImages";
|
||||
|
||||
describe("pickComposerFiles", () => {
|
||||
beforeEach(() => {
|
||||
mocks.documentUri = "file:///documents";
|
||||
mocks.pickFile.mockReset();
|
||||
mocks.copy.mockReset();
|
||||
mocks.delete.mockReset();
|
||||
mocks.open.mockReset();
|
||||
mocks.size.mockReset();
|
||||
mocks.size.mockImplementation((uri: string) => (uri.startsWith("content:") ? null : 42));
|
||||
});
|
||||
|
||||
it("copies picked files into app-owned storage without loading their contents", async () => {
|
||||
mocks.pickFile.mockResolvedValue({
|
||||
canceled: false,
|
||||
result: [
|
||||
{
|
||||
uri: "file:///downloads/report.pdf",
|
||||
name: "report.pdf",
|
||||
type: "application/pdf",
|
||||
size: 42,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({
|
||||
files: [
|
||||
{
|
||||
id: "attachment-id",
|
||||
type: "file",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
fileUri: "file:///documents/t3-composer-attachments/attachment-id-report.pdf",
|
||||
},
|
||||
],
|
||||
error: null,
|
||||
});
|
||||
expect(mocks.copy).toHaveBeenCalledWith(
|
||||
"file:///downloads/report.pdf",
|
||||
"file:///documents/t3-composer-attachments/attachment-id-report.pdf",
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to a usable name when the picker reports a blank one", async () => {
|
||||
mocks.pickFile.mockResolvedValue({
|
||||
canceled: false,
|
||||
result: [
|
||||
{
|
||||
uri: "file:///downloads/unnamed",
|
||||
name: " ",
|
||||
type: "application/pdf",
|
||||
size: 42,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await pickComposerFiles({ existingCount: 0 });
|
||||
expect(result.error).toBeNull();
|
||||
expect(result.files).toHaveLength(1);
|
||||
expect(result.files[0]?.name).toBe("file");
|
||||
});
|
||||
|
||||
it("rejects files that exceed the environment's advertised upload limit", async () => {
|
||||
mocks.pickFile.mockResolvedValue({
|
||||
canceled: false,
|
||||
result: [
|
||||
{
|
||||
uri: "file:///downloads/archive.zip",
|
||||
name: "archive.zip",
|
||||
type: "application/zip",
|
||||
size: 2 * 1024 * 1024,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await expect(pickComposerFiles({ existingCount: 0, maxBytes: 1024 * 1024 })).resolves.toEqual({
|
||||
files: [],
|
||||
error: "'archive.zip' exceeds the 1 MB attachment limit.",
|
||||
});
|
||||
expect(mocks.copy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("never accepts files above the 50 MB contract limit", async () => {
|
||||
mocks.pickFile.mockResolvedValue({
|
||||
canceled: false,
|
||||
result: [
|
||||
{
|
||||
uri: "file:///downloads/archive.zip",
|
||||
name: "archive.zip",
|
||||
type: "application/zip",
|
||||
size: 51 * 1024 * 1024,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await expect(
|
||||
pickComposerFiles({ existingCount: 0, maxBytes: 80 * 1024 * 1024 }),
|
||||
).resolves.toEqual({
|
||||
files: [],
|
||||
error: "'archive.zip' exceeds the 50 MB attachment limit.",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a file that grew after the picker reported its size", async () => {
|
||||
mocks.pickFile.mockResolvedValue({
|
||||
canceled: false,
|
||||
result: [
|
||||
{
|
||||
uri: "file:///downloads/archive.zip",
|
||||
name: "archive.zip",
|
||||
type: "application/zip",
|
||||
size: 42,
|
||||
},
|
||||
],
|
||||
});
|
||||
mocks.size.mockReturnValue(2 * 1024 * 1024);
|
||||
|
||||
await expect(pickComposerFiles({ existingCount: 0, maxBytes: 1024 * 1024 })).resolves.toEqual({
|
||||
files: [],
|
||||
error: "'archive.zip' exceeds the 1 MB attachment limit.",
|
||||
});
|
||||
expect(mocks.copy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stops copying an unknown-size content URI when it exceeds the attachment limit", async () => {
|
||||
const maxBytes = 1024 * 1024;
|
||||
let remainingBytes = maxBytes + 1;
|
||||
const source = {
|
||||
readBytes: vi.fn((length: number) => {
|
||||
const size = Math.min(length, remainingBytes);
|
||||
remainingBytes -= size;
|
||||
return new Uint8Array(size);
|
||||
}),
|
||||
close: vi.fn(),
|
||||
};
|
||||
const destination = { writeBytes: vi.fn(), close: vi.fn() };
|
||||
mocks.open.mockImplementation((uri: string) =>
|
||||
uri.startsWith("content:") ? source : destination,
|
||||
);
|
||||
|
||||
await expect(
|
||||
persistComposerAttachmentFile("content://shared/large", "large.bin", maxBytes),
|
||||
).rejects.toThrow("'large.bin' exceeds the 1 MB attachment limit.");
|
||||
|
||||
expect(source.close).toHaveBeenCalledOnce();
|
||||
expect(destination.close).toHaveBeenCalledOnce();
|
||||
expect(mocks.delete).toHaveBeenCalledWith(
|
||||
"file:///documents/t3-composer-attachments/attachment-id-large.bin",
|
||||
);
|
||||
expect(mocks.copy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a copy that delivered more bytes than the source reported", async () => {
|
||||
const maxBytes = 1024 * 1024;
|
||||
// An Android content: stream can report a small size and still deliver
|
||||
// more bytes; the persisted copy is what must satisfy the limit.
|
||||
mocks.size.mockImplementation((uri: string) =>
|
||||
uri.startsWith("content:") ? 42 : 2 * 1024 * 1024,
|
||||
);
|
||||
|
||||
await expect(
|
||||
persistComposerAttachmentFile("content://shared/liar", "liar.bin", maxBytes),
|
||||
).rejects.toThrow("'liar.bin' exceeds the 1 MB attachment limit.");
|
||||
|
||||
expect(mocks.copy).toHaveBeenCalledOnce();
|
||||
expect(mocks.delete).toHaveBeenCalledWith(
|
||||
"file:///documents/t3-composer-attachments/attachment-id-liar.bin",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports an empty file without calling it oversized", async () => {
|
||||
mocks.size.mockReturnValue(0);
|
||||
mocks.pickFile.mockResolvedValue({
|
||||
canceled: false,
|
||||
result: [
|
||||
{
|
||||
uri: "file:///downloads/empty.txt",
|
||||
name: "empty.txt",
|
||||
type: "text/plain",
|
||||
size: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({
|
||||
files: [],
|
||||
error: "'empty.txt' is empty or could not be read.",
|
||||
});
|
||||
});
|
||||
|
||||
it("copies an Android SAF file when the picker reports an unknown zero size", async () => {
|
||||
const reader = {
|
||||
readBytes: vi
|
||||
.fn()
|
||||
.mockReturnValueOnce(new Uint8Array(42))
|
||||
.mockReturnValueOnce(new Uint8Array()),
|
||||
close: vi.fn(),
|
||||
};
|
||||
const writer = { writeBytes: vi.fn(), close: vi.fn() };
|
||||
mocks.size.mockImplementation((uri: string) => (uri.startsWith("content:") ? 0 : 42));
|
||||
mocks.open.mockImplementation((uri: string) => (uri.startsWith("content:") ? reader : writer));
|
||||
mocks.pickFile.mockResolvedValue({
|
||||
canceled: false,
|
||||
result: [
|
||||
{
|
||||
uri: "content://shared/report",
|
||||
name: "report.pdf",
|
||||
type: "application/pdf",
|
||||
size: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({
|
||||
files: [
|
||||
{
|
||||
id: "attachment-id",
|
||||
type: "file",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
fileUri: "file:///documents/t3-composer-attachments/attachment-id-report.pdf",
|
||||
},
|
||||
],
|
||||
error: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the remaining slot for the first valid file after an oversized selection", async () => {
|
||||
mocks.pickFile.mockResolvedValue({
|
||||
canceled: false,
|
||||
result: [
|
||||
{
|
||||
uri: "file:///downloads/huge.zip",
|
||||
name: "huge.zip",
|
||||
type: "application/zip",
|
||||
size: 2 * 1024 * 1024,
|
||||
},
|
||||
{
|
||||
uri: "file:///downloads/report.pdf",
|
||||
name: "report.pdf",
|
||||
type: "application/pdf",
|
||||
size: 42,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await pickComposerFiles({ existingCount: 7, maxBytes: 1024 * 1024 });
|
||||
|
||||
expect(result.files.map((file) => file.name)).toEqual(["report.pdf"]);
|
||||
});
|
||||
|
||||
it("removes the partial destination file when a copy fails midway", async () => {
|
||||
mocks.copy.mockImplementation(() => {
|
||||
throw new Error("disk full");
|
||||
});
|
||||
|
||||
await expect(
|
||||
persistComposerAttachmentFile("file:///downloads/report.pdf", "report.pdf"),
|
||||
).rejects.toThrow("disk full");
|
||||
|
||||
expect(mocks.delete).toHaveBeenCalledWith(
|
||||
"file:///documents/t3-composer-attachments/attachment-id-report.pdf",
|
||||
);
|
||||
});
|
||||
|
||||
it("deletes app-owned attachments without touching user-owned files", async () => {
|
||||
await removePersistedComposerAttachmentFile(
|
||||
"file:///documents/t3-composer-attachments/report.pdf",
|
||||
);
|
||||
await removePersistedComposerAttachmentFile("file:///downloads/report.pdf");
|
||||
|
||||
expect(mocks.delete).toHaveBeenCalledOnce();
|
||||
expect(mocks.delete).toHaveBeenCalledWith(
|
||||
"file:///documents/t3-composer-attachments/report.pdf",
|
||||
);
|
||||
});
|
||||
|
||||
it("removes a restored attachment from the current iOS document container", async () => {
|
||||
const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf";
|
||||
const oldUri = `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`;
|
||||
mocks.documentUri =
|
||||
"file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
|
||||
|
||||
await removePersistedComposerAttachmentFile(oldUri);
|
||||
await removePersistedComposerAttachmentFile(
|
||||
`file:///var/mobile/Containers/Shared/FileProvider/other/Documents/t3-composer-attachments/${fileName}`,
|
||||
);
|
||||
await removePersistedComposerAttachmentFile(
|
||||
`${mocks.documentUri}/t3-composer-attachments/..%2F..%2Fsender.pdf`,
|
||||
);
|
||||
|
||||
expect(mocks.delete.mock.calls).toEqual([
|
||||
[`${mocks.documentUri}/t3-composer-attachments/${fileName}`],
|
||||
]);
|
||||
});
|
||||
|
||||
it("copies an open-in-place source from its actual container without rebasing it", async () => {
|
||||
const sourceUri =
|
||||
"file:///var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/33333333-3333-4333-8333-333333333333-report.pdf";
|
||||
mocks.documentUri =
|
||||
"file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
|
||||
|
||||
await persistComposerAttachmentFile(sourceUri, "report.pdf");
|
||||
|
||||
expect(mocks.copy).toHaveBeenCalledWith(
|
||||
sourceUri,
|
||||
`${mocks.documentUri}/t3-composer-attachments/attachment-id-report.pdf`,
|
||||
);
|
||||
expect(mocks.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,21 @@
|
||||
import {
|
||||
clampFileAttachmentUploadBytes,
|
||||
fileAttachmentTooLargeMessage,
|
||||
} from "@t3tools/client-runtime/state/attachments";
|
||||
import {
|
||||
isProviderSendTurnSupportedImageMimeType,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type EnvironmentId,
|
||||
type UploadChatImageAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
import type { PickMultipleFilesResult } from "expo-file-system";
|
||||
import { estimateBase64ByteSize } from "./base64";
|
||||
import {
|
||||
COMPOSER_ATTACHMENT_DIRECTORY,
|
||||
resolveOwnedComposerAttachmentFileUri,
|
||||
} from "./composerAttachmentFiles";
|
||||
import { beginForegroundHandoff } from "./foreground-handoff";
|
||||
import { uuidv4 } from "./uuid";
|
||||
|
||||
@@ -13,6 +24,19 @@ export interface DraftComposerImageAttachment extends UploadChatImageAttachment
|
||||
readonly previewUri: string;
|
||||
}
|
||||
|
||||
export interface DraftComposerFileAttachment {
|
||||
readonly id: string;
|
||||
readonly type: "file";
|
||||
readonly name: string;
|
||||
readonly mimeType: string;
|
||||
readonly sizeBytes: number;
|
||||
readonly fileUri: string;
|
||||
readonly uploadedAttachmentId?: string;
|
||||
readonly uploadEnvironmentId?: EnvironmentId;
|
||||
}
|
||||
|
||||
export type DraftComposerAttachment = DraftComposerImageAttachment | DraftComposerFileAttachment;
|
||||
|
||||
/** Wire shape for startTurn: pure uploads without client draft id / previewUri. */
|
||||
export function toUploadChatImageAttachments(
|
||||
attachments: ReadonlyArray<DraftComposerImageAttachment>,
|
||||
@@ -27,6 +51,189 @@ export function toUploadChatImageAttachments(
|
||||
}
|
||||
|
||||
const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
|
||||
const ATTACHMENT_COPY_CHUNK_BYTES = 64 * 1024;
|
||||
|
||||
export async function persistComposerAttachmentFile(
|
||||
uri: string,
|
||||
name: string,
|
||||
maxBytes?: number,
|
||||
): Promise<string> {
|
||||
const { Directory, File, FileMode, Paths } = await import("expo-file-system");
|
||||
const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY);
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
const safeName =
|
||||
Array.from(name, (character) =>
|
||||
character === "/" || character === "\\" || character.charCodeAt(0) < 32 ? "-" : character,
|
||||
).join("") || "file";
|
||||
const destination = new File(directory, `${uuidv4()}-${safeName}`);
|
||||
const source = new File(uri);
|
||||
const sourceSize = source.size;
|
||||
if (
|
||||
maxBytes !== undefined &&
|
||||
(sourceSize === null || (sourceSize === 0 && uri.startsWith("content:")))
|
||||
) {
|
||||
destination.create();
|
||||
try {
|
||||
const reader = source.open(FileMode.ReadOnly);
|
||||
try {
|
||||
const writer = destination.open(FileMode.WriteOnly);
|
||||
try {
|
||||
let copiedBytes = 0;
|
||||
while (true) {
|
||||
const chunk = reader.readBytes(
|
||||
Math.min(ATTACHMENT_COPY_CHUNK_BYTES, maxBytes - copiedBytes + 1),
|
||||
);
|
||||
if (chunk.byteLength === 0) {
|
||||
break;
|
||||
}
|
||||
copiedBytes += chunk.byteLength;
|
||||
if (copiedBytes > maxBytes) {
|
||||
throw new Error(fileAttachmentTooLargeMessage(name, maxBytes));
|
||||
}
|
||||
writer.writeBytes(chunk);
|
||||
}
|
||||
} finally {
|
||||
writer.close();
|
||||
}
|
||||
} finally {
|
||||
reader.close();
|
||||
}
|
||||
} catch (error) {
|
||||
if (destination.exists) {
|
||||
destination.delete();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return destination.uri;
|
||||
}
|
||||
|
||||
if (maxBytes !== undefined && sourceSize !== null && sourceSize > maxBytes) {
|
||||
throw new Error(fileAttachmentTooLargeMessage(name, maxBytes));
|
||||
}
|
||||
try {
|
||||
await source.copy(destination);
|
||||
} catch (error) {
|
||||
// A failed copy can leave a partial destination file behind with no URI
|
||||
// returned to release it later; delete it before surfacing the failure.
|
||||
try {
|
||||
if (destination.exists) {
|
||||
destination.delete();
|
||||
}
|
||||
} catch (cleanupError) {
|
||||
console.warn("[composer-attachments] could not remove a partial copy", cleanupError);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
// An Android content: stream can deliver more bytes than the size it
|
||||
// reported before the copy. Validate the persisted copy so an oversized
|
||||
// file is never retained under a stale recorded size.
|
||||
const copiedSize = destination.size;
|
||||
if (maxBytes !== undefined && copiedSize !== null && copiedSize > maxBytes) {
|
||||
try {
|
||||
if (destination.exists) {
|
||||
destination.delete();
|
||||
}
|
||||
} catch (cleanupError) {
|
||||
console.warn("[composer-attachments] could not remove an oversized copy", cleanupError);
|
||||
}
|
||||
throw new Error(fileAttachmentTooLargeMessage(name, maxBytes));
|
||||
}
|
||||
return destination.uri;
|
||||
}
|
||||
|
||||
export async function removePersistedComposerAttachmentFile(uri: string): Promise<void> {
|
||||
try {
|
||||
const { File, Paths } = await import("expo-file-system");
|
||||
const ownedUri = resolveOwnedComposerAttachmentFileUri(uri, Paths.document.uri);
|
||||
if (ownedUri === null) {
|
||||
return;
|
||||
}
|
||||
const file = new File(ownedUri);
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("[composer-attachments] could not remove local file", error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function pickComposerFiles(input: {
|
||||
readonly existingCount: number;
|
||||
readonly maxBytes?: number;
|
||||
}): Promise<{
|
||||
readonly files: ReadonlyArray<DraftComposerFileAttachment>;
|
||||
readonly error: string | null;
|
||||
}> {
|
||||
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
|
||||
if (remainingSlots <= 0) {
|
||||
return {
|
||||
files: [],
|
||||
error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
|
||||
};
|
||||
}
|
||||
|
||||
const { File } = await import("expo-file-system");
|
||||
const endHandoff = beginForegroundHandoff();
|
||||
let result: PickMultipleFilesResult;
|
||||
try {
|
||||
result = await File.pickFileAsync({ multipleFiles: true });
|
||||
} finally {
|
||||
endHandoff();
|
||||
}
|
||||
if (result.canceled) {
|
||||
return { files: [], error: null };
|
||||
}
|
||||
|
||||
const maxBytes = clampFileAttachmentUploadBytes(
|
||||
input.maxBytes ?? PROVIDER_SEND_TURN_MAX_FILE_BYTES,
|
||||
);
|
||||
const attachments: DraftComposerFileAttachment[] = [];
|
||||
let error: string | null = null;
|
||||
let exceededAttachmentLimit = false;
|
||||
for (const file of result.result) {
|
||||
if (attachments.length >= remainingSlots) {
|
||||
exceededAttachmentLimit = true;
|
||||
break;
|
||||
}
|
||||
// A SAF/document picker can hand back a blank display name; the wire
|
||||
// contract rejects empty names at send time, so fall back before the name
|
||||
// reaches storage, errors, or the attachment itself.
|
||||
const name = file.name.trim().length > 0 ? file.name : "file";
|
||||
const sizeBytes = file.size ?? null;
|
||||
if (sizeBytes !== null && sizeBytes > maxBytes) {
|
||||
error = fileAttachmentTooLargeMessage(name, maxBytes);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const fileUri = await persistComposerAttachmentFile(file.uri, name, maxBytes);
|
||||
const storedSizeBytes = new File(fileUri).size ?? sizeBytes ?? 0;
|
||||
if (storedSizeBytes <= 0) {
|
||||
await removePersistedComposerAttachmentFile(fileUri);
|
||||
error = `'${name}' is empty or could not be read.`;
|
||||
continue;
|
||||
}
|
||||
if (storedSizeBytes > maxBytes) {
|
||||
await removePersistedComposerAttachmentFile(fileUri);
|
||||
error = fileAttachmentTooLargeMessage(name, maxBytes);
|
||||
continue;
|
||||
}
|
||||
attachments.push({
|
||||
id: uuidv4(),
|
||||
type: "file",
|
||||
name,
|
||||
mimeType: file.type || "application/octet-stream",
|
||||
sizeBytes: storedSizeBytes,
|
||||
fileUri,
|
||||
});
|
||||
} catch (cause) {
|
||||
error = cause instanceof Error ? cause.message : `Could not read '${name}'.`;
|
||||
}
|
||||
}
|
||||
if (exceededAttachmentLimit) {
|
||||
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`;
|
||||
}
|
||||
return { files: attachments, error };
|
||||
}
|
||||
|
||||
async function loadImagePicker() {
|
||||
try {
|
||||
|
||||
@@ -2,13 +2,15 @@ import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
ThreadId,
|
||||
type ChatFileAttachment,
|
||||
type ModelSelection,
|
||||
type ProjectId,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
type UploadChatImageAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { toUploadChatImageAttachments, type DraftComposerImageAttachment } from "./composerImages";
|
||||
import { toUploadChatImageAttachments, type DraftComposerAttachment } from "./composerImages";
|
||||
|
||||
export function deriveThreadTitleFromPrompt(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
@@ -28,7 +30,8 @@ export interface ProjectThreadStartTurnSpec {
|
||||
readonly messageId: string;
|
||||
readonly createdAt: string;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly uploadedAttachments?: ReadonlyArray<UploadChatImageAttachment | ChatFileAttachment>;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly interactionMode: ProviderInteractionMode;
|
||||
@@ -55,7 +58,11 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe
|
||||
messageId: MessageId.make(spec.messageId),
|
||||
role: "user" as const,
|
||||
text: spec.text,
|
||||
attachments: toUploadChatImageAttachments(spec.attachments),
|
||||
attachments:
|
||||
spec.uploadedAttachments ??
|
||||
toUploadChatImageAttachments(
|
||||
spec.attachments.filter((attachment) => attachment.type === "image"),
|
||||
),
|
||||
},
|
||||
modelSelection: spec.modelSelection,
|
||||
titleSeed: title,
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { createAttachmentEnvironmentAtoms } from "@t3tools/client-runtime/state/attachments";
|
||||
|
||||
import { connectionAtomRuntime } from "../connection/runtime";
|
||||
|
||||
export const attachmentEnvironment = createAttachmentEnvironmentAtoms(connectionAtomRuntime);
|
||||
@@ -0,0 +1,353 @@
|
||||
import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import type { QueuedThreadMessage } from "./thread-outbox-model";
|
||||
|
||||
const harness = vi.hoisted(() => ({
|
||||
manager: null as unknown as ReturnType<
|
||||
typeof import("./thread-outbox-manager").createThreadOutboxManager
|
||||
>,
|
||||
writeGates: [] as Array<{
|
||||
readonly promise: Promise<void>;
|
||||
readonly started: (message: QueuedThreadMessage) => void;
|
||||
}>,
|
||||
}));
|
||||
|
||||
vi.mock("./thread-outbox", async () => {
|
||||
const { createThreadOutboxManager } = await import("./thread-outbox-manager");
|
||||
const { appAtomRegistry } = await import("./atom-registry");
|
||||
harness.manager = createThreadOutboxManager({
|
||||
registry: appAtomRegistry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
write: async (message) => {
|
||||
const pending = harness.writeGates.shift();
|
||||
if (pending) {
|
||||
pending.started(message);
|
||||
await pending.promise;
|
||||
}
|
||||
},
|
||||
remove: async () => undefined,
|
||||
},
|
||||
});
|
||||
const manager = harness.manager;
|
||||
return {
|
||||
threadOutboxManager: manager,
|
||||
flushThreadOutbox: async () => undefined,
|
||||
threadOutboxRevision: (messageId: QueuedThreadMessage["messageId"]) =>
|
||||
manager.revisionOf(messageId),
|
||||
updateThreadOutboxMessage: (message: QueuedThreadMessage, expectedRevision?: number) =>
|
||||
manager.update(message, expectedRevision),
|
||||
};
|
||||
});
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import {
|
||||
capturePendingTaskEditorWriteBaseline,
|
||||
flushPendingTaskEditorWrite,
|
||||
} from "./pending-task-editor-writes";
|
||||
import {
|
||||
composerDraftsAtom,
|
||||
getComposerDraftSnapshot,
|
||||
type ComposerDraft,
|
||||
} from "./use-composer-drafts";
|
||||
|
||||
function queuedMessage(messageId: string, text: string): QueuedThreadMessage {
|
||||
return {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
messageId: MessageId.make(messageId),
|
||||
commandId: CommandId.make(`command-${messageId}`),
|
||||
text,
|
||||
attachments: [],
|
||||
createdAt: "2026-08-28T12:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
function draft(text: string): ComposerDraft {
|
||||
return {
|
||||
text,
|
||||
attachments: [],
|
||||
runtimeMode: "full-access",
|
||||
};
|
||||
}
|
||||
|
||||
function setDraft(draftKey: string, value: ComposerDraft): void {
|
||||
appAtomRegistry.set(composerDraftsAtom, { [draftKey]: value });
|
||||
}
|
||||
|
||||
function queuedMessageText(messageId: QueuedThreadMessage["messageId"]): string | null {
|
||||
const messages = Object.values(
|
||||
appAtomRegistry.get(harness.manager.queuedMessagesByThreadKeyAtom),
|
||||
).flat();
|
||||
return messages.find((message) => message.messageId === messageId)?.text ?? null;
|
||||
}
|
||||
|
||||
function blockNextWrite() {
|
||||
let resolveWrite!: () => void;
|
||||
let rejectWrite!: (error: Error) => void;
|
||||
let markStarted!: (message: QueuedThreadMessage) => void;
|
||||
const promise = new Promise<void>((resolve, reject) => {
|
||||
resolveWrite = resolve;
|
||||
rejectWrite = reject;
|
||||
});
|
||||
const started = new Promise<QueuedThreadMessage>((resolve) => {
|
||||
markStarted = resolve;
|
||||
});
|
||||
harness.writeGates.push({ promise, started: markStarted });
|
||||
return {
|
||||
started,
|
||||
resolve: resolveWrite,
|
||||
reject: rejectWrite,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
harness.writeGates.length = 0;
|
||||
appAtomRegistry.set(harness.manager.queuedMessagesByThreadKeyAtom, {});
|
||||
appAtomRegistry.set(composerDraftsAtom, {});
|
||||
});
|
||||
|
||||
describe("pending task editor writes", () => {
|
||||
it("chains a reopened editor that closes before the previous save finishes", async () => {
|
||||
const original = queuedMessage("message-close-before-save", "original");
|
||||
const firstEdit = queuedMessage("message-close-before-save", "first edit");
|
||||
const secondEdit = queuedMessage("message-close-before-save", "second edit");
|
||||
const draftKey = "pending-task:message-close-before-save";
|
||||
await harness.manager.enqueue(original);
|
||||
|
||||
setDraft(draftKey, draft(firstEdit.text));
|
||||
const firstBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
|
||||
const firstWriteGate = blockNextWrite();
|
||||
const firstSave = flushPendingTaskEditorWrite({
|
||||
message: firstEdit,
|
||||
baseline: firstBaseline,
|
||||
draftKey,
|
||||
});
|
||||
await firstWriteGate.started;
|
||||
|
||||
const secondBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
|
||||
setDraft(draftKey, draft(secondEdit.text));
|
||||
const secondWriteGate = blockNextWrite();
|
||||
const secondSave = flushPendingTaskEditorWrite({
|
||||
message: secondEdit,
|
||||
baseline: secondBaseline,
|
||||
draftKey,
|
||||
});
|
||||
|
||||
firstWriteGate.resolve();
|
||||
await expect(firstSave).resolves.toBe(false);
|
||||
await expect(secondWriteGate.started).resolves.toMatchObject({ text: secondEdit.text });
|
||||
secondWriteGate.resolve();
|
||||
|
||||
await expect(secondSave).resolves.toBe(true);
|
||||
expect(queuedMessageText(original.messageId)).toBe(secondEdit.text);
|
||||
});
|
||||
|
||||
it("keeps a captured predecessor after that predecessor finishes", async () => {
|
||||
const original = queuedMessage("message-finished-predecessor", "original");
|
||||
const firstEdit = queuedMessage("message-finished-predecessor", "first edit");
|
||||
const secondEdit = queuedMessage("message-finished-predecessor", "second edit");
|
||||
const draftKey = "pending-task:message-finished-predecessor";
|
||||
await harness.manager.enqueue(original);
|
||||
|
||||
setDraft(draftKey, draft(firstEdit.text));
|
||||
const firstWriteGate = blockNextWrite();
|
||||
const firstSave = flushPendingTaskEditorWrite({
|
||||
message: firstEdit,
|
||||
baseline: capturePendingTaskEditorWriteBaseline(original.messageId),
|
||||
draftKey,
|
||||
});
|
||||
await firstWriteGate.started;
|
||||
const secondBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
|
||||
|
||||
firstWriteGate.resolve();
|
||||
await expect(firstSave).resolves.toBe(true);
|
||||
|
||||
setDraft(draftKey, draft(secondEdit.text));
|
||||
const secondWriteGate = blockNextWrite();
|
||||
const secondSave = flushPendingTaskEditorWrite({
|
||||
message: secondEdit,
|
||||
baseline: secondBaseline,
|
||||
draftKey,
|
||||
});
|
||||
await secondWriteGate.started;
|
||||
secondWriteGate.resolve();
|
||||
|
||||
await expect(secondSave).resolves.toBe(true);
|
||||
expect(queuedMessageText(original.messageId)).toBe(secondEdit.text);
|
||||
});
|
||||
|
||||
it("chains three rapid editor saves in order", async () => {
|
||||
const original = queuedMessage("message-three-saves", "original");
|
||||
const firstEdit = queuedMessage("message-three-saves", "first edit");
|
||||
const secondEdit = queuedMessage("message-three-saves", "second edit");
|
||||
const thirdEdit = queuedMessage("message-three-saves", "third edit");
|
||||
const draftKey = "pending-task:message-three-saves";
|
||||
await harness.manager.enqueue(original);
|
||||
|
||||
setDraft(draftKey, draft(firstEdit.text));
|
||||
const firstWriteGate = blockNextWrite();
|
||||
const firstSave = flushPendingTaskEditorWrite({
|
||||
message: firstEdit,
|
||||
baseline: capturePendingTaskEditorWriteBaseline(original.messageId),
|
||||
draftKey,
|
||||
});
|
||||
await firstWriteGate.started;
|
||||
|
||||
const secondBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
|
||||
setDraft(draftKey, draft(secondEdit.text));
|
||||
const secondWriteGate = blockNextWrite();
|
||||
const secondSave = flushPendingTaskEditorWrite({
|
||||
message: secondEdit,
|
||||
baseline: secondBaseline,
|
||||
draftKey,
|
||||
});
|
||||
|
||||
const thirdBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
|
||||
setDraft(draftKey, draft(thirdEdit.text));
|
||||
const thirdWriteGate = blockNextWrite();
|
||||
const thirdSave = flushPendingTaskEditorWrite({
|
||||
message: thirdEdit,
|
||||
baseline: thirdBaseline,
|
||||
draftKey,
|
||||
});
|
||||
|
||||
firstWriteGate.resolve();
|
||||
await expect(firstSave).resolves.toBe(false);
|
||||
await secondWriteGate.started;
|
||||
secondWriteGate.resolve();
|
||||
await expect(secondSave).resolves.toBe(false);
|
||||
await thirdWriteGate.started;
|
||||
thirdWriteGate.resolve();
|
||||
|
||||
await expect(thirdSave).resolves.toBe(true);
|
||||
expect(queuedMessageText(original.messageId)).toBe(thirdEdit.text);
|
||||
});
|
||||
|
||||
it("keeps the handed-off revision when the middle editor write fails", async () => {
|
||||
const original = queuedMessage("message-middle-failure", "original");
|
||||
const firstEdit = queuedMessage("message-middle-failure", "first edit");
|
||||
const failedEdit = queuedMessage("message-middle-failure", "failed edit");
|
||||
const finalEdit = queuedMessage("message-middle-failure", "final edit");
|
||||
const draftKey = "pending-task:message-middle-failure";
|
||||
await harness.manager.enqueue(original);
|
||||
|
||||
setDraft(draftKey, draft(firstEdit.text));
|
||||
const firstWriteGate = blockNextWrite();
|
||||
const firstSave = flushPendingTaskEditorWrite({
|
||||
message: firstEdit,
|
||||
baseline: capturePendingTaskEditorWriteBaseline(original.messageId),
|
||||
draftKey,
|
||||
});
|
||||
await firstWriteGate.started;
|
||||
|
||||
const failedBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
|
||||
setDraft(draftKey, draft(failedEdit.text));
|
||||
const failedWriteGate = blockNextWrite();
|
||||
const failedSave = flushPendingTaskEditorWrite({
|
||||
message: failedEdit,
|
||||
baseline: failedBaseline,
|
||||
draftKey,
|
||||
});
|
||||
|
||||
const finalBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
|
||||
setDraft(draftKey, draft(finalEdit.text));
|
||||
const finalWriteGate = blockNextWrite();
|
||||
const finalSave = flushPendingTaskEditorWrite({
|
||||
message: finalEdit,
|
||||
baseline: finalBaseline,
|
||||
draftKey,
|
||||
});
|
||||
|
||||
firstWriteGate.resolve();
|
||||
await expect(firstSave).resolves.toBe(false);
|
||||
await failedWriteGate.started;
|
||||
failedWriteGate.reject(new Error("disk full"));
|
||||
await expect(failedSave).rejects.toMatchObject({ _tag: "ThreadOutboxManagerError" });
|
||||
await finalWriteGate.started;
|
||||
finalWriteGate.resolve();
|
||||
|
||||
await expect(finalSave).resolves.toBe(true);
|
||||
expect(queuedMessageText(original.messageId)).toBe(finalEdit.text);
|
||||
});
|
||||
|
||||
it("does not overwrite an unrelated update accepted after capture", async () => {
|
||||
const original = queuedMessage("message-unrelated-update", "original");
|
||||
const editorEdit = queuedMessage("message-unrelated-update", "editor edit");
|
||||
const unrelatedEdit = queuedMessage("message-unrelated-update", "unrelated edit");
|
||||
const draftKey = "pending-task:message-unrelated-update";
|
||||
await harness.manager.enqueue(original);
|
||||
|
||||
const editorBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
|
||||
const revision = harness.manager.revisionOf(original.messageId);
|
||||
await expect(harness.manager.update(unrelatedEdit, revision)).resolves.toBe(true);
|
||||
setDraft(draftKey, draft(editorEdit.text));
|
||||
|
||||
await expect(
|
||||
flushPendingTaskEditorWrite({
|
||||
message: editorEdit,
|
||||
baseline: editorBaseline,
|
||||
draftKey,
|
||||
}),
|
||||
).resolves.toBe(false);
|
||||
expect(queuedMessageText(original.messageId)).toBe(unrelatedEdit.text);
|
||||
});
|
||||
|
||||
it("lets a later editor retry after its predecessor write fails", async () => {
|
||||
const original = queuedMessage("message-write-retry", "original");
|
||||
const failedEdit = queuedMessage("message-write-retry", "failed edit");
|
||||
const retryEdit = queuedMessage("message-write-retry", "retry edit");
|
||||
const draftKey = "pending-task:message-write-retry";
|
||||
await harness.manager.enqueue(original);
|
||||
|
||||
setDraft(draftKey, draft(failedEdit.text));
|
||||
const failedWriteGate = blockNextWrite();
|
||||
const failedSave = flushPendingTaskEditorWrite({
|
||||
message: failedEdit,
|
||||
baseline: capturePendingTaskEditorWriteBaseline(original.messageId),
|
||||
draftKey,
|
||||
});
|
||||
await failedWriteGate.started;
|
||||
|
||||
const retryBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
|
||||
setDraft(draftKey, draft(retryEdit.text));
|
||||
const retryWriteGate = blockNextWrite();
|
||||
const retrySave = flushPendingTaskEditorWrite({
|
||||
message: retryEdit,
|
||||
baseline: retryBaseline,
|
||||
draftKey,
|
||||
});
|
||||
|
||||
failedWriteGate.reject(new Error("disk full"));
|
||||
await expect(failedSave).rejects.toMatchObject({ _tag: "ThreadOutboxManagerError" });
|
||||
await retryWriteGate.started;
|
||||
retryWriteGate.resolve();
|
||||
|
||||
await expect(retrySave).resolves.toBe(true);
|
||||
expect(queuedMessageText(original.messageId)).toBe(retryEdit.text);
|
||||
});
|
||||
|
||||
it("does not permit cleanup after a newer editor makes the draft unsendable", async () => {
|
||||
const original = queuedMessage("message-unsendable-draft", "original");
|
||||
const editorEdit = queuedMessage("message-unsendable-draft", "saved edit");
|
||||
const draftKey = "pending-task:message-unsendable-draft";
|
||||
await harness.manager.enqueue(original);
|
||||
|
||||
setDraft(draftKey, draft(editorEdit.text));
|
||||
const writeGate = blockNextWrite();
|
||||
const save = flushPendingTaskEditorWrite({
|
||||
message: editorEdit,
|
||||
baseline: capturePendingTaskEditorWriteBaseline(original.messageId),
|
||||
draftKey,
|
||||
});
|
||||
await writeGate.started;
|
||||
|
||||
setDraft(draftKey, draft(""));
|
||||
writeGate.resolve();
|
||||
|
||||
await expect(save).resolves.toBe(false);
|
||||
expect(getComposerDraftSnapshot(draftKey).text).toBe("");
|
||||
expect(queuedMessageText(original.messageId)).toBe(editorEdit.text);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import type { QueuedThreadMessage } from "./thread-outbox";
|
||||
import { threadOutboxRevision, updateThreadOutboxMessage } from "./thread-outbox";
|
||||
import { getComposerDraftSnapshot, sameComposerDraftState } from "./use-composer-drafts";
|
||||
|
||||
type PendingTaskEditorWriteResult =
|
||||
| {
|
||||
readonly status: "complete";
|
||||
readonly updated: boolean;
|
||||
readonly nextRevision: number;
|
||||
}
|
||||
| {
|
||||
readonly status: "failed";
|
||||
readonly error: unknown;
|
||||
readonly nextRevision: number;
|
||||
};
|
||||
|
||||
const pendingWrites = new Map<
|
||||
QueuedThreadMessage["messageId"],
|
||||
Promise<PendingTaskEditorWriteResult>
|
||||
>();
|
||||
|
||||
/**
|
||||
* Captures this editor's outbox revision and any editor save it must follow.
|
||||
* The returned promise keeps that predecessor even after its map entry clears.
|
||||
*/
|
||||
export function capturePendingTaskEditorWriteBaseline(
|
||||
messageId: QueuedThreadMessage["messageId"],
|
||||
): Promise<number> {
|
||||
const capturedRevision = threadOutboxRevision(messageId);
|
||||
const predecessor = pendingWrites.get(messageId);
|
||||
if (!predecessor) {
|
||||
return Promise.resolve(capturedRevision);
|
||||
}
|
||||
return predecessor.then(
|
||||
({ nextRevision }) => Math.max(capturedRevision, nextRevision),
|
||||
() => capturedRevision,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves one dismissed editor after its captured predecessor. A true result
|
||||
* means both the outbox write and this editor's draft snapshot still match.
|
||||
*/
|
||||
export function flushPendingTaskEditorWrite(input: {
|
||||
readonly message: QueuedThreadMessage;
|
||||
readonly baseline: Promise<number>;
|
||||
readonly draftKey: string;
|
||||
}): Promise<boolean> {
|
||||
const { message } = input;
|
||||
const draftSnapshot = getComposerDraftSnapshot(input.draftKey);
|
||||
const write = input.baseline.then(
|
||||
async (expectedRevision): Promise<PendingTaskEditorWriteResult> => {
|
||||
try {
|
||||
const updated = await updateThreadOutboxMessage(message, expectedRevision);
|
||||
return {
|
||||
status: "complete",
|
||||
updated,
|
||||
nextRevision: expectedRevision + (updated ? 1 : 0),
|
||||
};
|
||||
} catch (error) {
|
||||
// A failed write does not advance the outbox, but later editor saves
|
||||
// still need the expected revision handed off by its predecessor.
|
||||
return {
|
||||
status: "failed",
|
||||
error,
|
||||
nextRevision: expectedRevision,
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
pendingWrites.set(message.messageId, write);
|
||||
const removeWrite = (): void => {
|
||||
if (pendingWrites.get(message.messageId) === write) {
|
||||
pendingWrites.delete(message.messageId);
|
||||
}
|
||||
};
|
||||
void write.then(removeWrite, removeWrite);
|
||||
|
||||
return write.then((result) => {
|
||||
if (result.status === "failed") {
|
||||
throw result.error;
|
||||
}
|
||||
return (
|
||||
result.updated &&
|
||||
sameComposerDraftState(draftSnapshot, getComposerDraftSnapshot(input.draftKey))
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -46,8 +46,15 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
((message: string, error: unknown) => {
|
||||
console.warn(message, error);
|
||||
});
|
||||
let loadPromise: Promise<void> | null = null;
|
||||
let loadPromise: Promise<boolean> | null = null;
|
||||
let mutationQueue: Promise<void> = Promise.resolve();
|
||||
// Monotonic per-message write counter. Every accepted write (enqueue publish
|
||||
// or update) bumps it, so a writer that captured a revision before slow work
|
||||
// (an attachment upload) is rejected before its stale payload reaches disk.
|
||||
const revisions = new Map<MessageId, number>();
|
||||
const bumpRevision = (messageId: MessageId): void => {
|
||||
revisions.set(messageId, (revisions.get(messageId) ?? 0) + 1);
|
||||
};
|
||||
|
||||
const serialize = <A>(mutation: () => Promise<A>): Promise<A> => {
|
||||
const result = mutationQueue.then(mutation, mutation);
|
||||
@@ -65,13 +72,17 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
options.registry.set(queuedMessagesByThreadKeyAtom, groupQueuedThreadMessages(messages));
|
||||
};
|
||||
|
||||
const load = (): Promise<void> => {
|
||||
// Resolves true when hydration completed; false when the read failed (the
|
||||
// next call retries). Destructive callers (the attachment sweep) must not
|
||||
// treat a failed hydration as an empty queue.
|
||||
const load = (): Promise<boolean> => {
|
||||
if (loadPromise !== null) {
|
||||
return loadPromise;
|
||||
}
|
||||
loadPromise = serialize(async () => {
|
||||
const persistedMessages = await options.storage.load();
|
||||
setMessages([...persistedMessages, ...currentMessages()]);
|
||||
return true;
|
||||
}).catch((cause) => {
|
||||
loadPromise = null;
|
||||
warn(
|
||||
@@ -84,6 +95,7 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
return false;
|
||||
});
|
||||
return loadPromise;
|
||||
};
|
||||
@@ -93,6 +105,7 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
// the message back out if it fails (durability only matters for crash
|
||||
// recovery, not for the in-session queue).
|
||||
const enqueue = (message: QueuedThreadMessage): Promise<void> => {
|
||||
bumpRevision(message.messageId);
|
||||
setMessages([
|
||||
...currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
|
||||
message,
|
||||
@@ -105,6 +118,17 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
// id may have optimistically replaced this attempt while the write was
|
||||
// in flight, and its entry must survive this attempt's failure.
|
||||
setMessages(currentMessages().filter((candidate) => candidate !== message));
|
||||
// A concurrent update losing its post-write race compensates by
|
||||
// persisting this message's payload before this write settles. When
|
||||
// no same-id entry survives the rollback, drop that disk copy too, or
|
||||
// a restart resurrects a message the queue no longer holds.
|
||||
if (!currentMessages().some((candidate) => candidate.messageId === message.messageId)) {
|
||||
try {
|
||||
await options.storage.remove(message);
|
||||
} catch {
|
||||
// Best effort: bootstrap reconciles the queue against storage.
|
||||
}
|
||||
}
|
||||
throw new ThreadOutboxManagerError({
|
||||
operation: "enqueue",
|
||||
environmentId: message.environmentId,
|
||||
@@ -126,12 +150,22 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
// Rewrites an already-queued message. A no-op when the message has been
|
||||
// removed in the meantime (e.g. deleted or delivered), so a trailing editor
|
||||
// flush can never resurrect it. Returns whether the message was updated.
|
||||
const update = (message: QueuedThreadMessage): Promise<boolean> =>
|
||||
//
|
||||
// `expectedRevision` makes the update a compare-and-set: pass the revision
|
||||
// read before starting slow work, and the update is rejected before the
|
||||
// stale payload is persisted when any other write was accepted since. An
|
||||
// enqueue can still publish synchronously while the durable write below is
|
||||
// in flight, so the revision is re-checked after the write too; the stale
|
||||
// payload it just persisted is then overwritten with the winning payload
|
||||
// inside this mutation, so a crash before the winner's own serialized write
|
||||
// cannot leave stale state on disk.
|
||||
const update = (message: QueuedThreadMessage, expectedRevision?: number): Promise<boolean> =>
|
||||
serialize(async () => {
|
||||
const exists = currentMessages().some(
|
||||
(candidate) => candidate.messageId === message.messageId,
|
||||
);
|
||||
if (!exists) {
|
||||
const staleOrMissing = (): boolean =>
|
||||
!currentMessages().some((candidate) => candidate.messageId === message.messageId) ||
|
||||
(expectedRevision !== undefined &&
|
||||
(revisions.get(message.messageId) ?? 0) !== expectedRevision);
|
||||
if (staleOrMissing()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
@@ -145,6 +179,21 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
cause,
|
||||
});
|
||||
}
|
||||
if (staleOrMissing()) {
|
||||
const winner = currentMessages().find(
|
||||
(candidate) => candidate.messageId === message.messageId,
|
||||
);
|
||||
if (winner !== undefined) {
|
||||
try {
|
||||
await options.storage.write(winner);
|
||||
} catch {
|
||||
// The winner's own serialized write follows this mutation and
|
||||
// owns the failure handling for its payload.
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
bumpRevision(message.messageId);
|
||||
setMessages([
|
||||
...currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
|
||||
message,
|
||||
@@ -152,8 +201,29 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
return true;
|
||||
});
|
||||
|
||||
const remove = (message: QueuedThreadMessage): Promise<void> =>
|
||||
// `expectedRevision` makes the removal a compare-and-set too: an edit
|
||||
// accepted after the caller decided to remove (restore-to-composer reads
|
||||
// the payload it is about to delete) keeps the newer message queued.
|
||||
// `canRemove` adds a live ownership check for state such as an open editor,
|
||||
// which can change without writing a new message revision.
|
||||
const remove = (
|
||||
message: QueuedThreadMessage,
|
||||
expectedRevision?: number,
|
||||
canRemove?: () => boolean,
|
||||
): Promise<QueuedThreadMessage | null> =>
|
||||
serialize(async () => {
|
||||
const removalCanceled = (): boolean =>
|
||||
(expectedRevision !== undefined &&
|
||||
(revisions.get(message.messageId) ?? 0) !== expectedRevision) ||
|
||||
canRemove?.() === false;
|
||||
if (removalCanceled()) {
|
||||
return null;
|
||||
}
|
||||
// The live payload may carry attachments an accepted update added after
|
||||
// the caller's snapshot; the caller releases files from what actually
|
||||
// leaves the queue.
|
||||
const removed =
|
||||
currentMessages().find((candidate) => candidate.messageId === message.messageId) ?? message;
|
||||
try {
|
||||
await options.storage.remove(message);
|
||||
} catch (cause) {
|
||||
@@ -165,13 +235,46 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
cause,
|
||||
});
|
||||
}
|
||||
if (removalCanceled()) {
|
||||
// An enqueue or editor lock can win while storage removal is in
|
||||
// flight. Restore the live payload here, before any queued mutation
|
||||
// gets its turn, so this canceled removal is durable on its own.
|
||||
const winner = currentMessages().find(
|
||||
(candidate) => candidate.messageId === message.messageId,
|
||||
);
|
||||
if (winner !== undefined) {
|
||||
try {
|
||||
await options.storage.write(winner);
|
||||
} catch (cause) {
|
||||
throw new ThreadOutboxManagerError({
|
||||
operation: "remove",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
setMessages(
|
||||
currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
|
||||
);
|
||||
// Tombstone, not delete: a same-id retry restarting at revision 1 would
|
||||
// otherwise match a stale writer's expectedRevision from before the
|
||||
// removal (ABA).
|
||||
bumpRevision(message.messageId);
|
||||
return removed;
|
||||
});
|
||||
|
||||
const clearEnvironment = (environmentId: EnvironmentId): Promise<void> =>
|
||||
serialize(async () => {
|
||||
const clearEnvironment = (
|
||||
environmentId: EnvironmentId,
|
||||
): Promise<ReadonlyArray<QueuedThreadMessage>> => {
|
||||
// Enqueues publish before their serialized writes. Capture revisions now,
|
||||
// but wait for earlier mutations before reading messages: a message that
|
||||
// changes after this request must not enter the clear set.
|
||||
const revisionsAtRequest = new Map(revisions);
|
||||
return serialize(async () => {
|
||||
const persisted = await options.storage.load().catch((cause) => {
|
||||
warn(
|
||||
"[thread-outbox] failed to load messages while clearing environment",
|
||||
@@ -188,32 +291,91 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
const allMessages = flattenQueuedThreadMessages(
|
||||
groupQueuedThreadMessages([...persisted, ...currentMessages()]),
|
||||
);
|
||||
const removedMessageIds = new Set<MessageId>();
|
||||
const candidates = allMessages.filter(
|
||||
(message) =>
|
||||
message.environmentId === environmentId &&
|
||||
(revisions.get(message.messageId) ?? 0) ===
|
||||
(revisionsAtRequest.get(message.messageId) ?? 0),
|
||||
);
|
||||
const candidateRevisions = new Map(
|
||||
candidates.map(
|
||||
(message) => [message.messageId, revisions.get(message.messageId) ?? 0] as const,
|
||||
),
|
||||
);
|
||||
const removedFromStorage = new Set<MessageId>();
|
||||
|
||||
await Promise.all(
|
||||
allMessages
|
||||
.filter((message) => message.environmentId === environmentId)
|
||||
.map(async (message) => {
|
||||
try {
|
||||
await options.storage.remove(message);
|
||||
removedMessageIds.add(message.messageId);
|
||||
} catch (cause) {
|
||||
warn(
|
||||
"[thread-outbox] failed to clear persisted message",
|
||||
new ThreadOutboxManagerError({
|
||||
operation: "clear-environment-remove",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}),
|
||||
candidates.map(async (message) => {
|
||||
try {
|
||||
await options.storage.remove(message);
|
||||
removedFromStorage.add(message.messageId);
|
||||
} catch (cause) {
|
||||
warn(
|
||||
"[thread-outbox] failed to clear persisted message",
|
||||
new ThreadOutboxManagerError({
|
||||
operation: "clear-environment-remove",
|
||||
environmentId: message.environmentId,
|
||||
threadId: message.threadId,
|
||||
messageId: message.messageId,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
setMessages(allMessages.filter((message) => !removedMessageIds.has(message.messageId)));
|
||||
// A same-id enqueue can publish while one of the removes above waits.
|
||||
// Put its payload back before the later serialized enqueue write runs.
|
||||
await Promise.all(
|
||||
candidates.map(async (message) => {
|
||||
if (
|
||||
!removedFromStorage.has(message.messageId) ||
|
||||
(revisions.get(message.messageId) ?? 0) === candidateRevisions.get(message.messageId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const retained = currentMessages().find(
|
||||
(candidate) => candidate.messageId === message.messageId,
|
||||
);
|
||||
if (retained === undefined) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await options.storage.write(retained);
|
||||
} catch (cause) {
|
||||
warn(
|
||||
"[thread-outbox] failed to restore message retained during environment clear",
|
||||
new ThreadOutboxManagerError({
|
||||
operation: "clear-environment-remove",
|
||||
environmentId: retained.environmentId,
|
||||
threadId: retained.threadId,
|
||||
messageId: retained.messageId,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const removed = candidates.filter(
|
||||
(message) =>
|
||||
removedFromStorage.has(message.messageId) &&
|
||||
(revisions.get(message.messageId) ?? 0) === candidateRevisions.get(message.messageId),
|
||||
);
|
||||
const removedMessageIds = new Set(removed.map((message) => message.messageId));
|
||||
const reconciledMessages = flattenQueuedThreadMessages(
|
||||
groupQueuedThreadMessages([...allMessages, ...currentMessages()]),
|
||||
).filter((message) => !removedMessageIds.has(message.messageId));
|
||||
for (const message of removed) {
|
||||
bumpRevision(message.messageId);
|
||||
}
|
||||
setMessages(reconciledMessages);
|
||||
// The caller releases these messages' attachment files; reporting what
|
||||
// was actually removed keeps the release set honest even when this
|
||||
// function's own load produced the messages.
|
||||
return removed;
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
queuedMessagesByThreadKeyAtom,
|
||||
@@ -221,6 +383,8 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
load,
|
||||
enqueue,
|
||||
confirmQueued,
|
||||
/** Current write revision for a queued message; input to update's CAS. */
|
||||
revisionOf: (messageId: MessageId): number => revisions.get(messageId) ?? 0,
|
||||
update,
|
||||
remove,
|
||||
clearEnvironment,
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
|
||||
import {
|
||||
clampFileAttachmentUploadBytes,
|
||||
fileAttachmentTooLargeMessage,
|
||||
} from "@t3tools/client-runtime/state/attachments";
|
||||
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
CommandId,
|
||||
@@ -17,8 +21,8 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { DraftComposerAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerAttachment } from "../lib/composerImages";
|
||||
import { scopedThreadKey } from "../lib/scopedEntities";
|
||||
|
||||
const THREAD_OUTBOX_SCHEMA_VERSION = 3;
|
||||
@@ -43,7 +47,7 @@ export const QueuedThreadMessageSchema = Schema.Struct({
|
||||
messageId: MessageId,
|
||||
commandId: CommandId,
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
attachments: Schema.Array(DraftComposerAttachmentSchema),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
runtimeMode: Schema.optional(RuntimeMode),
|
||||
interactionMode: Schema.optional(ProviderInteractionMode),
|
||||
@@ -72,7 +76,7 @@ export interface QueuedThreadMessage {
|
||||
readonly messageId: MessageId;
|
||||
readonly commandId: CommandId;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly modelSelection?: ModelSelectionType;
|
||||
readonly runtimeMode?: RuntimeModeType;
|
||||
readonly interactionMode?: ProviderInteractionModeType;
|
||||
@@ -172,6 +176,48 @@ export function resolveThreadOutboxDeliveryAction(input: {
|
||||
return input.environmentConnected ? "send" : "wait";
|
||||
}
|
||||
|
||||
export type ThreadOutboxDispatchStep =
|
||||
| { readonly step: "wait" }
|
||||
| { readonly step: "remove" }
|
||||
| { readonly step: "retry" }
|
||||
| { readonly step: "restore"; readonly reason: string }
|
||||
| { readonly step: "send" };
|
||||
|
||||
/**
|
||||
* Orders the resolved delivery action against the file-capability gate. The
|
||||
* gate applies only to a message that will send: a message whose thread
|
||||
* already exists (or is gone) must be removed even while the server config is
|
||||
* still loading, and a missing config defers with a retry instead of parking
|
||||
* the message forever.
|
||||
*/
|
||||
export function resolveThreadOutboxDispatchStep(input: {
|
||||
readonly deliveryAction: ThreadOutboxDeliveryAction;
|
||||
readonly fileAttachments: ReadonlyArray<{ readonly name: string; readonly sizeBytes: number }>;
|
||||
/** Null while the environment's server config has not synced yet. */
|
||||
readonly serverConfig: { readonly maxFileUploadBytes: number | undefined } | null;
|
||||
}): ThreadOutboxDispatchStep {
|
||||
if (input.deliveryAction !== "send") {
|
||||
return { step: input.deliveryAction };
|
||||
}
|
||||
if (input.fileAttachments.length === 0) {
|
||||
return { step: "send" };
|
||||
}
|
||||
if (input.serverConfig === null) {
|
||||
return { step: "retry" };
|
||||
}
|
||||
const maxBytes = input.serverConfig.maxFileUploadBytes;
|
||||
if (maxBytes === undefined) {
|
||||
return { step: "restore", reason: "This server does not support file attachments." };
|
||||
}
|
||||
const effectiveMaxBytes = clampFileAttachmentUploadBytes(maxBytes);
|
||||
const oversized = input.fileAttachments.find(
|
||||
(attachment) => attachment.sizeBytes > effectiveMaxBytes,
|
||||
);
|
||||
return oversized
|
||||
? { step: "restore", reason: fileAttachmentTooLargeMessage(oversized.name, effectiveMaxBytes) }
|
||||
: { step: "send" };
|
||||
}
|
||||
|
||||
/**
|
||||
* A queued creation can only be dispatched once its payload would pass server
|
||||
* validation; incomplete payloads stay pending until the user edits them.
|
||||
@@ -209,7 +255,7 @@ export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
|
||||
}
|
||||
|
||||
export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
|
||||
export type ThreadOutboxFailureAction = "retry" | "discard";
|
||||
export type ThreadOutboxFailureAction = "retry" | "restore";
|
||||
|
||||
export function resolveThreadOutboxFailureAction(input: {
|
||||
readonly stage: ThreadOutboxCommandStage;
|
||||
@@ -223,5 +269,5 @@ export function resolveThreadOutboxFailureAction(input: {
|
||||
) {
|
||||
return "retry";
|
||||
}
|
||||
return "discard";
|
||||
return "restore";
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
import { CommandId, EnvironmentId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const harness = vi.hoisted(() => ({
|
||||
cleanup: vi.fn(),
|
||||
clearDraft: vi.fn<typeof import("./use-composer-drafts").clearComposerDraft>(),
|
||||
flushDrafts: vi.fn<typeof import("./use-composer-drafts").flushComposerDrafts>(async () => {}),
|
||||
waitForDrafts: vi.fn<typeof import("./use-composer-drafts").waitForComposerDraftsLoaded>(
|
||||
async () => {},
|
||||
),
|
||||
manager: null as unknown as ReturnType<
|
||||
typeof import("./thread-outbox-manager").createThreadOutboxManager
|
||||
>,
|
||||
}));
|
||||
|
||||
vi.mock("./thread-outbox", async () => {
|
||||
const { createThreadOutboxManager } = await import("./thread-outbox-manager");
|
||||
const { appAtomRegistry } = await import("./atom-registry");
|
||||
harness.manager = createThreadOutboxManager({
|
||||
registry: appAtomRegistry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
write: async () => undefined,
|
||||
remove: async () => undefined,
|
||||
},
|
||||
});
|
||||
return { threadOutboxManager: harness.manager };
|
||||
});
|
||||
|
||||
vi.mock("./use-composer-drafts", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("./use-composer-drafts")>();
|
||||
return {
|
||||
...original,
|
||||
clearComposerDraft: harness.clearDraft,
|
||||
flushComposerDrafts: harness.flushDrafts,
|
||||
scheduleUnusedComposerAttachmentCleanup: harness.cleanup,
|
||||
waitForComposerDraftsLoaded: harness.waitForDrafts,
|
||||
};
|
||||
});
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { clearThreadOutboxEnvironment, removeThreadOutboxMessage } from "./thread-outbox-removal";
|
||||
import type { QueuedThreadMessage } from "./thread-outbox-model";
|
||||
import { composerDraftsAtom } from "./use-composer-drafts";
|
||||
|
||||
function queuedMessage(input: {
|
||||
readonly environmentId: string;
|
||||
readonly messageId: string;
|
||||
readonly fileUri: string;
|
||||
readonly creation?: true;
|
||||
}): QueuedThreadMessage {
|
||||
return {
|
||||
environmentId: EnvironmentId.make(input.environmentId),
|
||||
threadId: ThreadId.make(`thread-${input.messageId}`),
|
||||
messageId: MessageId.make(input.messageId),
|
||||
commandId: CommandId.make(`command-${input.messageId}`),
|
||||
text: "Review the report",
|
||||
attachments: [
|
||||
{
|
||||
id: `file-${input.messageId}`,
|
||||
type: "file",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
fileUri: input.fileUri,
|
||||
},
|
||||
],
|
||||
...(input.creation
|
||||
? {
|
||||
creation: {
|
||||
projectId: ProjectId.make(`project-${input.messageId}`),
|
||||
workspaceMode: "local" as const,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
createdAt: "2026-08-24T12:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
appAtomRegistry.set(harness.manager.queuedMessagesByThreadKeyAtom, {});
|
||||
appAtomRegistry.set(composerDraftsAtom, {});
|
||||
harness.cleanup.mockClear();
|
||||
harness.clearDraft.mockClear();
|
||||
harness.flushDrafts.mockReset();
|
||||
harness.flushDrafts.mockResolvedValue(undefined);
|
||||
harness.waitForDrafts.mockReset();
|
||||
harness.waitForDrafts.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
describe("thread outbox removal", () => {
|
||||
it("releases a removed message's attachment files with the removal itself", async () => {
|
||||
const message = queuedMessage({
|
||||
environmentId: "environment-1",
|
||||
messageId: "message-1",
|
||||
fileUri: "file:///documents/t3-composer-attachments/report.pdf",
|
||||
});
|
||||
await harness.manager.enqueue(message);
|
||||
|
||||
await removeThreadOutboxMessage(message);
|
||||
|
||||
expect(appAtomRegistry.get(harness.manager.queuedMessagesByThreadKeyAtom)).toEqual({});
|
||||
expect(harness.cleanup).toHaveBeenCalledExactlyOnceWith(message.attachments);
|
||||
});
|
||||
|
||||
it("keeps an edited message and its files when a revision-checked removal loses", async () => {
|
||||
const message = queuedMessage({
|
||||
environmentId: "environment-1",
|
||||
messageId: "message-edited",
|
||||
fileUri: "file:///documents/t3-composer-attachments/report.pdf",
|
||||
creation: true,
|
||||
});
|
||||
await harness.manager.enqueue(message);
|
||||
const revision = harness.manager.revisionOf(message.messageId);
|
||||
const edited = { ...message, text: "edited while restoring" };
|
||||
await harness.manager.update(edited);
|
||||
|
||||
await expect(removeThreadOutboxMessage(message, revision)).resolves.toBe(false);
|
||||
|
||||
expect(harness.cleanup).not.toHaveBeenCalled();
|
||||
expect(harness.waitForDrafts).not.toHaveBeenCalled();
|
||||
expect(harness.clearDraft).not.toHaveBeenCalled();
|
||||
expect(harness.flushDrafts).not.toHaveBeenCalled();
|
||||
const remaining = Object.values(
|
||||
appAtomRegistry.get(harness.manager.queuedMessagesByThreadKeyAtom),
|
||||
).flat();
|
||||
expect(remaining).toEqual([edited]);
|
||||
});
|
||||
|
||||
it("clears a removed pending task draft and includes its editor-only files", async () => {
|
||||
const message = queuedMessage({
|
||||
environmentId: "environment-1",
|
||||
messageId: "message-pending",
|
||||
fileUri: "file:///documents/t3-composer-attachments/queued.pdf",
|
||||
creation: true,
|
||||
});
|
||||
const editorOnlyFile = {
|
||||
id: "file-editor-only",
|
||||
type: "file" as const,
|
||||
name: "editor-only.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 84,
|
||||
fileUri: "file:///documents/t3-composer-attachments/editor-only.pdf",
|
||||
};
|
||||
const draftKey = `pending-task:${message.messageId}`;
|
||||
appAtomRegistry.set(composerDraftsAtom, {
|
||||
[draftKey]: { text: "edited", attachments: [editorOnlyFile] },
|
||||
});
|
||||
await harness.manager.enqueue(message);
|
||||
|
||||
await expect(removeThreadOutboxMessage(message)).resolves.toBe(true);
|
||||
|
||||
expect(harness.waitForDrafts).toHaveBeenCalledOnce();
|
||||
expect(harness.clearDraft).toHaveBeenCalledExactlyOnceWith(draftKey, {
|
||||
deferAttachmentCleanup: true,
|
||||
});
|
||||
expect(harness.flushDrafts).toHaveBeenCalledOnce();
|
||||
expect(harness.cleanup).toHaveBeenCalledExactlyOnceWith([
|
||||
...message.attachments,
|
||||
editorOnlyFile,
|
||||
]);
|
||||
expect(harness.flushDrafts.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
harness.cleanup.mock.invocationCallOrder[0]!,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not flush composer drafts when a removed creation has no editor draft", async () => {
|
||||
const message = queuedMessage({
|
||||
environmentId: "environment-1",
|
||||
messageId: "message-without-editor-draft",
|
||||
fileUri: "file:///documents/t3-composer-attachments/queued.pdf",
|
||||
creation: true,
|
||||
});
|
||||
await harness.manager.enqueue(message);
|
||||
|
||||
await expect(removeThreadOutboxMessage(message)).resolves.toBe(true);
|
||||
|
||||
expect(harness.waitForDrafts).toHaveBeenCalledOnce();
|
||||
expect(harness.clearDraft).not.toHaveBeenCalled();
|
||||
expect(harness.flushDrafts).not.toHaveBeenCalled();
|
||||
expect(harness.cleanup).toHaveBeenCalledExactlyOnceWith(message.attachments);
|
||||
});
|
||||
|
||||
it("releases only the cleared environment's queued attachment files", async () => {
|
||||
const cleared = queuedMessage({
|
||||
environmentId: "environment-1",
|
||||
messageId: "message-cleared",
|
||||
fileUri: "file:///documents/t3-composer-attachments/cleared.pdf",
|
||||
});
|
||||
const kept = queuedMessage({
|
||||
environmentId: "environment-2",
|
||||
messageId: "message-kept",
|
||||
fileUri: "file:///documents/t3-composer-attachments/kept.pdf",
|
||||
});
|
||||
await harness.manager.enqueue(cleared);
|
||||
await harness.manager.enqueue(kept);
|
||||
|
||||
await clearThreadOutboxEnvironment(cleared.environmentId);
|
||||
|
||||
expect(harness.cleanup).toHaveBeenCalledExactlyOnceWith(cleared.attachments);
|
||||
const remaining = Object.values(
|
||||
appAtomRegistry.get(harness.manager.queuedMessagesByThreadKeyAtom),
|
||||
).flat();
|
||||
expect(remaining.map((message) => message.messageId)).toEqual([kept.messageId]);
|
||||
});
|
||||
|
||||
it("clears only removed pending drafts and keeps drafts for live messages", async () => {
|
||||
const cleared = queuedMessage({
|
||||
environmentId: "environment-1",
|
||||
messageId: "message-cleared-pending",
|
||||
fileUri: "file:///documents/t3-composer-attachments/cleared-pending.pdf",
|
||||
creation: true,
|
||||
});
|
||||
const replaced = queuedMessage({
|
||||
environmentId: "environment-1",
|
||||
messageId: "message-replaced-pending",
|
||||
fileUri: "file:///documents/t3-composer-attachments/replaced-pending.pdf",
|
||||
creation: true,
|
||||
});
|
||||
const kept = queuedMessage({
|
||||
environmentId: "environment-2",
|
||||
messageId: "message-kept-pending",
|
||||
fileUri: "file:///documents/t3-composer-attachments/kept-pending.pdf",
|
||||
creation: true,
|
||||
});
|
||||
const replacement = { ...replaced, text: "replacement queued while drafts hydrate" };
|
||||
const editorOnlyFile = {
|
||||
id: "file-cleared-editor",
|
||||
type: "file" as const,
|
||||
name: "cleared-editor.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 84,
|
||||
fileUri: "file:///documents/t3-composer-attachments/cleared-editor.pdf",
|
||||
};
|
||||
const hydrationStarted = Promise.withResolvers<void>();
|
||||
const hydrationBarrier = Promise.withResolvers<void>();
|
||||
harness.waitForDrafts.mockImplementationOnce(async () => {
|
||||
hydrationStarted.resolve();
|
||||
await hydrationBarrier.promise;
|
||||
});
|
||||
const clearedDraftKey = `pending-task:${cleared.messageId}`;
|
||||
appAtomRegistry.set(composerDraftsAtom, {
|
||||
[clearedDraftKey]: { text: "edited", attachments: [editorOnlyFile] },
|
||||
[`pending-task:${replaced.messageId}`]: { text: "replacement", attachments: [] },
|
||||
[`pending-task:${kept.messageId}`]: { text: "other environment", attachments: [] },
|
||||
});
|
||||
await Promise.all([
|
||||
harness.manager.enqueue(cleared),
|
||||
harness.manager.enqueue(replaced),
|
||||
harness.manager.enqueue(kept),
|
||||
]);
|
||||
|
||||
const clearing = clearThreadOutboxEnvironment(cleared.environmentId);
|
||||
await hydrationStarted.promise;
|
||||
const replacing = harness.manager.enqueue(replacement);
|
||||
hydrationBarrier.resolve();
|
||||
await clearing;
|
||||
await replacing;
|
||||
|
||||
expect(harness.clearDraft).toHaveBeenCalledExactlyOnceWith(clearedDraftKey, {
|
||||
deferAttachmentCleanup: true,
|
||||
});
|
||||
expect(harness.cleanup).toHaveBeenCalledExactlyOnceWith([
|
||||
...cleared.attachments,
|
||||
...replaced.attachments,
|
||||
editorOnlyFile,
|
||||
]);
|
||||
const remaining = Object.values(
|
||||
appAtomRegistry.get(harness.manager.queuedMessagesByThreadKeyAtom),
|
||||
).flat();
|
||||
expect(remaining).toEqual(expect.arrayContaining([replacement, kept]));
|
||||
});
|
||||
|
||||
it("keeps removal successful when pending draft persistence fails", async () => {
|
||||
const message = queuedMessage({
|
||||
environmentId: "environment-1",
|
||||
messageId: "message-draft-flush-fails",
|
||||
fileUri: "file:///documents/t3-composer-attachments/queued.pdf",
|
||||
creation: true,
|
||||
});
|
||||
const flushError = new Error("composer storage unavailable");
|
||||
const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
harness.flushDrafts.mockRejectedValueOnce(flushError);
|
||||
appAtomRegistry.set(composerDraftsAtom, {
|
||||
[`pending-task:${message.messageId}`]: { text: "edited", attachments: [] },
|
||||
});
|
||||
await harness.manager.enqueue(message);
|
||||
|
||||
try {
|
||||
await expect(removeThreadOutboxMessage(message)).resolves.toBe(true);
|
||||
|
||||
expect(harness.clearDraft).toHaveBeenCalledOnce();
|
||||
expect(harness.cleanup).not.toHaveBeenCalled();
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
"[thread-outbox] failed to clean up removed pending task drafts",
|
||||
flushError,
|
||||
);
|
||||
expect(appAtomRegistry.get(harness.manager.queuedMessagesByThreadKeyAtom)).toEqual({});
|
||||
} finally {
|
||||
warning.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { threadOutboxManager } from "./thread-outbox";
|
||||
import type { QueuedThreadMessage } from "./thread-outbox-model";
|
||||
import {
|
||||
clearComposerDraft,
|
||||
composerDraftsAtom,
|
||||
flushComposerDrafts,
|
||||
scheduleUnusedComposerAttachmentCleanup,
|
||||
waitForComposerDraftsLoaded,
|
||||
} from "./use-composer-drafts";
|
||||
|
||||
async function cleanUpRemovedMessages(
|
||||
removedMessages: ReadonlyArray<QueuedThreadMessage>,
|
||||
): Promise<void> {
|
||||
const attachments = removedMessages.flatMap((message) => message.attachments);
|
||||
const removedCreations = removedMessages.filter((message) => message.creation !== undefined);
|
||||
if (removedCreations.length === 0) {
|
||||
scheduleUnusedComposerAttachmentCleanup(attachments);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await waitForComposerDraftsLoaded();
|
||||
const liveMessageIds = new Set(
|
||||
Object.values(appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom))
|
||||
.flat()
|
||||
.map((message) => message.messageId),
|
||||
);
|
||||
const drafts = appAtomRegistry.get(composerDraftsAtom);
|
||||
let clearedDraft = false;
|
||||
for (const message of removedCreations) {
|
||||
if (liveMessageIds.has(message.messageId)) {
|
||||
continue;
|
||||
}
|
||||
const draftKey = `pending-task:${message.messageId}`;
|
||||
const draft = drafts[draftKey];
|
||||
if (draft === undefined) {
|
||||
continue;
|
||||
}
|
||||
attachments.push(...draft.attachments);
|
||||
clearComposerDraft(draftKey, { deferAttachmentCleanup: true });
|
||||
clearedDraft = true;
|
||||
}
|
||||
if (clearedDraft) {
|
||||
await flushComposerDrafts();
|
||||
}
|
||||
} catch (error) {
|
||||
// The outbox removal is already durable. Keep the files and report the
|
||||
// secondary cleanup failure without changing the successful result.
|
||||
console.warn("[thread-outbox] failed to clean up removed pending task drafts", error);
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleUnusedComposerAttachmentCleanup(attachments);
|
||||
}
|
||||
|
||||
/**
|
||||
* The only way a queued message leaves the outbox. Removal also releases the
|
||||
* message's local attachment files (via the reference-counting sweep, so a
|
||||
* file still referenced by a draft or another queued message survives).
|
||||
* Keeping release inside the removal call means no call site can forget it.
|
||||
*
|
||||
* `expectedRevision` (from `threadOutboxRevision`) and `canRemove` make the
|
||||
* removal a compare-and-set: when an edit was accepted or an editor takes the
|
||||
* message, it stays queued, nothing is released, and this returns false.
|
||||
*/
|
||||
export async function removeThreadOutboxMessage(
|
||||
message: QueuedThreadMessage,
|
||||
expectedRevision?: number,
|
||||
canRemove?: () => boolean,
|
||||
): Promise<boolean> {
|
||||
const removed = await threadOutboxManager.remove(message, expectedRevision, canRemove);
|
||||
if (removed === null) {
|
||||
return false;
|
||||
}
|
||||
// The removed payload, not the caller's snapshot: an accepted update may
|
||||
// have added files the snapshot never saw.
|
||||
await cleanUpRemovedMessages([removed]);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Removes every queued message of an environment and releases their files. */
|
||||
export async function clearThreadOutboxEnvironment(environmentId: EnvironmentId): Promise<void> {
|
||||
// clearEnvironment loads and merges persisted messages itself and reports
|
||||
// what it actually removed, so the release set cannot miss messages a
|
||||
// failed earlier hydration would have hidden.
|
||||
const removed = await threadOutboxManager.clearEnvironment(environmentId);
|
||||
await cleanUpRemovedMessages(removed);
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
isQueuedThreadCreationSendable,
|
||||
modelSelectionsEqual,
|
||||
resolveThreadOutboxDeliveryAction,
|
||||
resolveThreadOutboxDispatchStep,
|
||||
resolveThreadOutboxFailureAction,
|
||||
resolveQueuedThreadSettings,
|
||||
shouldRetryThreadOutboxDelivery,
|
||||
@@ -78,6 +79,29 @@ describe("thread outbox", () => {
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("persists generic attachment paths without embedding their contents", () => {
|
||||
const message = {
|
||||
...queuedMessage({
|
||||
messageId: "message-file",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
}),
|
||||
attachments: [
|
||||
{
|
||||
id: "file-1",
|
||||
type: "file" as const,
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
fileUri: "file:///documents/report.pdf",
|
||||
uploadedAttachmentId: "pending-report-pdf",
|
||||
uploadEnvironmentId: EnvironmentId.make("environment-1"),
|
||||
},
|
||||
],
|
||||
} satisfies QueuedThreadMessage;
|
||||
|
||||
expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(message))).toEqual(message);
|
||||
});
|
||||
|
||||
it("persists the exact selector snapshot while remaining compatible with v1 messages", () => {
|
||||
const legacyMessage = queuedMessage({
|
||||
messageId: "message-1",
|
||||
@@ -357,6 +381,34 @@ describe("thread outbox", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("drops the disk entry when a failed enqueue leaves no queued message behind", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const removed: string[] = [];
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
write: async () => {
|
||||
throw new Error("disk full");
|
||||
},
|
||||
remove: async (message) => {
|
||||
removed.push(message.messageId);
|
||||
},
|
||||
},
|
||||
});
|
||||
const message = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
|
||||
// A concurrent update losing its race can compensate-write this payload
|
||||
// to disk before this write fails; rollback must clear that copy or a
|
||||
// restart resurrects the message.
|
||||
await expect(manager.enqueue(message)).rejects.toBeInstanceOf(ThreadOutboxManagerError);
|
||||
expect(removed).toEqual(["message-1"]);
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("keeps a same-id retry queued when the first attempt's write fails", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
let failNextWrite = true;
|
||||
@@ -457,6 +509,445 @@ describe("thread outbox", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("rejects a stale revision before its payload reaches durable storage", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const writes: string[] = [];
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
write: async (message) => {
|
||||
writes.push(message.text);
|
||||
},
|
||||
remove: async () => undefined,
|
||||
},
|
||||
});
|
||||
const original = queuedMessage({
|
||||
messageId: "message-edit-race",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const edited = { ...original, text: "keep my changes" };
|
||||
|
||||
await manager.enqueue(original);
|
||||
// Revision captured before slow work (an attachment upload) starts.
|
||||
const revision = manager.revisionOf(original.messageId);
|
||||
await manager.update(edited);
|
||||
|
||||
await expect(manager.update({ ...original, text: "stale upload" }, revision)).resolves.toBe(
|
||||
false,
|
||||
);
|
||||
// The losing writer was rejected before persisting: no stale payload can
|
||||
// sit on disk waiting to resurrect on the next load.
|
||||
expect(writes).toEqual([original.text, "keep my changes"]);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [edited],
|
||||
});
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("does not publish a stale attachment update after a replacement appears during its write", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const writes: string[] = [];
|
||||
let resumeWrite: () => void = () => {};
|
||||
let signalWriteStarted: () => void = () => {};
|
||||
const writeStarted = new Promise<void>((resolve) => {
|
||||
signalWriteStarted = resolve;
|
||||
});
|
||||
const writeBarrier = new Promise<void>((resolve) => {
|
||||
resumeWrite = resolve;
|
||||
});
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
write: async (message) => {
|
||||
writes.push(message.text);
|
||||
if (message.text === "stale upload") {
|
||||
signalWriteStarted();
|
||||
await writeBarrier;
|
||||
}
|
||||
},
|
||||
remove: async () => undefined,
|
||||
},
|
||||
});
|
||||
const original = queuedMessage({
|
||||
messageId: "message-write-race",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const replacement = { ...original, text: "newer edit" };
|
||||
|
||||
await manager.enqueue(original);
|
||||
const update = manager.update(
|
||||
{ ...original, text: "stale upload" },
|
||||
manager.revisionOf(original.messageId),
|
||||
);
|
||||
await writeStarted;
|
||||
const enqueue = manager.enqueue(replacement);
|
||||
resumeWrite();
|
||||
|
||||
await expect(update).resolves.toBe(false);
|
||||
// The losing update re-writes the winning payload inside its own
|
||||
// mutation, before the replacement's serialized write lands, so a crash
|
||||
// between the two cannot leave the stale payload on disk.
|
||||
expect(writes).toEqual([original.text, "stale upload", "newer edit", "newer edit"]);
|
||||
await enqueue;
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [replacement],
|
||||
});
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("refuses to remove a message that was rewritten after the removal decision", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const stored = new Map<MessageId, QueuedThreadMessage>();
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [...stored.values()],
|
||||
write: async (message) => {
|
||||
stored.set(message.messageId, message);
|
||||
},
|
||||
remove: async (message) => {
|
||||
stored.delete(message.messageId);
|
||||
},
|
||||
},
|
||||
});
|
||||
const original = queuedMessage({
|
||||
messageId: "message-remove-race",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const edited = { ...original, text: "edited while restoring" };
|
||||
|
||||
await manager.enqueue(original);
|
||||
// Revision captured when restore-to-composer read the payload it intends
|
||||
// to remove; the edit accepted afterwards must survive the removal.
|
||||
const revision = manager.revisionOf(original.messageId);
|
||||
await manager.update(edited);
|
||||
|
||||
await expect(manager.remove(original, revision)).resolves.toBe(null);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [edited],
|
||||
});
|
||||
expect(stored.get(original.messageId)).toEqual(edited);
|
||||
|
||||
await expect(manager.remove(edited, manager.revisionOf(edited.messageId))).resolves.toEqual(
|
||||
edited,
|
||||
);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({});
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("keeps a retry enqueued when its publish races a revision-checked removal", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const stored = new Map<MessageId, QueuedThreadMessage>();
|
||||
const removeStarted = Promise.withResolvers<void>();
|
||||
const removeBarrier = Promise.withResolvers<void>();
|
||||
const replacementWriteStarted = Promise.withResolvers<void>();
|
||||
const replacementWriteBarrier = Promise.withResolvers<void>();
|
||||
const original = queuedMessage({
|
||||
messageId: "message-remove-enqueue-race",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const retried = { ...original, text: "retried" };
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [...stored.values()],
|
||||
write: async (message) => {
|
||||
if (message === retried) {
|
||||
replacementWriteStarted.resolve();
|
||||
await replacementWriteBarrier.promise;
|
||||
}
|
||||
stored.set(message.messageId, message);
|
||||
},
|
||||
remove: async (message) => {
|
||||
removeStarted.resolve();
|
||||
await removeBarrier.promise;
|
||||
stored.delete(message.messageId);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await manager.enqueue(original);
|
||||
const removal = manager.remove(original, manager.revisionOf(original.messageId));
|
||||
let removalSettled = false;
|
||||
void removal.then(() => {
|
||||
removalSettled = true;
|
||||
});
|
||||
await removeStarted.promise;
|
||||
// Published synchronously while the durable remove is still in flight.
|
||||
const enqueue = manager.enqueue(retried);
|
||||
removeBarrier.resolve();
|
||||
await replacementWriteStarted.promise;
|
||||
|
||||
// The canceled removal itself restores the durable winner. The queued
|
||||
// enqueue write has not had a chance to run yet.
|
||||
expect(removalSettled).toBe(false);
|
||||
replacementWriteBarrier.resolve();
|
||||
await expect(removal).resolves.toBe(null);
|
||||
expect(stored.get(original.messageId)).toEqual(retried);
|
||||
await enqueue;
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [retried],
|
||||
});
|
||||
expect(stored.get(original.messageId)).toEqual(retried);
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("restores a message when its live removal predicate changes during storage removal", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const stored = new Map<MessageId, QueuedThreadMessage>();
|
||||
const removeStarted = Promise.withResolvers<void>();
|
||||
const removeBarrier = Promise.withResolvers<void>();
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [...stored.values()],
|
||||
write: async (message) => {
|
||||
stored.set(message.messageId, message);
|
||||
},
|
||||
remove: async (message) => {
|
||||
removeStarted.resolve();
|
||||
await removeBarrier.promise;
|
||||
stored.delete(message.messageId);
|
||||
},
|
||||
},
|
||||
});
|
||||
const message = queuedMessage({
|
||||
messageId: "message-remove-predicate-race",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
let canRemove = true;
|
||||
|
||||
await manager.enqueue(message);
|
||||
const removal = manager.remove(message, manager.revisionOf(message.messageId), () => canRemove);
|
||||
await removeStarted.promise;
|
||||
canRemove = false;
|
||||
removeBarrier.resolve();
|
||||
|
||||
await expect(removal).resolves.toBe(null);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [message],
|
||||
});
|
||||
expect(stored.get(message.messageId)).toEqual(message);
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("preserves concurrent enqueues while clearing an environment", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const stored = new Map<MessageId, QueuedThreadMessage>();
|
||||
const removeStarted = Promise.withResolvers<void>();
|
||||
const removeBarrier = Promise.withResolvers<void>();
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [...stored.values()],
|
||||
write: async (message) => {
|
||||
stored.set(message.messageId, message);
|
||||
},
|
||||
remove: async (message) => {
|
||||
if (message.environmentId === EnvironmentId.make("environment-clear")) {
|
||||
removeStarted.resolve();
|
||||
await removeBarrier.promise;
|
||||
}
|
||||
stored.delete(message.messageId);
|
||||
},
|
||||
},
|
||||
});
|
||||
const replaced = queuedMessage({
|
||||
environmentId: "environment-clear",
|
||||
messageId: "message-replaced-during-clear",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const removed = queuedMessage({
|
||||
environmentId: "environment-clear",
|
||||
messageId: "message-removed-by-clear",
|
||||
createdAt: "2026-06-08T10:00:02.000Z",
|
||||
});
|
||||
const kept = queuedMessage({
|
||||
environmentId: "environment-keep",
|
||||
messageId: "message-other-environment",
|
||||
createdAt: "2026-06-08T10:00:03.000Z",
|
||||
});
|
||||
const replacement = { ...replaced, text: "replacement" };
|
||||
const added = queuedMessage({
|
||||
environmentId: "environment-clear",
|
||||
messageId: "message-added-during-clear",
|
||||
createdAt: "2026-06-08T10:00:04.000Z",
|
||||
});
|
||||
|
||||
await Promise.all([manager.enqueue(replaced), manager.enqueue(removed), manager.enqueue(kept)]);
|
||||
const clearing = manager.clearEnvironment(replaced.environmentId);
|
||||
await removeStarted.promise;
|
||||
const replacing = manager.enqueue(replacement);
|
||||
const adding = manager.enqueue(added);
|
||||
removeBarrier.resolve();
|
||||
|
||||
await expect(clearing).resolves.toEqual([removed]);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-clear:thread-1": [replacement, added],
|
||||
"environment-keep:thread-1": [kept],
|
||||
});
|
||||
expect(stored.get(replacement.messageId)).toEqual(replacement);
|
||||
expect(stored.has(removed.messageId)).toBe(false);
|
||||
|
||||
await Promise.all([replacing, adding]);
|
||||
expect([...stored.values()]).toEqual(expect.arrayContaining([replacement, added, kept]));
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("does not restore a message removed before a queued environment clear starts", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const stored = new Map<MessageId, QueuedThreadMessage>();
|
||||
const removeStarted = Promise.withResolvers<void>();
|
||||
const removeBarrier = Promise.withResolvers<void>();
|
||||
let removeCalls = 0;
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [...stored.values()],
|
||||
write: async (message) => {
|
||||
stored.set(message.messageId, message);
|
||||
},
|
||||
remove: async (message) => {
|
||||
removeCalls += 1;
|
||||
if (removeCalls === 1) {
|
||||
removeStarted.resolve();
|
||||
await removeBarrier.promise;
|
||||
}
|
||||
stored.delete(message.messageId);
|
||||
},
|
||||
},
|
||||
});
|
||||
const message = queuedMessage({
|
||||
environmentId: "environment-clear",
|
||||
messageId: "message-removed-before-clear",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
|
||||
await manager.enqueue(message);
|
||||
const removal = manager.remove(message);
|
||||
await removeStarted.promise;
|
||||
const clearing = manager.clearEnvironment(message.environmentId);
|
||||
removeBarrier.resolve();
|
||||
|
||||
await expect(removal).resolves.toEqual(message);
|
||||
await expect(clearing).resolves.toEqual([]);
|
||||
expect(removeCalls).toBe(1);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({});
|
||||
expect(stored.has(message.messageId)).toBe(false);
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("keeps an enqueue published while an environment clear waits to start", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const stored = new Map<MessageId, QueuedThreadMessage>();
|
||||
const mutationStarted = Promise.withResolvers<void>();
|
||||
const mutationBarrier = Promise.withResolvers<void>();
|
||||
let removeCalls = 0;
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [...stored.values()],
|
||||
write: async (message) => {
|
||||
stored.set(message.messageId, message);
|
||||
},
|
||||
remove: async () => {
|
||||
removeCalls += 1;
|
||||
},
|
||||
},
|
||||
});
|
||||
const blocker = manager.serialize(async () => {
|
||||
mutationStarted.resolve();
|
||||
await mutationBarrier.promise;
|
||||
});
|
||||
await mutationStarted.promise;
|
||||
const clearing = manager.clearEnvironment(EnvironmentId.make("environment-clear"));
|
||||
const added = queuedMessage({
|
||||
environmentId: "environment-clear",
|
||||
messageId: "message-enqueued-before-clear-start",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const enqueue = manager.enqueue(added);
|
||||
mutationBarrier.resolve();
|
||||
|
||||
await blocker;
|
||||
await expect(clearing).resolves.toEqual([]);
|
||||
expect(removeCalls).toBe(0);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-clear:thread-1": [added],
|
||||
});
|
||||
await enqueue;
|
||||
expect(stored.get(added.messageId)).toEqual(added);
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("removes an already-created pending task before the file-capability gate runs", () => {
|
||||
// The creation's startTurn already made the thread, so the resolver wants
|
||||
// the queued message removed. A missing server config (or missing file
|
||||
// support) must not turn that into a restore, which would duplicate the
|
||||
// task as a draft.
|
||||
const fileAttachments = [{ name: "report.pdf", sizeBytes: 42 }];
|
||||
expect(
|
||||
resolveThreadOutboxDispatchStep({
|
||||
deliveryAction: "remove",
|
||||
fileAttachments,
|
||||
serverConfig: null,
|
||||
}),
|
||||
).toEqual({ step: "remove" });
|
||||
expect(
|
||||
resolveThreadOutboxDispatchStep({
|
||||
deliveryAction: "remove",
|
||||
fileAttachments,
|
||||
serverConfig: { maxFileUploadBytes: undefined },
|
||||
}),
|
||||
).toEqual({ step: "remove" });
|
||||
});
|
||||
|
||||
it("retries instead of parking a file message while the server config loads", () => {
|
||||
expect(
|
||||
resolveThreadOutboxDispatchStep({
|
||||
deliveryAction: "send",
|
||||
fileAttachments: [{ name: "report.pdf", sizeBytes: 42 }],
|
||||
serverConfig: null,
|
||||
}),
|
||||
).toEqual({ step: "retry" });
|
||||
});
|
||||
|
||||
it("gates a sending file message on the server's file support and limit", () => {
|
||||
expect(
|
||||
resolveThreadOutboxDispatchStep({
|
||||
deliveryAction: "send",
|
||||
fileAttachments: [{ name: "report.pdf", sizeBytes: 42 }],
|
||||
serverConfig: { maxFileUploadBytes: undefined },
|
||||
}),
|
||||
).toEqual({ step: "restore", reason: "This server does not support file attachments." });
|
||||
expect(
|
||||
resolveThreadOutboxDispatchStep({
|
||||
deliveryAction: "send",
|
||||
fileAttachments: [{ name: "big.zip", sizeBytes: 2 * 1024 * 1024 }],
|
||||
serverConfig: { maxFileUploadBytes: 1024 * 1024 },
|
||||
}),
|
||||
).toEqual({ step: "restore", reason: "'big.zip' exceeds the 1 MB attachment limit." });
|
||||
expect(
|
||||
resolveThreadOutboxDispatchStep({
|
||||
deliveryAction: "send",
|
||||
fileAttachments: [{ name: "report.pdf", sizeBytes: 42 }],
|
||||
serverConfig: { maxFileUploadBytes: 1024 * 1024 },
|
||||
}),
|
||||
).toEqual({ step: "send" });
|
||||
});
|
||||
|
||||
it("sends a message without file attachments before the server config loads", () => {
|
||||
expect(
|
||||
resolveThreadOutboxDispatchStep({
|
||||
deliveryAction: "send",
|
||||
fileAttachments: [],
|
||||
serverConfig: null,
|
||||
}),
|
||||
).toEqual({ step: "send" });
|
||||
});
|
||||
|
||||
it("only removes a missing-thread message after shell synchronization is live", () => {
|
||||
expect(
|
||||
resolveThreadOutboxDeliveryAction({
|
||||
@@ -618,6 +1109,6 @@ describe("thread outbox", () => {
|
||||
error: deterministicFailure,
|
||||
interrupted: false,
|
||||
}),
|
||||
).toBe("discard");
|
||||
).toBe("restore");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,3 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { createThreadOutboxManager } from "./thread-outbox-manager";
|
||||
import type { QueuedThreadMessage } from "./thread-outbox-model";
|
||||
@@ -36,15 +34,23 @@ export function confirmThreadOutboxMessageQueued(message: QueuedThreadMessage):
|
||||
return threadOutboxManager.confirmQueued(message);
|
||||
}
|
||||
|
||||
/** Rewrite a queued message; no-op (false) if it was removed in the meantime. */
|
||||
export function updateThreadOutboxMessage(message: QueuedThreadMessage): Promise<boolean> {
|
||||
return threadOutboxManager.update(message);
|
||||
/**
|
||||
* Rewrite a queued message; no-op (false) if it was removed in the meantime,
|
||||
* or (with `expectedRevision` from `threadOutboxRevision`) if any other write
|
||||
* was accepted since the revision was read.
|
||||
*/
|
||||
export function updateThreadOutboxMessage(
|
||||
message: QueuedThreadMessage,
|
||||
expectedRevision?: number,
|
||||
): Promise<boolean> {
|
||||
return threadOutboxManager.update(message, expectedRevision);
|
||||
}
|
||||
|
||||
export function removeThreadOutboxMessage(message: QueuedThreadMessage): Promise<void> {
|
||||
return threadOutboxManager.remove(message);
|
||||
/** Snapshot of a queued message's write revision, for update's CAS. */
|
||||
export function threadOutboxRevision(messageId: QueuedThreadMessage["messageId"]): number {
|
||||
return threadOutboxManager.revisionOf(messageId);
|
||||
}
|
||||
|
||||
export function clearThreadOutboxEnvironment(environmentId: EnvironmentId): Promise<void> {
|
||||
return threadOutboxManager.clearEnvironment(environmentId);
|
||||
}
|
||||
// Removal lives in `thread-outbox-removal.ts`: taking a message out of the
|
||||
// outbox must also release its local attachment files, and that owner needs
|
||||
// the composer draft state this module must not depend on.
|
||||
@@ -1,6 +1,12 @@
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { vi } from "vite-plus/test";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { onTestFinished, vi } from "vite-plus/test";
|
||||
|
||||
const composerDraftFileMocks = vi.hoisted(() => {
|
||||
let document = "";
|
||||
@@ -79,14 +85,39 @@ const composerDraftFileMocks = vi.hoisted(() => {
|
||||
};
|
||||
});
|
||||
|
||||
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: "/documents" },
|
||||
}));
|
||||
|
||||
vi.mock("../lib/composerImages", () => ({
|
||||
removePersistedComposerAttachmentFile: composerAttachmentCleanupMocks.remove,
|
||||
}));
|
||||
|
||||
vi.mock("../lib/attachmentUpload", () => ({
|
||||
releasePendingAttachmentUploads: composerAttachmentCleanupMocks.releaseUploads,
|
||||
}));
|
||||
|
||||
vi.mock("../features/sharing/incoming-share-storage", () => ({
|
||||
loadIncomingShareDrafts: incomingShareStorageMocks.load,
|
||||
}));
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { threadOutboxManager } from "./thread-outbox";
|
||||
import {
|
||||
appendComposerDraftAttachments,
|
||||
clearComposerDraftContentState,
|
||||
clearComposerDraftsEnvironment,
|
||||
ComposerDraftPersistenceError,
|
||||
@@ -100,12 +131,15 @@ import {
|
||||
flushComposerDrafts,
|
||||
getComposerDraftSnapshot,
|
||||
mergeComposerDraftContentState,
|
||||
releaseUnusedComposerAttachmentFiles,
|
||||
removeComposerDraftsForEnvironment,
|
||||
resetComposerDraftsLoadState,
|
||||
restoreComposerDraftSnapshotState,
|
||||
setComposerDraftText,
|
||||
setStickyComposerModelSelection,
|
||||
stickyComposerModelSelectionAtom,
|
||||
undoComposerDraftMerge,
|
||||
undoComposerDraftMergeState,
|
||||
} from "./use-composer-drafts";
|
||||
|
||||
const DRAFT: ComposerDraft = {
|
||||
@@ -123,9 +157,449 @@ afterEach(() => {
|
||||
composerDraftFileMocks.resetWrites();
|
||||
appAtomRegistry.set(composerDraftsAtom, {});
|
||||
appAtomRegistry.set(stickyComposerModelSelectionAtom, null);
|
||||
appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
|
||||
composerAttachmentCleanupMocks.remove.mockClear();
|
||||
composerAttachmentCleanupMocks.releaseUploads.mockReset();
|
||||
composerAttachmentCleanupMocks.releaseUploads.mockResolvedValue(undefined);
|
||||
incomingShareStorageMocks.load.mockReset();
|
||||
incomingShareStorageMocks.load.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
describe("mobile composer drafts", () => {
|
||||
// Hydration is one-shot per module instance and the attachment sweep now
|
||||
// triggers it too, so this test must observe it before any sweep test runs.
|
||||
it("waits for persisted drafts before copying content between projects", async () => {
|
||||
const sourceKey = "new-task:environment-1:project-1";
|
||||
const targetKey = "new-task:environment-1:project-2";
|
||||
const unrelatedKey = "environment-1:thread-1";
|
||||
const source = { text: "Current task", attachments: [] } satisfies ComposerDraft;
|
||||
const target = { text: "Persisted target", attachments: [] } satisfies ComposerDraft;
|
||||
const unrelated = { text: "Keep me", attachments: [] } satisfies ComposerDraft;
|
||||
|
||||
composerDraftFileMocks.setDocument({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
[targetKey]: target,
|
||||
[unrelatedKey]: unrelated,
|
||||
},
|
||||
});
|
||||
composerDraftFileMocks.blockRead();
|
||||
appAtomRegistry.set(composerDraftsAtom, { [sourceKey]: source });
|
||||
|
||||
const copy = copyComposerDraftContentIfEmpty(sourceKey, targetKey);
|
||||
expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({ [sourceKey]: source });
|
||||
|
||||
composerDraftFileMocks.releaseRead();
|
||||
await copy;
|
||||
|
||||
expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({
|
||||
[sourceKey]: source,
|
||||
[targetKey]: target,
|
||||
[unrelatedKey]: unrelated,
|
||||
});
|
||||
});
|
||||
|
||||
it("hydrates generic file attachments from their saved local paths", () => {
|
||||
const file = {
|
||||
id: "file-1",
|
||||
type: "file" as const,
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
fileUri: "file:///documents/report.pdf",
|
||||
};
|
||||
|
||||
expect(
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"environment-1:thread-1": { text: "Review this file", attachments: [file] },
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
"environment-1:thread-1": { text: "Review this file", attachments: [file] },
|
||||
});
|
||||
});
|
||||
|
||||
it("caps appended attachments at the send limit against the live draft", () => {
|
||||
const makeAttachment = (id: string) => ({
|
||||
id,
|
||||
type: "file" as const,
|
||||
name: `${id}.pdf`,
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
fileUri: `file:///documents/t3-composer-attachments/${id}.pdf`,
|
||||
});
|
||||
const existing = Array.from({ length: 7 }, (_, index) => makeAttachment(`held-${index}`));
|
||||
appAtomRegistry.set(composerDraftsAtom, {
|
||||
"environment-1:thread-cap": { text: "send this", attachments: existing },
|
||||
});
|
||||
|
||||
const rejected = appendComposerDraftAttachments("environment-1:thread-cap", [
|
||||
makeAttachment("incoming-1"),
|
||||
makeAttachment("incoming-2"),
|
||||
]);
|
||||
|
||||
expect(rejected).toBe(1);
|
||||
const draft = appAtomRegistry.get(composerDraftsAtom)["environment-1:thread-cap"];
|
||||
expect(draft?.attachments).toHaveLength(8);
|
||||
expect(draft?.attachments.at(-1)?.id).toBe("incoming-1");
|
||||
|
||||
// Restore paths bypass the cap so a failed send never drops its files.
|
||||
const overflowRejected = appendComposerDraftAttachments(
|
||||
"environment-1:thread-cap",
|
||||
[makeAttachment("restored-1")],
|
||||
{ allowOverflow: true },
|
||||
);
|
||||
expect(overflowRejected).toBe(0);
|
||||
expect(
|
||||
appAtomRegistry.get(composerDraftsAtom)["environment-1:thread-cap"]?.attachments,
|
||||
).toHaveLength(9);
|
||||
});
|
||||
|
||||
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("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("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", () => {
|
||||
expect(
|
||||
decodePersistedComposerDrafts({
|
||||
@@ -603,37 +1077,6 @@ describe("mobile composer drafts", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("waits for persisted drafts before copying content between projects", async () => {
|
||||
const sourceKey = "new-task:environment-1:project-1";
|
||||
const targetKey = "new-task:environment-1:project-2";
|
||||
const unrelatedKey = "environment-1:thread-1";
|
||||
const source = { text: "Current task", attachments: [] } satisfies ComposerDraft;
|
||||
const target = { text: "Persisted target", attachments: [] } satisfies ComposerDraft;
|
||||
const unrelated = { text: "Keep me", attachments: [] } satisfies ComposerDraft;
|
||||
|
||||
composerDraftFileMocks.setDocument({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
[targetKey]: target,
|
||||
[unrelatedKey]: unrelated,
|
||||
},
|
||||
});
|
||||
composerDraftFileMocks.blockRead();
|
||||
appAtomRegistry.set(composerDraftsAtom, { [sourceKey]: source });
|
||||
|
||||
const copy = copyComposerDraftContentIfEmpty(sourceKey, targetKey);
|
||||
expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({ [sourceKey]: source });
|
||||
|
||||
composerDraftFileMocks.releaseRead();
|
||||
await copy;
|
||||
|
||||
expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({
|
||||
[sourceKey]: source,
|
||||
[targetKey]: target,
|
||||
[unrelatedKey]: unrelated,
|
||||
});
|
||||
});
|
||||
|
||||
it("lands a still-debounced draft write when flushed", async () => {
|
||||
const draftKey = "environment-1:thread-1";
|
||||
setComposerDraftText(draftKey, "typed right before the restart");
|
||||
@@ -656,4 +1099,219 @@ describe("mobile composer drafts", () => {
|
||||
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("persists an async merge rollback with the sticky model selection", async () => {
|
||||
const draftKey = "environment-1:thread-1";
|
||||
const snapshot: ComposerDraft = { text: "typed before", attachments: [] };
|
||||
const merged: ComposerDraft = {
|
||||
text: "typed before\n\nqueued text",
|
||||
attachments: [],
|
||||
};
|
||||
composerDraftFileMocks.setDocument({
|
||||
schemaVersion: 1,
|
||||
drafts: { [draftKey]: merged },
|
||||
stickyModelSelection: {
|
||||
instanceId: "codex",
|
||||
model: "gpt-5.6-sol",
|
||||
},
|
||||
});
|
||||
|
||||
await undoComposerDraftMerge(draftKey, snapshot, merged);
|
||||
|
||||
expect(JSON.parse(composerDraftFileMocks.getDocument())).toEqual({
|
||||
schemaVersion: 1,
|
||||
drafts: { [draftKey]: snapshot },
|
||||
stickyModelSelection: {
|
||||
instanceId: "codex",
|
||||
model: "gpt-5.6-sol",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
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",
|
||||
};
|
||||
// The user edited the text (forcing the partial undo) and also switched
|
||||
// interaction mode, but never touched the merge-written runtime mode.
|
||||
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],
|
||||
};
|
||||
// The user rewrote the leading text and attached a file mid-recovery.
|
||||
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],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
// Edits that broke the merged suffix keep their text untouched; only the
|
||||
// inserted attachments still come out.
|
||||
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");
|
||||
// A restore re-owns the second file while the first deletion is in
|
||||
// flight, after the sweep already decided both were unused.
|
||||
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]]);
|
||||
});
|
||||
|
||||
// Uses a fresh module instance (hydration is one-shot), so it stays last.
|
||||
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", attachments: [file] },
|
||||
});
|
||||
expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -14,10 +14,12 @@ import { useEffect } from "react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { writeFileAtomically } from "../lib/atomic-file";
|
||||
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { DraftComposerAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import { composerAttachmentFileReferenceKey } from "../lib/composerAttachmentFiles";
|
||||
import type { DraftComposerAttachment } from "../lib/composerImages";
|
||||
import { SerializedAsyncQueue } from "../lib/serialized-async-queue";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { flushThreadOutbox, threadOutboxManager } from "./thread-outbox";
|
||||
|
||||
const COMPOSER_DRAFTS_SCHEMA_VERSION = 1;
|
||||
const COMPOSER_DRAFTS_DIRECTORY = "composer-drafts";
|
||||
@@ -40,7 +42,7 @@ export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<Compo
|
||||
|
||||
export interface ComposerDraft {
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly importedShareIds?: ReadonlyArray<string>;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
@@ -50,7 +52,7 @@ export interface ComposerDraft {
|
||||
|
||||
export interface ComposerDraftContent {
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly sourceShareId?: string;
|
||||
}
|
||||
|
||||
@@ -75,7 +77,7 @@ const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
|
||||
|
||||
const ComposerDraftSchema = Schema.Struct({
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
attachments: Schema.Array(DraftComposerAttachmentSchema),
|
||||
importedShareIds: Schema.optional(Schema.Array(Schema.String)),
|
||||
modelSelection: Schema.optional(ModelSelectionSchema),
|
||||
runtimeMode: Schema.optional(RuntimeModeSchema),
|
||||
@@ -284,6 +286,156 @@ export async function flushComposerDrafts(): Promise<void> {
|
||||
} while (persistTimer !== null);
|
||||
}
|
||||
|
||||
function isComposerAttachmentFileReferenced(fileUri: string): boolean {
|
||||
const referenceKey = composerAttachmentFileReferenceKey(fileUri);
|
||||
const drafts = Object.values(appAtomRegistry.get(composerDraftsAtom));
|
||||
const queuedMessages = Object.values(
|
||||
appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
|
||||
).flat();
|
||||
return [...drafts, ...queuedMessages].some((owner) =>
|
||||
owner.attachments.some(
|
||||
(attachment) =>
|
||||
attachment.type === "file" &&
|
||||
composerAttachmentFileReferenceKey(attachment.fileUri) === referenceKey,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function isComposerAttachmentUploadReferenced(
|
||||
environmentId: EnvironmentId,
|
||||
attachmentId: string,
|
||||
): boolean {
|
||||
const drafts = Object.values(appAtomRegistry.get(composerDraftsAtom));
|
||||
const queuedMessages = Object.values(
|
||||
appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
|
||||
).flat();
|
||||
return [...drafts, ...queuedMessages].some((owner) =>
|
||||
owner.attachments.some(
|
||||
(attachment) =>
|
||||
attachment.type === "file" &&
|
||||
attachment.uploadEnvironmentId === environmentId &&
|
||||
attachment.uploadedAttachmentId === attachmentId,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function releaseUnusedComposerAttachmentFiles(
|
||||
attachments: ReadonlyArray<DraftComposerAttachment>,
|
||||
): Promise<void> {
|
||||
const candidates = new Set(
|
||||
attachments
|
||||
.filter((attachment) => attachment.type === "file")
|
||||
.map((attachment) => attachment.fileUri),
|
||||
);
|
||||
const uploadCandidates = new Map<EnvironmentId, Set<string>>();
|
||||
for (const attachment of attachments) {
|
||||
if (
|
||||
attachment.type !== "file" ||
|
||||
attachment.uploadEnvironmentId === undefined ||
|
||||
attachment.uploadedAttachmentId === undefined
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const ids = uploadCandidates.get(attachment.uploadEnvironmentId) ?? new Set<string>();
|
||||
ids.add(attachment.uploadedAttachmentId);
|
||||
uploadCandidates.set(attachment.uploadEnvironmentId, ids);
|
||||
}
|
||||
if (candidates.size === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Persisted drafts must hydrate before the reference scan. On a cold start
|
||||
// the atom is still empty, and every file a persisted draft owns would look
|
||||
// unused. Hydrate before flushing so a pending pre-hydration write cannot
|
||||
// land an incomplete snapshot either.
|
||||
await waitForComposerDraftsLoaded();
|
||||
await flushComposerDrafts();
|
||||
if (!(await threadOutboxManager.load())) {
|
||||
// An unreadable outbox store must not look like an empty queue: deleting
|
||||
// now would take bytes a persisted queued message still needs. Skip the
|
||||
// sweep; the next one retries hydration.
|
||||
return;
|
||||
}
|
||||
await flushThreadOutbox();
|
||||
|
||||
const allFilesReferenced = [...candidates].every(isComposerAttachmentFileReferenced);
|
||||
const allUploadsReferenced = [...uploadCandidates].every(([environmentId, attachmentIds]) =>
|
||||
[...attachmentIds].every((attachmentId) =>
|
||||
isComposerAttachmentUploadReferenced(environmentId, attachmentId),
|
||||
),
|
||||
);
|
||||
if (allFilesReferenced && allUploadsReferenced) {
|
||||
return;
|
||||
}
|
||||
|
||||
let incomingShareFileUris: ReadonlySet<string>;
|
||||
try {
|
||||
const { loadIncomingShareDrafts } = await import("../features/sharing/incoming-share-storage");
|
||||
const incomingShares = await loadIncomingShareDrafts({ strict: true });
|
||||
incomingShareFileUris = new Set(
|
||||
incomingShares.flatMap((share) =>
|
||||
share.attachments.flatMap((attachment) =>
|
||||
attachment.type === "file"
|
||||
? [composerAttachmentFileReferenceKey(attachment.fileUri)]
|
||||
: [],
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn("[composer-attachments] could not verify incoming share ownership", error);
|
||||
return;
|
||||
}
|
||||
|
||||
const { removePersistedComposerAttachmentFile } = await import("../lib/composerImages");
|
||||
for (const fileUri of candidates) {
|
||||
// Re-check ownership immediately before each deletion: a restore or edit
|
||||
// can re-own a file after an earlier scan decided it was unused.
|
||||
if (
|
||||
isComposerAttachmentFileReferenced(fileUri) ||
|
||||
incomingShareFileUris.has(composerAttachmentFileReferenceKey(fileUri))
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
await removePersistedComposerAttachmentFile(fileUri);
|
||||
}
|
||||
|
||||
if (uploadCandidates.size > 0) {
|
||||
const { releasePendingAttachmentUploads } = await import("../lib/attachmentUpload");
|
||||
for (const [environmentId, attachmentIds] of uploadCandidates) {
|
||||
for (const attachmentId of attachmentIds) {
|
||||
// A different draft or queued message can reuse the same pending
|
||||
// upload with another local URI. Re-check the server-side ownership
|
||||
// key immediately before deletion.
|
||||
if (isComposerAttachmentUploadReferenced(environmentId, attachmentId)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
await releasePendingAttachmentUploads(environmentId, [attachmentId]);
|
||||
} catch (error) {
|
||||
// The server expires stale pending uploads. Local discard must still
|
||||
// complete when the environment is disconnected or deletion fails.
|
||||
console.warn("[composer-attachments] could not remove pending upload", {
|
||||
environmentId,
|
||||
attachmentId,
|
||||
error,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function scheduleUnusedComposerAttachmentCleanup(
|
||||
attachments: ReadonlyArray<DraftComposerAttachment>,
|
||||
): void {
|
||||
if (!attachments.some((attachment) => attachment.type === "file")) {
|
||||
return;
|
||||
}
|
||||
void releaseUnusedComposerAttachmentFiles(attachments).catch((error) => {
|
||||
console.warn("[composer-attachments] could not remove unused files", error);
|
||||
});
|
||||
}
|
||||
|
||||
function schedulePersistComposerState(): void {
|
||||
if (persistTimer !== null) {
|
||||
clearTimeout(persistTimer);
|
||||
@@ -344,6 +496,14 @@ export function ensureComposerDraftsLoaded(): void {
|
||||
});
|
||||
}
|
||||
|
||||
/** Wait until persisted drafts have been merged into the in-memory composer state. */
|
||||
export async function waitForComposerDraftsLoaded(): Promise<void> {
|
||||
ensureComposerDraftsLoaded();
|
||||
if (loadPromise !== null) {
|
||||
await loadPromise;
|
||||
}
|
||||
}
|
||||
|
||||
function updateComposerDrafts(
|
||||
update: (current: Record<string, ComposerDraft>) => Record<string, ComposerDraft>,
|
||||
): void {
|
||||
@@ -392,29 +552,49 @@ export function appendComposerDraftText(draftKey: string, value: string): void {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends attachments to a draft, capped at the send limit against the draft's
|
||||
* live state (callers may have counted before an await; the picker can race
|
||||
* concurrent adds). Overflowed file attachments are released. Returns how many
|
||||
* were rejected. Restore paths pass allowOverflow so a failed send never drops
|
||||
* the message's own attachments.
|
||||
*/
|
||||
export function appendComposerDraftAttachments(
|
||||
draftKey: string,
|
||||
attachments: ReadonlyArray<DraftComposerImageAttachment>,
|
||||
): void {
|
||||
attachments: ReadonlyArray<DraftComposerAttachment>,
|
||||
options?: { readonly allowOverflow?: boolean },
|
||||
): number {
|
||||
if (attachments.length === 0) {
|
||||
return;
|
||||
return 0;
|
||||
}
|
||||
let rejected: ReadonlyArray<DraftComposerAttachment> = [];
|
||||
updateComposerDrafts((current) => {
|
||||
const existing = normalizeDraft(current[draftKey]);
|
||||
const remaining = options?.allowOverflow
|
||||
? attachments.length
|
||||
: Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - existing.attachments.length);
|
||||
const accepted = attachments.slice(0, remaining);
|
||||
rejected = attachments.slice(remaining);
|
||||
if (accepted.length === 0) {
|
||||
return current;
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
[draftKey]: {
|
||||
...existing,
|
||||
attachments: [...existing.attachments, ...attachments],
|
||||
attachments: [...existing.attachments, ...accepted],
|
||||
},
|
||||
};
|
||||
});
|
||||
scheduleUnusedComposerAttachmentCleanup(rejected);
|
||||
return rejected.length;
|
||||
}
|
||||
|
||||
export function replaceComposerDraftAttachments(
|
||||
draftKey: string,
|
||||
attachments: ReadonlyArray<DraftComposerImageAttachment>,
|
||||
attachments: ReadonlyArray<DraftComposerAttachment>,
|
||||
): void {
|
||||
const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
|
||||
updateComposerDrafts((current) => {
|
||||
const draft = {
|
||||
...normalizeDraft(current[draftKey]),
|
||||
@@ -430,9 +610,14 @@ export function replaceComposerDraftAttachments(
|
||||
[draftKey]: draft,
|
||||
};
|
||||
});
|
||||
const retainedIds = new Set(attachments.map((attachment) => attachment.id));
|
||||
scheduleUnusedComposerAttachmentCleanup(
|
||||
previousAttachments.filter((attachment) => !retainedIds.has(attachment.id)),
|
||||
);
|
||||
}
|
||||
|
||||
export function removeComposerDraftAttachment(draftKey: string, imageId: string): void {
|
||||
const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
|
||||
updateComposerDrafts((current) => {
|
||||
const existing = normalizeDraft(current[draftKey]);
|
||||
const draft = {
|
||||
@@ -449,6 +634,9 @@ export function removeComposerDraftAttachment(draftKey: string, imageId: string)
|
||||
[draftKey]: draft,
|
||||
};
|
||||
});
|
||||
scheduleUnusedComposerAttachmentCleanup(
|
||||
previousAttachments.filter((attachment) => attachment.id === imageId),
|
||||
);
|
||||
}
|
||||
|
||||
export function updateComposerDraftSettings(
|
||||
@@ -691,17 +879,130 @@ export async function restoreComposerDraftSnapshot(
|
||||
);
|
||||
}
|
||||
|
||||
export function sameComposerDraftState(a: ComposerDraft, b: ComposerDraft): boolean {
|
||||
return (
|
||||
a.text === b.text &&
|
||||
a.attachments === b.attachments &&
|
||||
a.importedShareIds === b.importedShareIds &&
|
||||
a.modelSelection === b.modelSelection &&
|
||||
a.runtimeMode === b.runtimeMode &&
|
||||
a.interactionMode === b.interactionMode &&
|
||||
a.workspaceSelection === b.workspaceSelection
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Undoes an abandoned mergeComposerDraftContent. When the draft is untouched
|
||||
* since `merged` (the state captured right after the merge), the pre-merge
|
||||
* snapshot comes back exactly. When the user edited the draft during the
|
||||
* merge's awaits, only what the merge inserted (the appended text and the new
|
||||
* attachments) is taken back out, so the user's edits survive the rollback.
|
||||
*/
|
||||
export function undoComposerDraftMergeState(
|
||||
current: Record<string, ComposerDraft>,
|
||||
draftKey: string,
|
||||
snapshot: ComposerDraft,
|
||||
merged: ComposerDraft,
|
||||
): Record<string, ComposerDraft> {
|
||||
const existing = normalizeDraft(current[draftKey]);
|
||||
if (sameComposerDraftState(existing, merged)) {
|
||||
return restoreComposerDraftSnapshotState(current, draftKey, snapshot);
|
||||
}
|
||||
const insertedText = merged.text.startsWith(snapshot.text)
|
||||
? merged.text.slice(snapshot.text.length)
|
||||
: "";
|
||||
const snapshotAttachmentIds = new Set(snapshot.attachments.map((attachment) => attachment.id));
|
||||
const insertedAttachmentIds = new Set(
|
||||
merged.attachments
|
||||
.filter((attachment) => !snapshotAttachmentIds.has(attachment.id))
|
||||
.map((attachment) => attachment.id),
|
||||
);
|
||||
// A setting still holding the merge's value is the merge's doing: restore
|
||||
// the snapshot's. One the user changed since the merge stays theirs.
|
||||
const undoSetting = <
|
||||
K extends "modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection",
|
||||
>(
|
||||
key: K,
|
||||
): ComposerDraft[K] => (existing[key] === merged[key] ? snapshot[key] : existing[key]);
|
||||
const text =
|
||||
insertedText.length > 0 && existing.text.startsWith(merged.text)
|
||||
? snapshot.text + existing.text.slice(merged.text.length)
|
||||
: insertedText.length > 0 && existing.text.endsWith(insertedText)
|
||||
? existing.text.slice(0, existing.text.length - insertedText.length)
|
||||
: existing.text;
|
||||
const draft = {
|
||||
...existing,
|
||||
text,
|
||||
attachments: existing.attachments.filter(
|
||||
(attachment) => !insertedAttachmentIds.has(attachment.id),
|
||||
),
|
||||
modelSelection: undoSetting("modelSelection"),
|
||||
runtimeMode: undoSetting("runtimeMode"),
|
||||
interactionMode: undoSetting("interactionMode"),
|
||||
workspaceSelection: undoSetting("workspaceSelection"),
|
||||
};
|
||||
if (isEmptyDraft(draft)) {
|
||||
const next = { ...current };
|
||||
delete next[draftKey];
|
||||
return next;
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
[draftKey]: draft,
|
||||
};
|
||||
}
|
||||
|
||||
/** Applies undoComposerDraftMergeState and lands it durably. */
|
||||
export async function undoComposerDraftMerge(
|
||||
draftKey: string,
|
||||
snapshot: ComposerDraft,
|
||||
merged: ComposerDraft,
|
||||
): Promise<void> {
|
||||
ensureComposerDraftsLoaded();
|
||||
if (loadPromise !== null) {
|
||||
await loadPromise;
|
||||
}
|
||||
if (persistTimer !== null) {
|
||||
clearTimeout(persistTimer);
|
||||
persistTimer = null;
|
||||
}
|
||||
const next = undoComposerDraftMergeState(
|
||||
appAtomRegistry.get(composerDraftsAtom),
|
||||
draftKey,
|
||||
snapshot,
|
||||
merged,
|
||||
);
|
||||
appAtomRegistry.set(composerDraftsAtom, next);
|
||||
await persistenceQueue.run(() =>
|
||||
writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
|
||||
);
|
||||
}
|
||||
|
||||
export function clearComposerDraftContent(
|
||||
draftKey: string,
|
||||
options?: {
|
||||
readonly clearModelSelection?: boolean;
|
||||
readonly clearWorkspaceSelection?: boolean;
|
||||
// Send clears the draft while the durable outbox write is still in
|
||||
// flight. Sweeping then would race the write: a failed enqueue rolls the
|
||||
// message out of the queue mid-sweep and its files get deleted right
|
||||
// before the failure handler restores them. The sender re-schedules
|
||||
// cleanup once the write settles.
|
||||
readonly deferAttachmentCleanup?: boolean;
|
||||
},
|
||||
): void {
|
||||
const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
|
||||
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options));
|
||||
if (!options?.deferAttachmentCleanup) {
|
||||
scheduleUnusedComposerAttachmentCleanup(previousAttachments);
|
||||
}
|
||||
}
|
||||
|
||||
export function clearComposerDraft(draftKey: string): void {
|
||||
export function clearComposerDraft(
|
||||
draftKey: string,
|
||||
options?: { readonly deferAttachmentCleanup?: boolean },
|
||||
): void {
|
||||
const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
|
||||
updateComposerDrafts((current) => {
|
||||
if (!current[draftKey]) {
|
||||
return current;
|
||||
@@ -710,6 +1011,9 @@ export function clearComposerDraft(draftKey: string): void {
|
||||
delete next[draftKey];
|
||||
return next;
|
||||
});
|
||||
if (!options?.deferAttachmentCleanup) {
|
||||
scheduleUnusedComposerAttachmentCleanup(previousAttachments);
|
||||
}
|
||||
}
|
||||
|
||||
export function removeComposerDraftsForEnvironment(
|
||||
@@ -732,10 +1036,11 @@ export async function clearComposerDraftsEnvironment(environmentId: EnvironmentI
|
||||
await loadPromise;
|
||||
}
|
||||
|
||||
const next = removeComposerDraftsForEnvironment(
|
||||
appAtomRegistry.get(composerDraftsAtom),
|
||||
environmentId,
|
||||
);
|
||||
const current = appAtomRegistry.get(composerDraftsAtom);
|
||||
const next = removeComposerDraftsForEnvironment(current, environmentId);
|
||||
const removedAttachments = Object.entries(current)
|
||||
.filter(([draftKey]) => next[draftKey] === undefined)
|
||||
.flatMap(([, draft]) => draft.attachments);
|
||||
|
||||
if (persistTimer !== null) {
|
||||
clearTimeout(persistTimer);
|
||||
@@ -745,6 +1050,7 @@ export async function clearComposerDraftsEnvironment(environmentId: EnvironmentI
|
||||
await persistenceQueue.run(() =>
|
||||
writePersistedComposerState(next, appAtomRegistry.get(stickyComposerModelSelectionAtom)),
|
||||
);
|
||||
await releaseUnusedComposerAttachmentFiles(removedAttachments);
|
||||
}
|
||||
|
||||
export function useComposerDraft(draftKey: string | null): ComposerDraft {
|
||||
|
||||
@@ -6,6 +6,7 @@ import * as Cause from "effect/Cause";
|
||||
import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
type EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProviderInteractionMode,
|
||||
@@ -26,6 +27,7 @@ import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
|
||||
import {
|
||||
convertPastedImagesToAttachments,
|
||||
pasteComposerClipboard,
|
||||
pickComposerFiles,
|
||||
pickComposerImages,
|
||||
} from "../lib/composerImages";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
@@ -42,6 +44,7 @@ import {
|
||||
getComposerDraftSnapshot,
|
||||
mergeComposerDraftContent,
|
||||
removeComposerDraftAttachment,
|
||||
scheduleUnusedComposerAttachmentCleanup,
|
||||
setComposerDraftText,
|
||||
updateComposerDraftSettings,
|
||||
useComposerDraft,
|
||||
@@ -65,7 +68,14 @@ export function appendReviewCommentToDraft(input: {
|
||||
const separator = existing.trim().length > 0 && !existing.endsWith("\n") ? "\n\n" : "";
|
||||
setComposerDraftText(threadKey, `${existing}${separator}${input.text}`);
|
||||
if (input.attachments && input.attachments.length > 0) {
|
||||
appendComposerDraftAttachments(threadKey, input.attachments);
|
||||
// Capped: a review comment is new content, not a send-failure restore, so
|
||||
// it must not push the draft over the send limit. Overflow is released.
|
||||
const rejectedCount = appendComposerDraftAttachments(threadKey, input.attachments);
|
||||
if (rejectedCount > 0) {
|
||||
setPendingConnectionError(
|
||||
`${rejectedCount} comment attachment${rejectedCount === 1 ? " was" : "s were"} not added. Messages can contain at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,6 +181,17 @@ export function useThreadComposerState() {
|
||||
if (text.length === 0 && attachments.length === 0) {
|
||||
return null;
|
||||
}
|
||||
// A send-failure restore appends with allowOverflow so it never drops the
|
||||
// user's files, which can leave the draft over the cap. Sending it anyway
|
||||
// would enqueue a message that outbox recovery rejects forever, so block
|
||||
// here until the user removes attachments.
|
||||
if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
|
||||
Alert.alert(
|
||||
"Too many attachments",
|
||||
`Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
|
||||
(entry) => entry.instanceId === thread.modelSelection.instanceId,
|
||||
@@ -255,18 +276,26 @@ export function useThreadComposerState() {
|
||||
interactionMode: draft.interactionMode ?? thread.interactionMode,
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
clearComposerDraftContent(threadKey);
|
||||
enqueuePromise.catch((error: unknown) => {
|
||||
// Restore text via merge (idempotent) but attachments via the uncapped
|
||||
// append: the merge path slots existing attachments first and truncates
|
||||
// at the send limit, which would silently drop this message's images if
|
||||
// the user attached new ones while the write was in flight.
|
||||
void mergeComposerDraftContent(threadKey, { text, attachments: [] });
|
||||
appendComposerDraftAttachments(threadKey, attachments);
|
||||
setPendingConnectionError(
|
||||
error instanceof Error ? error.message : "Failed to save the queued message.",
|
||||
);
|
||||
});
|
||||
clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
|
||||
enqueuePromise.then(
|
||||
() => {
|
||||
// The queued message owns the files now; the sweep sees that and
|
||||
// spares them. Deferred to here so a failed write cannot roll the
|
||||
// message out of the queue mid-sweep and lose the bytes.
|
||||
scheduleUnusedComposerAttachmentCleanup(attachments);
|
||||
},
|
||||
(error: unknown) => {
|
||||
// Restore text via merge (idempotent) but attachments via the uncapped
|
||||
// append: the merge path slots existing attachments first and truncates
|
||||
// at the send limit, which would silently drop this message's images if
|
||||
// the user attached new ones while the write was in flight.
|
||||
void mergeComposerDraftContent(threadKey, { text, attachments: [] });
|
||||
appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
|
||||
setPendingConnectionError(
|
||||
error instanceof Error ? error.message : "Failed to save the queued message.",
|
||||
);
|
||||
},
|
||||
);
|
||||
return messageId;
|
||||
}, [
|
||||
selectedEnvironmentRuntime?.serverConfig?.providers,
|
||||
@@ -296,14 +325,50 @@ export function useThreadComposerState() {
|
||||
const result = await pickComposerImages({
|
||||
existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
|
||||
});
|
||||
if (result.images.length > 0) {
|
||||
appendComposerDraftAttachments(threadKey, result.images);
|
||||
}
|
||||
if (result.error) {
|
||||
setPendingConnectionError(result.error);
|
||||
const rejectedImageCount = appendComposerDraftAttachments(threadKey, result.images);
|
||||
const problems = [
|
||||
...(result.error ? [result.error] : []),
|
||||
...(rejectedImageCount > 0
|
||||
? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`]
|
||||
: []),
|
||||
];
|
||||
if (problems.length > 0) {
|
||||
Alert.alert("Could not attach image", problems.join("\n\n"));
|
||||
}
|
||||
}, [composerDrafts, selectedThreadShell]);
|
||||
|
||||
const onPickDraftFiles = useCallback(async () => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
const maxBytes =
|
||||
selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.fileAttachments
|
||||
?.maxUploadBytes;
|
||||
if (maxBytes === undefined) {
|
||||
Alert.alert("Could not attach file", "This server does not support file attachments.");
|
||||
return;
|
||||
}
|
||||
|
||||
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
|
||||
// pickComposerFiles clamps the advertised limit to the contract maximum.
|
||||
const result = await pickComposerFiles({
|
||||
existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
|
||||
maxBytes,
|
||||
});
|
||||
const rejectedCount = appendComposerDraftAttachments(threadKey, result.files);
|
||||
// The picker error and the live-cap rejection can both happen in one
|
||||
// pick; report both in a single alert.
|
||||
const problems = [
|
||||
...(result.error ? [result.error] : []),
|
||||
...(rejectedCount > 0
|
||||
? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`]
|
||||
: []),
|
||||
];
|
||||
if (problems.length > 0) {
|
||||
Alert.alert("Could not attach file", problems.join("\n\n"));
|
||||
}
|
||||
}, [composerDrafts, selectedEnvironmentRuntime?.serverConfig, selectedThreadShell]);
|
||||
|
||||
const onPasteIntoDraft = useCallback(async () => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
@@ -313,14 +378,16 @@ export function useThreadComposerState() {
|
||||
const result = await pasteComposerClipboard({
|
||||
existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
|
||||
});
|
||||
if (result.images.length > 0) {
|
||||
appendComposerDraftAttachments(threadKey, result.images);
|
||||
}
|
||||
const rejectedPasteCount = appendComposerDraftAttachments(threadKey, result.images);
|
||||
if (result.text) {
|
||||
appendComposerDraftText(threadKey, result.text);
|
||||
}
|
||||
if (result.error) {
|
||||
setPendingConnectionError(result.error);
|
||||
} else if (rejectedPasteCount > 0) {
|
||||
setPendingConnectionError(
|
||||
`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
|
||||
);
|
||||
}
|
||||
}, [composerDrafts, selectedThreadShell]);
|
||||
|
||||
@@ -404,6 +471,7 @@ export function useThreadComposerState() {
|
||||
interactionMode,
|
||||
onChangeDraftMessage,
|
||||
onPickDraftImages,
|
||||
onPickDraftFiles,
|
||||
onPasteIntoDraft,
|
||||
onNativePasteImages,
|
||||
onRemoveDraftImage,
|
||||
|
||||
@@ -0,0 +1,574 @@
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import type { PreparedTurnAttachments } from "../lib/attachmentUpload";
|
||||
|
||||
const harness = vi.hoisted(() => ({
|
||||
manager: null as unknown as ReturnType<
|
||||
typeof import("./thread-outbox-manager").createThreadOutboxManager
|
||||
>,
|
||||
removePersistedFile: vi.fn(async () => undefined),
|
||||
removeOutboxMessage: vi.fn(async (_message: QueuedThreadMessage) => undefined),
|
||||
prepareTurnAttachments: vi.fn<typeof import("../lib/attachmentUpload").prepareTurnAttachments>(),
|
||||
setPendingConnectionError: vi.fn(),
|
||||
draftFile: (() => {
|
||||
let document = "";
|
||||
let writeError: Error | null = null;
|
||||
return {
|
||||
setDocument(value: unknown) {
|
||||
document = JSON.stringify(value);
|
||||
},
|
||||
setWriteError(error: Error | null) {
|
||||
writeError = error;
|
||||
},
|
||||
Directory: class {
|
||||
create() {}
|
||||
},
|
||||
File: class {
|
||||
exists = true;
|
||||
parentDirectory = null;
|
||||
|
||||
create() {}
|
||||
|
||||
moveSync() {}
|
||||
|
||||
async text() {
|
||||
return document;
|
||||
}
|
||||
|
||||
write(value: string) {
|
||||
if (writeError) {
|
||||
throw writeError;
|
||||
}
|
||||
document = value;
|
||||
}
|
||||
},
|
||||
};
|
||||
})(),
|
||||
}));
|
||||
|
||||
vi.mock("expo-file-system", () => ({
|
||||
Directory: harness.draftFile.Directory,
|
||||
File: harness.draftFile.File,
|
||||
Paths: { document: "/documents" },
|
||||
}));
|
||||
|
||||
vi.mock("../lib/composerImages", () => ({
|
||||
removePersistedComposerAttachmentFile: harness.removePersistedFile,
|
||||
toUploadChatImageAttachments: () => [],
|
||||
}));
|
||||
|
||||
vi.mock("../lib/uuid", () => ({
|
||||
uuidv4: () => "00000000-0000-4000-8000-000000000000",
|
||||
randomHex: () => "abcd",
|
||||
}));
|
||||
|
||||
vi.mock("../lib/attachmentUpload", () => ({
|
||||
prepareTurnAttachments: harness.prepareTurnAttachments,
|
||||
}));
|
||||
|
||||
vi.mock("./entities", () => ({
|
||||
useProjects: () => [],
|
||||
useServerConfigs: () => new Map(),
|
||||
useThreadShells: () => [],
|
||||
}));
|
||||
|
||||
vi.mock("./threads", () => ({
|
||||
threadEnvironment: {},
|
||||
}));
|
||||
|
||||
vi.mock("./use-atom-command", () => ({
|
||||
useAtomCommand: () => async () => undefined,
|
||||
}));
|
||||
|
||||
vi.mock("./use-thread-outbox", async () => {
|
||||
const { Atom } = await import("effect/unstable/reactivity");
|
||||
return {
|
||||
editingQueuedMessageIdsAtom: Atom.make<Record<string, boolean>>({}).pipe(Atom.keepAlive),
|
||||
useThreadOutboxMessages: () => ({}),
|
||||
useThreadOutboxShellStatuses: () => new Map(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("./use-remote-environment-registry", () => ({
|
||||
setPendingConnectionError: harness.setPendingConnectionError,
|
||||
useRemoteConnectionStatus: () => ({ connectedEnvironments: [] }),
|
||||
}));
|
||||
|
||||
vi.mock("./thread-outbox", async () => {
|
||||
const { createThreadOutboxManager } = await import("./thread-outbox-manager");
|
||||
const { appAtomRegistry } = await import("./atom-registry");
|
||||
harness.manager = createThreadOutboxManager({
|
||||
registry: appAtomRegistry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
write: async () => undefined,
|
||||
remove: (message) => harness.removeOutboxMessage(message),
|
||||
},
|
||||
});
|
||||
const manager = harness.manager;
|
||||
return {
|
||||
threadOutboxManager: manager,
|
||||
flushThreadOutbox: async () => undefined,
|
||||
ensureThreadOutboxLoaded: () => undefined,
|
||||
confirmThreadOutboxMessageQueued: (message: never) => manager.confirmQueued(message),
|
||||
updateThreadOutboxMessage: (message: never, expectedRevision?: number) =>
|
||||
manager.update(message, expectedRevision),
|
||||
threadOutboxRevision: (messageId: never) => manager.revisionOf(messageId),
|
||||
};
|
||||
});
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import type { QueuedThreadMessage } from "./thread-outbox-model";
|
||||
import * as composerDrafts from "./use-composer-drafts";
|
||||
import { editingQueuedMessageIdsAtom } from "./use-thread-outbox";
|
||||
import {
|
||||
completeQueuedMessageDelivery,
|
||||
prepareQueuedMessageAttachments,
|
||||
recoverEditedCreationAfterDelivery,
|
||||
removeAcknowledgedExistingThreadMessage,
|
||||
restoreRejectedQueuedMessage,
|
||||
} from "./use-thread-outbox-drain";
|
||||
|
||||
function queuedMessage(input: {
|
||||
readonly messageId: string;
|
||||
readonly text: string;
|
||||
readonly fileUri?: string;
|
||||
}): QueuedThreadMessage {
|
||||
return {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
messageId: MessageId.make(input.messageId),
|
||||
commandId: CommandId.make(`command-${input.messageId}`),
|
||||
text: input.text,
|
||||
attachments: input.fileUri
|
||||
? [
|
||||
{
|
||||
id: `file-${input.messageId}`,
|
||||
type: "file",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
fileUri: input.fileUri,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
createdAt: "2026-08-24T12:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
function withReusedFileUpload(
|
||||
message: QueuedThreadMessage,
|
||||
attachmentId: string,
|
||||
): QueuedThreadMessage {
|
||||
return {
|
||||
...message,
|
||||
attachments: message.attachments.map((attachment) =>
|
||||
attachment.type === "file"
|
||||
? {
|
||||
...attachment,
|
||||
uploadedAttachmentId: attachmentId,
|
||||
uploadEnvironmentId: message.environmentId,
|
||||
}
|
||||
: attachment,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function remainingMessages(): ReadonlyArray<QueuedThreadMessage> {
|
||||
return Object.values(appAtomRegistry.get(harness.manager.queuedMessagesByThreadKeyAtom)).flat();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
harness.draftFile.setDocument({ schemaVersion: 1, drafts: {} });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
appAtomRegistry.set(harness.manager.queuedMessagesByThreadKeyAtom, {});
|
||||
appAtomRegistry.set(composerDrafts.composerDraftsAtom, {});
|
||||
appAtomRegistry.set(editingQueuedMessageIdsAtom, {});
|
||||
harness.draftFile.setWriteError(null);
|
||||
harness.removePersistedFile.mockClear();
|
||||
harness.removeOutboxMessage.mockClear();
|
||||
harness.prepareTurnAttachments.mockReset();
|
||||
harness.setPendingConnectionError.mockClear();
|
||||
});
|
||||
|
||||
describe("thread outbox attachment preparation", () => {
|
||||
it("abandons reused uploads when an editor saves changed text during verification", async () => {
|
||||
const message = withReusedFileUpload(
|
||||
queuedMessage({
|
||||
messageId: "message-reused-upload-race",
|
||||
text: "original text",
|
||||
fileUri: "file:///documents/t3-composer-attachments/reused.pdf",
|
||||
}),
|
||||
"pending-reused-upload",
|
||||
);
|
||||
const preparationStarted = Promise.withResolvers<void>();
|
||||
const preparationBarrier = Promise.withResolvers<PreparedTurnAttachments>();
|
||||
const releaseUploads = vi.fn(async () => undefined);
|
||||
harness.prepareTurnAttachments.mockImplementationOnce(async () => {
|
||||
preparationStarted.resolve();
|
||||
return preparationBarrier.promise;
|
||||
});
|
||||
await harness.manager.enqueue(message);
|
||||
appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true });
|
||||
|
||||
const preparation = prepareQueuedMessageAttachments(message);
|
||||
await preparationStarted.promise;
|
||||
const edited = { ...message, text: "saved editor text" };
|
||||
await harness.manager.update(edited);
|
||||
appAtomRegistry.set(editingQueuedMessageIdsAtom, {});
|
||||
preparationBarrier.resolve({
|
||||
status: "ready",
|
||||
attachments: [],
|
||||
draftAttachments: message.attachments,
|
||||
pendingAttachmentIds: ["pending-reused-upload"],
|
||||
releaseUploads,
|
||||
});
|
||||
|
||||
await expect(preparation).resolves.toEqual({ status: "abandoned" });
|
||||
expect(remainingMessages()).toEqual([edited]);
|
||||
expect(releaseUploads).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps an unchanged queued payload ready after attachment reuse", async () => {
|
||||
const message = withReusedFileUpload(
|
||||
queuedMessage({
|
||||
messageId: "message-reused-upload-current",
|
||||
text: "unchanged text",
|
||||
fileUri: "file:///documents/t3-composer-attachments/current.pdf",
|
||||
}),
|
||||
"pending-reused-upload",
|
||||
);
|
||||
const releaseUploads = vi.fn(async () => undefined);
|
||||
harness.prepareTurnAttachments.mockResolvedValueOnce({
|
||||
status: "ready",
|
||||
attachments: [],
|
||||
draftAttachments: message.attachments,
|
||||
pendingAttachmentIds: ["pending-reused-upload"],
|
||||
releaseUploads,
|
||||
});
|
||||
await harness.manager.enqueue(message);
|
||||
const revision = harness.manager.revisionOf(message.messageId);
|
||||
appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true });
|
||||
|
||||
await expect(prepareQueuedMessageAttachments(message)).resolves.toMatchObject({
|
||||
status: "ready",
|
||||
persistedMessage: message,
|
||||
deliveryRevision: revision,
|
||||
});
|
||||
expect(releaseUploads).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the known next revision after persisting uploaded references", async () => {
|
||||
const message = queuedMessage({
|
||||
messageId: "message-new-upload-revision",
|
||||
text: "upload this file",
|
||||
fileUri: "file:///documents/t3-composer-attachments/new.pdf",
|
||||
});
|
||||
const uploadedAttachments = message.attachments.map((attachment) =>
|
||||
attachment.type === "file"
|
||||
? {
|
||||
...attachment,
|
||||
uploadedAttachmentId: "pending-new-upload",
|
||||
uploadEnvironmentId: message.environmentId,
|
||||
}
|
||||
: attachment,
|
||||
);
|
||||
harness.prepareTurnAttachments.mockImplementationOnce(async (input) => {
|
||||
expect(await input.persistUploadedReferences?.(uploadedAttachments)).toBe("persisted");
|
||||
return {
|
||||
status: "ready",
|
||||
attachments: [],
|
||||
draftAttachments: uploadedAttachments,
|
||||
pendingAttachmentIds: ["pending-new-upload"],
|
||||
releaseUploads: async () => undefined,
|
||||
};
|
||||
});
|
||||
await harness.manager.enqueue(message);
|
||||
const revision = harness.manager.revisionOf(message.messageId);
|
||||
|
||||
const result = await prepareQueuedMessageAttachments(message);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "ready",
|
||||
persistedMessage: { attachments: uploadedAttachments },
|
||||
deliveryRevision: revision + 1,
|
||||
});
|
||||
expect(harness.manager.revisionOf(message.messageId)).toBe(revision + 1);
|
||||
});
|
||||
|
||||
it("does not prepare a payload that was already replaced", async () => {
|
||||
const message = queuedMessage({ messageId: "message-stale-before-upload", text: "old" });
|
||||
await harness.manager.enqueue(message);
|
||||
const edited = { ...message, text: "new" };
|
||||
await harness.manager.update(edited);
|
||||
|
||||
await expect(prepareQueuedMessageAttachments(message)).resolves.toEqual({
|
||||
status: "abandoned",
|
||||
});
|
||||
expect(harness.prepareTurnAttachments).not.toHaveBeenCalled();
|
||||
expect(remainingMessages()).toEqual([edited]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("thread outbox drain delivery cleanup", () => {
|
||||
it("retries only cleanup after an acknowledged send removal fails", async () => {
|
||||
const message = queuedMessage({ messageId: "message-acknowledged", text: "delivered" });
|
||||
const acknowledged = new Set([message.messageId]);
|
||||
harness.removeOutboxMessage.mockRejectedValueOnce(new Error("storage unavailable"));
|
||||
await harness.manager.enqueue(message);
|
||||
|
||||
await expect(removeAcknowledgedExistingThreadMessage(message, acknowledged)).resolves.toBe(
|
||||
false,
|
||||
);
|
||||
expect(remainingMessages()).toEqual([message]);
|
||||
expect(acknowledged).toEqual(new Set([message.messageId]));
|
||||
|
||||
await expect(removeAcknowledgedExistingThreadMessage(message, acknowledged)).resolves.toBe(
|
||||
true,
|
||||
);
|
||||
expect(remainingMessages()).toEqual([]);
|
||||
expect(acknowledged).toEqual(new Set());
|
||||
});
|
||||
|
||||
it("keeps an edited message and its files when delivery cleanup loses the revision race", async () => {
|
||||
const message = queuedMessage({
|
||||
messageId: "message-edited",
|
||||
text: "original",
|
||||
fileUri: "file:///documents/t3-composer-attachments/report.pdf",
|
||||
});
|
||||
await harness.manager.enqueue(message);
|
||||
const deliveryRevision = harness.manager.revisionOf(message.messageId);
|
||||
const edited = { ...message, text: "edited while the turn delivered" };
|
||||
await harness.manager.update(edited);
|
||||
|
||||
await expect(completeQueuedMessageDelivery(message, deliveryRevision)).resolves.toBe("edited");
|
||||
|
||||
expect(remainingMessages()).toEqual([edited]);
|
||||
expect(harness.removePersistedFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("removes the delivered message when no edit was accepted", async () => {
|
||||
const message = queuedMessage({ messageId: "message-clean", text: "hello" });
|
||||
await harness.manager.enqueue(message);
|
||||
const deliveryRevision = harness.manager.revisionOf(message.messageId);
|
||||
|
||||
await expect(completeQueuedMessageDelivery(message, deliveryRevision)).resolves.toBe("removed");
|
||||
|
||||
expect(remainingMessages()).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps a delivered message when its editor opens during storage removal", async () => {
|
||||
const message = queuedMessage({
|
||||
messageId: "message-editor-removal-race",
|
||||
text: "keep editor changes",
|
||||
fileUri: "file:///documents/t3-composer-attachments/editor-race.pdf",
|
||||
});
|
||||
const removeStarted = Promise.withResolvers<void>();
|
||||
const removeBarrier = Promise.withResolvers<void>();
|
||||
harness.removeOutboxMessage.mockImplementationOnce(async () => {
|
||||
removeStarted.resolve();
|
||||
await removeBarrier.promise;
|
||||
});
|
||||
await harness.manager.enqueue(message);
|
||||
const deliveryRevision = harness.manager.revisionOf(message.messageId);
|
||||
|
||||
const cleanup = completeQueuedMessageDelivery(message, deliveryRevision);
|
||||
await removeStarted.promise;
|
||||
appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true });
|
||||
removeBarrier.resolve();
|
||||
|
||||
await expect(cleanup).resolves.toBe("edited");
|
||||
expect(remainingMessages()).toEqual([message]);
|
||||
expect(harness.removePersistedFile).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("thread outbox delivered creation recovery", () => {
|
||||
it("keeps an edit accepted while the older payload is persisted to the draft", async () => {
|
||||
const message = queuedMessage({
|
||||
messageId: "message-recovery-race",
|
||||
text: "original queued text",
|
||||
fileUri: "file:///documents/t3-composer-attachments/report.pdf",
|
||||
});
|
||||
const originalMergeComposerDraftContent = composerDrafts.mergeComposerDraftContent;
|
||||
const mergeCompleted = Promise.withResolvers<void>();
|
||||
const releaseRecovery = Promise.withResolvers<void>();
|
||||
const mergeSpy = vi
|
||||
.spyOn(composerDrafts, "mergeComposerDraftContent")
|
||||
.mockImplementation(async (draftKey, content) => {
|
||||
const result = await originalMergeComposerDraftContent(draftKey, content);
|
||||
mergeCompleted.resolve();
|
||||
await releaseRecovery.promise;
|
||||
return result;
|
||||
});
|
||||
|
||||
try {
|
||||
await harness.manager.enqueue(message);
|
||||
const recovery = recoverEditedCreationAfterDelivery(message);
|
||||
await mergeCompleted.promise;
|
||||
|
||||
const newer = { ...message, text: "edited while recovery persisted the draft" };
|
||||
await harness.manager.update(newer);
|
||||
|
||||
releaseRecovery.resolve();
|
||||
await expect(recovery).resolves.toBe(false);
|
||||
|
||||
expect(remainingMessages()).toEqual([newer]);
|
||||
expect(
|
||||
composerDrafts.getComposerDraftSnapshot(`${message.environmentId}:${message.threadId}`),
|
||||
).toMatchObject({ text: message.text, attachments: [] });
|
||||
expect(harness.removePersistedFile).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
releaseRecovery.resolve();
|
||||
mergeSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves recovery to an editor that opens while the draft persists", async () => {
|
||||
const message = queuedMessage({
|
||||
messageId: "message-recovery-editor",
|
||||
text: "recover this text",
|
||||
fileUri: "file:///documents/t3-composer-attachments/editor.pdf",
|
||||
});
|
||||
const originalMergeComposerDraftContent = composerDrafts.mergeComposerDraftContent;
|
||||
const mergeCompleted = Promise.withResolvers<void>();
|
||||
const releaseRecovery = Promise.withResolvers<void>();
|
||||
const mergeSpy = vi
|
||||
.spyOn(composerDrafts, "mergeComposerDraftContent")
|
||||
.mockImplementation(async (draftKey, content) => {
|
||||
const result = await originalMergeComposerDraftContent(draftKey, content);
|
||||
mergeCompleted.resolve();
|
||||
await releaseRecovery.promise;
|
||||
return result;
|
||||
});
|
||||
|
||||
try {
|
||||
await harness.manager.enqueue(message);
|
||||
const recovery = recoverEditedCreationAfterDelivery(message);
|
||||
await mergeCompleted.promise;
|
||||
appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true });
|
||||
|
||||
releaseRecovery.resolve();
|
||||
await expect(recovery).resolves.toBe(true);
|
||||
|
||||
expect(remainingMessages()).toEqual([message]);
|
||||
expect(
|
||||
composerDrafts.getComposerDraftSnapshot(`${message.environmentId}:${message.threadId}`),
|
||||
).toMatchObject({ text: message.text, attachments: [] });
|
||||
expect(harness.removePersistedFile).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
releaseRecovery.resolve();
|
||||
mergeSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("retries a failed removal without duplicating recovered draft content", async () => {
|
||||
const message = queuedMessage({
|
||||
messageId: "message-recovery-removal",
|
||||
text: "recover once",
|
||||
fileUri: "file:///documents/t3-composer-attachments/retry.pdf",
|
||||
});
|
||||
const draftKey = `${message.environmentId}:${message.threadId}`;
|
||||
const removeSpy = vi
|
||||
.spyOn(harness.manager, "remove")
|
||||
.mockRejectedValueOnce(new Error("storage unavailable"));
|
||||
|
||||
try {
|
||||
await harness.manager.enqueue(message);
|
||||
|
||||
await expect(recoverEditedCreationAfterDelivery(message)).resolves.toBe(false);
|
||||
expect(remainingMessages()).toEqual([message]);
|
||||
|
||||
await expect(recoverEditedCreationAfterDelivery(message)).resolves.toBe(true);
|
||||
|
||||
const draft = composerDrafts.getComposerDraftSnapshot(draftKey);
|
||||
expect(draft.text).toBe(message.text);
|
||||
expect(draft.attachments).toEqual(message.attachments);
|
||||
expect(remainingMessages()).toEqual([]);
|
||||
expect(harness.removePersistedFile).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
removeSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the queue entry when the recovered draft cannot persist", async () => {
|
||||
const message = queuedMessage({
|
||||
messageId: "message-recovery-persistence",
|
||||
text: "recover after persistence returns",
|
||||
});
|
||||
await harness.manager.enqueue(message);
|
||||
harness.draftFile.setWriteError(new Error("disk full"));
|
||||
|
||||
await expect(recoverEditedCreationAfterDelivery(message)).resolves.toBe(false);
|
||||
|
||||
expect(remainingMessages()).toEqual([message]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("thread outbox recovery rollback", () => {
|
||||
it("restores a rejected new task into its durable project draft", async () => {
|
||||
const message: QueuedThreadMessage = {
|
||||
...queuedMessage({ messageId: "message-creation-restore", text: "new task text" }),
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" },
|
||||
creation: {
|
||||
projectId: ProjectId.make("project-1"),
|
||||
workspaceMode: "local",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
};
|
||||
await harness.manager.enqueue(message);
|
||||
|
||||
await expect(restoreRejectedQueuedMessage(message, "rejected by server")).resolves.toBe(
|
||||
"restored",
|
||||
);
|
||||
|
||||
expect(
|
||||
composerDrafts.getComposerDraftSnapshot(
|
||||
`new-task:${message.environmentId}:${message.creation!.projectId}`,
|
||||
),
|
||||
).toMatchObject({
|
||||
text: message.text,
|
||||
attachments: message.attachments,
|
||||
modelSelection: message.modelSelection,
|
||||
});
|
||||
expect(remainingMessages()).toEqual([]);
|
||||
expect(harness.setPendingConnectionError).toHaveBeenCalledWith("rejected by server");
|
||||
});
|
||||
|
||||
it("rolls a failed recovery merge back so the retry cannot duplicate the text", async () => {
|
||||
const message = queuedMessage({ messageId: "message-restore", text: "queued text" });
|
||||
const draftKey = `${message.environmentId}:${message.threadId}`;
|
||||
appAtomRegistry.set(composerDrafts.composerDraftsAtom, {
|
||||
[draftKey]: { text: "typed offline", attachments: [] },
|
||||
});
|
||||
await harness.manager.enqueue(message);
|
||||
|
||||
harness.draftFile.setWriteError(new Error("disk full"));
|
||||
await expect(restoreRejectedQueuedMessage(message, "too large")).resolves.toBe("retry");
|
||||
|
||||
// The merge was rolled back and the message stayed queued for the retry.
|
||||
expect(composerDrafts.getComposerDraftSnapshot(draftKey).text).toBe("typed offline");
|
||||
expect(remainingMessages()).toEqual([message]);
|
||||
|
||||
harness.draftFile.setWriteError(null);
|
||||
await expect(restoreRejectedQueuedMessage(message, "too large")).resolves.toBe("restored");
|
||||
|
||||
// The recovered text landed exactly once and the message left the queue.
|
||||
expect(composerDrafts.getComposerDraftSnapshot(draftKey).text).toBe(
|
||||
"typed offline\n\nqueued text",
|
||||
);
|
||||
expect(remainingMessages()).toEqual([]);
|
||||
expect(harness.setPendingConnectionError).toHaveBeenCalledWith("too large");
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
type MessageId,
|
||||
} from "@t3tools/contracts";
|
||||
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
|
||||
@@ -15,36 +16,56 @@ import * as Cause from "effect/Cause";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { scopedThreadKey } from "../lib/scopedEntities";
|
||||
import { scopedProjectKey, scopedThreadKey } from "../lib/scopedEntities";
|
||||
import { buildProjectThreadStartTurnInput } from "../lib/projectThreadStartTurn";
|
||||
import { toUploadChatImageAttachments } from "../lib/composerImages";
|
||||
import { prepareTurnAttachments, type PreparedTurnAttachments } from "../lib/attachmentUpload";
|
||||
import { randomHex } from "../lib/uuid";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { useProjects, useThreadShells } from "./entities";
|
||||
import { useProjects, useServerConfigs, useThreadShells } from "./entities";
|
||||
import {
|
||||
confirmThreadOutboxMessageQueued,
|
||||
ensureThreadOutboxLoaded,
|
||||
removeThreadOutboxMessage,
|
||||
threadOutboxManager,
|
||||
threadOutboxRevision,
|
||||
updateThreadOutboxMessage,
|
||||
} from "./thread-outbox";
|
||||
import { removeThreadOutboxMessage } from "./thread-outbox-removal";
|
||||
import {
|
||||
isQueuedThreadCreationSendable,
|
||||
modelSelectionsEqual,
|
||||
resolveThreadOutboxDeliveryAction,
|
||||
resolveThreadOutboxDispatchStep,
|
||||
resolveThreadOutboxFailureAction,
|
||||
resolveQueuedThreadSettings,
|
||||
shouldRetryThreadOutboxDelivery,
|
||||
threadOutboxRetryDelayMs,
|
||||
type QueuedThreadCreation,
|
||||
type QueuedThreadMessage,
|
||||
type ThreadOutboxCommandStage,
|
||||
} from "./thread-outbox-model";
|
||||
import { threadEnvironment } from "./threads";
|
||||
import { environmentThreadShells, threadEnvironment } from "./threads";
|
||||
import {
|
||||
appendComposerDraftAttachments,
|
||||
composerDraftsAtom,
|
||||
flushComposerDrafts,
|
||||
type ComposerDraft,
|
||||
getComposerDraftSnapshot,
|
||||
mergeComposerDraftContent,
|
||||
replaceComposerDraftAttachments,
|
||||
undoComposerDraftMerge,
|
||||
updateComposerDraftSettings,
|
||||
waitForComposerDraftsLoaded,
|
||||
} from "./use-composer-drafts";
|
||||
import { useAtomCommand } from "./use-atom-command";
|
||||
import {
|
||||
editingQueuedMessageIdsAtom,
|
||||
useThreadOutboxMessages,
|
||||
useThreadOutboxShellStatuses,
|
||||
} from "./use-thread-outbox";
|
||||
import { useRemoteConnectionStatus } from "./use-remote-environment-registry";
|
||||
import {
|
||||
setPendingConnectionError,
|
||||
useRemoteConnectionStatus,
|
||||
} from "./use-remote-environment-registry";
|
||||
|
||||
export const dispatchingQueuedMessageIdAtom = Atom.make<MessageId | null>(null).pipe(
|
||||
Atom.keepAlive,
|
||||
@@ -85,6 +106,384 @@ function settingsCommandId(message: QueuedThreadMessage, setting: string): Comma
|
||||
return CommandId.make(`${message.commandId}:${setting}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads a queued message's attachments and persists the uploaded ids back
|
||||
* onto the queued message. The revision-checked update means an edit accepted
|
||||
* while the bytes uploaded wins: this attempt abandons and the next drain pass
|
||||
* re-reads the message.
|
||||
* `deliveryRevision` is the revision of the payload this attempt will send,
|
||||
* used for the delivery removal's compare-and-set.
|
||||
*/
|
||||
export async function prepareQueuedMessageAttachments(queuedMessage: QueuedThreadMessage): Promise<
|
||||
| {
|
||||
readonly status: "ready";
|
||||
readonly prepared: PreparedTurnAttachments;
|
||||
readonly persistedMessage: QueuedThreadMessage;
|
||||
readonly deliveryRevision: number;
|
||||
}
|
||||
| { readonly status: "abandoned" }
|
||||
> {
|
||||
if (!(await confirmThreadOutboxMessageQueued(queuedMessage))) {
|
||||
return { status: "abandoned" };
|
||||
}
|
||||
const revision = threadOutboxRevision(queuedMessage.messageId);
|
||||
if (!isQueuedMessagePayloadCurrent(queuedMessage, revision)) {
|
||||
return { status: "abandoned" };
|
||||
}
|
||||
let persistedMessage = queuedMessage;
|
||||
let deliveryRevision = revision;
|
||||
const result = await prepareTurnAttachments({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
attachments: queuedMessage.attachments,
|
||||
persistUploadedReferences: async (draftAttachments) => {
|
||||
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
|
||||
return "abandon";
|
||||
}
|
||||
const updatedMessage = { ...queuedMessage, attachments: draftAttachments };
|
||||
if (!(await updateThreadOutboxMessage(updatedMessage, revision))) {
|
||||
return "abandon";
|
||||
}
|
||||
persistedMessage = updatedMessage;
|
||||
deliveryRevision = revision + 1;
|
||||
return "persisted";
|
||||
},
|
||||
});
|
||||
if (
|
||||
result.status === "abandoned" ||
|
||||
!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)
|
||||
) {
|
||||
return { status: "abandoned" };
|
||||
}
|
||||
return { status: "ready", prepared: result, persistedMessage, deliveryRevision };
|
||||
}
|
||||
|
||||
function isQueuedMessagePayloadCurrent(
|
||||
message: QueuedThreadMessage,
|
||||
expectedRevision: number,
|
||||
): boolean {
|
||||
return (
|
||||
threadOutboxRevision(message.messageId) === expectedRevision &&
|
||||
Object.values(appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom))
|
||||
.flat()
|
||||
.some((candidate) => candidate === message)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a delivered message from the outbox. The revision and editor checks
|
||||
* preserve a creation payload when its pending-task editor owns newer work.
|
||||
* The outcome tells the caller whether removal completed, ownership changed,
|
||||
* or storage cleanup failed. Exported for tests.
|
||||
*/
|
||||
export async function completeQueuedMessageDelivery(
|
||||
queuedMessage: QueuedThreadMessage,
|
||||
deliveryRevision: number,
|
||||
): Promise<"removed" | "edited" | "failed"> {
|
||||
// The editor may have taken the entry while startTurn was in flight; its
|
||||
// unsaved edits have not bumped the revision yet, so the CAS alone would
|
||||
// let removal win and the editor would lose them once it saves.
|
||||
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
|
||||
return "edited";
|
||||
}
|
||||
try {
|
||||
// Removal also releases the message's local attachment files.
|
||||
const removed = await removeThreadOutboxMessage(
|
||||
queuedMessage,
|
||||
deliveryRevision,
|
||||
() => !appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId],
|
||||
);
|
||||
if (!removed) {
|
||||
console.warn(
|
||||
"[thread-outbox] delivered message was edited before cleanup; keeping the newer message",
|
||||
{
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
},
|
||||
);
|
||||
return "edited";
|
||||
}
|
||||
return "removed";
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to remove delivered queued message", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return "failed";
|
||||
}
|
||||
}
|
||||
|
||||
/** Retries local cleanup for an existing-thread send acknowledged in this drain lifetime. */
|
||||
export async function removeAcknowledgedExistingThreadMessage(
|
||||
queuedMessage: QueuedThreadMessage,
|
||||
acknowledgedMessageIds: Set<MessageId>,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const removed = await removeThreadOutboxMessage(queuedMessage);
|
||||
if (removed) {
|
||||
acknowledgedMessageIds.delete(queuedMessage.messageId);
|
||||
}
|
||||
return removed;
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to remove acknowledged queued message", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A creation delivered its startTurn but an edit won the cleanup race, so the
|
||||
* edited payload is still queued. The next drain would see the created thread
|
||||
* and take the creation "remove" path, silently discarding the edit; hand the
|
||||
* edited content to the new thread's composer instead and remove the entry.
|
||||
* Returns true when recovery is complete or an open editor owns the next
|
||||
* action, and false when the drain should retry with backoff.
|
||||
* Exported for tests; the drain is the only production caller.
|
||||
*/
|
||||
export async function recoverEditedCreationAfterDelivery(
|
||||
queuedMessage: QueuedThreadMessage,
|
||||
): Promise<boolean> {
|
||||
const kept = Object.values(appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom))
|
||||
.flat()
|
||||
.find((candidate) => candidate.messageId === queuedMessage.messageId);
|
||||
if (!kept) {
|
||||
return true;
|
||||
}
|
||||
const keptRevision = threadOutboxRevision(kept.messageId);
|
||||
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[kept.messageId]) {
|
||||
return true;
|
||||
}
|
||||
const draftKey = scopedThreadKey(kept.environmentId, kept.threadId);
|
||||
try {
|
||||
// Merge before removing: the draft's reference keeps the removal sweep
|
||||
// from deleting the attachment files. allowOverflow mirrors the
|
||||
// send-failure restore; the send path refuses over-cap drafts, so the
|
||||
// state stays recoverable.
|
||||
await mergeComposerDraftContent(draftKey, { text: kept.text, attachments: [] });
|
||||
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[kept.messageId]) {
|
||||
return true;
|
||||
}
|
||||
if (threadOutboxRevision(kept.messageId) !== keptRevision) {
|
||||
return false;
|
||||
}
|
||||
const existingAttachmentIds = new Set(
|
||||
getComposerDraftSnapshot(draftKey).attachments.map((attachment) => attachment.id),
|
||||
);
|
||||
appendComposerDraftAttachments(
|
||||
draftKey,
|
||||
kept.attachments.filter((attachment) => !existingAttachmentIds.has(attachment.id)),
|
||||
{ allowOverflow: true },
|
||||
);
|
||||
// Only settings the queued message actually carries: spreading explicit
|
||||
// undefined would clear choices the user already made on the draft.
|
||||
updateComposerDraftSettings(draftKey, {
|
||||
...(kept.modelSelection !== undefined ? { modelSelection: kept.modelSelection } : {}),
|
||||
...(kept.runtimeMode !== undefined ? { runtimeMode: kept.runtimeMode } : {}),
|
||||
...(kept.interactionMode !== undefined ? { interactionMode: kept.interactionMode } : {}),
|
||||
});
|
||||
// The append only schedules a debounced write; the queue entry is the
|
||||
// only durable copy until the draft lands, so flush before removing.
|
||||
await flushComposerDrafts();
|
||||
} catch (error) {
|
||||
// Keep the entry queued. The drain retries with backoff, and the merge is
|
||||
// idempotent so content that persisted before the failure is not repeated.
|
||||
console.warn("[thread-outbox] could not hand an edited pending task to the composer", error);
|
||||
return false;
|
||||
}
|
||||
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[kept.messageId]) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
return await removeThreadOutboxMessage(
|
||||
kept,
|
||||
keptRevision,
|
||||
() => !appAtomRegistry.get(editingQueuedMessageIdsAtom)[kept.messageId],
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] could not remove recovered pending task", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Exported for tests; the drain is the only production caller. */
|
||||
export async function restoreRejectedQueuedMessage(
|
||||
queuedMessage: QueuedThreadMessage,
|
||||
message: string,
|
||||
): Promise<"restored" | "deferred" | "blocked" | "retry"> {
|
||||
const draftKey = recoveryDraftKey(queuedMessage);
|
||||
// Set once the merge publishes, cleared once the queued message is removed.
|
||||
// The catch below uses it to take the merged content back out, so a retry
|
||||
// after a mid-recovery failure cannot append the recovered text again.
|
||||
let rollback: { readonly snapshot: ComposerDraft; readonly merged: ComposerDraft } | null = null;
|
||||
try {
|
||||
if (
|
||||
appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId] ||
|
||||
!(await confirmThreadOutboxMessageQueued(queuedMessage)) ||
|
||||
appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]
|
||||
) {
|
||||
return "deferred";
|
||||
}
|
||||
// The confirmation above checked this exact payload is what is queued, so
|
||||
// the current revision guards the removal at the end against an edit
|
||||
// accepted while this recovery ran.
|
||||
const revision = threadOutboxRevision(queuedMessage.messageId);
|
||||
|
||||
await waitForComposerDraftsLoaded();
|
||||
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
|
||||
return "deferred";
|
||||
}
|
||||
const originalDraft = getComposerDraftSnapshot(draftKey);
|
||||
const existingAttachmentIds = new Set(
|
||||
originalDraft.attachments.map((attachment) => attachment.id),
|
||||
);
|
||||
const addedAttachmentCount = queuedMessage.attachments.filter(
|
||||
(attachment) => !existingAttachmentIds.has(attachment.id),
|
||||
).length;
|
||||
if (existingAttachmentIds.size + addedAttachmentCount > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
|
||||
setPendingConnectionError(
|
||||
`Remove attachments from the draft before restoring this message. Messages can contain at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,
|
||||
);
|
||||
return "blocked";
|
||||
}
|
||||
|
||||
let mergedDraft: ComposerDraft;
|
||||
try {
|
||||
await mergeComposerDraftContent(draftKey, {
|
||||
text: queuedMessage.text,
|
||||
attachments: queuedMessage.attachments,
|
||||
});
|
||||
} finally {
|
||||
// Snapshots for the rollbacks below: undoComposerDraftMerge restores
|
||||
// the original draft only while it is untouched, and otherwise takes
|
||||
// out just what this recovery inserted so edits typed during the awaits
|
||||
// survive. Captured in a finally because mergeComposerDraftContent
|
||||
// publishes before its persistence await: even its failure leaves the
|
||||
// merged content in the draft.
|
||||
mergedDraft = getComposerDraftSnapshot(draftKey);
|
||||
rollback = { snapshot: originalDraft, merged: mergedDraft };
|
||||
}
|
||||
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
|
||||
await undoComposerDraftMerge(draftKey, originalDraft, mergedDraft);
|
||||
return "deferred";
|
||||
}
|
||||
updateComposerDraftSettings(draftKey, {
|
||||
...(queuedMessage.modelSelection ? { modelSelection: queuedMessage.modelSelection } : {}),
|
||||
...(queuedMessage.runtimeMode ? { runtimeMode: queuedMessage.runtimeMode } : {}),
|
||||
...(queuedMessage.interactionMode ? { interactionMode: queuedMessage.interactionMode } : {}),
|
||||
...(queuedMessage.creation
|
||||
? {
|
||||
workspaceSelection: {
|
||||
mode: queuedMessage.creation.workspaceMode,
|
||||
branch: queuedMessage.creation.branch,
|
||||
worktreePath: queuedMessage.creation.worktreePath,
|
||||
...(queuedMessage.creation.startFromOrigin !== undefined
|
||||
? { startFromOrigin: queuedMessage.creation.startFromOrigin }
|
||||
: {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
const restoredDraft = getComposerDraftSnapshot(draftKey);
|
||||
rollback = { snapshot: originalDraft, merged: restoredDraft };
|
||||
await flushComposerDrafts();
|
||||
if (
|
||||
appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId] ||
|
||||
!(await confirmThreadOutboxMessageQueued(queuedMessage)) ||
|
||||
appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]
|
||||
) {
|
||||
await undoComposerDraftMerge(draftKey, originalDraft, restoredDraft);
|
||||
return "deferred";
|
||||
}
|
||||
// Revision-checked: an edit that landed after the confirmation above
|
||||
// must not be deleted with the pre-edit payload this recovery restored.
|
||||
if (
|
||||
!(await removeThreadOutboxMessage(
|
||||
queuedMessage,
|
||||
revision,
|
||||
() => !appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId],
|
||||
))
|
||||
) {
|
||||
await undoComposerDraftMerge(draftKey, originalDraft, restoredDraft);
|
||||
return "deferred";
|
||||
}
|
||||
// The queued message is gone; from here the draft owns the content and
|
||||
// must never be rolled back.
|
||||
rollback = null;
|
||||
setPendingConnectionError(message);
|
||||
return "restored";
|
||||
} catch (error) {
|
||||
if (rollback !== null) {
|
||||
// Take the recovered content back out (keeping edits typed since) so
|
||||
// the retry's merge starts clean instead of appending a duplicate. The
|
||||
// in-memory rollback lands even when its own persistence write fails.
|
||||
await undoComposerDraftMerge(draftKey, rollback.snapshot, rollback.merged).catch(
|
||||
(undoError) => {
|
||||
console.warn("[thread-outbox] failed to persist a recovery rollback", undoError);
|
||||
},
|
||||
);
|
||||
}
|
||||
console.warn("[thread-outbox] failed to restore an undeliverable message", error);
|
||||
setPendingConnectionError(
|
||||
error instanceof Error ? error.message : "The unsent message could not be restored.",
|
||||
);
|
||||
return "retry";
|
||||
}
|
||||
}
|
||||
|
||||
function recoveryDraftKey(queuedMessage: QueuedThreadMessage): string {
|
||||
return queuedMessage.creation
|
||||
? `new-task:${scopedProjectKey(queuedMessage.environmentId, queuedMessage.creation.projectId)}`
|
||||
: scopedThreadKey(queuedMessage.environmentId, queuedMessage.threadId);
|
||||
}
|
||||
|
||||
async function preserveUploadedAttachmentsForEditor(
|
||||
originalMessage: QueuedThreadMessage,
|
||||
uploadedMessage: QueuedThreadMessage,
|
||||
): Promise<void> {
|
||||
if (!originalMessage.creation) {
|
||||
return;
|
||||
}
|
||||
|
||||
const draftKey = `pending-task:${originalMessage.messageId}`;
|
||||
const draft = getComposerDraftSnapshot(draftKey);
|
||||
const uploadedById = new Map(
|
||||
uploadedMessage.attachments
|
||||
.filter((attachment) => attachment.type === "file")
|
||||
.map((attachment) => [attachment.id, attachment] as const),
|
||||
);
|
||||
let changed = false;
|
||||
const nextAttachments = draft.attachments.map((attachment) => {
|
||||
if (attachment.type !== "file") {
|
||||
return attachment;
|
||||
}
|
||||
const uploaded = uploadedById.get(attachment.id);
|
||||
if (
|
||||
!uploaded?.uploadedAttachmentId ||
|
||||
uploaded.uploadEnvironmentId !== originalMessage.environmentId ||
|
||||
(attachment.uploadedAttachmentId === uploaded.uploadedAttachmentId &&
|
||||
attachment.uploadEnvironmentId === uploaded.uploadEnvironmentId)
|
||||
) {
|
||||
return attachment;
|
||||
}
|
||||
changed = true;
|
||||
return {
|
||||
...attachment,
|
||||
uploadedAttachmentId: uploaded.uploadedAttachmentId,
|
||||
uploadEnvironmentId: uploaded.uploadEnvironmentId,
|
||||
};
|
||||
});
|
||||
if (changed) {
|
||||
replaceComposerDraftAttachments(draftKey, nextAttachments);
|
||||
await flushComposerDrafts();
|
||||
}
|
||||
}
|
||||
|
||||
export function useThreadOutboxDrain(): void {
|
||||
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
|
||||
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
|
||||
@@ -102,11 +501,76 @@ export function useThreadOutboxDrain(): void {
|
||||
const shellStatuses = useThreadOutboxShellStatuses();
|
||||
const threads = useThreadShells();
|
||||
const projects = useProjects();
|
||||
const serverConfigs = useServerConfigs();
|
||||
const { connectedEnvironments } = useRemoteConnectionStatus();
|
||||
const [retryTick, setRetryTick] = useState(0);
|
||||
const retryAttemptRef = useRef(new Map<MessageId, number>());
|
||||
const retryNotBeforeRef = useRef(new Map<MessageId, number>());
|
||||
const retryTimersRef = useRef(new Map<MessageId, ReturnType<typeof setTimeout>>());
|
||||
const acknowledgedExistingThreadMessageIdsRef = useRef(new Set<MessageId>());
|
||||
const blockedRecoverySubscriptionsRef = useRef(
|
||||
new Map<
|
||||
MessageId,
|
||||
{ readonly message: QueuedThreadMessage; readonly unsubscribe: () => void }
|
||||
>(),
|
||||
);
|
||||
|
||||
const scheduleQueuedMessageRetry = useCallback((messageId: MessageId) => {
|
||||
const retryAttempt = (retryAttemptRef.current.get(messageId) ?? 0) + 1;
|
||||
retryAttemptRef.current.set(messageId, retryAttempt);
|
||||
const retryDelayMs = threadOutboxRetryDelayMs(retryAttempt);
|
||||
retryNotBeforeRef.current.set(messageId, Date.now() + retryDelayMs);
|
||||
const pendingTimer = retryTimersRef.current.get(messageId);
|
||||
if (pendingTimer !== undefined) {
|
||||
clearTimeout(pendingTimer);
|
||||
}
|
||||
const retryTimer = setTimeout(() => {
|
||||
retryTimersRef.current.delete(messageId);
|
||||
setRetryTick((current) => current + 1);
|
||||
}, retryDelayMs);
|
||||
retryTimersRef.current.set(messageId, retryTimer);
|
||||
}, []);
|
||||
|
||||
const restoreQueuedMessage = useCallback(
|
||||
async (queuedMessage: QueuedThreadMessage, message: string): Promise<boolean> => {
|
||||
const result = await restoreRejectedQueuedMessage(queuedMessage, message);
|
||||
if (result !== "blocked") {
|
||||
return result !== "retry";
|
||||
}
|
||||
|
||||
if (!blockedRecoverySubscriptionsRef.current.has(queuedMessage.messageId)) {
|
||||
const draftKey = recoveryDraftKey(queuedMessage);
|
||||
const editorDraftKey = queuedMessage.creation
|
||||
? `pending-task:${queuedMessage.messageId}`
|
||||
: null;
|
||||
const currentDrafts = appAtomRegistry.get(composerDraftsAtom);
|
||||
const blockedAttachments = currentDrafts[draftKey]?.attachments;
|
||||
const editorAttachments =
|
||||
editorDraftKey === null ? undefined : currentDrafts[editorDraftKey]?.attachments;
|
||||
const unsubscribe = appAtomRegistry.subscribe(composerDraftsAtom, (drafts) => {
|
||||
if (
|
||||
drafts[draftKey]?.attachments === blockedAttachments &&
|
||||
(editorDraftKey === null || drafts[editorDraftKey]?.attachments === editorAttachments)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const active = blockedRecoverySubscriptionsRef.current.get(queuedMessage.messageId);
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
blockedRecoverySubscriptionsRef.current.delete(queuedMessage.messageId);
|
||||
active.unsubscribe();
|
||||
setRetryTick((current) => current + 1);
|
||||
});
|
||||
blockedRecoverySubscriptionsRef.current.set(queuedMessage.messageId, {
|
||||
message: queuedMessage,
|
||||
unsubscribe,
|
||||
});
|
||||
}
|
||||
return true;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
ensureThreadOutboxLoaded();
|
||||
@@ -115,6 +579,10 @@ export function useThreadOutboxDrain(): void {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
retryTimersRef.current.clear();
|
||||
for (const blocked of blockedRecoverySubscriptionsRef.current.values()) {
|
||||
blocked.unsubscribe();
|
||||
}
|
||||
blockedRecoverySubscriptionsRef.current.clear();
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -122,53 +590,36 @@ export function useThreadOutboxDrain(): void {
|
||||
const reportFailure = (
|
||||
commandResult: AtomCommandResult<unknown, unknown>,
|
||||
stage: ThreadOutboxCommandStage,
|
||||
): boolean => {
|
||||
): { readonly action: "retry" | "restore"; readonly message: string } | null => {
|
||||
if (!AsyncResult.isFailure(commandResult)) {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
const error = Cause.squash(commandResult.cause);
|
||||
const action = resolveThreadOutboxFailureAction({
|
||||
stage,
|
||||
error: Cause.squash(commandResult.cause),
|
||||
error,
|
||||
interrupted: Cause.hasInterruptsOnly(commandResult.cause),
|
||||
});
|
||||
const retry = action === "retry";
|
||||
console.warn("[thread-outbox] queued message delivery failed", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
stage,
|
||||
cause: commandResult.cause,
|
||||
retry,
|
||||
action,
|
||||
});
|
||||
return retry;
|
||||
return {
|
||||
action,
|
||||
message: error instanceof Error ? error.message : "The message could not be sent.",
|
||||
};
|
||||
};
|
||||
const completeDelivery = async (
|
||||
deliveryResult: AtomCommandResult<unknown, unknown>,
|
||||
): Promise<boolean> => {
|
||||
if (reportFailure(deliveryResult, "start-turn")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await removeThreadOutboxMessage(queuedMessage);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to remove delivered queued message", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
return { reportFailure, completeDelivery };
|
||||
return { reportFailure };
|
||||
}, []);
|
||||
|
||||
const sendQueuedMessage = useCallback(
|
||||
async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
|
||||
const settings = resolveQueuedThreadSettings(queuedMessage, thread);
|
||||
const { reportFailure, completeDelivery } = makeDeliveryHelpers(queuedMessage);
|
||||
const { reportFailure } = makeDeliveryHelpers(queuedMessage);
|
||||
|
||||
if (!modelSelectionsEqual(settings.modelSelection, thread.modelSelection)) {
|
||||
const updateResult = await updateThreadMetadata({
|
||||
@@ -217,6 +668,37 @@ export function useThreadOutboxDrain(): void {
|
||||
}
|
||||
}
|
||||
|
||||
let prepared: PreparedTurnAttachments;
|
||||
let persistedMessage: QueuedThreadMessage;
|
||||
let deliveryRevision: number;
|
||||
try {
|
||||
const preparedResult = await prepareQueuedMessageAttachments(queuedMessage);
|
||||
if (preparedResult.status === "abandoned") {
|
||||
return true;
|
||||
}
|
||||
prepared = preparedResult.prepared;
|
||||
persistedMessage = preparedResult.persistedMessage;
|
||||
deliveryRevision = preparedResult.deliveryRevision;
|
||||
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
|
||||
await preserveUploadedAttachmentsForEditor(
|
||||
queuedMessage,
|
||||
preparedResult.persistedMessage,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to upload attachments", error);
|
||||
if (!shouldRetryThreadOutboxDelivery(error)) {
|
||||
return restoreQueuedMessage(
|
||||
queuedMessage,
|
||||
error instanceof Error ? error.message : "An attachment could not upload.",
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) {
|
||||
return true;
|
||||
}
|
||||
const deliveryResult = await startTurn({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
@@ -226,7 +708,7 @@ export function useThreadOutboxDrain(): void {
|
||||
messageId: queuedMessage.messageId,
|
||||
role: "user",
|
||||
text: queuedMessage.text,
|
||||
attachments: toUploadChatImageAttachments(queuedMessage.attachments),
|
||||
attachments: prepared.attachments,
|
||||
},
|
||||
modelSelection: settings.modelSelection,
|
||||
runtimeMode: settings.runtimeMode,
|
||||
@@ -234,7 +716,26 @@ export function useThreadOutboxDrain(): void {
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
return completeDelivery(deliveryResult);
|
||||
const failure = reportFailure(deliveryResult, "start-turn");
|
||||
if (failure?.action === "retry") {
|
||||
return false;
|
||||
}
|
||||
if (failure?.action === "restore") {
|
||||
return restoreQueuedMessage(persistedMessage, failure.message);
|
||||
}
|
||||
acknowledgedExistingThreadMessageIdsRef.current.add(persistedMessage.messageId);
|
||||
const delivered =
|
||||
(await completeQueuedMessageDelivery(persistedMessage, deliveryRevision)) === "removed";
|
||||
if (delivered) {
|
||||
acknowledgedExistingThreadMessageIdsRef.current.delete(persistedMessage.messageId);
|
||||
// The delivered turn holds its own copy of the bytes. A failed delete
|
||||
// is surfaced (never fails the delivered turn); the server also
|
||||
// expires leaked pending uploads.
|
||||
await prepared.releaseUploads().catch((error) => {
|
||||
console.warn("[thread-outbox] could not delete consumed pending uploads", error);
|
||||
});
|
||||
}
|
||||
return delivered;
|
||||
},
|
||||
[
|
||||
makeDeliveryHelpers,
|
||||
@@ -242,6 +743,7 @@ export function useThreadOutboxDrain(): void {
|
||||
setThreadRuntimeMode,
|
||||
startTurn,
|
||||
updateThreadMetadata,
|
||||
restoreQueuedMessage,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -255,7 +757,37 @@ export function useThreadOutboxDrain(): void {
|
||||
if (modelSelection === undefined) {
|
||||
return false;
|
||||
}
|
||||
const { completeDelivery } = makeDeliveryHelpers(queuedMessage);
|
||||
let prepared: PreparedTurnAttachments;
|
||||
let persistedMessage: QueuedThreadMessage;
|
||||
let deliveryRevision: number;
|
||||
try {
|
||||
const preparedResult = await prepareQueuedMessageAttachments(queuedMessage);
|
||||
if (preparedResult.status === "abandoned") {
|
||||
return true;
|
||||
}
|
||||
prepared = preparedResult.prepared;
|
||||
persistedMessage = preparedResult.persistedMessage;
|
||||
deliveryRevision = preparedResult.deliveryRevision;
|
||||
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
|
||||
await preserveUploadedAttachmentsForEditor(
|
||||
queuedMessage,
|
||||
preparedResult.persistedMessage,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to upload attachments", error);
|
||||
if (!shouldRetryThreadOutboxDelivery(error)) {
|
||||
return restoreQueuedMessage(
|
||||
queuedMessage,
|
||||
error instanceof Error ? error.message : "An attachment could not upload.",
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) {
|
||||
return true;
|
||||
}
|
||||
const deliveryResult = await startTurn({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: buildProjectThreadStartTurnInput({
|
||||
@@ -267,6 +799,7 @@ export function useThreadOutboxDrain(): void {
|
||||
createdAt: queuedMessage.createdAt,
|
||||
text: queuedMessage.text.trim(),
|
||||
attachments: queuedMessage.attachments,
|
||||
uploadedAttachments: prepared.attachments,
|
||||
modelSelection,
|
||||
runtimeMode: queuedMessage.runtimeMode ?? DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: queuedMessage.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
@@ -277,9 +810,35 @@ export function useThreadOutboxDrain(): void {
|
||||
worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex),
|
||||
}),
|
||||
});
|
||||
return completeDelivery(deliveryResult);
|
||||
const { reportFailure } = makeDeliveryHelpers(queuedMessage);
|
||||
const failure = reportFailure(deliveryResult, "start-turn");
|
||||
if (failure?.action === "retry") {
|
||||
return false;
|
||||
}
|
||||
if (failure?.action === "restore") {
|
||||
return restoreQueuedMessage(persistedMessage, failure.message);
|
||||
}
|
||||
const outcome = await completeQueuedMessageDelivery(persistedMessage, deliveryRevision);
|
||||
if (outcome === "edited") {
|
||||
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
|
||||
// The editor holds the entry with unsaved edits; merging the queue
|
||||
// payload now would duplicate the delivered turn. Once the editor
|
||||
// saves, the duplicate-creation removal below recovers the edits.
|
||||
return true;
|
||||
}
|
||||
// The thread exists now, so the next drain would remove the edited
|
||||
// payload as a duplicate creation. Hand it to the thread's composer.
|
||||
return recoverEditedCreationAfterDelivery(persistedMessage);
|
||||
}
|
||||
if (outcome === "removed") {
|
||||
await prepared.releaseUploads().catch((error) => {
|
||||
console.warn("[thread-outbox] could not delete consumed pending uploads", error);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
[makeDeliveryHelpers, startTurn],
|
||||
[makeDeliveryHelpers, restoreQueuedMessage, startTurn],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -287,14 +846,63 @@ export function useThreadOutboxDrain(): void {
|
||||
return;
|
||||
}
|
||||
|
||||
const queuedMessageIds = new Set(
|
||||
Object.values(queuedMessagesByThreadKey)
|
||||
.flat()
|
||||
.map((message) => message.messageId),
|
||||
);
|
||||
for (const messageId of acknowledgedExistingThreadMessageIdsRef.current) {
|
||||
if (!queuedMessageIds.has(messageId)) {
|
||||
acknowledgedExistingThreadMessageIdsRef.current.delete(messageId);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [threadKey, queuedMessages] of Object.entries(queuedMessagesByThreadKey)) {
|
||||
const nextQueuedMessage = queuedMessages[0];
|
||||
if (!nextQueuedMessage) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
nextQueuedMessage.creation === undefined &&
|
||||
acknowledgedExistingThreadMessageIdsRef.current.has(nextQueuedMessage.messageId)
|
||||
) {
|
||||
if ((retryNotBeforeRef.current.get(nextQueuedMessage.messageId) ?? 0) > Date.now()) {
|
||||
continue;
|
||||
}
|
||||
beginDispatchingQueuedMessage(nextQueuedMessage.messageId);
|
||||
void removeAcknowledgedExistingThreadMessage(
|
||||
nextQueuedMessage,
|
||||
acknowledgedExistingThreadMessageIdsRef.current,
|
||||
)
|
||||
.then((removed) => {
|
||||
if (!removed) {
|
||||
scheduleQueuedMessageRetry(nextQueuedMessage.messageId);
|
||||
return;
|
||||
}
|
||||
retryAttemptRef.current.delete(nextQueuedMessage.messageId);
|
||||
retryNotBeforeRef.current.delete(nextQueuedMessage.messageId);
|
||||
const pendingTimer = retryTimersRef.current.get(nextQueuedMessage.messageId);
|
||||
if (pendingTimer !== undefined) {
|
||||
clearTimeout(pendingTimer);
|
||||
retryTimersRef.current.delete(nextQueuedMessage.messageId);
|
||||
}
|
||||
})
|
||||
.finally(() => finishDispatchingQueuedMessage(nextQueuedMessage.messageId));
|
||||
return;
|
||||
}
|
||||
if (editingQueuedMessageIds[nextQueuedMessage.messageId]) {
|
||||
continue;
|
||||
}
|
||||
const blockedRecovery = blockedRecoverySubscriptionsRef.current.get(
|
||||
nextQueuedMessage.messageId,
|
||||
);
|
||||
if (blockedRecovery) {
|
||||
if (blockedRecovery.message === nextQueuedMessage) {
|
||||
continue;
|
||||
}
|
||||
blockedRecoverySubscriptionsRef.current.delete(nextQueuedMessage.messageId);
|
||||
blockedRecovery.unsubscribe();
|
||||
}
|
||||
if ((retryNotBeforeRef.current.get(nextQueuedMessage.messageId) ?? 0) > Date.now()) {
|
||||
continue;
|
||||
}
|
||||
@@ -316,9 +924,53 @@ export function useThreadOutboxDrain(): void {
|
||||
environmentConnected: environment?.connectionState === "connected",
|
||||
threadBusy: thread?.session?.status === "running" || thread?.session?.status === "starting",
|
||||
});
|
||||
if (deliveryAction === "wait") {
|
||||
// The delivery action resolves first; the file-capability gate applies
|
||||
// only to a message that will send. Gating earlier would restore a
|
||||
// creation whose startTurn already made the thread as a duplicate draft
|
||||
// instead of removing it.
|
||||
const serverConfig = serverConfigs.get(nextQueuedMessage.environmentId);
|
||||
const dispatchStep = resolveThreadOutboxDispatchStep({
|
||||
deliveryAction,
|
||||
fileAttachments: nextQueuedMessage.attachments.filter(
|
||||
(attachment) => attachment.type === "file",
|
||||
),
|
||||
serverConfig: serverConfig
|
||||
? {
|
||||
maxFileUploadBytes:
|
||||
serverConfig.environment.capabilities.fileAttachments?.maxUploadBytes,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
if (dispatchStep.step === "wait") {
|
||||
continue;
|
||||
}
|
||||
if (dispatchStep.step === "retry") {
|
||||
// The environment is connected but its config has not synced yet.
|
||||
// Back off and retry instead of parking the message forever.
|
||||
scheduleQueuedMessageRetry(nextQueuedMessage.messageId);
|
||||
continue;
|
||||
}
|
||||
if (dispatchStep.step === "restore") {
|
||||
const attachmentError = dispatchStep.reason;
|
||||
beginDispatchingQueuedMessage(nextQueuedMessage.messageId);
|
||||
void confirmThreadOutboxMessageQueued(nextQueuedMessage)
|
||||
.then((queued) => {
|
||||
if (
|
||||
!queued ||
|
||||
appAtomRegistry.get(editingQueuedMessageIdsAtom)[nextQueuedMessage.messageId]
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return restoreQueuedMessage(nextQueuedMessage, attachmentError);
|
||||
})
|
||||
.then((restored) => {
|
||||
if (!restored) {
|
||||
scheduleQueuedMessageRetry(nextQueuedMessage.messageId);
|
||||
}
|
||||
})
|
||||
.finally(() => finishDispatchingQueuedMessage(nextQueuedMessage.messageId));
|
||||
return;
|
||||
}
|
||||
// The live project shell is preferred for the workspace path, with the
|
||||
// snapshot taken at enqueue time as the fallback so a task never dies
|
||||
// just because its project shell is not loaded.
|
||||
@@ -368,8 +1020,36 @@ export function useThreadOutboxDrain(): void {
|
||||
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[nextQueuedMessage.messageId]) {
|
||||
return true;
|
||||
}
|
||||
// The shell state is equally stale. Re-run the same delivery policy
|
||||
// against the live thread snapshot so a vanished thread or newly
|
||||
// created target defers, while busy existing threads can still steer.
|
||||
if (deliveryAction === "send") {
|
||||
const liveThread = findThread(
|
||||
appAtomRegistry.get(environmentThreadShells.threadShellsAtom),
|
||||
nextQueuedMessage,
|
||||
);
|
||||
const liveThreadBusy =
|
||||
liveThread?.session?.status === "running" || liveThread?.session?.status === "starting";
|
||||
const liveDeliveryAction = resolveThreadOutboxDeliveryAction({
|
||||
isCreation: creation !== undefined,
|
||||
threadExists: liveThread !== undefined,
|
||||
shellStatus,
|
||||
environmentConnected: environment?.connectionState === "connected",
|
||||
threadBusy: liveThreadBusy,
|
||||
});
|
||||
if (liveDeliveryAction !== "send") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return deliveryAction === "remove"
|
||||
? removeQueuedMessage("[thread-outbox] failed to remove message for a missing thread")
|
||||
? creation !== undefined
|
||||
? // A creation entry that survived its delivery cleanup either
|
||||
// holds edits (recover them) or the delivered payload (a
|
||||
// recovered duplicate the user can delete). Restart loses any
|
||||
// in-memory distinction, and losing edits is the worse failure,
|
||||
// so recovery is unconditional here.
|
||||
recoverEditedCreationAfterDelivery(nextQueuedMessage)
|
||||
: removeQueuedMessage("[thread-outbox] failed to remove message for a missing thread")
|
||||
: creation !== undefined
|
||||
? creationProjectCwd !== null
|
||||
? sendQueuedCreation(nextQueuedMessage, creation, creationProjectCwd)
|
||||
@@ -391,19 +1071,7 @@ export function useThreadOutboxDrain(): void {
|
||||
return;
|
||||
}
|
||||
|
||||
const retryAttempt = (retryAttemptRef.current.get(nextQueuedMessage.messageId) ?? 0) + 1;
|
||||
retryAttemptRef.current.set(nextQueuedMessage.messageId, retryAttempt);
|
||||
const retryDelayMs = threadOutboxRetryDelayMs(retryAttempt);
|
||||
retryNotBeforeRef.current.set(nextQueuedMessage.messageId, Date.now() + retryDelayMs);
|
||||
const pendingTimer = retryTimersRef.current.get(nextQueuedMessage.messageId);
|
||||
if (pendingTimer !== undefined) {
|
||||
clearTimeout(pendingTimer);
|
||||
}
|
||||
const retryTimer = setTimeout(() => {
|
||||
retryTimersRef.current.delete(nextQueuedMessage.messageId);
|
||||
setRetryTick((current) => current + 1);
|
||||
}, retryDelayMs);
|
||||
retryTimersRef.current.set(nextQueuedMessage.messageId, retryTimer);
|
||||
scheduleQueuedMessageRetry(nextQueuedMessage.messageId);
|
||||
})
|
||||
.finally(() => {
|
||||
finishDispatchingQueuedMessage(nextQueuedMessage.messageId);
|
||||
@@ -417,8 +1085,11 @@ export function useThreadOutboxDrain(): void {
|
||||
projects,
|
||||
queuedMessagesByThreadKey,
|
||||
retryTick,
|
||||
restoreQueuedMessage,
|
||||
scheduleQueuedMessageRetry,
|
||||
sendQueuedCreation,
|
||||
sendQueuedMessage,
|
||||
serverConfigs,
|
||||
shellStatuses,
|
||||
threads,
|
||||
]);
|
||||
|
||||
+10
-7
@@ -4,20 +4,23 @@ Messages can contain up to 120,000 characters. If a draft is longer, T3 Code kee
|
||||
composer and shows how many characters need to be removed. Shorten the draft or split it into
|
||||
multiple messages, then send again in the same thread.
|
||||
|
||||
You can attach images up to 10 MB. On servers that support file uploads, web and desktop can also
|
||||
You can attach images up to 10 MB. On servers that support file uploads, you can also
|
||||
attach text files, PDFs, ZIP archives, and other files. Each file can be up to the limit advertised
|
||||
by the server, capped at 50 MB. Each message can contain up to eight attachments in total. Files
|
||||
upload directly to the environment, where your agent can read, copy, or edit them by their file path.
|
||||
|
||||
On web and desktop, attachments upload as soon as you add them. The send button becomes available
|
||||
after every upload finishes. Failed uploads can be retried or removed. On mobile, attachments are
|
||||
currently limited to images.
|
||||
after every upload finishes. Failed uploads can be retried or removed. On mobile, the **+** control
|
||||
offers Photos, and adds Files when the connected server supports file uploads. You can share a file
|
||||
into T3 Code from any app through the system share sheet. Mobile uploads happen when the message
|
||||
sends, so queued messages keep their files until they deliver. Select a received file on mobile
|
||||
to save it or open it in another app through the system share sheet.
|
||||
|
||||
Select a video attachment before or after sending to play it with the browser's built-in controls.
|
||||
Playback depends on the video formats and codecs that the browser supports.
|
||||
On web and desktop, select a video attachment before or after sending to play it with the browser's
|
||||
built-in controls. Playback depends on the video formats and codecs that the browser supports.
|
||||
|
||||
If you reload before a file finishes uploading, the draft keeps the file's name and shows **Attach
|
||||
again** next to it. Attach the file again or remove it, then send.
|
||||
On web and desktop, if you reload before a file finishes uploading, the draft keeps the file's name
|
||||
and shows **Attach again** next to it. Attach the file again or remove it, then send.
|
||||
|
||||
On web and desktop, HEIC and HEIF photos are automatically converted to JPEG when you drag them into
|
||||
the composer or paste them into a message.
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
diff --git a/android/src/main/java/expo/modules/sharing/SharingRecords.kt b/android/src/main/java/expo/modules/sharing/SharingRecords.kt
|
||||
index 0b87b53f632e82f9b4c09c066d5a67e4ab2525a4..65f1c57faef3ba8caac9e137341f2b8312bb5f86 100644
|
||||
--- a/android/src/main/java/expo/modules/sharing/SharingRecords.kt
|
||||
+++ b/android/src/main/java/expo/modules/sharing/SharingRecords.kt
|
||||
@@ -52,7 +52,8 @@ enum class ContentType(val value: String) : Enumerable {
|
||||
internal data class SharePayload(
|
||||
@Field var value: String = "",
|
||||
@Field var shareType: ShareType = ShareType.Text,
|
||||
- @Field var mimeType: String = "text/plain"
|
||||
+ @Field var mimeType: String = "text/plain",
|
||||
+ @Field var originalName: String? = null
|
||||
) : Record
|
||||
|
||||
@OptimizedRecord
|
||||
diff --git a/android/src/main/java/expo/modules/sharing/dataParsers/SimpleShareIntentDataParser.kt b/android/src/main/java/expo/modules/sharing/dataParsers/SimpleShareIntentDataParser.kt
|
||||
index 8dd50e8f04022d183884a57e4d61a7e1711b9e49..481cdb4bc64ea5ae49919071f686324f6d56d55c 100644
|
||||
--- a/android/src/main/java/expo/modules/sharing/dataParsers/SimpleShareIntentDataParser.kt
|
||||
+++ b/android/src/main/java/expo/modules/sharing/dataParsers/SimpleShareIntentDataParser.kt
|
||||
@@ -3,6 +3,7 @@ package expo.modules.sharing
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
+import android.provider.OpenableColumns
|
||||
|
||||
internal class SimpleShareIntentDataParser {
|
||||
companion object {
|
||||
@@ -17,21 +18,26 @@ internal class SimpleShareIntentDataParser {
|
||||
}
|
||||
|
||||
private fun handleSendAction(context: Context, intent: Intent, type: String): List<SharePayload> {
|
||||
- return if (type == "text/plain") {
|
||||
- val text = intent.getStringExtra(Intent.EXTRA_TEXT) ?: return emptyList()
|
||||
- val isUrl = android.util.Patterns.WEB_URL.matcher(text).matches()
|
||||
-
|
||||
- listOf(
|
||||
+ val stream = intent.getParcelableExtraCompat<Uri>(Intent.EXTRA_STREAM)
|
||||
+ val text = intent.getStringExtra(Intent.EXTRA_TEXT)
|
||||
+ if (stream == null) {
|
||||
+ if (!type.startsWith("text/") || text == null) return emptyList()
|
||||
+ return listOf(
|
||||
SharePayload().apply {
|
||||
value = text
|
||||
- shareType = if (isUrl) ShareType.Url else ShareType.Text
|
||||
- mimeType = "text/plain"
|
||||
+ shareType = if (android.util.Patterns.WEB_URL.matcher(text).matches()) ShareType.Url else ShareType.Text
|
||||
+ mimeType = type
|
||||
}
|
||||
)
|
||||
- } else {
|
||||
- val uri = intent.getParcelableExtraCompat<Uri>(Intent.EXTRA_STREAM)
|
||||
- listOfNotNull(uri?.let { createUriPayload(context, it, type) })
|
||||
}
|
||||
+ val filePayload = createUriPayload(context, stream, type)
|
||||
+ if (text.isNullOrBlank()) return listOf(filePayload)
|
||||
+ val textPayload = SharePayload().apply {
|
||||
+ value = text
|
||||
+ shareType = if (android.util.Patterns.WEB_URL.matcher(text).matches()) ShareType.Url else ShareType.Text
|
||||
+ mimeType = "text/plain"
|
||||
+ }
|
||||
+ return listOf(textPayload, filePayload)
|
||||
}
|
||||
|
||||
private fun handleSendMultipleAction(context: Context, intent: Intent, type: String): List<SharePayload> {
|
||||
@@ -41,10 +47,25 @@ internal class SimpleShareIntentDataParser {
|
||||
|
||||
private fun createUriPayload(context: Context, uri: Uri, defaultType: String): SharePayload {
|
||||
val specificType = context.contentResolver.getType(uri) ?: defaultType
|
||||
+ // A blank DISPLAY_NAME must stay null: consumers treat originalName as
|
||||
+ // the attachment name, and an empty name fails contract validation.
|
||||
+ val displayName = runCatching {
|
||||
+ context.contentResolver.query(
|
||||
+ uri,
|
||||
+ arrayOf(OpenableColumns.DISPLAY_NAME),
|
||||
+ null,
|
||||
+ null,
|
||||
+ null
|
||||
+ )?.use { cursor ->
|
||||
+ val column = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
|
||||
+ if (column >= 0 && cursor.moveToFirst()) cursor.getString(column) else null
|
||||
+ }
|
||||
+ }.getOrNull()?.takeIf { it.isNotBlank() }
|
||||
return SharePayload().apply {
|
||||
value = uri.toString()
|
||||
- shareType = ShareType.fromMimeType(specificType)
|
||||
+ shareType = if (specificType.startsWith("text/")) ShareType.File else ShareType.fromMimeType(specificType)
|
||||
mimeType = specificType
|
||||
+ originalName = displayName
|
||||
}
|
||||
}
|
||||
}
|
||||
diff --git a/build/Sharing.types.d.ts b/build/Sharing.types.d.ts
|
||||
index e9820b061bddce91657ab7144fde98d0543a3b8e..364d63273cb3e209c6490de6dd869a01c8728fcc 100644
|
||||
--- a/build/Sharing.types.d.ts
|
||||
+++ b/build/Sharing.types.d.ts
|
||||
@@ -77,6 +77,11 @@ export type SharePayload = {
|
||||
* @default 'text/plain'
|
||||
*/
|
||||
mimeType?: string;
|
||||
+ /**
|
||||
+ * The display name of a shared file, when the source app provided one.
|
||||
+ * Populated on Android from the content resolver's `DISPLAY_NAME`.
|
||||
+ */
|
||||
+ originalName?: string | null;
|
||||
};
|
||||
export type BaseResolvedSharePayload = SharePayload & {
|
||||
/**
|
||||
diff --git a/src/Sharing.types.ts b/src/Sharing.types.ts
|
||||
index d9a5ad38f5fe2856b365eb91b71abd640314a5cc..21ea45f04b88cce272e2e02de24c5e4eb8157e82 100644
|
||||
--- a/src/Sharing.types.ts
|
||||
+++ b/src/Sharing.types.ts
|
||||
@@ -85,6 +85,12 @@ export type SharePayload = {
|
||||
* @default 'text/plain'
|
||||
*/
|
||||
mimeType?: string;
|
||||
+
|
||||
+ /**
|
||||
+ * The display name of a shared file, when the source app provided one.
|
||||
+ * Populated on Android from the content resolver's `DISPLAY_NAME`.
|
||||
+ */
|
||||
+ originalName?: string | null;
|
||||
};
|
||||
|
||||
export type BaseResolvedSharePayload = SharePayload & {
|
||||
Generated
+3
-2
@@ -91,6 +91,7 @@ patchedDependencies:
|
||||
'@react-native-menu/[email protected]': f63d256bf6a97a873b5e628eb595bd6ef0075ddd5bdd890fc920f7a6024290dd
|
||||
'@react-navigation/[email protected]': e667c3cef8c78bb9ff4882ee5bd23a432247b843060a9499eb5f07e9e2295552
|
||||
[email protected]: af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6
|
||||
[email protected]: 8d2e3b10eb3f52036a9a086800180ec6cebf3b75bccc5b1775117a7244d4ac45
|
||||
[email protected]: 808eb26f9e57cf4945efd3985af4d9c764da6f91f4c9764433cc868602bbf4d3
|
||||
[email protected]: 6e4339347bc5bb3c9ea67d85ff5c814058b211c5750f247aba59d07869a2e787
|
||||
[email protected]: 825622aae63a8fb5b904f3c77908a0e216261d727ea171709f2c0b6088422675
|
||||
@@ -363,7 +364,7 @@ importers:
|
||||
version: 57.0.2([email protected])
|
||||
expo-sharing:
|
||||
specifier: ~57.0.16
|
||||
version: 57.0.16([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])
|
||||
version: 57.0.16(patch_hash=8d2e3b10eb3f52036a9a086800180ec6cebf3b75bccc5b1775117a7244d4ac45)([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])
|
||||
expo-splash-screen:
|
||||
specifier: ~57.0.8
|
||||
version: 57.0.8([email protected])([email protected])
|
||||
@@ -16542,7 +16543,7 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected]):
|
||||
[email protected](patch_hash=8d2e3b10eb3f52036a9a086800180ec6cebf3b75bccc5b1775117a7244d4ac45)([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected]):
|
||||
dependencies:
|
||||
'@expo/config-plugins': 57.0.9([email protected])
|
||||
'@expo/config-types': 57.0.2
|
||||
|
||||
@@ -153,6 +153,7 @@ patchedDependencies:
|
||||
"@react-native-menu/[email protected]": patches/@[email protected]
|
||||
"@react-navigation/[email protected]": patches/@react-navigation%[email protected]
|
||||
[email protected]: patches/[email protected]
|
||||
[email protected]: patches/[email protected]
|
||||
[email protected]: patches/[email protected]
|
||||
[email protected]: patches/[email protected]
|
||||
[email protected]: patches/[email protected]
|
||||
|
||||
Reference in new issue
Block a user