Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Show download progress on phones and send big files to the browser download (#11599)

[._.]/dac905ef683d
diff --git a/client/src/components/DownloadManager.jsx b/client/src/components/DownloadManager.jsx
index b0599cedc1..cfc702cc3d 100644
--- a/client/src/components/DownloadManager.jsx
+++ b/client/src/components/DownloadManager.jsx
@@ -1,6 +1,8 @@
import { useEffect, useRef, useState } from 'react';
import Modal from './ui/Modal.jsx';
-import { assetDownloadUrl, installStandaloneDownloadHandler, prepareDownload } from '../lib/standaloneDownload.js';
+import ProgressBar from './ui/ProgressBar.jsx';
+import { SHARE_SHEET_MAX_BYTES, assetDownloadUrl, installStandaloneDownloadHandler, prepareDownload } from '../lib/standaloneDownload.js';
+import { formatBytes } from '../utils/formatters.js';
// One app-level surface for all same-origin download links on share-capable
// touch browsers and Home Screen apps. The file stays available after canceling
@@ -10,6 +12,8 @@ export default function DownloadManager() {
const [file, setFile] = useState(null);
const [error, setError] = useState('');
const [sharing, setSharing] = useState(false);
+ const [progress, setProgress] = useState(null);
+ const [tooLarge, setTooLarge] = useState(null);
const pending = useRef(null);
useEffect(() => {
@@ -21,16 +25,21 @@ export default function DownloadManager() {
setFile(null);
setError('');
setSharing(false);
- prepareDownload(next, controller.signal).then((ready) => {
+ setProgress(null);
+ setTooLarge(null);
+ const onProgress = (next) => { if (!controller.signal.aborted) setProgress(next); };
+ prepareDownload(next, controller.signal, onProgress).then((ready) => {
if (!controller.signal.aborted) setFile(ready);
}).catch((err) => {
- if (!controller.signal.aborted) setError(`Download failed: ${err.message}`);
+ if (controller.signal.aborted) return;
+ if (err.code === 'DOWNLOAD_TOO_LARGE') setTooLarge({ bytes: err.bytes });
+ else setError(`Download failed: ${err.message}`);
});
});
return () => { uninstall(); pending.current?.abort(); };
}, []);
- const close = () => { pending.current?.abort(); setDownload(null); setFile(null); };
+ const close = () => { pending.current?.abort(); setDownload(null); setFile(null); setProgress(null); setTooLarge(null); };
const save = () => {
const controller = pending.current;
setSharing(true);
@@ -43,16 +52,31 @@ export default function DownloadManager() {
}).finally(() => { if (!controller.signal.aborted) setSharing(false); });
};
+ const preparing = Boolean(download) && !file && !error && !tooLarge;
+ const percent = progress?.total ? (progress.received / progress.total) * 100 : null;
+ const progressText = progress?.received > 0
+ ? (progress.total ? `${formatBytes(progress.received)} of ${formatBytes(progress.total)}` : `${formatBytes(progress.received)} loaded`)
+ : undefined;
+ const statusText = file ? 'Ready. Tap Save, then choose Save Video or Save to Files.'
+ : tooLarge ? `This file is ${tooLarge.bytes ? formatBytes(tooLarge.bytes) : `over ${formatBytes(SHARE_SHEET_MAX_BYTES)}`}, too big for the phone's save sheet. Tap Browser download to save it directly.`
+ : error ? 'Use the browser download or close and try again.'
+ : `Loading the file onto this device${percent == null ? '…' : ` (${Math.floor(percent)}%)`}`;
+
return <Modal open={Boolean(download)} onClose={close} ariaLabel="Save download" size="sm"
panelClassName="bg-port-card border border-port-border rounded-xl p-4 space-y-3">
<h2 className="text-lg font-semibold">Save download</h2>
<p className="text-sm break-all">{download?.filename}</p>
- <p role="status" className="text-sm text-port-text-muted">{file ? 'Ready. Tap Save, then choose Save Video or Save to Files.' : error ? 'Use the browser download or close and try again.' : 'Preparing download…'}</p>
+ <p role="status" className="text-sm text-port-text-muted">{statusText}</p>
+ {preparing && <div className="space-y-1">
+ <ProgressBar percent={percent} label="Download progress" valueText={progressText} />
+ {progress?.received > 0 && <p className="text-xs text-port-text-muted">{progressText}</p>}
+ </div>}
{error && <p role="alert" className="text-sm text-port-error">{error}</p>}
<div className="flex flex-wrap items-center gap-3">
- <button type="button" disabled={!file || sharing} onClick={save} className="min-h-[44px] rounded bg-port-accent text-port-bg px-4 disabled:opacity-50">{sharing ? 'Saving…' : 'Save'}</button>
+ {!tooLarge && <button type="button" disabled={!file || sharing} onClick={save} className="min-h-[44px] rounded bg-port-accent text-port-bg px-4 disabled:opacity-50">{sharing ? 'Saving…' : 'Save'}</button>}
<button type="button" onClick={close} className="min-h-[44px] px-3">Close</button>
- {download && <a href={assetDownloadUrl(download.url)} download={download.filename} data-native-download onClick={close} target="_blank" rel="noopener noreferrer" className="min-h-[44px] inline-flex items-center text-sm text-port-accent">Browser download</a>}
+ {download && <a href={assetDownloadUrl(download.url)} download={download.filename} data-native-download onClick={close} target="_blank" rel="noopener noreferrer"
+ className={tooLarge ? 'min-h-[44px] inline-flex items-center rounded bg-port-accent text-port-bg px-4' : 'min-h-[44px] inline-flex items-center text-sm text-port-accent'}>Browser download</a>}
</div>
</Modal>;
}
diff --git a/client/src/components/DownloadManager.test.jsx b/client/src/components/DownloadManager.test.jsx
index 32a4638ea1..821cb31279 100644
--- a/client/src/components/DownloadManager.test.jsx
+++ b/client/src/components/DownloadManager.test.jsx
@@ -23,7 +23,7 @@ it.each(['touch browser', 'Home Screen app'])('prepares both video downloads in
<RenderStatusPanel renderHistoryId="draft" finalVideo={{ src: '/data/videos/draft.mp4' }} />
</>);
fireEvent.click(screen.getByRole('link', { name: 'Download' }));
- expect(screen.getByRole('status')).toHaveTextContent('Preparing download');
+ expect(screen.getByRole('status')).toHaveTextContent('Loading the file onto this device');
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled();
await act(async () => finish({ ok: true, blob: async () => new Blob(['video'], { type: 'application/octet-stream' }) }));
expect(share).not.toHaveBeenCalled();
@@ -91,3 +91,50 @@ it('aborts a closed download and ignores its late response', async () => {
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(share).not.toHaveBeenCalled();
});
+
+function streamedResponse(chunks, headers = {}) {
+ const pending = [];
+ const read = vi.fn(() => new Promise((resolve) => { pending.push(resolve); }));
+ const cancel = vi.fn().mockResolvedValue();
+ const step = () => {
+ const resolve = pending.shift();
+ const chunk = chunks.shift();
+ resolve(chunk ? { done: false, value: chunk } : { done: true, value: undefined });
+ };
+ return { response: { ok: true, headers: new Headers(headers), body: { getReader: () => ({ read, cancel }), cancel } }, step, cancel };
+}
+
+it('shows how much of the file has loaded while it is prepared', async () => {
+ const stream = streamedResponse([new Uint8Array(300), new Uint8Array(700)], { 'content-length': '1000', 'content-type': 'video/mp4' });
+ fetch.mockResolvedValueOnce(stream.response);
+ renderLink();
+ fireEvent.click(screen.getByRole('link', { name: 'Download example' }));
+ await waitFor(() => expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '0'));
+ await act(async () => stream.step());
+ await waitFor(() => expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '30'));
+ expect(screen.getByRole('status')).toHaveTextContent('(30%)');
+ expect(screen.getByText('300 B of 1000 B')).toBeInTheDocument();
+ await act(async () => stream.step());
+ await act(async () => stream.step());
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled());
+ expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ expect(share.mock.calls[0][0].files[0]).toMatchObject({ name: 'example.mp4', type: 'video/mp4', size: 1000 });
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+});
+
+it.each(['Content-Length', 'streamed size'])('sends a file too big for phone memory to the browser download (%s)', async (measure) => {
+ const big = 101 * 1024 * 1024;
+ const stream = measure === 'Content-Length'
+ ? streamedResponse([], { 'content-length': String(big) })
+ : streamedResponse([{ byteLength: big }]);
+ fetch.mockResolvedValueOnce(stream.response);
+ renderLink();
+ fireEvent.click(screen.getByRole('link', { name: 'Download example' }));
+ if (measure !== 'Content-Length') await waitFor(() => expect(screen.getByRole('progressbar')).toBeInTheDocument()).then(() => act(async () => stream.step()));
+ expect(await screen.findByRole('status')).toHaveTextContent(measure === 'Content-Length' ? 'This file is 101 MB, too big for the phone' : 'This file is over 100 MB, too big for the phone');
+ expect(stream.cancel).toHaveBeenCalled();
+ expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Browser download' })).toHaveAttribute('href', '/data/videos/example.mp4?download=1');
+});
diff --git a/client/src/lib/standaloneDownload.js b/client/src/lib/standaloneDownload.js
index 7dd525bf4f..2f2e28c2ac 100644
--- a/client/src/lib/standaloneDownload.js
+++ b/client/src/lib/standaloneDownload.js
@@ -30,10 +30,44 @@ export function assetDownloadUrl(href) {
return `${url.pathname}${url.search}${url.hash}`;
}
-export async function prepareDownload({ url, filename }, signal) {
+// The share sheet needs the whole file in the browser's memory first. A phone
+// cannot hold a full-length final render (hundreds of MB), so anything larger
+// is refused here and the user is pointed at the native download instead.
+export const SHARE_SHEET_MAX_BYTES = 100 * 1024 * 1024;
+
+const tooLarge = (bytes) => Object.assign(new Error('Too large for the share sheet'), { code: 'DOWNLOAD_TOO_LARGE', bytes });
+
+export async function prepareDownload({ url, filename }, signal, onProgress) {
const res = await fetch(url, { credentials: 'same-origin', signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const blob = await res.blob();
+ const total = Number(res.headers?.get?.('content-length')) || null;
+ if (total > SHARE_SHEET_MAX_BYTES) {
+ res.body?.cancel?.().catch(() => {});
+ throw tooLarge(total);
+ }
+ let blob;
+ const reader = res.body?.getReader?.();
+ if (reader) {
+ const chunks = [];
+ let received = 0;
+ onProgress?.({ received, total });
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ received += value.byteLength;
+ // No Content-Length (chunked): stop as soon as the file proves too big.
+ // Its real size is unknown, so report none rather than the bytes read.
+ if (received > SHARE_SHEET_MAX_BYTES) {
+ reader.cancel().catch(() => {});
+ throw tooLarge(total);
+ }
+ onProgress?.({ received, total });
+ }
+ blob = new Blob(chunks, { type: res.headers?.get?.('content-type') || '' });
+ } else {
+ blob = await res.blob();
+ }
const ext = filename.split('.').pop()?.toLowerCase();
const type = blob.type && blob.type !== 'application/octet-stream' ? blob.type : (MIME_BY_EXT[ext] || blob.type);
const file = new File([blob], filename, { type });