feat(mobile): upload attachments while composing (#8978)
Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
1 parent
85b656ff30
commit
9bc7a56848
23 files changed
+1622
-118
No files matched your search
@@ -73,6 +73,7 @@ import { NATIVE_LIQUID_GLASS_SUPPORTED } from "./native/native-glass";
|
||||
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
|
||||
import { FORM_SHEET_PRESENTATION_OPTIONS } from "./native/sheet-surface";
|
||||
import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
|
||||
import { useComposerAttachmentUploadWorker } from "./state/composer-attachment-uploads";
|
||||
|
||||
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
|
||||
|
||||
@@ -355,6 +356,7 @@ function workspacePathFromState(state: NavigationState): string {
|
||||
// each enqueue, shell change, or reconnect.
|
||||
function ThreadOutboxDrainWorker() {
|
||||
useThreadOutboxDrain();
|
||||
useComposerAttachmentUploadWorker();
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,8 +10,14 @@ import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
|
||||
import { PresentationSource } from "./NativePresentation";
|
||||
import type { FilePreviewSource } from "./FilePreviewModal";
|
||||
import { isPdfFile } from "../lib/filePreview";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
retryComposerAttachmentUpload,
|
||||
useComposerAttachmentUploadState,
|
||||
} from "../state/composer-attachment-uploads";
|
||||
|
||||
export interface ComposerAttachmentStripProps {
|
||||
readonly environmentId?: EnvironmentId;
|
||||
/** Attachments to display. */
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
/** Called when the user removes an attachment. */
|
||||
@@ -30,7 +36,8 @@ export interface ComposerAttachmentStripProps {
|
||||
readonly removeButtonPlacement?: "overlay" | "gutter";
|
||||
}
|
||||
|
||||
export function ComposerAttachmentThumbnail(props: {
|
||||
type ComposerAttachmentThumbnailProps = {
|
||||
readonly environmentId?: EnvironmentId;
|
||||
readonly attachment: DraftComposerAttachment;
|
||||
readonly size: number;
|
||||
readonly borderRadius: number;
|
||||
@@ -40,7 +47,47 @@ export function ComposerAttachmentThumbnail(props: {
|
||||
attachment: DraftComposerFileAttachment,
|
||||
sourceIdentifier: string,
|
||||
) => void;
|
||||
}) {
|
||||
};
|
||||
|
||||
export function ComposerAttachmentThumbnail(props: ComposerAttachmentThumbnailProps) {
|
||||
const upload = useComposerAttachmentUploadState(props.environmentId, props.attachment.id);
|
||||
return (
|
||||
<View style={{ width: props.size, height: props.size }}>
|
||||
<ComposerAttachmentContent {...props} />
|
||||
{upload && upload.status !== "ready" ? (
|
||||
<Pressable
|
||||
accessibilityRole={upload.status === "failed" ? "button" : "text"}
|
||||
accessibilityLabel={
|
||||
upload.status === "failed"
|
||||
? `Retry uploading ${props.attachment.name}`
|
||||
: `Uploading ${props.attachment.name}, ${Math.floor(upload.progress * 100)}%`
|
||||
}
|
||||
accessibilityHint={upload.status === "failed" ? upload.reason : undefined}
|
||||
disabled={upload.status !== "failed"}
|
||||
onPress={() =>
|
||||
props.environmentId &&
|
||||
retryComposerAttachmentUpload(props.environmentId, props.attachment.id)
|
||||
}
|
||||
className="absolute bottom-0.5 left-0.5 flex-row items-center gap-0.5 rounded-full bg-black/70 px-1 py-0.5"
|
||||
>
|
||||
<SymbolView
|
||||
name={upload.status === "failed" ? "arrow.clockwise" : "arrow.up"}
|
||||
size={props.compact ? 8 : 10}
|
||||
tintColor="#ffffff"
|
||||
type="monochrome"
|
||||
/>
|
||||
{!props.compact ? (
|
||||
<Text className="text-2xs text-white">
|
||||
{upload.status === "failed" ? "Retry" : `${Math.floor(upload.progress * 100)}%`}
|
||||
</Text>
|
||||
) : null}
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ComposerAttachmentContent(props: ComposerAttachmentThumbnailProps) {
|
||||
const { attachment } = props;
|
||||
const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };
|
||||
if (attachment.type === "image") {
|
||||
@@ -213,6 +260,7 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
|
||||
}}
|
||||
>
|
||||
<ComposerAttachmentThumbnail
|
||||
environmentId={props.environmentId}
|
||||
attachment={attachment}
|
||||
size={size}
|
||||
borderRadius={radius}
|
||||
|
||||
@@ -26,6 +26,12 @@ vi.mock("../../connection/catalog", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("./cloud-drafts", () => ({ removeCloudEnvironments: {} }));
|
||||
vi.mock("../../state/use-composer-drafts", () => ({
|
||||
getComposerCloudAccountId: vi.fn(async () => null),
|
||||
restoreCloudComposerDrafts: vi.fn(async () => undefined),
|
||||
}));
|
||||
|
||||
vi.mock("./publicConfig", () => ({
|
||||
resolveCloudPublicConfig: vi.fn(() => ({
|
||||
clerk: { publishableKey: null },
|
||||
|
||||
@@ -5,14 +5,18 @@ import {
|
||||
reportAtomCommandResult,
|
||||
settleAsyncResult,
|
||||
settlePromise,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { type ReactNode, useEffect, useRef } from "react";
|
||||
|
||||
import { environmentCatalog } from "../../connection/catalog";
|
||||
import { runtime } from "../../lib/runtime";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import {
|
||||
getComposerCloudAccountId,
|
||||
restoreCloudComposerDrafts,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import {
|
||||
releaseAgentAwarenessRelayTokenProvider,
|
||||
setAgentAwarenessRelayTokenProvider,
|
||||
@@ -20,6 +24,7 @@ import {
|
||||
} from "../agent-awareness/remoteRegistration";
|
||||
import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding";
|
||||
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
|
||||
import { removeCloudEnvironments } from "./cloud-drafts";
|
||||
|
||||
function resetManagedRelayTokenCache() {
|
||||
return settleAsyncResult(() =>
|
||||
@@ -47,7 +52,7 @@ export function activateCloudRelayAccount(
|
||||
|
||||
function CloudAuthBridge(props: { readonly children: ReactNode }) {
|
||||
const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, {
|
||||
const removeRelayEnvironments = useAtomCommand(removeCloudEnvironments, {
|
||||
reportFailure: false,
|
||||
reportDefect: false,
|
||||
});
|
||||
@@ -81,32 +86,37 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
|
||||
clearConnectOnboardingRequest();
|
||||
}
|
||||
|
||||
const queueAccountCleanup = (
|
||||
const cleanUpAccount = async (
|
||||
previous: {
|
||||
readonly userId: string;
|
||||
readonly provider: () => Promise<string | null>;
|
||||
} | null,
|
||||
accountId: string | null,
|
||||
) => {
|
||||
const previousTransition = accountTransitionRef.current ?? Promise.resolve();
|
||||
accountTransitionRef.current = previousTransition.then(async () => {
|
||||
const cleanup = [
|
||||
resetManagedRelayTokenCache(),
|
||||
removeRelayEnvironments(),
|
||||
...(previous
|
||||
? [
|
||||
settleAsyncResult(() =>
|
||||
runtime.runPromiseExit(
|
||||
unregisterAgentAwarenessDeviceForCurrentUser(previous.provider),
|
||||
),
|
||||
const removal = await removeRelayEnvironments(accountId);
|
||||
if (removal._tag !== "Success") throw squashAtomCommandFailure(removal);
|
||||
const cleanup = [
|
||||
resetManagedRelayTokenCache(),
|
||||
...(previous
|
||||
? [
|
||||
settleAsyncResult(() =>
|
||||
runtime.runPromiseExit(
|
||||
unregisterAgentAwarenessDeviceForCurrentUser(previous.provider),
|
||||
),
|
||||
]
|
||||
: []),
|
||||
];
|
||||
const results = await Promise.all(cleanup);
|
||||
for (const result of results) {
|
||||
reportAtomCommandResult(result, { label: "cloud account cleanup" });
|
||||
}
|
||||
});
|
||||
),
|
||||
]
|
||||
: []),
|
||||
];
|
||||
const results = await Promise.all(cleanup);
|
||||
for (const result of results) {
|
||||
reportAtomCommandResult(result, { label: "cloud account cleanup" });
|
||||
}
|
||||
};
|
||||
const queueAccountCleanup = (previous: typeof previousTokenProviderRef.current) => {
|
||||
const previousTransition = accountTransitionRef.current ?? Promise.resolve();
|
||||
accountTransitionRef.current = previousTransition
|
||||
.catch(() => {})
|
||||
.then(() => cleanUpAccount(previous, previousObservedAccount ?? null));
|
||||
return accountTransitionRef.current;
|
||||
};
|
||||
|
||||
@@ -115,7 +125,9 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
|
||||
previousTokenProviderRef.current = null;
|
||||
deactivateCloudRelayAccount();
|
||||
if (previousObservedAccount !== null) {
|
||||
void queueAccountCleanup(previous);
|
||||
void settlePromise(() => queueAccountCleanup(previous)).then((result) => {
|
||||
reportAtomCommandResult(result, { label: "cloud account cleanup" });
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -133,13 +145,21 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
|
||||
}
|
||||
};
|
||||
const activateAfterTransition = (transition: Promise<void>) => {
|
||||
void (async () => {
|
||||
const result = await settlePromise(async () => {
|
||||
await transition;
|
||||
activateSession();
|
||||
});
|
||||
reportAtomCommandResult(result, { label: "cloud account activation" });
|
||||
const activation = (async () => {
|
||||
await transition;
|
||||
if (cancelled) return;
|
||||
const storedAccount = await getComposerCloudAccountId();
|
||||
if (storedAccount !== null && storedAccount !== userId) {
|
||||
await cleanUpAccount(null, storedAccount);
|
||||
}
|
||||
if (cancelled) return;
|
||||
await restoreCloudComposerDrafts(userId);
|
||||
activateSession();
|
||||
})();
|
||||
accountTransitionRef.current = activation;
|
||||
void settlePromise(() => activation).then((result) => {
|
||||
reportAtomCommandResult(result, { label: "cloud account activation" });
|
||||
});
|
||||
};
|
||||
if (
|
||||
previousObservedAccount !== undefined &&
|
||||
@@ -150,7 +170,9 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
|
||||
deactivateCloudRelayAccount();
|
||||
activateAfterTransition(queueAccountCleanup(previous));
|
||||
} else {
|
||||
activateAfterTransition(accountTransitionRef.current ?? Promise.resolve());
|
||||
// A failed disk write can be retried. The persisted account check above
|
||||
// still requires cleanup before activating a different account.
|
||||
activateAfterTransition((accountTransitionRef.current ?? Promise.resolve()).catch(() => {}));
|
||||
}
|
||||
|
||||
return () => {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
|
||||
import { createRuntimeCommand } from "@t3tools/client-runtime/state/runtime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SubscriptionRef from "effect/SubscriptionRef";
|
||||
|
||||
import { connectionAtomRuntime } from "../../connection/runtime";
|
||||
import { archiveCloudComposerDrafts } from "../../state/use-composer-drafts";
|
||||
|
||||
export class CloudDraftArchiveError extends Schema.TaggedErrorClass<CloudDraftArchiveError>()(
|
||||
"CloudDraftArchiveError",
|
||||
{
|
||||
environmentCount: Schema.Number,
|
||||
hasAccountId: Schema.Boolean,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Could not preserve local drafts for ${this.environmentCount} cloud environments before sign-out.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const removeCloudEnvironments = createRuntimeCommand(connectionAtomRuntime, {
|
||||
label: "cloud:preserve-drafts-and-remove-environments",
|
||||
execute: Effect.fn("removeCloudEnvironments")(function* (accountId: string | null) {
|
||||
const registry = yield* EnvironmentRegistry;
|
||||
const entries = yield* SubscriptionRef.get(registry.entries);
|
||||
const environmentIds = new Set(
|
||||
[...entries.values()]
|
||||
.filter((entry) => entry.target._tag === "RelayConnectionTarget")
|
||||
.map((entry) => entry.target.environmentId),
|
||||
);
|
||||
// Credentials are already revoked. A failed backup must leave the local
|
||||
// owners intact so a later sign-in can retry without losing their files.
|
||||
yield* Effect.tryPromise({
|
||||
try: () => archiveCloudComposerDrafts(accountId, environmentIds),
|
||||
catch: (cause) =>
|
||||
new CloudDraftArchiveError({
|
||||
environmentCount: environmentIds.size,
|
||||
hasAccountId: accountId !== null,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
yield* registry.removeRelayEnvironments();
|
||||
}),
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import {
|
||||
CommonActions,
|
||||
@@ -35,6 +36,10 @@ import {
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { ComposerAttachmentButton } from "../../components/ComposerAttachmentButton";
|
||||
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
|
||||
import {
|
||||
composerAttachmentUploadBlockReason,
|
||||
composerAttachmentUploadsAtom,
|
||||
} from "../../state/composer-attachment-uploads";
|
||||
import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
|
||||
import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
@@ -164,6 +169,16 @@ export function NewTaskDraftScreen(props: {
|
||||
connectedEnvironments.find(
|
||||
(environment) => environment.environmentId === selectedProject.environmentId,
|
||||
)?.connectionState === "connected";
|
||||
const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
|
||||
const attachmentBlockReason = selectedProject
|
||||
? composerAttachmentUploadBlockReason({
|
||||
environmentId: selectedProject.environmentId,
|
||||
attachments: flow.attachments,
|
||||
connected: environmentConnected,
|
||||
serverConfig: selectedEnvironmentServerConfig,
|
||||
states: uploadStates,
|
||||
})
|
||||
: null;
|
||||
const promptInputRef = useRef<ComposerEditorHandle>(null);
|
||||
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
|
||||
const [isComposerFocused, setIsComposerFocused] = useState(false);
|
||||
@@ -863,6 +878,7 @@ export function NewTaskDraftScreen(props: {
|
||||
const initialMessageText = draft.text.trim();
|
||||
|
||||
if (
|
||||
attachmentBlockReason !== null ||
|
||||
!modelSelection ||
|
||||
initialMessageText.length === 0 ||
|
||||
flow.submitting ||
|
||||
@@ -1017,6 +1033,7 @@ export function NewTaskDraftScreen(props: {
|
||||
|
||||
const isAndroid = Platform.OS === "android";
|
||||
const canStart =
|
||||
attachmentBlockReason === null &&
|
||||
Boolean(flow.selectedProject) &&
|
||||
Boolean(flow.selectedModel) &&
|
||||
flow.prompt.trim().length > 0 &&
|
||||
@@ -1216,6 +1233,7 @@ export function NewTaskDraftScreen(props: {
|
||||
{flow.attachments.length > 0 ? (
|
||||
<View className="px-[14px] pb-2.5">
|
||||
<ComposerAttachmentStrip
|
||||
environmentId={selectedProject.environmentId}
|
||||
attachments={flow.attachments}
|
||||
imageBorderRadius={16}
|
||||
imageSize={72}
|
||||
@@ -1317,11 +1335,12 @@ export function NewTaskDraftScreen(props: {
|
||||
{voicePresentation.showsSend ? (
|
||||
<ComposerActionButton
|
||||
accessibilityLabel={
|
||||
flow.submitting
|
||||
attachmentBlockReason ??
|
||||
(flow.submitting
|
||||
? "Starting task"
|
||||
: environmentConnected
|
||||
? "Start task"
|
||||
: "Queue task"
|
||||
: "Queue task")
|
||||
}
|
||||
disabled={!canStart}
|
||||
icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
@@ -21,6 +22,10 @@ import {
|
||||
} from "react";
|
||||
import { ActivityIndicator, Platform, Pressable, View, type ViewStyle } from "react-native";
|
||||
import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
|
||||
import {
|
||||
composerAttachmentUploadBlockReason,
|
||||
composerAttachmentUploadsAtom,
|
||||
} from "../../state/composer-attachment-uploads";
|
||||
import Animated, {
|
||||
FadeIn,
|
||||
FadeInDown,
|
||||
@@ -365,7 +370,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
const isExpanded = isFocused || settingsSheetPresentation.isActive;
|
||||
const showsCompactDictation = isVoiceInputPresented && !isExpanded;
|
||||
const isToolbarVisible = isExpanded || isVoiceInputPresented;
|
||||
const canSend = hasContent && !voiceInput.blocksSubmission;
|
||||
const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
|
||||
const attachmentBlockReason = composerAttachmentUploadBlockReason({
|
||||
environmentId: props.environmentId,
|
||||
attachments: props.draftAttachments,
|
||||
connected: props.connectionState === "connected",
|
||||
serverConfig: props.serverConfig,
|
||||
states: uploadStates,
|
||||
});
|
||||
const canSend = hasContent && !voiceInput.blocksSubmission && attachmentBlockReason === null;
|
||||
|
||||
// Keep the feed inset aligned with the card or compact dictation strip.
|
||||
useEffect(() => {
|
||||
@@ -617,6 +630,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
exiting={FadeOut.duration(120)}
|
||||
>
|
||||
<ComposerAttachmentStrip
|
||||
environmentId={props.environmentId}
|
||||
attachments={props.draftAttachments}
|
||||
onRemove={voiceInput.isBusy ? () => undefined : props.onRemoveDraftImage}
|
||||
onPressPreview={voiceInput.isBusy ? undefined : onPressPreview}
|
||||
@@ -668,6 +682,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
<View className="flex-row gap-1 pl-1">
|
||||
{props.draftAttachments.slice(0, 3).map((attachment) => (
|
||||
<ComposerAttachmentThumbnail
|
||||
environmentId={props.environmentId}
|
||||
key={attachment.id}
|
||||
attachment={attachment}
|
||||
size={30}
|
||||
@@ -703,10 +718,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
/>
|
||||
) : (
|
||||
<ComposerActionButton
|
||||
accessibilityLabel={sendLabel}
|
||||
accessibilityLabel={attachmentBlockReason ?? sendLabel}
|
||||
icon="arrow.up"
|
||||
variant="primary"
|
||||
disabled={!hasContent}
|
||||
disabled={!canSend}
|
||||
onPress={handleSend}
|
||||
/>
|
||||
)}
|
||||
@@ -794,7 +809,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
/>
|
||||
) : voicePresentation.showsSend ? (
|
||||
<ComposerActionButton
|
||||
accessibilityLabel={sendLabel}
|
||||
accessibilityLabel={attachmentBlockReason ?? sendLabel}
|
||||
icon="arrow.up"
|
||||
variant="primary"
|
||||
disabled={!canSend}
|
||||
|
||||
@@ -85,6 +85,9 @@ export function useCreateProjectThread() {
|
||||
prepared = await prepareTurnAttachments({
|
||||
environmentId: input.project.environmentId,
|
||||
attachments: input.initialAttachments,
|
||||
supportsImageUploads:
|
||||
appAtomRegistry.get(serverEnvironment.configValueAtom(input.project.environmentId))
|
||||
?.environment.capabilities.attachmentUploads === true,
|
||||
persistUploadedReferences: async (draftAttachments) => {
|
||||
await input.onAttachmentsUploaded(draftAttachments);
|
||||
return "persisted";
|
||||
|
||||
@@ -12,6 +12,8 @@ const mocks = vi.hoisted(() => ({
|
||||
runAtomCommand: vi.fn(),
|
||||
readAtom: vi.fn(),
|
||||
upload: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
deleteFile: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@t3tools/client-runtime/state/runtime", () => ({
|
||||
@@ -53,13 +55,25 @@ vi.mock("./uuid", () => ({
|
||||
|
||||
vi.mock("expo-file-system", () => ({
|
||||
File: class {
|
||||
constructor(readonly uri: string) {}
|
||||
readonly uri: string;
|
||||
exists = true;
|
||||
constructor(uri: string, name?: string) {
|
||||
this.uri = name ? `${uri}/${name}` : uri;
|
||||
}
|
||||
create() {}
|
||||
write(bytes: string, options: unknown) {
|
||||
mocks.writeFile(this.uri, bytes, options);
|
||||
}
|
||||
delete() {
|
||||
mocks.deleteFile(this.uri);
|
||||
}
|
||||
|
||||
upload(url: string, options: unknown) {
|
||||
return mocks.upload(this.uri, url, options);
|
||||
}
|
||||
},
|
||||
Paths: {
|
||||
cache: "file:///cache",
|
||||
get document() {
|
||||
return { uri: mocks.documentUri };
|
||||
},
|
||||
@@ -158,6 +172,8 @@ describe("prepareTurnAttachments", () => {
|
||||
mocks.runAtomCommand.mockReset();
|
||||
mocks.readAtom.mockReset();
|
||||
mocks.upload.mockReset();
|
||||
mocks.writeFile.mockReset();
|
||||
mocks.deleteFile.mockReset();
|
||||
mocks.readAtom.mockReturnValue(Option.some({ httpBaseUrl: "https://environment.example/" }));
|
||||
mocks.runAtomCommand.mockImplementation(async (_registry: unknown, command: unknown) =>
|
||||
command === mocks.createUploadUrl
|
||||
@@ -198,11 +214,11 @@ describe("prepareTurnAttachments", () => {
|
||||
expect(mocks.upload).toHaveBeenCalledWith(
|
||||
"file:///documents/report.pdf",
|
||||
"https://environment.example/api/attachments/upload/signed",
|
||||
{
|
||||
expect.objectContaining({
|
||||
httpMethod: "POST",
|
||||
uploadType: 0,
|
||||
headers: { "Content-Type": "application/pdf" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(prepared.status).toBe("ready");
|
||||
if (prepared.status !== "ready") return;
|
||||
@@ -354,6 +370,123 @@ describe("prepareTurnAttachments", () => {
|
||||
expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
|
||||
});
|
||||
|
||||
it("uploads image bytes over HTTP while retaining the durable offline image", async () => {
|
||||
const persisted = vi.fn(async () => "persisted" as const);
|
||||
const prepared = await prepareTurnAttachments({
|
||||
environmentId,
|
||||
attachments: [image],
|
||||
supportsImageUploads: true,
|
||||
persistUploadedReferences: persisted,
|
||||
});
|
||||
expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
|
||||
encoding: "base64",
|
||||
});
|
||||
expect(mocks.upload).toHaveBeenCalledWith(
|
||||
"file:///cache/t3-upload-uuid",
|
||||
"https://environment.example/api/attachments/upload/signed",
|
||||
expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
|
||||
);
|
||||
expect(mocks.deleteFile).toHaveBeenCalledExactlyOnceWith("file:///cache/t3-upload-uuid");
|
||||
expect(prepared.status).toBe("ready");
|
||||
if (prepared.status !== "ready") return;
|
||||
expect(prepared.attachments).toEqual([
|
||||
{
|
||||
type: "image",
|
||||
id: MINTED_ID,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
},
|
||||
]);
|
||||
expect(prepared.draftAttachments).toEqual([
|
||||
{ ...image, uploadedAttachmentId: MINTED_ID, uploadEnvironmentId: environmentId },
|
||||
]);
|
||||
expect(persisted).toHaveBeenCalledWith(prepared.draftAttachments);
|
||||
});
|
||||
|
||||
it("reuses an uploaded image and reuploads its local bytes after server expiry", async () => {
|
||||
const saved = {
|
||||
...image,
|
||||
uploadedAttachmentId: "saved-image",
|
||||
uploadEnvironmentId: environmentId,
|
||||
};
|
||||
const reused = await prepareTurnAttachments({
|
||||
environmentId,
|
||||
attachments: [saved],
|
||||
supportsImageUploads: true,
|
||||
});
|
||||
expect(reused.status === "ready" && reused.attachments[0]).toEqual({
|
||||
type: "image",
|
||||
id: "saved-image",
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
});
|
||||
expect(mocks.upload).not.toHaveBeenCalled();
|
||||
mocks.executeAtomQuery.mockResolvedValueOnce({
|
||||
_tag: "Failure",
|
||||
error: { _tag: "AssetAttachmentNotFoundError" },
|
||||
});
|
||||
const restored = await prepareTurnAttachments({
|
||||
environmentId,
|
||||
attachments: [saved],
|
||||
supportsImageUploads: true,
|
||||
});
|
||||
expect(restored.status === "ready" && restored.draftAttachments[0]).toEqual({
|
||||
...saved,
|
||||
uploadedAttachmentId: MINTED_ID,
|
||||
});
|
||||
expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
|
||||
encoding: "base64",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not reuse an image upload from another environment", async () => {
|
||||
const prepared = await prepareTurnAttachments({
|
||||
environmentId,
|
||||
attachments: [
|
||||
{
|
||||
...image,
|
||||
uploadedAttachmentId: "other-image",
|
||||
uploadEnvironmentId: EnvironmentId.make("other"),
|
||||
},
|
||||
],
|
||||
supportsImageUploads: true,
|
||||
});
|
||||
expect(mocks.executeAtomQuery).not.toHaveBeenCalled();
|
||||
expect(mocks.upload).toHaveBeenCalledOnce();
|
||||
expect(prepared.status === "ready" && prepared.draftAttachments[0]?.uploadEnvironmentId).toBe(
|
||||
environmentId,
|
||||
);
|
||||
});
|
||||
|
||||
it("aborts an active transfer without dropping local bytes or stamping a partial upload", async () => {
|
||||
const started = Promise.withResolvers<void>();
|
||||
const controller = new AbortController();
|
||||
const persist = vi.fn(async () => "persisted" as const);
|
||||
mocks.upload.mockImplementation(
|
||||
(_uri: string, _url: string, options: { signal: AbortSignal }) =>
|
||||
new Promise((_, reject) => {
|
||||
options.signal.addEventListener("abort", () => reject(new Error("cancelled")), {
|
||||
once: true,
|
||||
});
|
||||
started.resolve();
|
||||
}),
|
||||
);
|
||||
const preparing = prepareTurnAttachments({
|
||||
environmentId,
|
||||
attachments: [file],
|
||||
signal: controller.signal,
|
||||
persistUploadedReferences: persist,
|
||||
});
|
||||
await started.promise;
|
||||
controller.abort();
|
||||
expect(await preparing).toEqual({ status: "abandoned" });
|
||||
expect(persist).not.toHaveBeenCalled();
|
||||
expect(mocks.deleteFile).not.toHaveBeenCalled();
|
||||
expect(removeCallsFor(MINTED_ID)).toBe(1);
|
||||
});
|
||||
|
||||
it("removes pending uploads when the native HTTP request fails", async () => {
|
||||
mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
|
||||
|
||||
|
||||
@@ -9,9 +9,11 @@ import {
|
||||
import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import type {
|
||||
ChatFileAttachment,
|
||||
ChatImageAttachment,
|
||||
EnvironmentId,
|
||||
UploadChatImageAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
import { PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import { appAtomRegistry } from "../state/atom-registry";
|
||||
@@ -20,6 +22,7 @@ import { attachmentEnvironment } from "../state/attachments";
|
||||
import { environmentSession } from "../state/session";
|
||||
import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";
|
||||
import { toUploadChatImageAttachments, type DraftComposerAttachment } from "./composerImages";
|
||||
import { uuidv4 } from "./uuid";
|
||||
|
||||
/**
|
||||
* This module owns the server side of a composer attachment's lifecycle.
|
||||
@@ -31,7 +34,10 @@ import { toUploadChatImageAttachments, type DraftComposerAttachment } from "./co
|
||||
* owned by `removeThreadOutboxMessage` / the composer draft mutators, which
|
||||
* release files through `releaseUnusedComposerAttachmentFiles`.
|
||||
*/
|
||||
export type UploadedMobileAttachment = UploadChatImageAttachment | ChatFileAttachment;
|
||||
export type UploadedMobileAttachment =
|
||||
| UploadChatImageAttachment
|
||||
| ChatImageAttachment
|
||||
| ChatFileAttachment;
|
||||
|
||||
export function validateDraftFileAttachments(input: {
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
@@ -56,7 +62,7 @@ export function validateDraftFileAttachments(input: {
|
||||
return oversized ? fileAttachmentTooLargeMessage(oversized.name, maxBytes) : null;
|
||||
}
|
||||
|
||||
/** Keep uploaded file ids on durable drafts so a later send can reuse their bytes. */
|
||||
/** Keep uploaded ids alongside the local bytes so a later send can reuse them. */
|
||||
export function withUploadedMobileAttachmentReferences(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
@@ -65,8 +71,9 @@ export function withUploadedMobileAttachmentReferences(input: {
|
||||
return input.attachments.map((attachment, index) => {
|
||||
const uploaded = input.uploadedAttachments[index];
|
||||
if (
|
||||
attachment.type !== "file" ||
|
||||
uploaded?.type !== "file" ||
|
||||
!uploaded ||
|
||||
!("id" in uploaded) ||
|
||||
attachment.type !== uploaded.type ||
|
||||
(attachment.uploadedAttachmentId === uploaded.id &&
|
||||
attachment.uploadEnvironmentId === input.environmentId)
|
||||
) {
|
||||
@@ -145,21 +152,73 @@ export type PrepareTurnAttachmentsResult =
|
||||
| PreparedTurnAttachments
|
||||
| { readonly status: "abandoned" };
|
||||
|
||||
function uploadedReference(
|
||||
attachment: DraftComposerAttachment,
|
||||
id: string,
|
||||
): ChatImageAttachment | ChatFileAttachment {
|
||||
const fields = {
|
||||
id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
};
|
||||
return attachment.type === "image" ? { type: "image", ...fields } : { type: "file", ...fields };
|
||||
}
|
||||
|
||||
function attachmentUploadInput(attachment: DraftComposerAttachment) {
|
||||
const fields = {
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
};
|
||||
if (attachment.type === "file") return { type: "file" as const, ...fields };
|
||||
const mimeType = PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES.find(
|
||||
(type) => type === attachment.mimeType.toLowerCase(),
|
||||
);
|
||||
if (!mimeType) throw new Error(`Unsupported image type for '${attachment.name}'.`);
|
||||
return { ...fields, mimeType };
|
||||
}
|
||||
|
||||
async function uploadFileBytes(
|
||||
attachment: Extract<DraftComposerAttachment, { readonly type: "file" }>,
|
||||
attachment: DraftComposerAttachment,
|
||||
url: string,
|
||||
signal: AbortSignal,
|
||||
onProgress?: (progress: number) => void,
|
||||
): 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}).`);
|
||||
if (signal.aborted) throw new Error("Upload cancelled.");
|
||||
const file =
|
||||
attachment.type === "image"
|
||||
? new File(Paths.cache, `t3-upload-${uuidv4()}`)
|
||||
: new File(
|
||||
resolveOwnedComposerAttachmentFileUri(attachment.fileUri, Paths.document.uri) ??
|
||||
attachment.fileUri,
|
||||
);
|
||||
try {
|
||||
if (attachment.type === "image") {
|
||||
file.create();
|
||||
file.write(attachment.dataUrl.slice(attachment.dataUrl.indexOf(",") + 1), {
|
||||
encoding: "base64",
|
||||
});
|
||||
}
|
||||
const result = await file.upload(url, {
|
||||
httpMethod: "POST",
|
||||
uploadType: UploadType.BINARY_CONTENT,
|
||||
headers: { "Content-Type": attachment.mimeType },
|
||||
signal,
|
||||
...(onProgress
|
||||
? {
|
||||
onProgress: ({ bytesSent, totalBytes }) => {
|
||||
if (totalBytes > 0) onProgress(bytesSent / totalBytes);
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
if (result.status < 200 || result.status >= 300) {
|
||||
throw new Error(`Upload failed for '${attachment.name}' (${result.status}).`);
|
||||
}
|
||||
} finally {
|
||||
if (attachment.type === "image" && file.exists) file.delete();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,11 +235,16 @@ async function uploadFileBytes(
|
||||
export async function prepareTurnAttachments(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
/** Older environments continue to receive inline images. */
|
||||
readonly supportsImageUploads?: boolean;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly onUploadProgress?: (attachmentId: string, progress: number) => void;
|
||||
readonly persistUploadedReferences?: (
|
||||
draftAttachments: ReadonlyArray<DraftComposerAttachment>,
|
||||
) => Promise<"persisted" | "abandon">;
|
||||
}): Promise<PrepareTurnAttachmentsResult> {
|
||||
const { environmentId } = input;
|
||||
if (input.signal?.aborted) return { status: "abandoned" };
|
||||
const files = input.attachments.filter((attachment) => attachment.type === "file");
|
||||
const ready = (
|
||||
attachments: ReadonlyArray<UploadedMobileAttachment>,
|
||||
@@ -194,7 +258,7 @@ export async function prepareTurnAttachments(input: {
|
||||
releaseUploads: () => releasePendingAttachmentUploads(environmentId, pendingAttachmentIds),
|
||||
});
|
||||
|
||||
if (files.length === 0) {
|
||||
if (input.attachments.length === 0 || (files.length === 0 && !input.supportsImageUploads)) {
|
||||
return ready(
|
||||
toUploadChatImageAttachments(
|
||||
input.attachments.filter((attachment) => attachment.type === "image"),
|
||||
@@ -214,9 +278,13 @@ export async function prepareTurnAttachments(input: {
|
||||
const uploadedAttachments: UploadedMobileAttachment[] = [];
|
||||
const pendingAttachmentIds: string[] = [];
|
||||
const createdAttachmentIds: string[] = [];
|
||||
const controller = new AbortController();
|
||||
const abort = () => controller.abort();
|
||||
input.signal?.addEventListener("abort", abort, { once: true });
|
||||
try {
|
||||
for (const attachment of input.attachments) {
|
||||
if (attachment.type === "image") {
|
||||
if (controller.signal.aborted) throw new Error("Upload cancelled.");
|
||||
if (attachment.type === "image" && !input.supportsImageUploads) {
|
||||
uploadedAttachments.push(...toUploadChatImageAttachments([attachment]));
|
||||
continue;
|
||||
}
|
||||
@@ -238,13 +306,7 @@ export async function prepareTurnAttachments(input: {
|
||||
}
|
||||
if (verification.status === "verified") {
|
||||
pendingAttachmentIds.push(attachment.uploadedAttachmentId);
|
||||
uploadedAttachments.push({
|
||||
type: "file",
|
||||
id: attachment.uploadedAttachmentId,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
});
|
||||
uploadedAttachments.push(uploadedReference(attachment, attachment.uploadedAttachmentId));
|
||||
continue;
|
||||
}
|
||||
// "missing": the pending upload expired, upload the bytes again.
|
||||
@@ -255,12 +317,7 @@ export async function prepareTurnAttachments(input: {
|
||||
createUploadUrl: attachmentEnvironment.createUploadUrl,
|
||||
remove: attachmentEnvironment.remove,
|
||||
environmentId,
|
||||
upload: {
|
||||
type: "file",
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
},
|
||||
upload: attachmentUploadInput(attachment),
|
||||
// Read the connection at transfer time: the environment may have
|
||||
// reconnected on a new base URL since this cycle started.
|
||||
resolveUploadUrl: (relativeUrl) => {
|
||||
@@ -272,11 +329,18 @@ export async function prepareTurnAttachments(input: {
|
||||
: resolveAssetUrl(currentConnection.value.httpBaseUrl, relativeUrl);
|
||||
},
|
||||
transport: (url) => ({
|
||||
done: uploadFileBytes(attachment, url),
|
||||
// expo-file-system uploads cannot abort mid-flight.
|
||||
abort: () => {},
|
||||
done: uploadFileBytes(
|
||||
attachment,
|
||||
url,
|
||||
controller.signal,
|
||||
input.onUploadProgress
|
||||
? (progress) => input.onUploadProgress?.(attachment.id, progress)
|
||||
: undefined,
|
||||
),
|
||||
abort,
|
||||
}),
|
||||
onMinted: (attachmentId) => {
|
||||
if (controller.signal.aborted) return "cancel";
|
||||
pendingAttachmentIds.push(attachmentId);
|
||||
createdAttachmentIds.push(attachmentId);
|
||||
return "continue";
|
||||
@@ -287,15 +351,11 @@ export async function prepareTurnAttachments(input: {
|
||||
? 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,
|
||||
});
|
||||
uploadedAttachments.push(uploadedReference(attachment, result.attachmentId));
|
||||
}
|
||||
|
||||
if (controller.signal.aborted) throw new Error("Upload cancelled.");
|
||||
|
||||
const draftAttachments = withUploadedMobileAttachmentReferences({
|
||||
environmentId,
|
||||
attachments: input.attachments,
|
||||
@@ -313,6 +373,9 @@ export async function prepareTurnAttachments(input: {
|
||||
return ready(uploadedAttachments, pendingAttachmentIds, draftAttachments);
|
||||
} catch (error) {
|
||||
await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
|
||||
if (controller.signal.aborted) return { status: "abandoned" };
|
||||
throw error;
|
||||
} finally {
|
||||
input.signal?.removeEventListener("abort", abort);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ export const DraftComposerImageAttachmentSchema = Schema.Struct({
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
dataUrl: Schema.String,
|
||||
uploadedAttachmentId: Schema.optional(Schema.String),
|
||||
uploadEnvironmentId: Schema.optional(EnvironmentId),
|
||||
});
|
||||
|
||||
export const DraftComposerFileAttachmentSchema = Schema.Struct({
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
composerAttachmentUploadBlockReason,
|
||||
composerAttachmentUploadKey,
|
||||
composerDraftEnvironmentId,
|
||||
createComposerAttachmentUploadQueue,
|
||||
type ComposerAttachmentUploadRequest,
|
||||
type ComposerAttachmentUploadState,
|
||||
} from "./composerAttachmentUploadQueue";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
function request(id: string, environment = environmentId): ComposerAttachmentUploadRequest {
|
||||
return {
|
||||
environmentId: environment,
|
||||
attachment: {
|
||||
id,
|
||||
type: "file",
|
||||
name: `${id}.pdf`,
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
fileUri: `file:///documents/${id}.pdf`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("composer attachment upload queue", () => {
|
||||
it("bounds concurrency, deduplicates updates, and drains all attachments", async () => {
|
||||
const gates = new Map<string, ReturnType<typeof Promise.withResolvers<boolean>>>();
|
||||
const fourthStarted = Promise.withResolvers<void>();
|
||||
const firstThreeStarted = Promise.withResolvers<void>();
|
||||
let active = 0;
|
||||
let maximum = 0;
|
||||
const upload = vi.fn(async (input: ComposerAttachmentUploadRequest) => {
|
||||
active += 1;
|
||||
maximum = Math.max(maximum, active);
|
||||
const gate = Promise.withResolvers<boolean>();
|
||||
gates.set(input.attachment.id, gate);
|
||||
if (gates.size === 3) firstThreeStarted.resolve();
|
||||
if (gates.size === 4) fourthStarted.resolve();
|
||||
try {
|
||||
return await gate.promise;
|
||||
} finally {
|
||||
active -= 1;
|
||||
}
|
||||
});
|
||||
const queue = createComposerAttachmentUploadQueue({ upload, onChange: () => {} });
|
||||
const requests = [request("one"), request("two"), request("three"), request("four")];
|
||||
queue.sync(requests);
|
||||
queue.sync(requests);
|
||||
await firstThreeStarted.promise;
|
||||
expect(upload).toHaveBeenCalledTimes(3);
|
||||
gates.get("one")!.resolve(true);
|
||||
await fourthStarted.promise;
|
||||
for (const gate of gates.values()) gate.resolve(true);
|
||||
await queue.settled();
|
||||
queue.sync(requests);
|
||||
await queue.settled();
|
||||
expect(maximum).toBe(3);
|
||||
expect(upload).toHaveBeenCalledTimes(4);
|
||||
queue.dispose();
|
||||
});
|
||||
|
||||
it("cancels on disconnect and resumes from the same local draft on reconnect", async () => {
|
||||
const started = Promise.withResolvers<void>();
|
||||
let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
|
||||
let signal: AbortSignal | undefined;
|
||||
const upload = vi.fn(
|
||||
async (_request: ComposerAttachmentUploadRequest, currentSignal: AbortSignal) => {
|
||||
signal = currentSignal;
|
||||
started.resolve();
|
||||
return new Promise<boolean>((resolve) =>
|
||||
currentSignal.addEventListener("abort", () => resolve(false), { once: true }),
|
||||
);
|
||||
},
|
||||
);
|
||||
const queue = createComposerAttachmentUploadQueue({
|
||||
upload,
|
||||
onChange: (next) => {
|
||||
states = next;
|
||||
},
|
||||
});
|
||||
const local = request("offline-draft");
|
||||
queue.sync([local]);
|
||||
await started.promise;
|
||||
queue.sync([]);
|
||||
await queue.settled();
|
||||
expect(signal?.aborted).toBe(true);
|
||||
expect(states).toEqual({});
|
||||
upload.mockResolvedValueOnce(true);
|
||||
queue.sync([local]);
|
||||
await queue.settled();
|
||||
expect(upload.mock.calls[1]?.[0]).toBe(local);
|
||||
expect(states[composerAttachmentUploadKey(environmentId, local.attachment.id)]).toEqual({
|
||||
status: "ready",
|
||||
});
|
||||
expect(local.attachment).toMatchObject({ fileUri: "file:///documents/offline-draft.pdf" });
|
||||
queue.dispose();
|
||||
});
|
||||
|
||||
it("ignores a late completion after removal or environment switch", async () => {
|
||||
const gate = Promise.withResolvers<boolean>();
|
||||
const started = Promise.withResolvers<void>();
|
||||
let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
|
||||
const upload = vi.fn(async () => {
|
||||
started.resolve();
|
||||
return gate.promise;
|
||||
});
|
||||
const queue = createComposerAttachmentUploadQueue({
|
||||
upload,
|
||||
onChange: (next) => {
|
||||
states = next;
|
||||
},
|
||||
});
|
||||
queue.sync([request("photo")]);
|
||||
await started.promise;
|
||||
upload.mockResolvedValueOnce(true);
|
||||
const other = EnvironmentId.make("environment-2");
|
||||
queue.sync([request("photo", other)]);
|
||||
gate.resolve(true);
|
||||
await queue.settled();
|
||||
expect(states).toEqual({ [composerAttachmentUploadKey(other, "photo")]: { status: "ready" } });
|
||||
queue.sync([]);
|
||||
expect(states).toEqual({});
|
||||
queue.dispose();
|
||||
});
|
||||
|
||||
it("restarts a re-added attachment after its aborted transfer finishes settling", async () => {
|
||||
const firstStarted = Promise.withResolvers<void>();
|
||||
const firstSettled = Promise.withResolvers<boolean>();
|
||||
const secondStarted = Promise.withResolvers<void>();
|
||||
const secondSettled = Promise.withResolvers<boolean>();
|
||||
let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
|
||||
let firstSignal: AbortSignal | undefined;
|
||||
const upload = vi.fn(async (_request: ComposerAttachmentUploadRequest, signal: AbortSignal) => {
|
||||
if (!firstSignal) {
|
||||
firstSignal = signal;
|
||||
firstStarted.resolve();
|
||||
return firstSettled.promise;
|
||||
}
|
||||
secondStarted.resolve();
|
||||
return secondSettled.promise;
|
||||
});
|
||||
const queue = createComposerAttachmentUploadQueue({
|
||||
upload,
|
||||
onChange: (next) => {
|
||||
states = next;
|
||||
},
|
||||
});
|
||||
const local = request("re-added");
|
||||
queue.sync([local]);
|
||||
await firstStarted.promise;
|
||||
queue.sync([]);
|
||||
queue.sync([local]);
|
||||
expect(firstSignal?.aborted).toBe(true);
|
||||
expect(upload).toHaveBeenCalledOnce();
|
||||
firstSettled.resolve(false);
|
||||
await secondStarted.promise;
|
||||
expect(upload).toHaveBeenCalledTimes(2);
|
||||
secondSettled.resolve(true);
|
||||
await queue.settled();
|
||||
expect(states[composerAttachmentUploadKey(environmentId, local.attachment.id)]).toEqual({
|
||||
status: "ready",
|
||||
});
|
||||
queue.dispose();
|
||||
});
|
||||
|
||||
it("keeps failures stable until retry and reports bounded progress", async () => {
|
||||
let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
|
||||
const progress: number[] = [];
|
||||
const upload = vi.fn(
|
||||
async (
|
||||
_request: ComposerAttachmentUploadRequest,
|
||||
_signal: AbortSignal,
|
||||
report: (value: number) => void,
|
||||
): Promise<boolean> => {
|
||||
report(0.12);
|
||||
report(0.13);
|
||||
report(1.1);
|
||||
throw new Error("Server unavailable");
|
||||
},
|
||||
);
|
||||
const queue = createComposerAttachmentUploadQueue({
|
||||
upload,
|
||||
onChange: (next) => {
|
||||
states = next;
|
||||
const state = next[composerAttachmentUploadKey(environmentId, "file")];
|
||||
if (state?.status === "uploading") progress.push(state.progress);
|
||||
},
|
||||
});
|
||||
queue.sync([request("file")]);
|
||||
await queue.settled();
|
||||
queue.sync([request("file")]);
|
||||
expect(upload).toHaveBeenCalledOnce();
|
||||
expect(states[composerAttachmentUploadKey(environmentId, "file")]).toEqual({
|
||||
status: "failed",
|
||||
reason: "Server unavailable",
|
||||
});
|
||||
expect(progress).toEqual([0, 0.1, 1]);
|
||||
upload.mockImplementationOnce(async () => true);
|
||||
queue.retry(environmentId, "file");
|
||||
await queue.settled();
|
||||
expect(states[composerAttachmentUploadKey(environmentId, "file")]).toEqual({ status: "ready" });
|
||||
queue.dispose();
|
||||
});
|
||||
|
||||
it("does not spin when an upload's draft was abandoned before persistence", async () => {
|
||||
const upload = vi.fn(async () => false);
|
||||
const queue = createComposerAttachmentUploadQueue({ upload, onChange: () => {} });
|
||||
queue.sync([request("discarded")]);
|
||||
await queue.settled();
|
||||
expect(upload).toHaveBeenCalledOnce();
|
||||
queue.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe("draft upload scope and offline submission", () => {
|
||||
it("resolves thread, new-task, and queued-task drafts without crossing environments", () => {
|
||||
expect(composerDraftEnvironmentId("environment-1:thread", [])).toBe(environmentId);
|
||||
expect(composerDraftEnvironmentId("new-task:environment-1:project", [])).toBe(environmentId);
|
||||
expect(
|
||||
composerDraftEnvironmentId("pending-task:message", [{ messageId: "message", environmentId }]),
|
||||
).toBe(environmentId);
|
||||
expect(composerDraftEnvironmentId("pending-task:missing", [])).toBeNull();
|
||||
const colonEnvironment = EnvironmentId.make("a:vcs-status:b");
|
||||
expect(composerDraftEnvironmentId(`${colonEnvironment}:thread`, [])).toBe(colonEnvironment);
|
||||
expect(composerDraftEnvironmentId(`new-task:${colonEnvironment}:project`, [])).toBe(
|
||||
colonEnvironment,
|
||||
);
|
||||
});
|
||||
|
||||
it("allows offline queuing while a connected composer waits for upload or retry", () => {
|
||||
const key = composerAttachmentUploadKey(environmentId, "file");
|
||||
const input = {
|
||||
environmentId,
|
||||
attachments: [request("file").attachment],
|
||||
connected: true,
|
||||
serverConfig: {
|
||||
environment: {
|
||||
capabilities: { attachmentUploads: true, fileAttachments: { maxUploadBytes: 1024 } },
|
||||
},
|
||||
},
|
||||
states: {},
|
||||
};
|
||||
expect(composerAttachmentUploadBlockReason(input)).toBe("Attachment still uploading");
|
||||
expect(composerAttachmentUploadBlockReason({ ...input, connected: false })).toBeNull();
|
||||
expect(
|
||||
composerAttachmentUploadBlockReason({
|
||||
...input,
|
||||
states: { [key]: { status: "failed", reason: "Offline" } },
|
||||
}),
|
||||
).toBe("Retry or remove the failed attachment");
|
||||
expect(
|
||||
composerAttachmentUploadBlockReason({ ...input, states: { [key]: { status: "ready" } } }),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
import { EnvironmentId, type ServerConfig } from "@t3tools/contracts";
|
||||
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
|
||||
|
||||
import type { DraftComposerAttachment } from "./composerImages";
|
||||
|
||||
export interface ComposerAttachmentUploadRequest {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly attachment: DraftComposerAttachment;
|
||||
}
|
||||
|
||||
export type ComposerAttachmentUploadState =
|
||||
| { readonly status: "uploading"; readonly progress: number }
|
||||
| { readonly status: "ready" }
|
||||
| { readonly status: "failed"; readonly reason: string };
|
||||
|
||||
export function composerAttachmentUploadKey(
|
||||
environmentId: EnvironmentId,
|
||||
attachmentId: string,
|
||||
): string {
|
||||
return `${environmentId}:${attachmentId}`;
|
||||
}
|
||||
|
||||
export function composerDraftEnvironmentId(
|
||||
draftKey: string,
|
||||
queuedMessages: ReadonlyArray<{
|
||||
readonly messageId: string;
|
||||
readonly environmentId: EnvironmentId;
|
||||
}>,
|
||||
): EnvironmentId | null {
|
||||
if (draftKey.startsWith("pending-task:")) {
|
||||
return (
|
||||
queuedMessages.find((message) => `pending-task:${message.messageId}` === draftKey)
|
||||
?.environmentId ?? null
|
||||
);
|
||||
}
|
||||
const scope = draftKey.startsWith("new-task:") ? draftKey.slice("new-task:".length) : draftKey;
|
||||
const separator = scope.lastIndexOf(":");
|
||||
return separator > 0 ? EnvironmentId.make(scope.slice(0, separator)) : null;
|
||||
}
|
||||
|
||||
type UploadServerConfig = {
|
||||
readonly environment: {
|
||||
readonly capabilities: Pick<
|
||||
ServerConfig["environment"]["capabilities"],
|
||||
"attachmentUploads" | "fileAttachments"
|
||||
>;
|
||||
};
|
||||
};
|
||||
|
||||
export function canUploadComposerAttachment(
|
||||
attachment: DraftComposerAttachment,
|
||||
config: UploadServerConfig | null | undefined,
|
||||
): boolean {
|
||||
const capabilities = config?.environment.capabilities;
|
||||
return (
|
||||
capabilities?.attachmentUploads === true &&
|
||||
(attachment.type === "image" ||
|
||||
(capabilities.fileAttachments !== undefined &&
|
||||
attachment.sizeBytes <=
|
||||
clampFileAttachmentUploadBytes(capabilities.fileAttachments.maxUploadBytes)))
|
||||
);
|
||||
}
|
||||
|
||||
export function composerAttachmentUploadBlockReason(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly connected: boolean;
|
||||
readonly serverConfig: UploadServerConfig | null;
|
||||
readonly states: Readonly<Record<string, ComposerAttachmentUploadState>>;
|
||||
}): string | null {
|
||||
if (!input.connected) return null;
|
||||
for (const attachment of input.attachments) {
|
||||
if (!canUploadComposerAttachment(attachment, input.serverConfig)) continue;
|
||||
const state = input.states[composerAttachmentUploadKey(input.environmentId, attachment.id)];
|
||||
if (state?.status === "failed") return "Retry or remove the failed attachment";
|
||||
if (state?.status !== "ready") return "Attachment still uploading";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Bounds transfers across environments; disconnected or discarded drafts keep their local bytes. */
|
||||
export function createComposerAttachmentUploadQueue(options: {
|
||||
readonly upload: (
|
||||
request: ComposerAttachmentUploadRequest,
|
||||
signal: AbortSignal,
|
||||
onProgress: (progress: number) => void,
|
||||
) => Promise<boolean>;
|
||||
readonly onChange: (states: Readonly<Record<string, ComposerAttachmentUploadState>>) => void;
|
||||
}) {
|
||||
const jobs = new Map<
|
||||
string,
|
||||
{ readonly controller: AbortController; readonly done: Promise<void> }
|
||||
>();
|
||||
let desired = new Map<string, ComposerAttachmentUploadRequest>();
|
||||
let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
|
||||
let disposed = false;
|
||||
|
||||
function setState(key: string, state: ComposerAttachmentUploadState | undefined) {
|
||||
const previous = states[key];
|
||||
if (
|
||||
previous === state ||
|
||||
(previous?.status === "uploading" &&
|
||||
state?.status === "uploading" &&
|
||||
previous.progress === state.progress)
|
||||
)
|
||||
return;
|
||||
const next = { ...states };
|
||||
if (state) next[key] = state;
|
||||
else delete next[key];
|
||||
states = next;
|
||||
options.onChange(states);
|
||||
}
|
||||
|
||||
function pump() {
|
||||
if (disposed) return;
|
||||
for (const [key, request] of desired) {
|
||||
if (jobs.size >= 3) break;
|
||||
if (jobs.has(key) || states[key]?.status === "ready" || states[key]?.status === "failed")
|
||||
continue;
|
||||
const controller = new AbortController();
|
||||
setState(key, { status: "uploading", progress: 0 });
|
||||
// Publish the job before starting async work, including synchronous test transports.
|
||||
const done = Promise.resolve()
|
||||
.then(() =>
|
||||
options.upload(request, controller.signal, (progress) => {
|
||||
if (controller.signal.aborted) return;
|
||||
setState(key, {
|
||||
status: "uploading",
|
||||
progress: Math.floor(Math.max(0, Math.min(1, progress)) * 20) / 20,
|
||||
});
|
||||
}),
|
||||
)
|
||||
.then((persisted) => {
|
||||
if (!controller.signal.aborted && desired.has(key)) {
|
||||
if (!persisted) desired.delete(key);
|
||||
setState(key, persisted ? { status: "ready" } : undefined);
|
||||
}
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!controller.signal.aborted && desired.has(key)) {
|
||||
setState(key, {
|
||||
status: "failed",
|
||||
reason: error instanceof Error ? error.message : "Upload failed. Tap to retry.",
|
||||
});
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
jobs.delete(key);
|
||||
pump();
|
||||
});
|
||||
jobs.set(key, { controller, done });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
sync(requests: ReadonlyArray<ComposerAttachmentUploadRequest>) {
|
||||
if (disposed) return;
|
||||
desired = new Map(
|
||||
requests.map((request) => [
|
||||
composerAttachmentUploadKey(request.environmentId, request.attachment.id),
|
||||
request,
|
||||
]),
|
||||
);
|
||||
for (const [key, job] of jobs) {
|
||||
if (!desired.has(key)) job.controller.abort();
|
||||
}
|
||||
for (const key of Object.keys(states)) {
|
||||
if (!desired.has(key)) setState(key, undefined);
|
||||
}
|
||||
for (const key of desired.keys()) {
|
||||
if (!states[key]) setState(key, { status: "uploading", progress: 0 });
|
||||
}
|
||||
pump();
|
||||
},
|
||||
retry(environmentId: EnvironmentId, attachmentId: string) {
|
||||
const key = composerAttachmentUploadKey(environmentId, attachmentId);
|
||||
if (states[key]?.status !== "failed") return;
|
||||
setState(key, undefined);
|
||||
pump();
|
||||
},
|
||||
/** Waits for the current transfers, useful for shutdown and focused verification. */
|
||||
async settled() {
|
||||
while (jobs.size > 0) await Promise.all([...jobs.values()].map((job) => job.done));
|
||||
},
|
||||
dispose() {
|
||||
disposed = true;
|
||||
desired.clear();
|
||||
for (const job of jobs.values()) job.controller.abort();
|
||||
states = {};
|
||||
options.onChange(states);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -23,6 +23,8 @@ import { uuidv4 } from "./uuid";
|
||||
export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
|
||||
readonly id: string;
|
||||
readonly previewUri: string;
|
||||
readonly uploadedAttachmentId?: string;
|
||||
readonly uploadEnvironmentId?: EnvironmentId;
|
||||
}
|
||||
|
||||
export interface DraftComposerFileAttachment {
|
||||
|
||||
@@ -2,15 +2,14 @@ import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
ThreadId,
|
||||
type ChatFileAttachment,
|
||||
type ModelSelection,
|
||||
type ProjectId,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
type UploadChatImageAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { toUploadChatImageAttachments, type DraftComposerAttachment } from "./composerImages";
|
||||
import type { UploadedMobileAttachment } from "./attachmentUpload";
|
||||
|
||||
export function deriveThreadTitleFromPrompt(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
@@ -31,7 +30,7 @@ export interface ProjectThreadStartTurnSpec {
|
||||
readonly createdAt: string;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
readonly uploadedAttachments?: ReadonlyArray<UploadChatImageAttachment | ChatFileAttachment>;
|
||||
readonly uploadedAttachments?: ReadonlyArray<UploadedMobileAttachment>;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly interactionMode: ProviderInteractionMode;
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
import { prepareTurnAttachments } from "../lib/attachmentUpload";
|
||||
import {
|
||||
composerAttachmentUploadKey,
|
||||
composerDraftEnvironmentId,
|
||||
canUploadComposerAttachment,
|
||||
createComposerAttachmentUploadQueue,
|
||||
type ComposerAttachmentUploadState,
|
||||
} from "../lib/composerAttachmentUploadQueue";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { useServerConfigs } from "./entities";
|
||||
import { flattenQueuedThreadMessages, threadOutboxManager } from "./thread-outbox";
|
||||
import { useThreadOutboxMessages } from "./use-thread-outbox";
|
||||
import {
|
||||
composerDraftsAtom,
|
||||
ensureComposerDraftsLoaded,
|
||||
flushComposerDrafts,
|
||||
retainComposerAttachmentFileForPreview,
|
||||
setComposerDraftAttachmentUpload,
|
||||
} from "./use-composer-drafts";
|
||||
import { useRemoteConnectionStatus } from "./use-remote-environment-registry";
|
||||
|
||||
export { composerAttachmentUploadBlockReason } from "../lib/composerAttachmentUploadQueue";
|
||||
|
||||
export const composerAttachmentUploadsAtom = Atom.make<
|
||||
Readonly<Record<string, ComposerAttachmentUploadState>>
|
||||
>({}).pipe(Atom.keepAlive);
|
||||
const uploadStateAtom = Atom.family((key: string) =>
|
||||
Atom.map(composerAttachmentUploadsAtom, (states) => states[key]),
|
||||
);
|
||||
let uploadQueue: ReturnType<typeof createComposerAttachmentUploadQueue> | null = null;
|
||||
|
||||
export function useComposerAttachmentUploadState(
|
||||
environmentId: EnvironmentId | undefined,
|
||||
attachmentId: string,
|
||||
) {
|
||||
return useAtomValue(
|
||||
uploadStateAtom(environmentId ? composerAttachmentUploadKey(environmentId, attachmentId) : ""),
|
||||
);
|
||||
}
|
||||
|
||||
export function retryComposerAttachmentUpload(environmentId: EnvironmentId, attachmentId: string) {
|
||||
uploadQueue?.retry(environmentId, attachmentId);
|
||||
}
|
||||
|
||||
/** Runs outside mounted composers so a transfer can finish after navigation. */
|
||||
export function useComposerAttachmentUploadWorker() {
|
||||
const drafts = useAtomValue(composerDraftsAtom);
|
||||
const queuedMessages = useThreadOutboxMessages();
|
||||
const serverConfigs = useServerConfigs();
|
||||
const { connectedEnvironments } = useRemoteConnectionStatus();
|
||||
const queueRef = useRef<ReturnType<typeof createComposerAttachmentUploadQueue> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
ensureComposerDraftsLoaded();
|
||||
const queue = createComposerAttachmentUploadQueue({
|
||||
onChange: (states) => appAtomRegistry.set(composerAttachmentUploadsAtom, states),
|
||||
upload: async ({ environmentId, attachment }, signal, onProgress) => {
|
||||
const release =
|
||||
attachment.type === "file"
|
||||
? retainComposerAttachmentFileForPreview(attachment)
|
||||
: undefined;
|
||||
try {
|
||||
const result = await prepareTurnAttachments({
|
||||
environmentId,
|
||||
attachments: [attachment],
|
||||
supportsImageUploads: true,
|
||||
signal,
|
||||
onUploadProgress: (_, progress) => onProgress(progress),
|
||||
persistUploadedReferences: async ([uploaded]) => {
|
||||
if (signal.aborted || !uploaded) return "abandon";
|
||||
const queued = flattenQueuedThreadMessages(
|
||||
appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
|
||||
);
|
||||
let retained = false;
|
||||
for (const [key, draft] of Object.entries(appAtomRegistry.get(composerDraftsAtom))) {
|
||||
if (
|
||||
composerDraftEnvironmentId(key, queued) === environmentId &&
|
||||
draft.attachments.some((candidate) => candidate.id === attachment.id)
|
||||
) {
|
||||
retained = setComposerDraftAttachmentUpload(key, uploaded) || retained;
|
||||
}
|
||||
}
|
||||
if (!retained) return "abandon";
|
||||
await flushComposerDrafts();
|
||||
return "persisted";
|
||||
},
|
||||
});
|
||||
return result.status === "ready";
|
||||
} finally {
|
||||
release?.();
|
||||
}
|
||||
},
|
||||
});
|
||||
queueRef.current = queue;
|
||||
uploadQueue = queue;
|
||||
return () => {
|
||||
queue.dispose();
|
||||
if (uploadQueue === queue) uploadQueue = null;
|
||||
queueRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const queued = flattenQueuedThreadMessages(queuedMessages);
|
||||
const connected = new Set(
|
||||
connectedEnvironments
|
||||
.filter((environment) => environment.connectionState === "connected")
|
||||
.map((environment) => environment.environmentId),
|
||||
);
|
||||
const requests = Object.entries(drafts).flatMap(([key, draft]) => {
|
||||
const environmentId = composerDraftEnvironmentId(key, queued);
|
||||
if (environmentId === null || !connected.has(environmentId)) return [];
|
||||
return draft.attachments
|
||||
.filter((attachment) =>
|
||||
canUploadComposerAttachment(attachment, serverConfigs.get(environmentId)),
|
||||
)
|
||||
.map((attachment) => ({ environmentId, attachment }));
|
||||
});
|
||||
queueRef.current?.sync(requests);
|
||||
}, [connectedEnvironments, drafts, queuedMessages, serverConfigs]);
|
||||
}
|
||||
@@ -118,10 +118,12 @@ import { appAtomRegistry } from "./atom-registry";
|
||||
import { threadOutboxManager } from "./thread-outbox";
|
||||
import {
|
||||
appendComposerDraftAttachments,
|
||||
archiveCloudComposerDrafts,
|
||||
clearComposerDraftContentState,
|
||||
clearComposerDraftsEnvironment,
|
||||
ComposerDraftPersistenceError,
|
||||
composerDraftsAtom,
|
||||
composerCloudDraftsAtom,
|
||||
copyComposerDraftContentIfEmpty,
|
||||
copyComposerDraftContentState,
|
||||
decodePersistedComposerState,
|
||||
@@ -136,7 +138,10 @@ import {
|
||||
resetComposerDraftsLoadState,
|
||||
retainComposerAttachmentFileForPreview,
|
||||
restoreComposerDraftSnapshotState,
|
||||
restoreCloudComposerDrafts,
|
||||
setComposerDraftText,
|
||||
setComposerDraftAttachmentUpload,
|
||||
waitForComposerDraftsLoaded,
|
||||
setStickyComposerModelSelection,
|
||||
stickyComposerModelSelectionAtom,
|
||||
undoComposerDraftMerge,
|
||||
@@ -157,6 +162,7 @@ afterEach(() => {
|
||||
composerDraftFileMocks.setOnWrite(null);
|
||||
composerDraftFileMocks.resetWrites();
|
||||
appAtomRegistry.set(composerDraftsAtom, {});
|
||||
appAtomRegistry.set(composerCloudDraftsAtom, { accountId: null, signedOut: {} });
|
||||
appAtomRegistry.set(stickyComposerModelSelectionAtom, null);
|
||||
appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
|
||||
composerAttachmentCleanupMocks.remove.mockClear();
|
||||
@@ -320,6 +326,150 @@ describe("mobile composer drafts", () => {
|
||||
expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("retains offline image bytes and newer edits when an early upload finishes", async () => {
|
||||
const key = "environment-1:thread-1";
|
||||
const image = {
|
||||
id: "photo",
|
||||
type: "image" as const,
|
||||
name: "photo.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 3,
|
||||
dataUrl: "data:image/png;base64,YWJj",
|
||||
previewUri: "file:///photo.png",
|
||||
};
|
||||
const second = { ...image, id: "second", name: "second.png" };
|
||||
const uploaded = {
|
||||
...image,
|
||||
uploadedAttachmentId: "pending-photo",
|
||||
uploadEnvironmentId: EnvironmentId.make("environment-1"),
|
||||
};
|
||||
composerDraftFileMocks.setDocument({ schemaVersion: 1, drafts: {} });
|
||||
appendComposerDraftAttachments(key, [image]);
|
||||
setComposerDraftText(key, "Edited while uploading");
|
||||
appendComposerDraftAttachments(key, [second]);
|
||||
expect(setComposerDraftAttachmentUpload(key, uploaded)).toBe(true);
|
||||
await flushComposerDrafts();
|
||||
|
||||
appAtomRegistry.set(composerDraftsAtom, {});
|
||||
resetComposerDraftsLoadState();
|
||||
await waitForComposerDraftsLoaded();
|
||||
expect(getComposerDraftSnapshot(key)).toMatchObject({
|
||||
text: "Edited while uploading",
|
||||
attachments: [uploaded, second],
|
||||
});
|
||||
expect(setComposerDraftAttachmentUpload(key, { ...uploaded, id: "removed-photo" })).toBe(false);
|
||||
expect(getComposerDraftSnapshot(key).attachments).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("cleans up an unreferenced image upload even when there is no local file URI", async () => {
|
||||
const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
|
||||
onTestFinished(() => outboxLoad.mockRestore());
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
await releaseUnusedComposerAttachmentFiles([
|
||||
{
|
||||
id: "photo",
|
||||
type: "image",
|
||||
name: "photo.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 3,
|
||||
dataUrl: "data:image/png;base64,YWJj",
|
||||
previewUri: "file:///photo.png",
|
||||
uploadedAttachmentId: "pending-photo",
|
||||
uploadEnvironmentId: environmentId,
|
||||
},
|
||||
]);
|
||||
expect(composerAttachmentCleanupMocks.releaseUploads).toHaveBeenCalledWith(environmentId, [
|
||||
"pending-photo",
|
||||
]);
|
||||
expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps signed-out files through cleanup and restart, and restores only the owning account", async () => {
|
||||
const load = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
|
||||
onTestFinished(() => load.mockRestore());
|
||||
await waitForComposerDraftsLoaded();
|
||||
const environmentId = EnvironmentId.make("cloud-environment");
|
||||
const key = `${environmentId}:thread-1`;
|
||||
const file = {
|
||||
id: "local-pdf",
|
||||
type: "file" as const,
|
||||
name: "notes.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
fileUri: "file:///documents/t3-composer-attachments/notes.pdf",
|
||||
uploadEnvironmentId: environmentId,
|
||||
uploadedAttachmentId: "pending-pdf",
|
||||
};
|
||||
const queued = {
|
||||
environmentId,
|
||||
threadId: ThreadId.make("thread-2"),
|
||||
messageId: MessageId.make("queued-1"),
|
||||
commandId: CommandId.make("command-1"),
|
||||
text: "Send later",
|
||||
attachments: [file],
|
||||
createdAt: "2026-08-31T12:00:00.000Z",
|
||||
};
|
||||
appAtomRegistry.set(composerDraftsAtom, {
|
||||
[key]: { text: "Unsent notes", attachments: [file] },
|
||||
"direct-environment:thread-1": DRAFT,
|
||||
"pending-task:queued-1": { text: "Edited queued task", attachments: [file] },
|
||||
});
|
||||
appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, { queued: [queued] });
|
||||
await archiveCloudComposerDrafts("account-a", new Set([environmentId]));
|
||||
expect(appAtomRegistry.get(composerDraftsAtom)).toEqual({
|
||||
"direct-environment:thread-1": DRAFT,
|
||||
});
|
||||
// The registry can remove the active outbox and drafts after the backup lands.
|
||||
appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
|
||||
await clearComposerDraftsEnvironment(environmentId);
|
||||
await releaseUnusedComposerAttachmentFiles([file]);
|
||||
expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
|
||||
expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled();
|
||||
|
||||
appAtomRegistry.set(composerDraftsAtom, {});
|
||||
appAtomRegistry.set(composerCloudDraftsAtom, { accountId: null, signedOut: {} });
|
||||
resetComposerDraftsLoadState();
|
||||
await waitForComposerDraftsLoaded();
|
||||
await restoreCloudComposerDrafts("account-b");
|
||||
expect(getComposerDraftSnapshot(key).attachments).toEqual([]);
|
||||
expect(appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom)).toEqual({});
|
||||
const enqueue = vi.spyOn(threadOutboxManager, "enqueue").mockResolvedValue();
|
||||
onTestFinished(() => enqueue.mockRestore());
|
||||
await restoreCloudComposerDrafts("account-a");
|
||||
expect(getComposerDraftSnapshot(key)).toEqual({ text: "Unsent notes", attachments: [file] });
|
||||
expect(getComposerDraftSnapshot("pending-task:queued-1").text).toBe("Edited queued task");
|
||||
expect(enqueue).toHaveBeenCalledExactlyOnceWith(queued);
|
||||
expect(appAtomRegistry.get(composerCloudDraftsAtom).signedOut).toEqual({});
|
||||
const persisted = decodePersistedComposerState(
|
||||
JSON.parse(composerDraftFileMocks.getDocument()),
|
||||
);
|
||||
expect(persisted.drafts[key]?.attachments).toEqual([file]);
|
||||
expect(persisted.cloudDrafts.accountId).toBe("account-a");
|
||||
});
|
||||
|
||||
it("fails sign-out preservation before cleanup if a durable backup cannot be written", async () => {
|
||||
const load = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
|
||||
onTestFinished(() => load.mockRestore());
|
||||
await waitForComposerDraftsLoaded();
|
||||
appAtomRegistry.set(composerDraftsAtom, { "environment-1:thread-1": DRAFT });
|
||||
composerDraftFileMocks.setWriteError(new Error("Storage is full"));
|
||||
await expect(
|
||||
archiveCloudComposerDrafts("account-a", new Set([EnvironmentId.make("environment-1")])),
|
||||
).rejects.toThrow();
|
||||
expect(
|
||||
appAtomRegistry.get(composerCloudDraftsAtom).signedOut["account-a"]?.drafts[
|
||||
"environment-1:thread-1"
|
||||
],
|
||||
).toEqual(DRAFT);
|
||||
expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
|
||||
composerDraftFileMocks.setWriteError(null);
|
||||
await archiveCloudComposerDrafts(null, new Set([EnvironmentId.make("environment-1")]));
|
||||
expect(
|
||||
decodePersistedComposerState(JSON.parse(composerDraftFileMocks.getDocument())).cloudDrafts
|
||||
.signedOut["account-a"]?.drafts["environment-1:thread-1"],
|
||||
).toEqual(DRAFT);
|
||||
});
|
||||
|
||||
it("keeps a removed file until both playback and a share copy finish", async () => {
|
||||
const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true);
|
||||
onTestFinished(() => outboxLoad.mockRestore());
|
||||
|
||||
@@ -23,7 +23,14 @@ import {
|
||||
import type { DraftComposerAttachment, DraftComposerFileAttachment } from "../lib/composerImages";
|
||||
import { SerializedAsyncQueue } from "../lib/serialized-async-queue";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import {
|
||||
decodeQueuedThreadMessage,
|
||||
encodeQueuedThreadMessage,
|
||||
QueuedThreadMessageSchema,
|
||||
type QueuedThreadMessage,
|
||||
} from "./thread-outbox-model";
|
||||
import { flushThreadOutbox, threadOutboxManager } from "./thread-outbox";
|
||||
import { composerDraftEnvironmentId } from "../lib/composerAttachmentUploadQueue";
|
||||
|
||||
const COMPOSER_DRAFTS_SCHEMA_VERSION = 1;
|
||||
const COMPOSER_DRAFTS_DIRECTORY = "composer-drafts";
|
||||
@@ -93,6 +100,16 @@ const PersistedComposerDraftsSchema = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION),
|
||||
drafts: Schema.Record(Schema.String, ComposerDraftSchema),
|
||||
stickyModelSelection: Schema.optional(ModelSelectionSchema),
|
||||
cloudAccountId: Schema.optional(Schema.String),
|
||||
signedOutDrafts: Schema.optional(
|
||||
Schema.Record(
|
||||
Schema.String,
|
||||
Schema.Struct({
|
||||
drafts: Schema.Record(Schema.String, ComposerDraftSchema),
|
||||
queuedMessages: Schema.Array(QueuedThreadMessageSchema),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const decodePersistedComposerDraftsDocument = Schema.decodeUnknownSync(
|
||||
@@ -114,6 +131,21 @@ export const stickyComposerModelSelectionAtom = Atom.make<ModelSelection | null>
|
||||
Atom.withLabel("mobile:sticky-composer-model-selection"),
|
||||
);
|
||||
|
||||
interface SignedOutDrafts {
|
||||
readonly drafts: Record<string, ComposerDraft>;
|
||||
readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
|
||||
}
|
||||
|
||||
interface ComposerCloudDraftState {
|
||||
readonly accountId: string | null;
|
||||
readonly signedOut: Record<string, SignedOutDrafts>;
|
||||
}
|
||||
|
||||
export const composerCloudDraftsAtom = Atom.make<ComposerCloudDraftState>({
|
||||
accountId: null,
|
||||
signedOut: {},
|
||||
}).pipe(Atom.keepAlive);
|
||||
|
||||
let loadPromise: Promise<void> | null = null;
|
||||
let persistTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const persistenceQueue = new SerializedAsyncQueue();
|
||||
@@ -156,6 +188,7 @@ function isEmptyDraft(draft: ComposerDraft): boolean {
|
||||
export function decodePersistedComposerState(value: unknown): {
|
||||
readonly drafts: Record<string, ComposerDraft>;
|
||||
readonly stickyModelSelection: ModelSelection | null;
|
||||
readonly cloudDrafts: ComposerCloudDraftState;
|
||||
} {
|
||||
const parsed = decodePersistedComposerDraftsDocument(value);
|
||||
return {
|
||||
@@ -188,6 +221,18 @@ export function decodePersistedComposerState(value: unknown): {
|
||||
.filter(([, draft]) => !isEmptyDraft(draft) || (draft.importedShareIds?.length ?? 0) > 0),
|
||||
),
|
||||
stickyModelSelection: parsed.stickyModelSelection ?? null,
|
||||
cloudDrafts: {
|
||||
accountId: parsed.cloudAccountId ?? null,
|
||||
signedOut: Object.fromEntries(
|
||||
Object.entries(parsed.signedOutDrafts ?? {}).map(([id, saved]) => [
|
||||
id,
|
||||
{
|
||||
drafts: saved.drafts,
|
||||
queuedMessages: saved.queuedMessages.map(decodeQueuedThreadMessage),
|
||||
},
|
||||
]),
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -202,15 +247,18 @@ async function getComposerDraftsFile() {
|
||||
return new File(directory, COMPOSER_DRAFTS_FILE);
|
||||
}
|
||||
|
||||
async function loadPersistedComposerState(): Promise<{
|
||||
readonly drafts: Record<string, ComposerDraft>;
|
||||
readonly stickyModelSelection: ModelSelection | null;
|
||||
}> {
|
||||
async function loadPersistedComposerState(): Promise<
|
||||
ReturnType<typeof decodePersistedComposerState>
|
||||
> {
|
||||
let operation: ComposerDraftPersistenceError["operation"] = "open";
|
||||
try {
|
||||
const file = await getComposerDraftsFile();
|
||||
if (!file.exists) {
|
||||
return { drafts: {}, stickyModelSelection: null };
|
||||
return {
|
||||
drafts: {},
|
||||
stickyModelSelection: null,
|
||||
cloudDrafts: { accountId: null, signedOut: {} },
|
||||
};
|
||||
}
|
||||
operation = "read";
|
||||
const raw = await file.text();
|
||||
@@ -226,13 +274,18 @@ async function loadPersistedComposerState(): Promise<{
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
return { drafts: {}, stickyModelSelection: null };
|
||||
return {
|
||||
drafts: {},
|
||||
stickyModelSelection: null,
|
||||
cloudDrafts: { accountId: null, signedOut: {} },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function writePersistedComposerState(
|
||||
drafts: Record<string, ComposerDraft>,
|
||||
stickyModelSelection: ModelSelection | null,
|
||||
cloudDrafts = appAtomRegistry.get(composerCloudDraftsAtom),
|
||||
): Promise<void> {
|
||||
let operation: ComposerDraftPersistenceError["operation"] = "open";
|
||||
try {
|
||||
@@ -245,6 +298,20 @@ async function writePersistedComposerState(
|
||||
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
|
||||
drafts: nonEmptyDrafts,
|
||||
...(stickyModelSelection ? { stickyModelSelection } : {}),
|
||||
...(cloudDrafts.accountId ? { cloudAccountId: cloudDrafts.accountId } : {}),
|
||||
...(Object.keys(cloudDrafts.signedOut).length > 0
|
||||
? {
|
||||
signedOutDrafts: Object.fromEntries(
|
||||
Object.entries(cloudDrafts.signedOut).map(([id, saved]) => [
|
||||
id,
|
||||
{
|
||||
drafts: saved.drafts,
|
||||
queuedMessages: saved.queuedMessages.map(encodeQueuedThreadMessage),
|
||||
},
|
||||
]),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
} as const;
|
||||
const encoded = JSON.stringify(document);
|
||||
operation = "write";
|
||||
@@ -290,6 +357,13 @@ export async function flushComposerDrafts(): Promise<void> {
|
||||
} while (persistTimer !== null);
|
||||
}
|
||||
|
||||
function signedOutAttachmentOwners() {
|
||||
return Object.values(appAtomRegistry.get(composerCloudDraftsAtom).signedOut).flatMap((saved) => [
|
||||
...Object.values(saved.drafts),
|
||||
...saved.queuedMessages,
|
||||
]);
|
||||
}
|
||||
|
||||
function isComposerAttachmentFileReferenced(fileUri: string): boolean {
|
||||
if (isComposerAttachmentFileRetained(fileUri)) {
|
||||
return true;
|
||||
@@ -299,7 +373,7 @@ function isComposerAttachmentFileReferenced(fileUri: string): boolean {
|
||||
const queuedMessages = Object.values(
|
||||
appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
|
||||
).flat();
|
||||
return [...drafts, ...queuedMessages].some((owner) =>
|
||||
return [...drafts, ...queuedMessages, ...signedOutAttachmentOwners()].some((owner) =>
|
||||
owner.attachments.some(
|
||||
(attachment) =>
|
||||
attachment.type === "file" &&
|
||||
@@ -316,10 +390,9 @@ function isComposerAttachmentUploadReferenced(
|
||||
const queuedMessages = Object.values(
|
||||
appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
|
||||
).flat();
|
||||
return [...drafts, ...queuedMessages].some((owner) =>
|
||||
return [...drafts, ...queuedMessages, ...signedOutAttachmentOwners()].some((owner) =>
|
||||
owner.attachments.some(
|
||||
(attachment) =>
|
||||
attachment.type === "file" &&
|
||||
attachment.uploadEnvironmentId === environmentId &&
|
||||
attachment.uploadedAttachmentId === attachmentId,
|
||||
),
|
||||
@@ -337,7 +410,6 @@ export async function releaseUnusedComposerAttachmentFiles(
|
||||
const uploadCandidates = new Map<EnvironmentId, Set<string>>();
|
||||
for (const attachment of attachments) {
|
||||
if (
|
||||
attachment.type !== "file" ||
|
||||
attachment.uploadEnvironmentId === undefined ||
|
||||
attachment.uploadedAttachmentId === undefined
|
||||
) {
|
||||
@@ -347,7 +419,7 @@ export async function releaseUnusedComposerAttachmentFiles(
|
||||
ids.add(attachment.uploadedAttachmentId);
|
||||
uploadCandidates.set(attachment.uploadEnvironmentId, ids);
|
||||
}
|
||||
if (candidates.size === 0) {
|
||||
if (candidates.size === 0 && uploadCandidates.size === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -435,7 +507,11 @@ export async function releaseUnusedComposerAttachmentFiles(
|
||||
export function scheduleUnusedComposerAttachmentCleanup(
|
||||
attachments: ReadonlyArray<DraftComposerAttachment>,
|
||||
): void {
|
||||
if (!attachments.some((attachment) => attachment.type === "file")) {
|
||||
if (
|
||||
!attachments.some(
|
||||
(attachment) => attachment.type === "file" || attachment.uploadedAttachmentId !== undefined,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
void releaseUnusedComposerAttachmentFiles(attachments).catch((error) => {
|
||||
@@ -443,7 +519,7 @@ export function scheduleUnusedComposerAttachmentCleanup(
|
||||
});
|
||||
}
|
||||
|
||||
/** Keeps previews usable after send/removal, then retries the normal ownership cleanup. */
|
||||
/** Keeps a native preview or upload readable until it finishes, then retries ownership cleanup. */
|
||||
export function retainComposerAttachmentFileForPreview(
|
||||
attachment: DraftComposerFileAttachment,
|
||||
): () => void {
|
||||
@@ -484,6 +560,7 @@ export function ensureComposerDraftsLoaded(): void {
|
||||
}
|
||||
loadPromise = loadPersistedComposerState()
|
||||
.then((persisted) => {
|
||||
appAtomRegistry.set(composerCloudDraftsAtom, persisted.cloudDrafts);
|
||||
if (Object.keys(persisted.drafts).length > 0) {
|
||||
const current = appAtomRegistry.get(composerDraftsAtom);
|
||||
appAtomRegistry.set(composerDraftsAtom, {
|
||||
@@ -520,6 +597,192 @@ export async function waitForComposerDraftsLoaded(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function getComposerCloudAccountId(): Promise<string | null> {
|
||||
await waitForComposerDraftsLoaded();
|
||||
return appAtomRegistry.get(composerCloudDraftsAtom).accountId;
|
||||
}
|
||||
|
||||
/** Save an account's local work before its relay environments are removed. */
|
||||
export async function archiveCloudComposerDrafts(
|
||||
accountId: string | null,
|
||||
environmentIds: ReadonlySet<EnvironmentId>,
|
||||
): Promise<void> {
|
||||
await waitForComposerDraftsLoaded();
|
||||
if (!(await threadOutboxManager.load())) throw new Error("Could not preserve queued messages.");
|
||||
await flushThreadOutbox();
|
||||
const cloud = appAtomRegistry.get(composerCloudDraftsAtom);
|
||||
const owner = accountId ?? cloud.accountId;
|
||||
if (owner === null) return;
|
||||
const queued = Object.values(
|
||||
appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
|
||||
).flat();
|
||||
const current = appAtomRegistry.get(composerDraftsAtom);
|
||||
const remaining = { ...current };
|
||||
const savedDrafts = { ...cloud.signedOut[owner]?.drafts };
|
||||
for (const [key, draft] of Object.entries(current)) {
|
||||
const environmentId = composerDraftEnvironmentId(key, queued);
|
||||
if (environmentId !== null && environmentIds.has(environmentId)) {
|
||||
savedDrafts[key] = draft;
|
||||
delete remaining[key];
|
||||
}
|
||||
}
|
||||
const savedMessages = new Map(
|
||||
(cloud.signedOut[owner]?.queuedMessages ?? []).map((message) => [message.messageId, message]),
|
||||
);
|
||||
for (const message of queued) {
|
||||
if (environmentIds.has(message.environmentId)) savedMessages.set(message.messageId, message);
|
||||
}
|
||||
appAtomRegistry.set(composerDraftsAtom, remaining);
|
||||
appAtomRegistry.set(composerCloudDraftsAtom, {
|
||||
// Keep the owner through removal. A crash or failed cleanup can retry it
|
||||
// on cold start before a different account activates.
|
||||
accountId: owner,
|
||||
signedOut: {
|
||||
...cloud.signedOut,
|
||||
[owner]: { drafts: savedDrafts, queuedMessages: [...savedMessages.values()] },
|
||||
},
|
||||
});
|
||||
schedulePersistComposerState();
|
||||
await flushComposerDrafts();
|
||||
}
|
||||
|
||||
function sameDraftAttachmentIds(
|
||||
left: ReadonlyArray<DraftComposerAttachment>,
|
||||
right: ReadonlyArray<DraftComposerAttachment>,
|
||||
): boolean {
|
||||
return (
|
||||
left.length === right.length &&
|
||||
left.every((attachment, index) => attachment.id === right[index]?.id)
|
||||
);
|
||||
}
|
||||
|
||||
/** An in-flight delivery can finish after sign-out took its snapshot. */
|
||||
export async function removeDeliveredCloudQueuedMessage(
|
||||
message: QueuedThreadMessage,
|
||||
): Promise<void> {
|
||||
await waitForComposerDraftsLoaded();
|
||||
const cloud = appAtomRegistry.get(composerCloudDraftsAtom);
|
||||
const signedOut = { ...cloud.signedOut };
|
||||
let changed = false;
|
||||
for (const [accountId, saved] of Object.entries(signedOut)) {
|
||||
const archived = saved.queuedMessages.find(
|
||||
(candidate) =>
|
||||
candidate.environmentId === message.environmentId &&
|
||||
candidate.messageId === message.messageId,
|
||||
);
|
||||
if (
|
||||
!archived ||
|
||||
archived.commandId !== message.commandId ||
|
||||
archived.threadId !== message.threadId ||
|
||||
archived.text !== message.text ||
|
||||
!sameDraftAttachmentIds(archived.attachments, message.attachments)
|
||||
)
|
||||
continue;
|
||||
// Upload ids may change during preparation; user edits must remain recoverable.
|
||||
if (
|
||||
JSON.stringify([
|
||||
archived.modelSelection,
|
||||
archived.runtimeMode,
|
||||
archived.interactionMode,
|
||||
archived.creation,
|
||||
]) !==
|
||||
JSON.stringify([
|
||||
message.modelSelection,
|
||||
message.runtimeMode,
|
||||
message.interactionMode,
|
||||
message.creation,
|
||||
])
|
||||
)
|
||||
continue;
|
||||
const editorKey = `pending-task:${message.messageId}`;
|
||||
const editor = saved.drafts[editorKey];
|
||||
if (
|
||||
editor &&
|
||||
(editor.text !== message.text ||
|
||||
!sameDraftAttachmentIds(editor.attachments, message.attachments) ||
|
||||
(editor.modelSelection !== undefined &&
|
||||
JSON.stringify(editor.modelSelection) !== JSON.stringify(message.modelSelection)) ||
|
||||
(editor.runtimeMode !== undefined && editor.runtimeMode !== message.runtimeMode) ||
|
||||
(editor.interactionMode !== undefined &&
|
||||
editor.interactionMode !== message.interactionMode) ||
|
||||
(editor.workspaceSelection !== undefined &&
|
||||
(editor.workspaceSelection.mode !== message.creation?.workspaceMode ||
|
||||
editor.workspaceSelection.branch !== message.creation?.branch ||
|
||||
editor.workspaceSelection.worktreePath !== message.creation?.worktreePath ||
|
||||
(editor.workspaceSelection.startFromOrigin ?? false) !==
|
||||
(message.creation?.startFromOrigin ?? false))))
|
||||
)
|
||||
continue;
|
||||
const drafts = { ...saved.drafts };
|
||||
delete drafts[editorKey];
|
||||
signedOut[accountId] = {
|
||||
drafts,
|
||||
queuedMessages: saved.queuedMessages.filter((candidate) => candidate !== archived),
|
||||
};
|
||||
changed = true;
|
||||
}
|
||||
if (!changed) return;
|
||||
appAtomRegistry.set(composerCloudDraftsAtom, { ...cloud, signedOut });
|
||||
schedulePersistComposerState();
|
||||
try {
|
||||
await flushComposerDrafts();
|
||||
} catch (error) {
|
||||
// The live outbox can still remove this acknowledged message. Keep the
|
||||
// archive update pending so a later successful flush lands it too.
|
||||
schedulePersistComposerState();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Restores only this account, before its connections can deliver queued turns. */
|
||||
export async function restoreCloudComposerDrafts(accountId: string): Promise<void> {
|
||||
await waitForComposerDraftsLoaded();
|
||||
const cloud = appAtomRegistry.get(composerCloudDraftsAtom);
|
||||
const saved = cloud.signedOut[accountId];
|
||||
if (saved) {
|
||||
if (!(await threadOutboxManager.load())) throw new Error("Could not restore queued messages.");
|
||||
for (const message of saved.queuedMessages) {
|
||||
const alreadyQueued = Object.values(
|
||||
appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
|
||||
)
|
||||
.flat()
|
||||
.some((current) => current.messageId === message.messageId);
|
||||
if (!alreadyQueued) await threadOutboxManager.enqueue(message);
|
||||
}
|
||||
updateComposerDrafts((current) => {
|
||||
const restored = { ...current };
|
||||
for (const [key, draft] of Object.entries(saved.drafts)) {
|
||||
const existing = current[key];
|
||||
const attachmentIds = new Set(existing?.attachments.map((attachment) => attachment.id));
|
||||
restored[key] = existing
|
||||
? {
|
||||
...draft,
|
||||
...existing,
|
||||
text: mergeComposerDraftText(existing.text, draft.text),
|
||||
// A concurrent import must not lose files, even above the send limit.
|
||||
attachments: [
|
||||
...existing.attachments,
|
||||
...draft.attachments.filter((attachment) => !attachmentIds.has(attachment.id)),
|
||||
],
|
||||
importedShareIds: [
|
||||
...new Set([
|
||||
...(existing.importedShareIds ?? []),
|
||||
...(draft.importedShareIds ?? []),
|
||||
]),
|
||||
],
|
||||
}
|
||||
: draft;
|
||||
}
|
||||
return restored;
|
||||
});
|
||||
}
|
||||
const signedOut = { ...cloud.signedOut };
|
||||
delete signedOut[accountId];
|
||||
appAtomRegistry.set(composerCloudDraftsAtom, { accountId, signedOut });
|
||||
schedulePersistComposerState();
|
||||
await flushComposerDrafts();
|
||||
}
|
||||
|
||||
function updateComposerDrafts(
|
||||
update: (current: Record<string, ComposerDraft>) => Record<string, ComposerDraft>,
|
||||
): void {
|
||||
@@ -655,6 +918,41 @@ export function removeComposerDraftAttachment(draftKey: string, imageId: string)
|
||||
);
|
||||
}
|
||||
|
||||
/** Stamps a finished upload without overwriting text, removals, or newer attachments. */
|
||||
export function setComposerDraftAttachmentUpload(
|
||||
draftKey: string,
|
||||
attachment: DraftComposerAttachment,
|
||||
): boolean {
|
||||
let previous: DraftComposerAttachment | undefined;
|
||||
updateComposerDrafts((current) => {
|
||||
const draft = current[draftKey];
|
||||
previous = draft?.attachments.find((candidate) => candidate.id === attachment.id);
|
||||
if (!draft || !previous) return current;
|
||||
if (
|
||||
previous.uploadedAttachmentId === attachment.uploadedAttachmentId &&
|
||||
previous.uploadEnvironmentId === attachment.uploadEnvironmentId
|
||||
)
|
||||
return current;
|
||||
return {
|
||||
...current,
|
||||
[draftKey]: {
|
||||
...draft,
|
||||
attachments: draft.attachments.map((candidate) =>
|
||||
candidate.id === attachment.id
|
||||
? {
|
||||
...candidate,
|
||||
uploadedAttachmentId: attachment.uploadedAttachmentId,
|
||||
uploadEnvironmentId: attachment.uploadEnvironmentId,
|
||||
}
|
||||
: candidate,
|
||||
),
|
||||
},
|
||||
};
|
||||
});
|
||||
if (previous) scheduleUnusedComposerAttachmentCleanup([previous]);
|
||||
return previous !== undefined;
|
||||
}
|
||||
|
||||
export function updateComposerDraftSettings(
|
||||
draftKey: string,
|
||||
settings: Partial<ComposerDraftSettingsUpdate>,
|
||||
|
||||
@@ -56,6 +56,10 @@ import { enqueueThreadOutboxMessage } from "./thread-outbox";
|
||||
import { useThreadOutboxMessages } from "./use-thread-outbox";
|
||||
import { threadEnvironment } from "./threads";
|
||||
import { useAtomCommand } from "./use-atom-command";
|
||||
import {
|
||||
composerAttachmentUploadBlockReason,
|
||||
composerAttachmentUploadsAtom,
|
||||
} from "./composer-attachment-uploads";
|
||||
|
||||
export function appendReviewCommentToDraft(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -178,6 +182,16 @@ export function useThreadComposerState() {
|
||||
const thread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const text = draft.text.trim();
|
||||
const attachments = draft.attachments;
|
||||
if (
|
||||
composerAttachmentUploadBlockReason({
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
attachments,
|
||||
connected: selectedEnvironmentRuntime?.connectionState === "connected",
|
||||
serverConfig: selectedEnvironmentRuntime?.serverConfig ?? null,
|
||||
states: appAtomRegistry.get(composerAttachmentUploadsAtom),
|
||||
}) !== null
|
||||
)
|
||||
return null;
|
||||
if (text.length === 0 && attachments.length === 0) {
|
||||
return null;
|
||||
}
|
||||
@@ -298,7 +312,8 @@ export function useThreadComposerState() {
|
||||
);
|
||||
return messageId;
|
||||
}, [
|
||||
selectedEnvironmentRuntime?.serverConfig?.providers,
|
||||
selectedEnvironmentRuntime?.connectionState,
|
||||
selectedEnvironmentRuntime?.serverConfig,
|
||||
selectedThreadDetail,
|
||||
selectedThreadShell,
|
||||
uploadThreadFeedback,
|
||||
|
||||
@@ -193,6 +193,7 @@ beforeEach(() => {
|
||||
afterEach(() => {
|
||||
appAtomRegistry.set(harness.manager.queuedMessagesByThreadKeyAtom, {});
|
||||
appAtomRegistry.set(composerDrafts.composerDraftsAtom, {});
|
||||
appAtomRegistry.set(composerDrafts.composerCloudDraftsAtom, { accountId: null, signedOut: {} });
|
||||
appAtomRegistry.set(editingQueuedMessageIdsAtom, {});
|
||||
harness.draftFile.setWriteError(null);
|
||||
harness.removePersistedFile.mockClear();
|
||||
@@ -321,6 +322,72 @@ describe("thread outbox attachment preparation", () => {
|
||||
});
|
||||
|
||||
describe("thread outbox drain delivery cleanup", () => {
|
||||
it("removes an acknowledged outbox item even when the sign-out archive write fails", async () => {
|
||||
const message = queuedMessage({ messageId: "archive-write-failure", text: "Delivered" });
|
||||
await harness.manager.enqueue(message);
|
||||
await composerDrafts.archiveCloudComposerDrafts("account-a", new Set([message.environmentId]));
|
||||
harness.draftFile.setWriteError(new Error("Draft storage unavailable"));
|
||||
|
||||
await expect(
|
||||
completeQueuedMessageDelivery(message, harness.manager.revisionOf(message.messageId)),
|
||||
).resolves.toBe("removed");
|
||||
expect(remainingMessages()).toEqual([]);
|
||||
|
||||
harness.draftFile.setWriteError(null);
|
||||
await composerDrafts.flushComposerDrafts();
|
||||
appAtomRegistry.set(composerDrafts.composerCloudDraftsAtom, { accountId: null, signedOut: {} });
|
||||
composerDrafts.resetComposerDraftsLoadState();
|
||||
await composerDrafts.restoreCloudComposerDrafts("account-a");
|
||||
expect(remainingMessages()).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
"does not restore a message delivered after the sign-out snapshot (outbox already cleared: %s)",
|
||||
async (cleared) => {
|
||||
const message = queuedMessage({
|
||||
messageId: "delivered-during-sign-out",
|
||||
text: "Already delivered",
|
||||
});
|
||||
await harness.manager.enqueue(message);
|
||||
const deliveryRevision = harness.manager.revisionOf(message.messageId);
|
||||
await composerDrafts.archiveCloudComposerDrafts(
|
||||
"account-a",
|
||||
new Set([message.environmentId]),
|
||||
);
|
||||
expect(
|
||||
appAtomRegistry.get(composerDrafts.composerCloudDraftsAtom).signedOut["account-a"]
|
||||
?.queuedMessages,
|
||||
).toEqual([message]);
|
||||
|
||||
if (cleared) await harness.manager.clearEnvironment(message.environmentId);
|
||||
await expect(completeQueuedMessageDelivery(message, deliveryRevision)).resolves.toBe(
|
||||
cleared ? "edited" : "removed",
|
||||
);
|
||||
|
||||
// Restart before signing back in: the archived copy must be removed on disk too.
|
||||
appAtomRegistry.set(composerDrafts.composerCloudDraftsAtom, {
|
||||
accountId: null,
|
||||
signedOut: {},
|
||||
});
|
||||
composerDrafts.resetComposerDraftsLoadState();
|
||||
await composerDrafts.restoreCloudComposerDrafts("account-a");
|
||||
expect(remainingMessages()).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves an archived edit when an older payload finishes delivery", async () => {
|
||||
const message = queuedMessage({ messageId: "edited-during-sign-out", text: "Original" });
|
||||
await harness.manager.enqueue(message);
|
||||
const deliveryRevision = harness.manager.revisionOf(message.messageId);
|
||||
const edited = { ...message, text: "Keep this edit" };
|
||||
await harness.manager.update(edited);
|
||||
await composerDrafts.archiveCloudComposerDrafts("account-a", new Set([message.environmentId]));
|
||||
await harness.manager.clearEnvironment(message.environmentId);
|
||||
await expect(completeQueuedMessageDelivery(message, deliveryRevision)).resolves.toBe("edited");
|
||||
await composerDrafts.restoreCloudComposerDrafts("account-a");
|
||||
expect(remainingMessages()).toEqual([edited]);
|
||||
});
|
||||
|
||||
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]);
|
||||
|
||||
@@ -52,6 +52,7 @@ import {
|
||||
getComposerDraftSnapshot,
|
||||
mergeComposerDraftContent,
|
||||
replaceComposerDraftAttachments,
|
||||
removeDeliveredCloudQueuedMessage,
|
||||
undoComposerDraftMerge,
|
||||
updateComposerDraftSettings,
|
||||
waitForComposerDraftsLoaded,
|
||||
@@ -114,7 +115,10 @@ function settingsCommandId(message: QueuedThreadMessage, setting: string): Comma
|
||||
* `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<
|
||||
export async function prepareQueuedMessageAttachments(
|
||||
queuedMessage: QueuedThreadMessage,
|
||||
supportsImageUploads = false,
|
||||
): Promise<
|
||||
| {
|
||||
readonly status: "ready";
|
||||
readonly prepared: PreparedTurnAttachments;
|
||||
@@ -135,6 +139,7 @@ export async function prepareQueuedMessageAttachments(queuedMessage: QueuedThrea
|
||||
const result = await prepareTurnAttachments({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
attachments: queuedMessage.attachments,
|
||||
supportsImageUploads,
|
||||
persistUploadedReferences: async (draftAttachments) => {
|
||||
if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
|
||||
return "abandon";
|
||||
@@ -179,13 +184,19 @@ 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 {
|
||||
await removeDeliveredCloudQueuedMessage(queuedMessage).catch((error) => {
|
||||
console.warn("[thread-outbox] could not update sign-out snapshot after delivery", {
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
});
|
||||
// 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";
|
||||
}
|
||||
// Removal also releases the message's local attachment files.
|
||||
const removed = await removeThreadOutboxMessage(
|
||||
queuedMessage,
|
||||
@@ -221,6 +232,12 @@ export async function removeAcknowledgedExistingThreadMessage(
|
||||
acknowledgedMessageIds: Set<MessageId>,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
await removeDeliveredCloudQueuedMessage(queuedMessage).catch((error) => {
|
||||
console.warn("[thread-outbox] could not update sign-out snapshot after delivery", {
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
});
|
||||
const removed = await removeThreadOutboxMessage(queuedMessage);
|
||||
if (removed) {
|
||||
acknowledgedMessageIds.delete(queuedMessage.messageId);
|
||||
@@ -453,15 +470,10 @@ async function preserveUploadedAttachmentsForEditor(
|
||||
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),
|
||||
uploadedMessage.attachments.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 ||
|
||||
@@ -672,7 +684,11 @@ export function useThreadOutboxDrain(): void {
|
||||
let persistedMessage: QueuedThreadMessage;
|
||||
let deliveryRevision: number;
|
||||
try {
|
||||
const preparedResult = await prepareQueuedMessageAttachments(queuedMessage);
|
||||
const preparedResult = await prepareQueuedMessageAttachments(
|
||||
queuedMessage,
|
||||
serverConfigs.get(queuedMessage.environmentId)?.environment.capabilities
|
||||
.attachmentUploads === true,
|
||||
);
|
||||
if (preparedResult.status === "abandoned") {
|
||||
return true;
|
||||
}
|
||||
@@ -744,6 +760,7 @@ export function useThreadOutboxDrain(): void {
|
||||
startTurn,
|
||||
updateThreadMetadata,
|
||||
restoreQueuedMessage,
|
||||
serverConfigs,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -761,7 +778,11 @@ export function useThreadOutboxDrain(): void {
|
||||
let persistedMessage: QueuedThreadMessage;
|
||||
let deliveryRevision: number;
|
||||
try {
|
||||
const preparedResult = await prepareQueuedMessageAttachments(queuedMessage);
|
||||
const preparedResult = await prepareQueuedMessageAttachments(
|
||||
queuedMessage,
|
||||
serverConfigs.get(queuedMessage.environmentId)?.environment.capabilities
|
||||
.attachmentUploads === true,
|
||||
);
|
||||
if (preparedResult.status === "abandoned") {
|
||||
return true;
|
||||
}
|
||||
@@ -838,7 +859,7 @@ export function useThreadOutboxDrain(): void {
|
||||
}
|
||||
return false;
|
||||
},
|
||||
[makeDeliveryHelpers, restoreQueuedMessage, startTurn],
|
||||
[makeDeliveryHelpers, restoreQueuedMessage, serverConfigs, startTurn],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -138,6 +138,19 @@ connection policy. `EnvironmentOwnedDataCleanup` is part of this contract: on
|
||||
removal the registry clears its cache and calls the platform implementation, so
|
||||
web clears composer drafts and mobile clears drafts plus the thread outbox.
|
||||
|
||||
Mobile cloud sign-out first saves relay drafts and queued messages in the local
|
||||
composer store under the owning account. These saved copies retain attachment
|
||||
files during cleanup and remain outside the active composer and upload queue.
|
||||
Signing back into that account restores them before relay credentials activate.
|
||||
Directly paired environments keep their drafts and outbox when cloud sign-out runs.
|
||||
|
||||
Mobile composer attachments upload over HTTP while their environment is connected,
|
||||
with at most three concurrent transfers. Drafts retain local image data or an owned
|
||||
file URI alongside the pending upload ID. Sending verifies and reuses that ID, or
|
||||
uploads the local bytes again if it expired. Disconnecting cancels active transfers
|
||||
without discarding drafts; reconnecting resumes preparation. Older servers without
|
||||
attachment-upload support continue to receive inline images.
|
||||
|
||||
## Source Boundaries
|
||||
|
||||
Applications must import explicit package subpaths; the package intentionally
|
||||
|
||||
@@ -13,13 +13,16 @@ attach videos, text files, PDFs, ZIP archives, and other files. Each file can be
|
||||
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, tap **+** to open
|
||||
Attachments upload as soon as you add them while connected to a server that supports uploads.
|
||||
The send button becomes available after every upload finishes. Failed uploads can be retried or
|
||||
removed. On mobile, tap **+** to open
|
||||
the photo library from either the compact or expanded composer. When the connected server supports
|
||||
file uploads, **+** opens a menu beside the button with **Photo Library** and **Choose Files**.
|
||||
Videos use the server's file upload limit. You can also share photos, videos, and files into
|
||||
T3 Code from other apps 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
|
||||
T3 Code from other apps through the system share sheet. Mobile keeps a local copy of each draft
|
||||
attachment, so you can still preview it and queue messages while offline. Uploads resume when
|
||||
you reconnect. Drafts and queued messages survive app restarts; signing out of T3 Connect keeps
|
||||
them on your device until you sign back into the same account. Select a received file on mobile
|
||||
to preview it or open the system share options.
|
||||
|
||||
Tap an image or PDF before or after sending to open it. On iOS, images zoom from their thumbnail
|
||||
|
||||
Reference in new issue
Block a user