Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(web): replace the upload toast with a progress indicator (#7565)

Jacob Beckermanfb4d8968a2f1
diff --git a/apps/web/src/lib/core/component/Toast/Toast.tsx b/apps/web/src/lib/core/component/Toast/Toast.tsx
index 71b10fd40e..ccf99d6d32 100644
--- a/apps/web/src/lib/core/component/Toast/Toast.tsx
+++ b/apps/web/src/lib/core/component/Toast/Toast.tsx
@@ -798,22 +798,6 @@ function custom(
return toastId;
}
-// ─── upload helper (kept for backwards compat) ───────────────────────────────
-
-export function createUploadToast(message: string) {
- return toaster.show(
- (props) => (
- <ToastContent
- toastId={props.toastId}
- toastType={ToastType.LOADING}
- message={message}
- persistent={true}
- />
- ),
- { region: 'stable-toast' }
- );
-}
-
// ─── public API ──────────────────────────────────────────────────────────────
export const toast = {
diff --git a/apps/web/src/lib/core/component/Toast/ToastRegion.tsx b/apps/web/src/lib/core/component/Toast/ToastRegion.tsx
index bbc38b08d1..96c0563d1e 100644
--- a/apps/web/src/lib/core/component/Toast/ToastRegion.tsx
+++ b/apps/web/src/lib/core/component/Toast/ToastRegion.tsx
@@ -1,4 +1,7 @@
+import { UploadProgressIndicator } from '@core/component/UploadProgress/UploadProgressIndicator';
+import { isMobile } from '@core/mobile/isMobile';
import { Toast } from '@kobalte/core/toast';
+import { Show } from 'solid-js';
import { Portal } from 'solid-js/web';
export function ToastRegion() {
@@ -6,7 +9,7 @@ export function ToastRegion() {
<Portal>
{/*
Desktop stack, bottom-right. Persistent prompts get their own region
- capped at one visible card.
+ capped at one visible card. Upload progress sits nearest the corner.
*/}
<div class="fixed bottom-2 right-2 m-0 p-2 sm:p-4 list-none outline-none pointer-events-none z-toast-region flex flex-col items-end gap-2">
<Toast.Region
@@ -35,13 +38,9 @@ export function ToastRegion() {
>
<Toast.List class="flex flex-col gap-2" />
</Toast.Region>
- <Toast.Region
- regionId="stable-toast"
- duration={Infinity}
- swipeDirection="right"
- >
- <Toast.List class="flex flex-col gap-2" />
- </Toast.Region>
+ <Show when={!isMobile()}>
+ <UploadProgressIndicator />
+ </Show>
</div>
{/*
@@ -83,6 +82,11 @@ export function ToastRegion() {
>
<Toast.List class="flex flex-col gap-2" />
</Toast.Region>
+ <Show when={isMobile()}>
+ <div class="flex justify-center">
+ <UploadProgressIndicator />
+ </div>
+ </Show>
</div>
</Portal>
);
diff --git a/apps/web/src/lib/core/component/UploadProgress/UploadProgressIndicator.tsx b/apps/web/src/lib/core/component/UploadProgress/UploadProgressIndicator.tsx
new file mode 100644
index 0000000000..ddab42afe6
--- /dev/null
+++ b/apps/web/src/lib/core/component/UploadProgress/UploadProgressIndicator.tsx
@@ -0,0 +1,75 @@
+import { cn, Surface } from '@ui';
+import { Show } from 'solid-js';
+import { uploadProgress } from './uploadProgress';
+
+const RING_RADIUS = 6;
+const RING_CIRCUMFERENCE = 2 * Math.PI * RING_RADIUS;
+/** Arc length a spinning ring shows when progress can't be measured. */
+const INDETERMINATE_ARC = 0.25;
+
+function ProgressRing(props: { fraction: number | null }) {
+ const offset = () =>
+ RING_CIRCUMFERENCE * (1 - (props.fraction ?? INDETERMINATE_ARC));
+
+ return (
+ <svg
+ viewBox="0 0 16 16"
+ aria-hidden="true"
+ class={cn('size-4 shrink-0', props.fraction === null && 'animate-spin')}
+ >
+ <circle
+ cx="8"
+ cy="8"
+ r={RING_RADIUS}
+ fill="none"
+ stroke-width="2"
+ class="stroke-ink/15"
+ />
+ <circle
+ cx="8"
+ cy="8"
+ r={RING_RADIUS}
+ fill="none"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-dasharray={String(RING_CIRCUMFERENCE)}
+ stroke-dashoffset={offset()}
+ transform="rotate(-90 8 8)"
+ class="stroke-accent transition-[stroke-dashoffset] duration-150 ease-linear"
+ />
+ </svg>
+ );
+}
+
+/** Compact, non-dismissable indicator for every upload in flight. */
+export function UploadProgressIndicator() {
+ return (
+ <Show when={uploadProgress()}>
+ {(progress) => {
+ const percent = () => {
+ const fraction = progress().fraction;
+ return fraction === null ? undefined : Math.round(fraction * 100);
+ };
+ return (
+ <Surface
+ hideBorder
+ role="progressbar"
+ aria-label={progress().label}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={percent()}
+ class="pointer-events-auto flex size-auto max-w-xs items-center gap-2 rounded-full glass bg-toast px-3 py-1.5 text-sm text-ink"
+ >
+ <ProgressRing fraction={progress().fraction} />
+ <span class="min-w-0 truncate font-medium">{progress().label}</span>
+ <Show when={percent() !== undefined}>
+ <span class="shrink-0 tabular-nums text-ink-muted">
+ {percent()}%
+ </span>
+ </Show>
+ </Surface>
+ );
+ }}
+ </Show>
+ );
+}
diff --git a/apps/web/src/lib/core/component/UploadProgress/uploadProgress.test.ts b/apps/web/src/lib/core/component/UploadProgress/uploadProgress.test.ts
new file mode 100644
index 0000000000..7241aa3915
--- /dev/null
+++ b/apps/web/src/lib/core/component/UploadProgress/uploadProgress.test.ts
@@ -0,0 +1,76 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import {
+ trackUpload,
+ type UploadProgressHandle,
+ uploadProgress,
+} from './uploadProgress';
+
+const handles: UploadProgressHandle[] = [];
+function track(name: string, size: number) {
+ const handle = trackUpload(name, size);
+ handles.push(handle);
+ return handle;
+}
+
+afterEach(() => {
+ for (const handle of handles.splice(0)) handle.done();
+});
+
+describe('uploadProgress', () => {
+ it('is empty when nothing is uploading', () => {
+ expect(uploadProgress()).toBeNull();
+ });
+
+ it('spins while preparing, then reports bytes sent', () => {
+ const upload = track('Report', 200);
+ expect(uploadProgress()).toEqual({
+ label: 'Uploading Report',
+ fraction: null,
+ });
+
+ upload.sending(50);
+ expect(uploadProgress()?.fraction).toBe(0.25);
+ });
+
+ it('spins while the server processes the sent file', () => {
+ const upload = track('Report', 200);
+ upload.sending(200);
+ upload.processing();
+ expect(uploadProgress()?.fraction).toBeNull();
+ });
+
+ it('spins when the transport cannot measure bytes', () => {
+ track('Photo', 100).sending(null);
+ expect(uploadProgress()?.fraction).toBeNull();
+ });
+
+ it('combines concurrent uploads by bytes', () => {
+ const first = track('Report', 100);
+ const second = track('Deck', 300);
+ const third = track('Notes', 100);
+ first.sending(100);
+ first.processing();
+ second.sending(150);
+
+ expect(uploadProgress()).toEqual({
+ label: 'Uploading 3 files',
+ fraction: 0.5,
+ });
+
+ third.done();
+ expect(uploadProgress()?.label).toBe('Uploading 2 files');
+ expect(uploadProgress()?.fraction).toBe(250 / 400);
+ });
+
+ it('drops an upload once it is done', () => {
+ const upload = track('Report', 100);
+ upload.done();
+ upload.done();
+ expect(uploadProgress()).toBeNull();
+ });
+
+ it('never reports more than every byte', () => {
+ track('Report', 100).sending(150);
+ expect(uploadProgress()?.fraction).toBe(1);
+ });
+});
diff --git a/apps/web/src/lib/core/component/UploadProgress/uploadProgress.ts b/apps/web/src/lib/core/component/UploadProgress/uploadProgress.ts
new file mode 100644
index 0000000000..4f6c164862
--- /dev/null
+++ b/apps/web/src/lib/core/component/UploadProgress/uploadProgress.ts
@@ -0,0 +1,85 @@
+import { createSignal } from 'solid-js';
+import { match } from 'ts-pattern';
+
+type UploadPhase = 'preparing' | 'sending' | 'processing';
+
+type TrackedUpload = {
+ id: number;
+ name: string;
+ size: number;
+ phase: UploadPhase;
+ /** Bytes sent while `sending`; null when the transport can't report bytes. */
+ sent: number | null;
+};
+
+type UploadProgressSummary = {
+ label: string;
+ /**
+ * Share of all bytes sent, 0 to 1. Null while no upload is measurably
+ * sending (hashing, server processing, native transports), where only an
+ * indeterminate indicator is honest.
+ */
+ fraction: number | null;
+};
+
+export type UploadProgressHandle = {
+ /** Report bytes sent so far, or null when the transport can't measure them. */
+ sending: (sent: number | null) => void;
+ /** All bytes are sent; the server is still preparing the file. */
+ processing: () => void;
+ /** Stop tracking, whether the upload succeeded or failed. */
+ done: () => void;
+};
+
+const [uploads, setUploads] = createSignal<readonly TrackedUpload[]>([]);
+let nextId = 0;
+
+function update(id: number, patch: Partial<TrackedUpload>) {
+ setUploads((list) =>
+ list.map((upload) => (upload.id === id ? { ...upload, ...patch } : upload))
+ );
+}
+
+/** Show an upload in the global upload progress indicator until `done`. */
+export function trackUpload(name: string, size: number): UploadProgressHandle {
+ const id = ++nextId;
+ setUploads((list) => [
+ ...list,
+ { id, name, size, phase: 'preparing', sent: 0 },
+ ]);
+ return {
+ sending: (sent) => update(id, { phase: 'sending', sent }),
+ processing: () => update(id, { phase: 'processing' }),
+ done: () => setUploads((list) => list.filter((upload) => upload.id !== id)),
+ };
+}
+
+function sentBytes(upload: TrackedUpload): number {
+ return match(upload.phase)
+ .with('preparing', () => 0)
+ .with('sending', () => Math.min(upload.sent ?? 0, upload.size))
+ .with('processing', () => upload.size)
+ .exhaustive();
+}
+
+function summarizeUploads(
+ list: readonly TrackedUpload[]
+): UploadProgressSummary | null {
+ if (list.length === 0) return null;
+
+ const label =
+ list.length === 1
+ ? `Uploading ${list[0].name}`
+ : `Uploading ${list.length} files`;
+
+ const measurable = list.some(
+ (upload) => upload.phase === 'sending' && upload.sent !== null
+ );
+ const total = list.reduce((sum, upload) => sum + upload.size, 0);
+ if (!measurable || total <= 0) return { label, fraction: null };
+
+ const sent = list.reduce((sum, upload) => sum + sentBytes(upload), 0);
+ return { label, fraction: Math.min(1, sent / total) };
+}
+
+export const uploadProgress = () => summarizeUploads(uploads());
diff --git a/apps/web/src/lib/service-clients/service-storage/util/upload-native.test.ts b/apps/web/src/lib/service-clients/service-storage/util/upload-native.test.ts
index 8c36bc5875..cb795d5726 100644
--- a/apps/web/src/lib/service-clients/service-storage/util/upload-native.test.ts
+++ b/apps/web/src/lib/service-clients/service-storage/util/upload-native.test.ts
@@ -9,8 +9,10 @@ const mocks = vi.hoisted(() => ({
ready: vi.fn(),
createUploadZipRequest: vi.fn(),
bulkUploadStatus: vi.fn(),
- createUploadToast: vi.fn(),
- dismissToast: vi.fn(),
+ trackUpload: vi.fn(),
+ uploadSending: vi.fn(),
+ uploadProcessing: vi.fn(),
+ uploadDone: vi.fn(),
contentHash: vi.fn(),
fetch: vi.fn(),
}));
@@ -21,7 +23,9 @@ vi.mock('@tauri-apps/api/core', () => ({
vi.mock('@app/lib/analytics', () => ({ analytics: { track: vi.fn() } }));
vi.mock('@core/component/Toast/Toast', () => ({
toast: { success: vi.fn(), failure: vi.fn() },
- createUploadToast: mocks.createUploadToast,
+}));
+vi.mock('@core/component/UploadProgress/uploadProgress', () => ({
+ trackUpload: mocks.trackUpload,
}));
vi.mock('@core/constant/allBlocks', () => ({
blockAcceptedMimetypeToFileExtension: { 'application/pdf': 'pdf' },
@@ -31,9 +35,6 @@ vi.mock('@core/constant/PaywallState', () => ({
PaywallKey: {},
}));
vi.mock('@core/util/hash', () => ({ contentHash: mocks.contentHash }));
-vi.mock('@kobalte/core/toast', () => ({
- toaster: { dismiss: mocks.dismissToast },
-}));
vi.mock('@queries/storage/document-location', () => ({
waitForDocumentContentReady: mocks.ready,
}));
@@ -77,7 +78,11 @@ beforeEach(() => {
vi.resetAllMocks();
vi.stubGlobal('fetch', mocks.fetch);
mocks.contentHash.mockResolvedValue('cd'.repeat(32));
- mocks.createUploadToast.mockReturnValue(42);
+ mocks.trackUpload.mockReturnValue({
+ sending: mocks.uploadSending,
+ processing: mocks.uploadProcessing,
+ done: mocks.uploadDone,
+ });
mocks.browserPut.mockResolvedValue(ok(undefined));
mocks.createUploadZipRequest.mockResolvedValue(
ok({ presignedUrl: 'https://example.com/zip', requestId: 'zip-request' })
@@ -178,14 +183,14 @@ describe.each(['pdf', 'zip'])('%s upload checksums', (extension) => {
expect(mocks.browserPut).not.toHaveBeenCalled();
});
- it('dismisses the toast and creates no upload request if staged checksum calculation fails', async () => {
+ it('clears the progress indicator and creates no upload request if staged checksum calculation fails', async () => {
mocks.fetch.mockRejectedValue(new Error('Native bytes unavailable'));
await expect(
upload(stagedWithoutChecksum(), { unzipFolder: true })
).rejects.toThrow('Native bytes unavailable');
- expect(mocks.dismissToast).toHaveBeenCalledWith(42);
+ expect(mocks.uploadDone).toHaveBeenCalledOnce();
expect(mocks.createDocument).not.toHaveBeenCalled();
expect(mocks.createUploadZipRequest).not.toHaveBeenCalled();
expect(mocks.invoke).not.toHaveBeenCalled();
@@ -207,12 +212,50 @@ describe('browser upload checksums', () => {
buffer: bytes,
sha: 'cd'.repeat(32),
type: 'application/pdf',
+ onProgress: mocks.uploadSending,
});
expect(mocks.fetch).not.toHaveBeenCalled();
expect(mocks.invoke).not.toHaveBeenCalled();
+ expect(mocks.trackUpload).toHaveBeenCalledWith('browser', 0);
+ expect(mocks.uploadProcessing).toHaveBeenCalledOnce();
+ expect(mocks.uploadDone).toHaveBeenCalledOnce();
+ });
+
+ it('clears the progress indicator if the PUT throws', async () => {
+ const file = new File([], 'browser.pdf', { type: 'application/pdf' });
+ Object.defineProperty(file, 'arrayBuffer', {
+ value: async () => new ArrayBuffer(0),
+ });
+ mocks.browserPut.mockRejectedValue(new TypeError('Failed to fetch'));
+
+ await expect(upload(file)).rejects.toThrow('Failed to fetch');
+
+ expect(mocks.uploadProcessing).not.toHaveBeenCalled();
+ expect(mocks.uploadDone).toHaveBeenCalledOnce();
+ });
+
+ it('keeps the progress indicator until the server unpacks a folder', async () => {
+ let unpacked!: (projectId: string) => void;
+ mocks.bulkUploadStatus.mockReturnValue(
+ new Promise<string>((resolve) => {
+ unpacked = resolve;
+ })
+ );
+ const file = new File([], 'folder.zip', { type: 'application/zip' });
+ Object.defineProperty(file, 'arrayBuffer', {
+ value: async () => new ArrayBuffer(0),
+ });
+
+ const result = await upload(file, { unzipFolder: true });
+
+ expect(result.type).toBe('folder');
+ expect(mocks.uploadProcessing).toHaveBeenCalledOnce();
+ expect(mocks.uploadDone).not.toHaveBeenCalled();
+ unpacked('project');
+ await vi.waitFor(() => expect(mocks.uploadDone).toHaveBeenCalledOnce());
});
- it('dismisses the toast before creating a document if hashing fails', async () => {
+ it('clears the progress indicator before creating a document if hashing fails', async () => {
const file = new File([], 'browser.pdf', { type: 'application/pdf' });
Object.defineProperty(file, 'arrayBuffer', {
value: async () => new ArrayBuffer(0),
@@ -221,7 +264,7 @@ describe('browser upload checksums', () => {
await expect(upload(file)).rejects.toThrow('Hash failed');
- expect(mocks.dismissToast).toHaveBeenCalledWith(42);
+ expect(mocks.uploadDone).toHaveBeenCalledOnce();
expect(mocks.createDocument).not.toHaveBeenCalled();
expect(mocks.browserPut).not.toHaveBeenCalled();
});
diff --git a/apps/web/src/lib/service-clients/service-storage/util/upload.ts b/apps/web/src/lib/service-clients/service-storage/util/upload.ts
index 7c75b521f6..8936bcbdba 100644
--- a/apps/web/src/lib/service-clients/service-storage/util/upload.ts
+++ b/apps/web/src/lib/service-clients/service-storage/util/upload.ts
@@ -1,6 +1,10 @@
import { analytics } from '@app/lib/analytics';
import type { FileTypeString, MimeType } from '@core/block';
-import { createUploadToast, toast } from '@core/component/Toast/Toast';
+import { toast } from '@core/component/Toast/Toast';
+import {
+ trackUpload,
+ type UploadProgressHandle,
+} from '@core/component/UploadProgress/uploadProgress';
import { blockAcceptedMimetypeToFileExtension } from '@core/constant/allBlocks';
import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
import {
@@ -11,7 +15,6 @@ import {
uploadNativeStagedFileToPresignedUrl,
} from '@core/mobile/nativeStagedUpload';
import type { ResultError } from '@core/util/result';
-import { toaster } from '@kobalte/core/toast';
import { waitForDocumentContentReady } from '@queries/storage/document-location';
import { waitBulkUploadStatus } from '@service-connection/bulkUpload';
import {
@@ -24,10 +27,6 @@ import { storageWS } from '@service-storage/websocket';
import { FileTypeMap } from '../fileTypeMap';
import { uploadDocx } from './uploadDocx';
-const dismissToast = (toastId: number | null) => {
- if (toastId !== null) toaster.dismiss(toastId);
-};
-
/**
* Thrown when the backend rejects a document name as too long. Carries the
* limit so the UI can render its own copy without hardcoding the number.
@@ -44,6 +43,7 @@ const uploadWithPresignedUrl = async (params: {
buffer: ArrayBuffer;
sha: string;
type: MimeType;
+ onProgress?: (sent: number | null) => void;
}) => {
const uploadResult = await uploadToPresignedUrl(params);
return !uploadResult.isErr();
@@ -84,16 +84,37 @@ export type UploadFileOptions = {
export async function upload(
file: File,
options?: UploadFileOptions
+): Promise<UploadSuccess> {
+ const name = filenameWithoutExtension(file.name) ?? file.name;
+ const progress = options?.hideProgressIndicator
+ ? undefined
+ : trackUpload(name, getUploadFileSize(file));
+
+ try {
+ const result = await uploadWithProgress(file, name, options, progress);
+ if (result.type === 'folder') {
+ // The server keeps unpacking the folder after the zip is sent.
+ void result.projectId.finally(() => progress?.done());
+ } else {
+ progress?.done();
+ }
+ return result;
+ } catch (error) {
+ progress?.done();
+ throw error;
+ }
+}
+
+async function uploadWithProgress(
+ file: File,
+ name: string,
+ options: UploadFileOptions | undefined,
+ progress: UploadProgressHandle | undefined
): Promise<UploadSuccess> {
const { showPaywall } = usePaywallState();
// TODO: remove toast logic from dss upload util
- const handleUploadError = (
- err: ResultError<string>[] | Error | string,
- toastId: number | null
- ) => {
- dismissToast(toastId);
-
+ const handleUploadError = (err: ResultError<string>[] | Error | string) => {
if (Array.isArray(err) && err[0]?.code === DOCUMENT_NAME_TOO_LONG_CODE) {
let maxLength: number | undefined;
try {
@@ -145,38 +166,34 @@ export async function upload(
});
}
- let name = filenameWithoutExtension(file.name) ?? file.name;
-
- // Create toast notification if needed
- const toastId = !options?.hideProgressIndicator
- ? createUploadToast(`Uploading ${name}`)
- : null;
-
let source: UploadSource;
try {
source = await resolveUploadSource(file);
} catch (error) {
- return handleUploadError(
- error instanceof Error ? error : String(error),
- toastId
- );
+ return handleUploadError(error instanceof Error ? error : String(error));
}
const { sha } = source;
const putFile = async (presignedUrl: string, type: MimeType) => {
if (source.kind === 'bytes') {
- return uploadWithPresignedUrl({
+ const sent = await uploadWithPresignedUrl({
presignedUrl,
buffer: source.buffer,
sha,
type,
+ onProgress: progress?.sending,
});
+ if (sent) progress?.processing();
+ return sent;
}
+ // The native transport doesn't report bytes sent.
+ progress?.sending(null);
try {
await uploadNativeStagedFileToPresignedUrl(
{ ...source.staged, mimeType: type },
presignedUrl,
nativeUploadChecksum(sha)
);
+ progress?.processing();
return true;
} catch (error) {
console.error('Native staged upload failed', error);
@@ -191,7 +208,7 @@ export async function upload(
parentId: options?.projectId,
});
if (res.isErr()) {
- return handleUploadError(res.error, toastId);
+ return handleUploadError(res.error);
}
const { presignedUrl, requestId } = res.value;
@@ -201,19 +218,17 @@ export async function upload(
!requestId ||
!(await putFile(presignedUrl, 'application/zip'))
) {
- return handleUploadError('Failed to upload zip file', toastId);
+ return handleUploadError('Failed to upload zip file');
}
const projectIdPromise = waitBulkUploadStatus(requestId);
- // Wait for upload status and dismiss toast when complete
projectIdPromise.then((projectId) => {
if (projectId) {
toast.success(`Uploaded ${name}`);
} else {
toast.failure(`Failed to upload ${name}`);
}
- dismissToast(toastId);
});
return {
@@ -235,7 +250,7 @@ export async function upload(
jobId = await uploadJobPromise;
if (jobId == null) {
console.error('failed to upload docx', sha);
- return handleUploadError('Failed to upload docx file', toastId);
+ return handleUploadError('Failed to upload docx file');
}
if (!options?.skipWaitForDocxProcessing)
docxProcessingPromise = processingPromise;
@@ -251,7 +266,7 @@ export async function upload(
});
if (newfile.isErr()) {
- return handleUploadError(newfile.error, toastId);
+ return handleUploadError(newfile.error);
}
const { metadata, presignedUrl, contentType, fileType } = newfile.value;
@@ -269,7 +284,7 @@ export async function upload(
if (!(await putFile(presignedUrl, resolvedContentType))) {
console.error('failed to upload', documentId, 'removing...');
await storageServiceClient.deleteDocument({ documentId });
- return handleUploadError('Failed to upload file', toastId);
+ return handleUploadError('Failed to upload file');
}
// Document upload finalization is owned by the backend S3 ObjectCreated
@@ -295,8 +310,6 @@ export async function upload(
await docxProcessingPromise;
}
- dismissToast(toastId);
-
return {
type: 'document',
name,
diff --git a/apps/web/src/lib/service-clients/service-storage/util/uploadToPresignedUrl.test.ts b/apps/web/src/lib/service-clients/service-storage/util/uploadToPresignedUrl.test.ts
new file mode 100644
index 0000000000..02bdb6d7e3
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/util/uploadToPresignedUrl.test.ts
@@ -0,0 +1,124 @@
+import { isTauri } from '@core/util/platform';
+import { platformFetch } from '@core/util/platformFetch';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { uploadToPresignedUrl } from './uploadToPresignedUrl';
+
+vi.mock('@core/util/platform', () => ({ isTauri: vi.fn(() => false) }));
+vi.mock('@core/util/platformFetch', () => ({ platformFetch: vi.fn() }));
+
+class FakeXhr {
+ static instances: FakeXhr[] = [];
+ status = 0;
+ responseText = '';
+ onload: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ onabort: (() => void) | null = null;
+ upload = {
+ onprogress: null as ((event: Partial<ProgressEvent>) => void) | null,
+ };
+ open = vi.fn();
+ setRequestHeader = vi.fn();
+ send = vi.fn();
+ abort = vi.fn(() => this.onabort?.());
+
+ constructor() {
+ FakeXhr.instances.push(this);
+ }
+
+ respond(status: number, responseText = ''): void {
+ this.status = status;
+ this.responseText = responseText;
+ this.onload?.();
+ }
+}
+
+const xhr = () => FakeXhr.instances[0];
+const params = () => ({
+ presignedUrl: 'https://bucket.example/doc?signed',
+ buffer: new Uint8Array([1, 2, 3, 4]),
+ sha: 'ab'.repeat(32),
+ type: 'application/pdf',
+});
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ FakeXhr.instances = [];
+ vi.stubGlobal('XMLHttpRequest', FakeXhr);
+});
+afterEach(() => vi.unstubAllGlobals());
+
+describe('uploadToPresignedUrl with progress', () => {
+ it('PUTs the signed request over XHR and reports bytes sent', async () => {
+ const onProgress = vi.fn();
+ const pending = uploadToPresignedUrl({ ...params(), onProgress });
+
+ expect(xhr().open).toHaveBeenCalledWith(
+ 'PUT',
+ 'https://bucket.example/doc?signed'
+ );
+ expect(xhr().setRequestHeader.mock.calls).toEqual([
+ ['Content-Type', 'application/pdf'],
+ [
+ 'x-amz-checksum-sha256',
+ btoa(String.fromCharCode(...new Uint8Array(32).fill(171))),
+ ],
+ ]);
+ expect(onProgress).toHaveBeenLastCalledWith(0);
+
+ xhr().upload.onprogress?.({ loaded: 2 });
+ expect(onProgress).toHaveBeenLastCalledWith(2);
+
+ xhr().respond(200);
+ expect((await pending).isOk()).toBe(true);
+ expect(onProgress).toHaveBeenLastCalledWith(4);
+ expect(platformFetch).not.toHaveBeenCalled();
+ });
+
+ it('returns the response body as a server error', async () => {
+ const pending = uploadToPresignedUrl({ ...params(), onProgress: vi.fn() });
+ xhr().respond(403, 'SignatureDoesNotMatch');
+ expect((await pending)._unsafeUnwrapErr()).toEqual([
+ { code: 'SERVER_ERROR', message: 'SignatureDoesNotMatch' },
+ ]);
+ });
+
+ it('rejects on network failure, like fetch', async () => {
+ const pending = uploadToPresignedUrl({ ...params(), onProgress: vi.fn() });
+ xhr().onerror?.();
+ await expect(pending).rejects.toThrow(TypeError);
+ });
+
+ it('aborts with the signal and removes its listener', async () => {
+ const controller = new AbortController();
+ const remove = vi.spyOn(controller.signal, 'removeEventListener');
+ const pending = uploadToPresignedUrl({
+ ...params(),
+ signal: controller.signal,
+ onProgress: vi.fn(),
+ });
+ controller.abort();
+ await expect(pending).rejects.toThrow();
+ expect(xhr().abort).toHaveBeenCalledOnce();
+ expect(remove).toHaveBeenCalledWith('abort', expect.any(Function));
+ });
+
+ it('uses the native transport in Tauri and reports progress as unmeasurable', async () => {
+ vi.mocked(isTauri).mockReturnValue(true);
+ vi.mocked(platformFetch).mockResolvedValue(new Response(null));
+ const onProgress = vi.fn();
+
+ const result = await uploadToPresignedUrl({ ...params(), onProgress });
+
+ expect(result.isOk()).toBe(true);
+ expect(onProgress).toHaveBeenCalledExactlyOnceWith(null);
+ expect(FakeXhr.instances).toHaveLength(0);
+ });
+
+ it('keeps using fetch when no progress is requested', async () => {
+ vi.mocked(platformFetch).mockResolvedValue(new Response(null));
+
+ expect((await uploadToPresignedUrl(params())).isOk()).toBe(true);
+ expect(platformFetch).toHaveBeenCalledOnce();
+ expect(FakeXhr.instances).toHaveLength(0);
+ });
+});
diff --git a/apps/web/src/lib/service-clients/service-storage/util/uploadToPresignedUrl.ts b/apps/web/src/lib/service-clients/service-storage/util/uploadToPresignedUrl.ts
index 4b506fbfec..825d04e5e8 100644
--- a/apps/web/src/lib/service-clients/service-storage/util/uploadToPresignedUrl.ts
+++ b/apps/web/src/lib/service-clients/service-storage/util/uploadToPresignedUrl.ts
@@ -1,20 +1,29 @@
+import { isTauri } from '@core/util/platform';
import { platformFetch } from '@core/util/platformFetch';
import type { ResultError } from '@core/util/result';
import { err, ok, type Result } from 'neverthrow';
+type UploadResult = Result<void, ResultError<'SERVER_ERROR'>[]>;
+
export async function uploadToPresignedUrl({
presignedUrl,
buffer,
sha,
type,
signal,
+ onProgress,
}: {
presignedUrl: string;
buffer: BufferSource;
sha: string;
type: string;
signal?: AbortSignal;
-}): Promise<Result<void, ResultError<'SERVER_ERROR'>[]>> {
+ /**
+ * Bytes sent so far. Browsers report it as the body uploads; the Tauri HTTP
+ * plugin can't, so there it is only reported as null before the request.
+ */
+ onProgress?: (sent: number | null) => void;
+}): Promise<UploadResult> {
const blob = new Blob([buffer], { type });
const base64Sha = btoa(
@@ -23,14 +32,20 @@ export async function uploadToPresignedUrl({
.map((a) => String.fromCharCode(parseInt(a, 16)))
.join('')
);
+ const headers = {
+ 'Content-Type': type,
+ 'x-amz-checksum-sha256': base64Sha,
+ };
+
+ if (onProgress && !isTauri()) {
+ return uploadWithXhr({ presignedUrl, blob, headers, signal, onProgress });
+ }
+ onProgress?.(null);
const response = await platformFetch(presignedUrl, {
method: 'PUT',
body: blob,
- headers: {
- 'Content-Type': type,
- 'x-amz-checksum-sha256': base64Sha,
- },
+ headers,
signal,
});
@@ -41,3 +56,57 @@ export async function uploadToPresignedUrl({
return ok(undefined);
}
+
+/** `fetch` can't report upload progress, so the browser path uses XHR. */
+function uploadWithXhr({
+ presignedUrl,
+ blob,
+ headers,
+ signal,
+ onProgress,
+}: {
+ presignedUrl: string;
+ blob: Blob;
+ headers: Record<string, string>;
+ signal?: AbortSignal;
+ onProgress: (sent: number) => void;
+}): Promise<UploadResult> {
+ return new Promise((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+ const abort = () => xhr.abort();
+ const settle = () => signal?.removeEventListener('abort', abort);
+
+ xhr.upload.onprogress = (event) => onProgress(event.loaded);
+ xhr.onload = () => {
+ settle();
+ if (xhr.status >= 200 && xhr.status < 300) {
+ onProgress(blob.size);
+ resolve(ok(undefined));
+ } else {
+ resolve(err([{ code: 'SERVER_ERROR', message: xhr.responseText }]));
+ }
+ };
+ // Mirror fetch, which rejects on network failure and abort.
+ xhr.onerror = () => {
+ settle();
+ reject(new TypeError('Failed to upload file'));
+ };
+ xhr.onabort = () => {
+ settle();
+ reject(signal?.reason ?? new DOMException('Aborted', 'AbortError'));
+ };
+
+ if (signal?.aborted) {
+ reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
+ return;
+ }
+
+ xhr.open('PUT', presignedUrl);
+ for (const [name, value] of Object.entries(headers)) {
+ xhr.setRequestHeader(name, value);
+ }
+ onProgress(0);
+ xhr.send(blob);
+ signal?.addEventListener('abort', abort, { once: true });
+ });
+}