feat(web): attach PDFs, ZIPs, and other files to a turn (#8236)
Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
6a9d9f9882
commit
bcb855a633
30 files changed
+3934
-265
No files matched your search
@@ -0,0 +1,202 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import {
|
||||
EnvironmentId,
|
||||
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
|
||||
type AttachmentCreateUploadUrlInput,
|
||||
type AttachmentCreateUploadUrlResult,
|
||||
type AttachmentDeleteInput,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import type { AtomCommand } from "./runtime.ts";
|
||||
import {
|
||||
clampFileAttachmentUploadBytes,
|
||||
fileAttachmentTooLargeMessage,
|
||||
formatAttachmentSize,
|
||||
runAttachmentUploadCycle,
|
||||
verifyPersistedAttachmentUpload,
|
||||
} from "./attachments.ts";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
// The cycle threads the registry through to the commands untouched, so the
|
||||
// fakes below can ignore it.
|
||||
const registry = {} as AtomRegistry.AtomRegistry;
|
||||
|
||||
type CreateUploadUrlCommand = AtomCommand<
|
||||
{ readonly environmentId: EnvironmentId; readonly input: AttachmentCreateUploadUrlInput },
|
||||
AttachmentCreateUploadUrlResult,
|
||||
never
|
||||
>;
|
||||
|
||||
type RemoveCommand = AtomCommand<
|
||||
{ readonly environmentId: EnvironmentId; readonly input: AttachmentDeleteInput },
|
||||
unknown,
|
||||
never
|
||||
>;
|
||||
|
||||
function makeCreateUploadUrl(attachmentId: string): CreateUploadUrlCommand {
|
||||
return {
|
||||
label: "test:create-upload-url",
|
||||
run: async () =>
|
||||
AsyncResult.success<AttachmentCreateUploadUrlResult, never>({
|
||||
attachmentId,
|
||||
relativeUrl: `/api/attachments/upload/${attachmentId}`,
|
||||
expiresAt: 1,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
const removeCalls: string[] = [];
|
||||
const remove: RemoveCommand = {
|
||||
label: "test:remove",
|
||||
run: async (_registry, input) => {
|
||||
removeCalls.push(input.input.attachmentId);
|
||||
return AsyncResult.success(undefined);
|
||||
},
|
||||
};
|
||||
|
||||
const uploadInput: AttachmentCreateUploadUrlInput = {
|
||||
type: "file",
|
||||
name: "report.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 3,
|
||||
};
|
||||
|
||||
describe("runAttachmentUploadCycle", () => {
|
||||
it("mints, transfers, and reports the attachment id", async () => {
|
||||
const transferred: string[] = [];
|
||||
const result = await runAttachmentUploadCycle({
|
||||
registry,
|
||||
createUploadUrl: makeCreateUploadUrl("pending-1"),
|
||||
remove,
|
||||
environmentId,
|
||||
upload: uploadInput,
|
||||
resolveUploadUrl: (relativeUrl) => `https://environment.test${relativeUrl}`,
|
||||
transport: (url) => {
|
||||
transferred.push(url);
|
||||
return { done: Promise.resolve(), abort: () => {} };
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toEqual({ status: "uploaded", attachmentId: "pending-1" });
|
||||
expect(transferred).toEqual(["https://environment.test/api/attachments/upload/pending-1"]);
|
||||
});
|
||||
|
||||
it("deletes the fresh mint when the caller cancels at onMinted", async () => {
|
||||
removeCalls.length = 0;
|
||||
const result = await runAttachmentUploadCycle({
|
||||
registry,
|
||||
createUploadUrl: makeCreateUploadUrl("pending-cancelled"),
|
||||
remove,
|
||||
environmentId,
|
||||
upload: uploadInput,
|
||||
resolveUploadUrl: () => "https://environment.test/upload",
|
||||
transport: () => {
|
||||
throw new Error("transport must not run after cancel");
|
||||
},
|
||||
onMinted: () => "cancel",
|
||||
});
|
||||
|
||||
expect(result).toEqual({ status: "cancelled", attachmentId: "pending-cancelled" });
|
||||
expect(removeCalls).toEqual(["pending-cancelled"]);
|
||||
});
|
||||
|
||||
it("keeps the minted id on transfer failure so the caller can retry or release", async () => {
|
||||
removeCalls.length = 0;
|
||||
const result = await runAttachmentUploadCycle({
|
||||
registry,
|
||||
createUploadUrl: makeCreateUploadUrl("pending-failed"),
|
||||
remove,
|
||||
environmentId,
|
||||
upload: uploadInput,
|
||||
resolveUploadUrl: () => "https://environment.test/upload",
|
||||
transport: () => ({
|
||||
done: Promise.reject(new Error("Upload rejected (413)")),
|
||||
abort: () => {},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "failed",
|
||||
step: "transfer",
|
||||
attachmentId: "pending-failed",
|
||||
});
|
||||
expect(removeCalls).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("verifyPersistedAttachmentUpload", () => {
|
||||
it("hits the server on every verification instead of reusing a cached failure", async () => {
|
||||
// Mirrors the app's asset URL query atom: SWR-cached with a long stale
|
||||
// window and kept alive across calls. Without a forced refresh, the
|
||||
// second verification would read the cached failure and never retry.
|
||||
let lookups = 0;
|
||||
const assetUrlAtom = Atom.make(
|
||||
// Async like the real RPC, so the first read is still in flight when
|
||||
// the query decides whether a refresh is needed.
|
||||
Effect.promise(() => Promise.resolve()).pipe(
|
||||
Effect.flatMap(() => {
|
||||
lookups += 1;
|
||||
return lookups === 1
|
||||
? Effect.fail({ _tag: "TransportError" } as const)
|
||||
: Effect.succeed({ url: "/api/assets/pending-1" });
|
||||
}),
|
||||
),
|
||||
).pipe(Atom.swr({ staleTime: 60_000 }), Atom.keepAlive);
|
||||
const liveRegistry = AtomRegistry.make();
|
||||
|
||||
const verify = () =>
|
||||
verifyPersistedAttachmentUpload({
|
||||
registry: liveRegistry,
|
||||
createAssetUrl: () => assetUrlAtom,
|
||||
environmentId,
|
||||
attachmentId: "pending-1",
|
||||
});
|
||||
|
||||
const first = await verify();
|
||||
expect(first).toMatchObject({ status: "failed" });
|
||||
|
||||
const second = await verify();
|
||||
expect(second).toEqual({ status: "verified" });
|
||||
expect(lookups).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("file attachment limits", () => {
|
||||
it("clamps the advertised limit to the turn contract cap", () => {
|
||||
expect(clampFileAttachmentUploadBytes(1024)).toBe(1024);
|
||||
expect(clampFileAttachmentUploadBytes(PROVIDER_SEND_TURN_MAX_FILE_BYTES * 2)).toBe(
|
||||
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
|
||||
);
|
||||
});
|
||||
|
||||
it("formats attachment row sizes", () => {
|
||||
expect(formatAttachmentSize(3 * 1024 * 1024)).toBe("3.0 MB");
|
||||
expect(formatAttachmentSize(1)).toBe("1 KB");
|
||||
});
|
||||
|
||||
it("formats small upload limits without rounding them to zero MB", () => {
|
||||
expect(fileAttachmentTooLargeMessage("tiny.txt", 1)).toBe(
|
||||
"'tiny.txt' exceeds the 1 byte attachment limit.",
|
||||
);
|
||||
expect(fileAttachmentTooLargeMessage("small.txt", 1024)).toBe(
|
||||
"'small.txt' exceeds the 1 KB attachment limit.",
|
||||
);
|
||||
expect(fileAttachmentTooLargeMessage("exact.txt", 1025)).toBe(
|
||||
"'exact.txt' exceeds the 1025 bytes attachment limit.",
|
||||
);
|
||||
expect(fileAttachmentTooLargeMessage("medium.zip", 512 * 1024)).toBe(
|
||||
"'medium.zip' exceeds the 512 KB attachment limit.",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps whole-MB upload limits for standard server caps", () => {
|
||||
expect(fileAttachmentTooLargeMessage("one.bin", 1024 * 1024)).toBe(
|
||||
"'one.bin' exceeds the 1 MB attachment limit.",
|
||||
);
|
||||
expect(fileAttachmentTooLargeMessage("big.zip", 50 * 1024 * 1024)).toBe(
|
||||
"'big.zip' exceeds the 50 MB attachment limit.",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
|
||||
WS_METHODS,
|
||||
type AttachmentCreateUploadUrlInput,
|
||||
type AttachmentCreateUploadUrlResult,
|
||||
type AttachmentDeleteInput,
|
||||
type EnvironmentId,
|
||||
} from "@t3tools/contracts";
|
||||
import type { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import type { EnvironmentRegistry } from "../connection/registry.ts";
|
||||
import {
|
||||
createEnvironmentRpcCommand,
|
||||
executeAtomQuery,
|
||||
runAtomCommand,
|
||||
squashAtomCommandFailure,
|
||||
type AtomCommand,
|
||||
} from "./runtime.ts";
|
||||
|
||||
/**
|
||||
* RPC commands for pending chat attachment uploads. Mirrors
|
||||
* `createAssetEnvironmentAtoms`: each client instantiates it with its own
|
||||
* connection runtime (`attachmentEnvironment` in web and mobile).
|
||||
*/
|
||||
export function createAttachmentEnvironmentAtoms<R, E>(
|
||||
runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
|
||||
) {
|
||||
return {
|
||||
createUploadUrl: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-command:attachments:create-upload-url",
|
||||
tag: WS_METHODS.attachmentsCreateUploadUrl,
|
||||
}),
|
||||
remove: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-command:attachments:delete",
|
||||
tag: WS_METHODS.attachmentsDelete,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a failed asset lookup means the attachment no longer exists on the
|
||||
* server, as opposed to a transient transport failure. Pending uploads expire,
|
||||
* so this is the signal to upload the bytes again rather than retry the lookup.
|
||||
*
|
||||
* A structural `_tag` check rather than a schema check: the squashed cause of
|
||||
* a failed RPC is not guaranteed to be a decoded error class instance, only a
|
||||
* tagged value.
|
||||
*/
|
||||
export function isAssetAttachmentNotFoundFailure(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
error._tag === "AssetAttachmentNotFoundError"
|
||||
);
|
||||
}
|
||||
|
||||
export type PersistedAttachmentVerification =
|
||||
| { readonly status: "verified" }
|
||||
| { readonly status: "missing" }
|
||||
| { readonly status: "failed"; readonly error: unknown };
|
||||
|
||||
/**
|
||||
* Checks that a previously uploaded pending attachment still exists on the
|
||||
* server by minting an asset URL for it. `verified` means the send can reuse
|
||||
* the stored bytes, `missing` means the upload expired and the bytes must be
|
||||
* uploaded again, `failed` means the server could not be asked.
|
||||
*/
|
||||
export async function verifyPersistedAttachmentUpload<A, E>(input: {
|
||||
readonly registry: AtomRegistry.AtomRegistry;
|
||||
readonly createAssetUrl: (query: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly input: {
|
||||
readonly resource: { readonly _tag: "attachment"; readonly attachmentId: string };
|
||||
};
|
||||
}) => Atom.Atom<AsyncResult.AsyncResult<A, E>>;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly attachmentId: string;
|
||||
}): Promise<PersistedAttachmentVerification> {
|
||||
const result = await executeAtomQuery(
|
||||
input.registry,
|
||||
input.createAssetUrl({
|
||||
environmentId: input.environmentId,
|
||||
input: { resource: { _tag: "attachment", attachmentId: input.attachmentId } },
|
||||
}),
|
||||
// `refresh` forces a server round trip: the asset URL query atom caches
|
||||
// results (SWR), so a retry right after a transient failure would
|
||||
// otherwise re-observe the cached failure and never ask the server.
|
||||
{ reportFailure: false, reportDefect: false, refresh: true },
|
||||
);
|
||||
if (result._tag === "Success") {
|
||||
return { status: "verified" };
|
||||
}
|
||||
const error = squashAtomCommandFailure(result);
|
||||
return isAssetAttachmentNotFoundFailure(error)
|
||||
? { status: "missing" }
|
||||
: { status: "failed", error };
|
||||
}
|
||||
|
||||
type AttachmentCreateUploadUrlCommand<E> = AtomCommand<
|
||||
{ readonly environmentId: EnvironmentId; readonly input: AttachmentCreateUploadUrlInput },
|
||||
AttachmentCreateUploadUrlResult,
|
||||
E
|
||||
>;
|
||||
|
||||
type AttachmentRemoveCommand<E> = AtomCommand<
|
||||
{ readonly environmentId: EnvironmentId; readonly input: AttachmentDeleteInput },
|
||||
unknown,
|
||||
E
|
||||
>;
|
||||
|
||||
/** Fire-and-forget delete of a pending upload the client no longer references. */
|
||||
export function deletePendingAttachmentUpload<E>(input: {
|
||||
readonly registry: AtomRegistry.AtomRegistry;
|
||||
readonly remove: AttachmentRemoveCommand<E>;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly attachmentId: string;
|
||||
}): void {
|
||||
void runAtomCommand(
|
||||
input.registry,
|
||||
input.remove,
|
||||
{ environmentId: input.environmentId, input: { attachmentId: input.attachmentId } },
|
||||
{ reportFailure: false, reportDefect: false },
|
||||
);
|
||||
}
|
||||
|
||||
/** A running byte transfer: resolves when the server accepted the bytes. */
|
||||
export interface AttachmentByteUpload {
|
||||
readonly done: Promise<void>;
|
||||
readonly abort: () => void;
|
||||
}
|
||||
|
||||
export type AttachmentUploadCycleResult =
|
||||
| { readonly status: "uploaded"; readonly attachmentId: string }
|
||||
| { readonly status: "cancelled"; readonly attachmentId: string | null }
|
||||
| {
|
||||
readonly status: "failed";
|
||||
readonly step: "mint" | "resolve-url" | "transfer";
|
||||
readonly attachmentId: string | null;
|
||||
readonly error: unknown;
|
||||
};
|
||||
|
||||
/**
|
||||
* The platform-neutral upload cycle: mint a signed upload URL, resolve it
|
||||
* against the environment's HTTP base, and hand the bytes to a
|
||||
* platform-specific transport (XHR on web, `expo-file-system` on mobile).
|
||||
*
|
||||
* The cycle never deletes the minted pending upload on failure: callers keep
|
||||
* the returned `attachmentId` and decide between retry and release. The one
|
||||
* exception is `onMinted` returning `"cancel"`, where the caller already
|
||||
* abandoned the upload and the fresh mint is deleted before returning.
|
||||
*/
|
||||
export async function runAttachmentUploadCycle<E, RE>(input: {
|
||||
readonly registry: AtomRegistry.AtomRegistry;
|
||||
readonly createUploadUrl: AttachmentCreateUploadUrlCommand<E>;
|
||||
readonly remove: AttachmentRemoveCommand<RE>;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly upload: AttachmentCreateUploadUrlInput;
|
||||
readonly resolveUploadUrl: (relativeUrl: string) => string | null;
|
||||
readonly transport: (url: string) => AttachmentByteUpload;
|
||||
/** Observe the minted id (for cancellation bookkeeping) before bytes move. */
|
||||
readonly onMinted?: (attachmentId: string) => "continue" | "cancel";
|
||||
readonly onTransferStart?: (abort: () => void) => void;
|
||||
}): Promise<AttachmentUploadCycleResult> {
|
||||
const minted = await runAtomCommand(
|
||||
input.registry,
|
||||
input.createUploadUrl,
|
||||
{ environmentId: input.environmentId, input: input.upload },
|
||||
{ reportFailure: false },
|
||||
);
|
||||
if (minted._tag !== "Success") {
|
||||
return {
|
||||
status: "failed",
|
||||
step: "mint",
|
||||
attachmentId: null,
|
||||
error: squashAtomCommandFailure(minted),
|
||||
};
|
||||
}
|
||||
const attachmentId = minted.value.attachmentId;
|
||||
if (input.onMinted?.(attachmentId) === "cancel") {
|
||||
deletePendingAttachmentUpload({
|
||||
registry: input.registry,
|
||||
remove: input.remove,
|
||||
environmentId: input.environmentId,
|
||||
attachmentId,
|
||||
});
|
||||
return { status: "cancelled", attachmentId };
|
||||
}
|
||||
|
||||
const url = input.resolveUploadUrl(minted.value.relativeUrl);
|
||||
if (!url) {
|
||||
return {
|
||||
status: "failed",
|
||||
step: "resolve-url",
|
||||
attachmentId,
|
||||
error: new Error("The environment is not connected."),
|
||||
};
|
||||
}
|
||||
|
||||
const transfer = input.transport(url);
|
||||
input.onTransferStart?.(transfer.abort);
|
||||
try {
|
||||
await transfer.done;
|
||||
} catch (error) {
|
||||
return { status: "failed", step: "transfer", attachmentId, error };
|
||||
}
|
||||
return { status: "uploaded", attachmentId };
|
||||
}
|
||||
|
||||
/**
|
||||
* The effective per-file byte limit for a server that advertises
|
||||
* `capabilities.fileAttachments.maxUploadBytes`. The contract caps what a
|
||||
* turn may reference, so a larger advertised value must not admit files the
|
||||
* send would then refuse.
|
||||
*/
|
||||
export function clampFileAttachmentUploadBytes(advertisedMaxUploadBytes: number): number {
|
||||
return Math.min(advertisedMaxUploadBytes, PROVIDER_SEND_TURN_MAX_FILE_BYTES);
|
||||
}
|
||||
|
||||
/** "3.2 MB" / "48 KB" label for attachment rows. Never shows "0 KB". */
|
||||
export function formatAttachmentSize(sizeBytes: number): string {
|
||||
return sizeBytes >= 1024 * 1024
|
||||
? `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
: `${Math.max(1, Math.ceil(sizeBytes / 1024))} KB`;
|
||||
}
|
||||
|
||||
/** User-facing rejection for a file over the effective upload limit. */
|
||||
export function fileAttachmentTooLargeMessage(name: string, maxUploadBytes: number): string {
|
||||
const maxUploadSize =
|
||||
maxUploadBytes >= 1024 * 1024 && maxUploadBytes % (1024 * 1024) === 0
|
||||
? `${maxUploadBytes / (1024 * 1024)} MB`
|
||||
: maxUploadBytes >= 1024 && maxUploadBytes % 1024 === 0
|
||||
? `${maxUploadBytes / 1024} KB`
|
||||
: `${maxUploadBytes} ${maxUploadBytes === 1 ? "byte" : "bytes"}`;
|
||||
return `'${name}' exceeds the ${maxUploadSize} attachment limit.`;
|
||||
}
|
||||
@@ -327,15 +327,34 @@ export async function executeAtomCommand<A, E>(
|
||||
return result;
|
||||
}
|
||||
|
||||
export interface AtomQueryOptions extends AtomCommandOptions {
|
||||
/**
|
||||
* Force a fresh execution instead of accepting a value the atom already
|
||||
* holds (e.g. an SWR-cached result within its stale window). Used by
|
||||
* verification flows where a cached failure must not satisfy a retry.
|
||||
*/
|
||||
readonly refresh?: boolean;
|
||||
}
|
||||
|
||||
export async function executeAtomQuery<A, E>(
|
||||
registry: AtomRegistry.AtomRegistry,
|
||||
atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
|
||||
options: AtomCommandOptions = {},
|
||||
options: AtomQueryOptions = {},
|
||||
reporter: AtomCommandReporter = console,
|
||||
): Promise<AtomCommandResult<A, E>> {
|
||||
const query = Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* AtomRegistry.mount(registry, atom);
|
||||
if (options.refresh) {
|
||||
yield* Effect.sync(() => {
|
||||
// Only a settled value can be a leftover from an earlier read; a
|
||||
// computation that mounting just started is already fresh.
|
||||
const current = registry.get(atom);
|
||||
if (current._tag !== "Initial" && !current.waiting) {
|
||||
registry.refresh(atom);
|
||||
}
|
||||
});
|
||||
}
|
||||
return yield* AtomRegistry.getResult(registry, atom, {
|
||||
suspendOnWaiting: true,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user