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(downloads): expose file saving in channels and Drive (#8628)

gbirman788dde9b9deb
diff --git a/CLAUDE.md b/CLAUDE.md
index c412ca8c46..0b8dab369d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -79,6 +79,10 @@ Real files live in `.agents/`; tool-specific directories only symlink to it.
- Disagree when they're wrong. No flattery.
- Answer simple questions directly.
- For UI work, ask how it should behave on mobile unless that's obvious.
+- Ground UI proposals and prototypes in the existing Macro app screens and
+ design system, preserving its shell, typography, controls, and spacing.
+- Treat an approved UI proposal followed by a PR request as a request to
+ implement it; keep standalone prototypes outside the repository unless asked.
- Be brief. No justification essays, no time estimates.
**Environment**
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 1264bebd07..8c689b35ae 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -402,3 +402,23 @@ Set `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` when using the Nix Chrome binary.
Cognition, routines, preview control, and MCP share `agent_harness_service`.
Direct local hosts use port 8101 with the existing feature prefixes; the
instance proxy retains `/cognition`, `/scheduled-action`, and `/preview`.
+
+## File downloads
+
+Channel videos and Drive video/image/code/canvas/unknown previews share
+`createFileDownload` and `FileDownloadButton`. Keep menu and visible controls
+bound to the same controller. Download hands off directly to browser downloads
+or the native save picker; keep Share separate and do not add a custom
+confirmation sheet. Snapshot file/version before loading, cancel on disposal or
+selection change, and preserve original filenames from static-file metadata.
+Native Android and iOS use bounded byte exports. Older iOS binaries use Web
+Share until the optional file-export bridge ships. If browser activation expires
+while preparing a share, retain the bytes and let the same action's next tap
+open the system sheet synchronously. Browser success means handoff, not confirmed
+disk completion. See the native bridge's `tauri/file_export_plugin/AGENTS.md`.
+
+The backend-free browser regression downloads real fixture bytes from channel
+cards, the expanded viewer, and the shared Drive/standalone header on desktop,
+phone, and tablet:
+`bunx playwright test --config src/lib/core/component/FileDownload/browser-test/playwright.config.ts`.
+See the [download walkthrough](../../docs/agent-guide/files.md#downloading-files).
diff --git a/apps/web/docs/ios-releases.md b/apps/web/docs/ios-releases.md
index f973a61584..c5b0158cb4 100644
--- a/apps/web/docs/ios-releases.md
+++ b/apps/web/docs/ios-releases.md
@@ -5,6 +5,11 @@ binary update. Their IPC is optional: OTA-only clients retain frontend reload
markers and instance IDs, with missing native coverage explicitly reported.
See [reload diagnostics](../tauri/src-tauri/README.md#diagnosing-unexpected-webview-reloads).
+The optional `file_export_plugin` adds the native file save picker and share
+sheet. The web bundle probes availability and keeps Web Share on older binaries,
+so it does not raise the native floor. The picker itself still needs an App Store
+release; see [file exports](../tauri/file_export_plugin/AGENTS.md).
+
(The Android counterpart — `android-update`, `Android Native Check`, Google
Play as the source of truth — is described in `docs/development/android.md`.)
diff --git a/apps/web/src/components/app/FileDownloadHeader.tsx b/apps/web/src/components/app/FileDownloadHeader.tsx
new file mode 100644
index 0000000000..208179819e
--- /dev/null
+++ b/apps/web/src/components/app/FileDownloadHeader.tsx
@@ -0,0 +1,17 @@
+import { FileDownloadButton } from '@core/component/FileDownload';
+import type { FileDownloadController } from '@core/util/createFileDownload';
+import { HeaderActionGroup } from './HeaderActionGroup';
+import { SidePanel } from './side-panel/SidePanel';
+
+/** Shared by Drive previews and standalone file blocks. */
+export function FileDownloadHeader(props: {
+ download: FileDownloadController;
+}) {
+ return (
+ <SidePanel.HeaderActions>
+ <HeaderActionGroup label="File download">
+ <FileDownloadButton download={props.download} />
+ </HeaderActionGroup>
+ </SidePanel.HeaderActions>
+ );
+}
diff --git a/apps/web/src/features/block-video/component/TopBar.tsx b/apps/web/src/features/block-video/component/TopBar.tsx
index 2e67ef53bd..9cdefcb0fd 100644
--- a/apps/web/src/features/block-video/component/TopBar.tsx
+++ b/apps/web/src/features/block-video/component/TopBar.tsx
@@ -1,3 +1,4 @@
+import { FileDownloadHeader } from '@components/app/FileDownloadHeader';
import type { BlockTool } from '@components/app/ResponsiveBlockToolbar';
import {
ResponsiveBlockToolbar,
@@ -6,9 +7,7 @@ import {
import type { FileOperation } from '@components/app/split-layout/components/SplitFileMenu';
import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeader';
import { BlockItemSplitLabel } from '@components/app/split-layout/components/SplitLabel';
-
import { useBlockId } from '@core/block';
-import { toast } from '@core/component/Toast/Toast';
import {
getShareDrawerRecipientInput,
ShareTrigger,
@@ -16,16 +15,15 @@ import {
import { useShareModal } from '@core/component/TopBar/shareModal';
import { blockMetadataSignal } from '@core/signal/load';
import { useGetPermissions } from '@core/signal/permissions';
+import { createFileDownload } from '@core/util/createFileDownload';
import {
useBlockDocumentDownloadName,
useBlockDocumentName,
} from '@core/util/currentBlockDocumentName';
-import { downloadFile } from '@filesystem/download';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { catchToResult } from '@core/util/result';
import IconShared from '@icon/share.svg';
import Download from '@phosphor/download.svg';
-import Spinner from '@phosphor/spinner.svg';
-import { createCallback } from '@solid-primitives/rootless';
-import { createSignal } from 'solid-js';
import { useGetFileBlob } from '../signal/blockData';
export function TopBar() {
@@ -44,31 +42,14 @@ export function TopBar() {
owner: blockMetadataSignal()?.owner,
}));
- const downloadDocument = createCallback(async () => {
- const fileName = downloadName();
- const [progress, setProgress] = createSignal({ loaded: 0, total: 0 });
-
- const toastId = toast.custom(
- {
- title: `Downloading ${fileName}`,
- icon: () => <Spinner class="text-accent size-5 animate-spin" />,
- color: 'var(--color-accent)',
- content: () => <DownloadProgressBar progress={progress()} />,
- },
- { persistent: true }
- );
-
- try {
- const blob = await getBlob({ onProgress: setProgress });
- toast.dismiss(toastId);
- const { saved } = await downloadFile(blob, fileName);
- if (saved) toast.success(`Downloaded ${fileName}`);
- } catch (e) {
- toast.dismiss(toastId);
- console.error('error downloading file', e);
- toast.failure('Error downloading file');
- }
- });
+ const download = createFileDownload(() => ({
+ id: `${blockId}:${blockMetadataSignal()?.documentVersionId}`,
+ name: downloadName(),
+ load: (options) =>
+ catchToResult(async () => ({ blob: await getBlob(options) })),
+ }));
+ const downloadDocument = () =>
+ fireAndForget(download.start(), 'video-download');
const ops: FileOperation[] = [
{ op: 'rename' },
@@ -96,6 +77,7 @@ export function TopBar() {
return (
<>
+ <FileDownloadHeader download={download} />
<SplitHeaderLeft>
<BlockItemSplitLabel />
</SplitHeaderLeft>
@@ -112,46 +94,3 @@ export function TopBar() {
</>
);
}
-
-const SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB'];
-
-function formatBytes(bytes: number): string {
- if (bytes <= 0) return '0 B';
- const exp = Math.min(
- Math.floor(Math.log(bytes) / Math.log(1024)),
- SIZE_UNITS.length - 1
- );
- const value = bytes / 1024 ** exp;
- const decimals = exp === 0 || value >= 100 ? 0 : value >= 10 ? 1 : 2;
- return `${value.toFixed(decimals)} ${SIZE_UNITS[exp]}`;
-}
-
-function DownloadProgressBar(props: {
- progress: { loaded: number; total: number };
-}) {
- const hasTotal = () => props.progress.total > 0;
- const percent = () =>
- hasTotal()
- ? Math.min(
- 100,
- Math.round((props.progress.loaded / props.progress.total) * 100)
- )
- : 0;
-
- return (
- <div class="space-y-1">
- <div class="h-1 w-full bg-edge rounded-full overflow-hidden">
- <div
- class="h-full bg-accent transition-[width] duration-150 ease-linear"
- classList={{ 'animate-pulse w-full': !hasTotal() }}
- style={hasTotal() ? { width: `${percent()}%` } : undefined}
- />
- </div>
- <div class="text-xs text-ink-extra-muted">
- {hasTotal() ? `${percent()}% — ` : ''}
- {formatBytes(props.progress.loaded)}
- {hasTotal() ? ` of ${formatBytes(props.progress.total)}` : ''}
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/features/block-video/signal/blockData.ts b/apps/web/src/features/block-video/signal/blockData.ts
index 5f09707dcf..ca3e2ed84f 100644
--- a/apps/web/src/features/block-video/signal/blockData.ts
+++ b/apps/web/src/features/block-video/signal/blockData.ts
@@ -27,6 +27,7 @@ export const useGetFileUrl = () => {
};
type GetBlobOptions = {
+ signal?: AbortSignal;
onProgress?: (progress: FetchProgress) => void;
};
@@ -38,8 +39,10 @@ export const useGetFileBlob = () => {
options?: GetBlobOptions
) => {
const result = options?.onProgress
- ? await fetchPresignedBlobWithProgress(url, options.onProgress)
- : await fetchPresigned(url, 'blob');
+ ? await fetchPresignedBlobWithProgress(url, options.onProgress, {
+ signal: options.signal,
+ })
+ : await fetchPresigned(url, 'blob', { signal: options?.signal });
if (result.isErr()) {
throw new Error('unable to fetch from presigned url');
}
@@ -54,6 +57,7 @@ export const useGetFileBlob = () => {
const getBlob = async (options?: GetBlobOptions) => {
const url = await getPresignedUrl();
+ options?.signal?.throwIfAborted();
const blob = await fetchFromPresignedUrl(url, options);
return blob;
};
diff --git a/apps/web/src/features/channel/Media/MediaGrid.tsx b/apps/web/src/features/channel/Media/MediaGrid.tsx
index ed950630d7..73dabfa8d4 100644
--- a/apps/web/src/features/channel/Media/MediaGrid.tsx
+++ b/apps/web/src/features/channel/Media/MediaGrid.tsx
@@ -1,7 +1,10 @@
+import { FileDownloadButton } from '@core/component/FileDownload';
+import { createFileDownload } from '@core/util/createFileDownload';
import { constrainImageDimensions } from '@macro-inc/lexical-core/utils/media';
import ExpandIcon from '@phosphor/arrows-out-simple.svg';
import { Button, cn } from '@ui';
import { createMemo, createSignal, For, Match, Show, Switch } from 'solid-js';
+import { mediaDownloadSource } from '../queries/static-media-download';
import { MediaImage } from './MediaImage';
import { MediaVideo } from './MediaVideo';
import type { MediaItem } from './media-items';
@@ -82,66 +85,80 @@ function AttachmentImageTile(props: { item: MediaItem; onOpen?: () => void }) {
}
function MessageVideoTile(props: { item: MediaItem; onOpen: () => void }) {
+ const download = createFileDownload(() => mediaDownloadSource(props.item));
const [isInlinePlaying, setIsInlinePlaying] = createSignal(false);
const src = () => props.item.src;
const videoWidth = () => props.item.width ?? undefined;
const videoHeight = () => props.item.height ?? undefined;
return (
- <div class="group relative flex min-h-20 max-h-120 max-w-120 min-w-0 overflow-hidden rounded-2xl border border-edge bg-surface">
- <Show
- when={isInlinePlaying()}
- fallback={
- <>
- <button
- type="button"
- class="block max-w-full"
- onClick={props.onOpen}
- aria-label="Open video viewer"
- >
- <MediaVideo.Preview
- src={props.item.src}
- class="block max-h-120 max-w-full"
- width={videoWidth()}
- height={videoHeight()}
- />
- <MediaVideo.PlayOverlay class="[&_svg]:size-6" />
- </button>
- <button
- type="button"
- class="absolute bottom-2 left-2 rounded-md bg-surface/90 px-2 py-1 text-xs font-medium text-ink shadow-sm"
- onClick={(event) => {
- event.stopPropagation();
- setIsInlinePlaying(true);
- }}
- >
- Play inline
- </button>
- </>
- }
- >
- <video
- class="block max-h-120 max-w-full"
- controls
- autoplay
- playsinline
- src={src()}
- width={videoWidth()}
- height={videoHeight()}
- />
- </Show>
- <div class="absolute right-2 top-2 z-10">
- <Button
- variant="ghost"
- size="icon-md"
- onClick={(event) => {
- event.stopPropagation();
- props.onOpen();
- }}
- label="Open video viewer"
+ <div class="flex min-w-0 max-w-120 flex-col overflow-hidden rounded-2xl border border-edge bg-surface">
+ <div class="group relative flex min-h-20 max-h-120 min-w-0 overflow-hidden">
+ <Show
+ when={isInlinePlaying()}
+ fallback={
+ <>
+ <button
+ type="button"
+ class="block max-w-full"
+ onClick={props.onOpen}
+ aria-label="Open video viewer"
+ >
+ <MediaVideo.Preview
+ src={props.item.src}
+ class="block max-h-120 max-w-full"
+ width={videoWidth()}
+ height={videoHeight()}
+ />
+ <MediaVideo.PlayOverlay class="[&_svg]:size-6" />
+ </button>
+ <button
+ type="button"
+ class="absolute bottom-2 left-2 rounded-md bg-surface/90 px-2 py-1 text-xs font-medium text-ink shadow-sm"
+ onClick={(event) => {
+ event.stopPropagation();
+ setIsInlinePlaying(true);
+ }}
+ >
+ Play inline
+ </button>
+ </>
+ }
+ >
+ <video
+ class="block max-h-120 max-w-full"
+ controls
+ autoplay
+ playsinline
+ src={src()}
+ width={videoWidth()}
+ height={videoHeight()}
+ />
+ </Show>
+ <div class="absolute right-2 top-2 z-10">
+ <Button
+ variant="ghost"
+ size="icon-md"
+ onClick={(event) => {
+ event.stopPropagation();
+ props.onOpen();
+ }}
+ label="Open video viewer"
+ >
+ <ExpandIcon />
+ </Button>
+ </div>
+ </div>
+ <div class="flex items-center justify-between gap-2 border-t border-edge px-3 py-2">
+ <span
+ class="min-w-0 truncate text-sm text-ink-muted"
+ title={download.name() || 'Video'}
>
- <ExpandIcon />
- </Button>
+ {download.name() || 'Video'}
+ </span>
+ <div class="flex shrink-0 items-center">
+ <FileDownloadButton download={download} />
+ </div>
</div>
</div>
);
diff --git a/apps/web/src/features/channel/Media/MediaViewerDialog.tsx b/apps/web/src/features/channel/Media/MediaViewerDialog.tsx
index 4e73a1b411..339ed13e6e 100644
--- a/apps/web/src/features/channel/Media/MediaViewerDialog.tsx
+++ b/apps/web/src/features/channel/Media/MediaViewerDialog.tsx
@@ -1,12 +1,17 @@
+import { FileDownloadButton } from '@core/component/FileDownload';
import { Lightbox, LightboxToolbar } from '@core/component/Lightbox';
-
import { isMobile } from '@core/mobile/isMobile';
+import {
+ createFileDownload,
+ type FileDownloadController,
+} from '@core/util/createFileDownload';
import { Dialog } from '@kobalte/core/dialog';
import ChevronLeftIcon from '@phosphor/caret-left.svg';
import ChevronRightIcon from '@phosphor/caret-right.svg';
import XIcon from '@phosphor/x.svg';
import { Button, cn } from '@ui';
import { type Accessor, createMemo, Show } from 'solid-js';
+import { mediaDownloadSource } from '../queries/static-media-download';
import type { MediaItem } from './media-items';
type MediaViewerDialogProps = {
@@ -19,11 +24,13 @@ type MediaViewerDialogProps = {
function VideoViewerContent(props: {
item: Accessor<MediaItem>;
+ download: FileDownloadController;
onPrevious?: () => void;
onNext?: () => void;
indexLabel?: Accessor<string>;
navigationHidden?: boolean;
}) {
+ let opener: HTMLElement | undefined;
const navButtonClass =
'absolute top-1/2 -translate-y-1/2 bg-surface backdrop-blur-sm rounded-lg border border-edge p-2 shadow-md hover:bg-surface transition-colors disabled:cursor-not-allowed disabled:opacity-50';
@@ -71,8 +78,21 @@ function VideoViewerContent(props: {
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
>
- <Dialog.Content class="flex items-center justify-center bg-surface">
+ <Dialog.Content
+ class="flex items-center justify-center bg-surface"
+ onOpenAutoFocus={() => {
+ if (document.activeElement instanceof HTMLElement)
+ opener = document.activeElement;
+ }}
+ onCloseAutoFocus={(event) => {
+ if (opener?.isConnected) {
+ event.preventDefault();
+ opener.focus();
+ }
+ }}
+ >
<LightboxToolbar isVisible={true}>
+ <FileDownloadButton download={props.download} />
<Dialog.CloseButton
as={Button}
variant="ghost"
@@ -132,6 +152,10 @@ function VideoViewerContent(props: {
export function MediaViewerDialog(props: MediaViewerDialogProps) {
const currentItem = createMemo(() => props.items()[props.currentIndex()]);
+ const download = createFileDownload(() => {
+ const item = currentItem();
+ return item?.kind === 'video' ? mediaDownloadSource(item) : undefined;
+ });
const hasPrevious = () => props.currentIndex() > 0;
const hasNext = () => props.currentIndex() < props.items().length - 1;
const hasMultipleItems = () => props.items().length > 1;
@@ -149,7 +173,13 @@ export function MediaViewerDialog(props: MediaViewerDialogProps) {
};
return (
- <Dialog open={props.open} onOpenChange={props.onOpenChange}>
+ <Dialog
+ open={props.open}
+ onOpenChange={(open) => {
+ if (!open) download.cancel();
+ props.onOpenChange(open);
+ }}
+ >
<Dialog.Portal>
<Dialog.Overlay class="fixed inset-0 z-modal scrim-glass" />
<Show when={currentItem()}>
@@ -159,6 +189,7 @@ export function MediaViewerDialog(props: MediaViewerDialogProps) {
fallback={
<VideoViewerContent
item={item}
+ download={download}
onPrevious={hasPrevious() ? navigatePrevious : undefined}
onNext={hasNext() ? navigateNext : undefined}
indexLabel={hasMultipleItems() ? indexLabel : undefined}
diff --git a/apps/web/src/features/channel/queries/static-media-download.ts b/apps/web/src/features/channel/queries/static-media-download.ts
new file mode 100644
index 0000000000..f0ffd18613
--- /dev/null
+++ b/apps/web/src/features/channel/queries/static-media-download.ts
@@ -0,0 +1,31 @@
+import type { DownloadSource } from '@core/util/createFileDownload';
+import { staticFileClient } from '@service-static-files/client';
+import type { MediaItem } from '../Media/media-items';
+
+export function mediaDownloadSource(item: MediaItem): DownloadSource {
+ return {
+ id: item.id,
+ name: 'Video',
+ load: async (options) => {
+ const [metadata, result] = await Promise.all([
+ staticFileClient.getMetadata({ file_id: item.id }),
+ staticFileClient.getFileBlob({ file_id: item.id }, options),
+ ]);
+ return result.map((blob) => {
+ const extension = new Map([
+ ['video/mp4', 'mp4'],
+ ['video/quicktime', 'mov'],
+ ['video/webm', 'webm'],
+ ['video/ogg', 'ogv'],
+ ['video/x-matroska', 'mkv'],
+ ]).get(blob.type.split(';')[0].trim());
+ return {
+ blob,
+ name:
+ (metadata.isOk() && metadata.value.file_name) ||
+ `video-${item.id}${extension ? `.${extension}` : ''}`,
+ };
+ });
+ },
+ };
+}
diff --git a/apps/web/src/features/drive-view/components/DriveDetailView.tsx b/apps/web/src/features/drive-view/components/DriveDetailView.tsx
index 4116e29aaa..dcaae04d53 100644
--- a/apps/web/src/features/drive-view/components/DriveDetailView.tsx
+++ b/apps/web/src/features/drive-view/components/DriveDetailView.tsx
@@ -185,6 +185,7 @@ function StackEntityDetail(props: {
if (context.type !== 'document') return null;
return (
<FileDetailBreadcrumbItem
+ download={context.download}
value={props.entry.value}
metadata={props.entry.data}
order={props.order}
diff --git a/apps/web/src/features/drive-view/queries/file-document.ts b/apps/web/src/features/drive-view/queries/file-document.ts
index d266ab7d2e..2fae9cce2e 100644
--- a/apps/web/src/features/drive-view/queries/file-document.ts
+++ b/apps/web/src/features/drive-view/queries/file-document.ts
@@ -15,6 +15,7 @@ export type FileDocumentData = {
};
export type GetFileBlobOptions = {
+ signal?: AbortSignal;
onProgress?: (progress: FetchProgress) => void;
};
@@ -44,9 +45,12 @@ export async function getFileDocumentBlob(
options?: GetFileBlobOptions
): Promise<Blob> {
const url = await getFileDocumentUrl(data);
+ options?.signal?.throwIfAborted();
return throwOnErr(() =>
options?.onProgress
- ? fetchPresignedBlobWithProgress(url, options.onProgress)
- : fetchPresigned(url, 'blob')
+ ? fetchPresignedBlobWithProgress(url, options.onProgress, {
+ signal: options.signal,
+ })
+ : fetchPresigned(url, 'blob', { signal: options?.signal })
);
}
diff --git a/apps/web/src/features/drive-view/util/download-with-progress.tsx b/apps/web/src/features/drive-view/util/download-with-progress.tsx
deleted file mode 100644
index e1857ee18e..0000000000
--- a/apps/web/src/features/drive-view/util/download-with-progress.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-import { toast } from '@core/component/Toast/Toast';
-import { isPlatform } from '@core/util/platform';
-import { downloadFile } from '@filesystem/download';
-import Spinner from '@phosphor/spinner.svg';
-import type { FetchProgress } from '@service-storage/util/fetchPresigned';
-import { createSignal } from 'solid-js';
-
-const SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB'];
-
-function formatBytes(bytes: number): string {
- if (bytes <= 0) return '0 B';
- const exp = Math.min(
- Math.floor(Math.log(bytes) / Math.log(1024)),
- SIZE_UNITS.length - 1
- );
- const value = bytes / 1024 ** exp;
- const decimals = exp === 0 || value >= 100 ? 0 : value >= 10 ? 1 : 2;
- return `${value.toFixed(decimals)} ${SIZE_UNITS[exp]}`;
-}
-
-function DownloadProgressBar(props: { progress: FetchProgress }) {
- const hasTotal = () => props.progress.total > 0;
- const percent = () =>
- hasTotal()
- ? Math.min(
- 100,
- Math.round((props.progress.loaded / props.progress.total) * 100)
- )
- : 0;
-
- return (
- <div class="space-y-1">
- <div class="h-1 w-full overflow-hidden rounded-full bg-edge">
- <div
- class="h-full bg-accent transition-[width] duration-150 ease-linear"
- classList={{ 'animate-pulse w-full': !hasTotal() }}
- style={hasTotal() ? { width: `${percent()}%` } : undefined}
- />
- </div>
- <div class="text-xs text-ink-extra-muted">
- {hasTotal() ? `${percent()}% — ` : ''}
- {formatBytes(props.progress.loaded)}
- {hasTotal() ? ` of ${formatBytes(props.progress.total)}` : ''}
- </div>
- </div>
- );
-}
-
-export async function downloadWithProgress(
- fileName: string,
- load: (onProgress: (progress: FetchProgress) => void) => Promise<Blob>
-) {
- const [progress, setProgress] = createSignal<FetchProgress>({
- loaded: 0,
- total: 0,
- });
- const toastId = toast.custom(
- {
- title: `Downloading ${fileName}`,
- icon: () => <Spinner class="size-5 animate-spin text-accent" />,
- color: 'var(--color-accent)',
- content: () => <DownloadProgressBar progress={progress()} />,
- },
- { persistent: true }
- );
-
- try {
- const blob = await load(setProgress);
- toast.dismiss(toastId);
- const { saved } = await downloadFile(blob, fileName);
- if (saved) {
- toast.success(
- isPlatform('android') ? `Saved ${fileName}` : `Downloaded ${fileName}`
- );
- }
- } catch (error) {
- toast.dismiss(toastId);
- console.error('error downloading file', error);
- toast.failure('Error downloading file');
- }
-}
diff --git a/apps/web/src/features/drive-view/util/file-detail-context.ts b/apps/web/src/features/drive-view/util/file-detail-context.ts
index f4c31ba476..e0c003912a 100644
--- a/apps/web/src/features/drive-view/util/file-detail-context.ts
+++ b/apps/web/src/features/drive-view/util/file-detail-context.ts
@@ -1,4 +1,5 @@
import type { FileOperation } from '@components/app/split-layout/components/SplitFileMenu';
+import type { FileDownloadController } from '@core/util/createFileDownload';
import type { AccessLevel } from '@service-storage/generated/schemas/accessLevel';
import type { DocumentMetadata } from '@service-storage/generated/schemas/documentMetadata';
@@ -7,4 +8,5 @@ export type FileDetailContext<T> = {
documentMetadata: DocumentMetadata;
userAccessLevel: AccessLevel;
operations?: FileOperation[];
+ download?: FileDownloadController;
};
diff --git a/apps/web/src/features/drive-view/views/CanvasDetail.tsx b/apps/web/src/features/drive-view/views/CanvasDetail.tsx
index 2614bb7a54..45fa322938 100644
--- a/apps/web/src/features/drive-view/views/CanvasDetail.tsx
+++ b/apps/web/src/features/drive-view/views/CanvasDetail.tsx
@@ -5,9 +5,10 @@ import {
hasPermissions,
Permissions,
} from '@core/component/SharePermissions';
+import { createFileDownload } from '@core/util/createFileDownload';
import { fireAndForget } from '@core/util/fireAndForget';
-import { downloadFile } from '@filesystem/download';
import { useSearchParams } from '@solidjs/router';
+import { ok } from 'neverthrow';
import type { Accessor, JSX } from 'solid-js';
import { FileDetailLayout, FileDetailLoadGate } from '../components/FileDetail';
import { downloadFileOperation } from '../components/file-detail-operations';
@@ -27,18 +28,18 @@ function CanvasDetailContent(props: {
savedFile: Accessor<Blob | undefined>;
}) {
const analytics = useAnalytics();
- const downloadName = documentDownloadName(
- props.data.documentMetadata,
- 'Unknown Filename'
- );
- const operations = [
- downloadFileOperation(() => {
- fireAndForget(
- downloadFile(props.savedFile() ?? props.data.file, downloadName),
- 'drive-file-download'
- );
+ const download = createFileDownload(() => ({
+ id: `${props.data.documentMetadata.documentId}:${props.data.documentMetadata.documentVersionId}`,
+ name: documentDownloadName(props.data.documentMetadata, 'Unknown Filename'),
+ load: async () => {
analytics.track('download', { blockType: 'canvas' });
- }),
+ return ok({ blob: props.savedFile() ?? props.data.file });
+ },
+ }));
+ const operations = [
+ downloadFileOperation(() =>
+ fireAndForget(download.start(), 'drive-file-download')
+ ),
];
return (
@@ -48,6 +49,7 @@ function CanvasDetailContent(props: {
documentMetadata: props.data.documentMetadata,
userAccessLevel: props.data.userAccessLevel,
operations,
+ download,
})}
<div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">
{props.content}
diff --git a/apps/web/src/features/drive-view/views/CodeDetail.tsx b/apps/web/src/features/drive-view/views/CodeDetail.tsx
index 3729245352..02ffc10c54 100644
--- a/apps/web/src/features/drive-view/views/CodeDetail.tsx
+++ b/apps/web/src/features/drive-view/views/CodeDetail.tsx
@@ -6,9 +6,10 @@ import {
import { CodeModeControl } from '@block-code/component/CodeModeControl';
import { isHtmlFileType } from '@block-code/util/fileMode';
import { SidePanel } from '@components/app/side-panel';
+import { createFileDownload } from '@core/util/createFileDownload';
import { fireAndForget } from '@core/util/fireAndForget';
-import { downloadFile } from '@filesystem/download';
import { Rerun } from '@solid-primitives/keyed';
+import { ok } from 'neverthrow';
import {
type Accessor,
createSignal,
@@ -72,17 +73,18 @@ function CodeDetailSession(props: {
}) {
const analytics = useAnalytics();
const [text, setText] = createSignal(props.data.text);
- const operations = [
- downloadFileOperation(() => {
- fireAndForget(
- downloadFile(
- new Blob([text() ?? ''], { type: 'text/plain' }),
- documentDownloadName(props.data.documentMetadata)
- ),
- 'drive-file-download'
- );
+ const download = createFileDownload(() => ({
+ id: `${props.documentId}:${props.data.documentMetadata.documentVersionId}`,
+ name: documentDownloadName(props.data.documentMetadata),
+ load: async () => {
analytics.track('download', { blockType: 'code' });
- }),
+ return ok({ blob: new Blob([text() ?? ''], { type: 'text/plain' }) });
+ },
+ }));
+ const operations = [
+ downloadFileOperation(() =>
+ fireAndForget(download.start(), 'drive-file-download')
+ ),
];
return (
@@ -92,6 +94,7 @@ function CodeDetailSession(props: {
documentMetadata: props.data.documentMetadata,
userAccessLevel: props.data.userAccessLevel,
operations,
+ download,
})}
<CodeDetailContent
documentId={props.documentId}
diff --git a/apps/web/src/features/drive-view/views/FileDetailBreadcrumbItem.tsx b/apps/web/src/features/drive-view/views/FileDetailBreadcrumbItem.tsx
index db528e5e51..d7b92b4c1e 100644
--- a/apps/web/src/features/drive-view/views/FileDetailBreadcrumbItem.tsx
+++ b/apps/web/src/features/drive-view/views/FileDetailBreadcrumbItem.tsx
@@ -1,6 +1,7 @@
import { DocumentTitleHoverCard } from '@app/components/entity-detail/DocumentTitleHoverCard';
import { ViewBreadcrumbs } from '@app/components/view-shell';
import { useBlockEntityCommands } from '@app/features/next-soup/actions';
+import { FileDownloadHeader } from '@components/app/FileDownloadHeader';
import type { FileOperation } from '@components/app/split-layout/components/SplitFileMenu';
import { SplitFileMenu } from '@components/app/split-layout/components/SplitFileMenu';
import {
@@ -10,10 +11,12 @@ import {
import type { BlockAlias, BlockName } from '@core/block';
import { EntityIcon } from '@core/component/EntityIcon';
import { getPermissions } from '@core/component/SharePermissions';
+import type { FileDownloadController } from '@core/util/createFileDownload';
import { buildEntityData } from '@entity';
import { useItemRawName } from '@queries/preview';
import type { AccessLevel } from '@service-storage/generated/schemas/accessLevel';
import type { DocumentMetadata } from '@service-storage/generated/schemas/documentMetadata';
+import { Show } from 'solid-js';
export function FileDetailBreadcrumbItem(props: {
value: string;
@@ -24,6 +27,7 @@ export function FileDetailBreadcrumbItem(props: {
blockType: BlockName | BlockAlias;
fallbackName?: string;
operations?: FileOperation[];
+ download?: FileDownloadController;
onClose: () => void;
onDuplicate: (id: string, name: string) => void;
}) {
@@ -62,51 +66,56 @@ export function FileDetailBreadcrumbItem(props: {
});
return (
- <ViewBreadcrumbs.Item
- value={props.value}
- metadata={props.metadata}
- order={props.order}
- >
- {(item) => (
- <div class="flex min-w-0 items-center motion-safe:animate-[dialog-overlay-open_150ms_ease-out]">
- <DocumentTitleHoverCard
- documentId={documentId()}
- name={documentName()}
- ownerId={props.documentMetadata.owner}
- createdAt={props.documentMetadata.createdAt}
- updatedAt={props.documentMetadata.updatedAt}
- >
- <ViewBreadcrumbs.Button
- class="gap-1.5"
- isActive={item.isActive()}
- onClick={item.onSelect}
+ <>
+ <Show when={props.download}>
+ {(download) => <FileDownloadHeader download={download()} />}
+ </Show>
+ <ViewBreadcrumbs.Item
+ value={props.value}
+ metadata={props.metadata}
+ order={props.order}
+ >
+ {(item) => (
+ <div class="flex min-w-0 items-center motion-safe:animate-[dialog-overlay-open_150ms_ease-out]">
+ <DocumentTitleHoverCard
+ documentId={documentId()}
+ name={documentName()}
+ ownerId={props.documentMetadata.owner}
+ createdAt={props.documentMetadata.createdAt}
+ updatedAt={props.documentMetadata.updatedAt}
>
- <EntityIcon
- targetType={
- props.blockType === 'unknown'
- ? (props.documentMetadata.fileType ?? props.blockType)
- : props.blockType
- }
- size="xs"
- class="shrink-0"
+ <ViewBreadcrumbs.Button
+ class="gap-1.5"
+ isActive={item.isActive()}
+ onClick={item.onSelect}
+ >
+ <EntityIcon
+ targetType={
+ props.blockType === 'unknown'
+ ? (props.documentMetadata.fileType ?? props.blockType)
+ : props.blockType
+ }
+ size="xs"
+ class="shrink-0"
+ />
+ <span class="truncate">{documentName()}</span>
+ </ViewBreadcrumbs.Button>
+ </DocumentTitleHoverCard>
+ <div class="shrink-0">
+ <SplitFileMenu
+ id={documentId()}
+ itemType="document"
+ name={documentName()}
+ ops={fileOperations()}
+ entityKind={props.blockType}
+ permissions={getPermissions(props.userAccessLevel)}
+ onDuplicate={(id) => props.onDuplicate(id, documentName())}
+ onDelete={props.onClose}
/>
- <span class="truncate">{documentName()}</span>
- </ViewBreadcrumbs.Button>
- </DocumentTitleHoverCard>
- <div class="shrink-0">
- <SplitFileMenu
- id={documentId()}
- itemType="document"
- name={documentName()}
- ops={fileOperations()}
- entityKind={props.blockType}
- permissions={getPermissions(props.userAccessLevel)}
- onDuplicate={(id) => props.onDuplicate(id, documentName())}
- onDelete={props.onClose}
- />
+ </div>
</div>
- </div>
- )}
- </ViewBreadcrumbs.Item>
+ )}
+ </ViewBreadcrumbs.Item>
+ </>
);
}
diff --git a/apps/web/src/features/drive-view/views/ImageDetail.tsx b/apps/web/src/features/drive-view/views/ImageDetail.tsx
index 6003fd9efa..180493888e 100644
--- a/apps/web/src/features/drive-view/views/ImageDetail.tsx
+++ b/apps/web/src/features/drive-view/views/ImageDetail.tsx
@@ -1,6 +1,7 @@
import { ImageContent } from '@block-image/component/ImageContent';
+import { createFileDownload } from '@core/util/createFileDownload';
import { fireAndForget } from '@core/util/fireAndForget';
-import { downloadFile } from '@filesystem/download';
+import { ok } from 'neverthrow';
import type { JSX } from 'solid-js';
import { FileDetailLayout, FileDetailLoadGate } from '../components/FileDetail';
import { downloadFileOperation } from '../components/file-detail-operations';
@@ -18,16 +19,15 @@ export function ImageDetailDocument(props: {
data: ImageDocumentData;
children?: (context: ImageDetailContext) => JSX.Element;
}) {
+ const download = createFileDownload(() => ({
+ id: `${props.documentId}:${props.data.documentMetadata.documentVersionId}`,
+ name: documentDownloadName(props.data.documentMetadata),
+ load: async () => ok({ blob: props.data.file }),
+ }));
const operations = [
- downloadFileOperation(() => {
- fireAndForget(
- downloadFile(
- props.data.file,
- documentDownloadName(props.data.documentMetadata)
- ),
- 'drive-file-download'
- );
- }),
+ downloadFileOperation(() =>
+ fireAndForget(download.start(), 'drive-file-download')
+ ),
];
return (
@@ -41,6 +41,7 @@ export function ImageDetailDocument(props: {
documentMetadata: props.data.documentMetadata,
userAccessLevel: props.data.userAccessLevel,
operations,
+ download,
})}
<ImageContent
file={props.data.file}
diff --git a/apps/web/src/features/drive-view/views/UnknownDetail.tsx b/apps/web/src/features/drive-view/views/UnknownDetail.tsx
index b26648dd44..5da797df1c 100644
--- a/apps/web/src/features/drive-view/views/UnknownDetail.tsx
+++ b/apps/web/src/features/drive-view/views/UnknownDetail.tsx
@@ -1,9 +1,9 @@
import { UnknownContent } from '@block-unknown/component/UnknownContent';
import { getPermissions } from '@core/component/SharePermissions';
-import { toast } from '@core/component/Toast/Toast';
import { useShareModal } from '@core/component/TopBar/shareModal';
+import { createFileDownload } from '@core/util/createFileDownload';
import { fireAndForget } from '@core/util/fireAndForget';
-import { downloadFile } from '@filesystem/download';
+import { catchToResult } from '@core/util/result';
import type { JSX } from 'solid-js';
import { FileDetailLayout, FileDetailLoadGate } from '../components/FileDetail';
import { downloadFileOperation } from '../components/file-detail-operations';
@@ -30,23 +30,24 @@ export function UnknownDetailDocument(props: {
userPermissions: getPermissions(props.data.userAccessLevel),
owner: props.data.documentMetadata.owner,
}));
- const downloadName = () => documentDownloadName(props.data.documentMetadata);
-
- const downloadDocument = async () => {
- try {
- const file = await getFileDocumentBlob({
- documentId: props.documentId,
- documentVersionId: props.data.documentMetadata.documentVersionId,
- });
- await downloadFile(file, downloadName());
- } catch (error) {
- console.error('error downloading file', error);
- toast.failure('Error downloading file');
- }
- };
+ const download = createFileDownload(() => {
+ const documentId = props.documentId;
+ const metadata = props.data.documentMetadata;
+ return {
+ id: `${documentId}:${metadata.documentVersionId}`,
+ name: documentDownloadName(metadata),
+ load: (options) =>
+ catchToResult(async () => ({
+ blob: await getFileDocumentBlob(
+ { documentId, documentVersionId: metadata.documentVersionId },
+ options
+ ),
+ })),
+ };
+ });
const operations = [
downloadFileOperation(() =>
- fireAndForget(downloadDocument(), 'drive-file-download')
+ fireAndForget(download.start(), 'drive-file-download')
),
];
@@ -62,12 +63,13 @@ export function UnknownDetailDocument(props: {
documentMetadata: props.data.documentMetadata,
userAccessLevel: props.data.userAccessLevel,
operations,
+ download,
})}
<UnknownContent
fileName={props.data.documentMetadata.documentName}
onShare={openShare}
onDownload={() =>
- fireAndForget(downloadDocument(), 'drive-file-download')
+ fireAndForget(download.start(), 'drive-file-download')
}
/>
</FileDetailLayout>
diff --git a/apps/web/src/features/drive-view/views/VideoDetail.tsx b/apps/web/src/features/drive-view/views/VideoDetail.tsx
index cc9b0d22d9..1faa8445d6 100644
--- a/apps/web/src/features/drive-view/views/VideoDetail.tsx
+++ b/apps/web/src/features/drive-view/views/VideoDetail.tsx
@@ -1,5 +1,7 @@
import { VideoContent } from '@block-video/component/VideoContent';
+import { createFileDownload } from '@core/util/createFileDownload';
import { fireAndForget } from '@core/util/fireAndForget';
+import { catchToResult } from '@core/util/result';
import type { JSX } from 'solid-js';
import { FileDetailLayout, FileDetailLoadGate } from '../components/FileDetail';
import { downloadFileOperation } from '../components/file-detail-operations';
@@ -9,7 +11,6 @@ import {
type VideoDocumentData,
} from '../queries/video-document';
import { documentDownloadName } from '../util/document-download-name';
-import { downloadWithProgress } from '../util/download-with-progress';
import type { FileDetailContext } from '../util/file-detail-context';
export type VideoDetailContext = FileDetailContext<VideoDocumentData>;
@@ -19,22 +20,25 @@ export function VideoDetailDocument(props: {
data: VideoDocumentData;
children?: (context: VideoDetailContext) => JSX.Element;
}) {
+ const download = createFileDownload(() => {
+ const documentId = props.documentId;
+ const metadata = props.data.documentMetadata;
+ return {
+ id: `${documentId}:${metadata.documentVersionId}`,
+ name: documentDownloadName(metadata),
+ load: (options) =>
+ catchToResult(async () => ({
+ blob: await getFileDocumentBlob(
+ { documentId, documentVersionId: metadata.documentVersionId },
+ options
+ ),
+ })),
+ };
+ });
const operations = [
- downloadFileOperation(() => {
- const fileName = documentDownloadName(props.data.documentMetadata);
- fireAndForget(
- downloadWithProgress(fileName, (onProgress) =>
- getFileDocumentBlob(
- {
- documentId: props.documentId,
- documentVersionId: props.data.documentMetadata.documentVersionId,
- },
- { onProgress }
- )
- ),
- 'drive-view'
- );
- }),
+ downloadFileOperation(() =>
+ fireAndForget(download.start(), 'drive-file-download')
+ ),
];
return (
@@ -49,6 +53,7 @@ export function VideoDetailDocument(props: {
documentMetadata: props.data.documentMetadata,
userAccessLevel: props.data.userAccessLevel,
operations,
+ download,
})}
<VideoContent
videoUrl={props.data.videoUrl}
diff --git a/apps/web/src/lib/core/component/FileDownload.tsx b/apps/web/src/lib/core/component/FileDownload.tsx
new file mode 100644
index 0000000000..b230077230
--- /dev/null
+++ b/apps/web/src/lib/core/component/FileDownload.tsx
@@ -0,0 +1,72 @@
+import type { FileDownloadController } from '@core/util/createFileDownload';
+import { fireAndForget } from '@core/util/fireAndForget';
+import DownloadIcon from '@phosphor/download-simple.svg';
+import ShareIcon from '@phosphor/export.svg';
+import SpinnerIcon from '@phosphor/spinner.svg';
+import { Button } from '@ui';
+import { Show } from 'solid-js';
+
+export function FileDownloadButton(props: {
+ download: FileDownloadController;
+}) {
+ const preparing = () => {
+ const { loaded, total } = props.download.progress();
+ return total > 0
+ ? `Preparing ${Math.min(100, Math.round((loaded / total) * 100))}%`
+ : 'Preparing…';
+ };
+ const saveBusy = () =>
+ props.download.busy() && props.download.action() === 'save';
+ const shareBusy = () =>
+ props.download.busy() && props.download.action() === 'share';
+ return (
+ <>
+ <Show when={!props.download.busy() || props.download.action() === 'save'}>
+ <Button
+ variant="ghost"
+ size="md"
+ disabled={props.download.busy()}
+ onClick={() => fireAndForget(props.download.start(), 'file-download')}
+ >
+ <Show when={saveBusy()} fallback={<DownloadIcon />}>
+ <SpinnerIcon class="animate-spin" />
+ </Show>
+ {saveBusy()
+ ? preparing()
+ : props.download.phase() === 'error' &&
+ props.download.action() === 'save'
+ ? 'Retry download'
+ : props.download.phase() === 'ready' &&
+ props.download.action() === 'save'
+ ? 'Save file'
+ : 'Download'}
+ </Button>
+ </Show>
+ <Show
+ when={
+ props.download.canOfferShare() &&
+ (!props.download.busy() || props.download.action() === 'share')
+ }
+ >
+ <Button
+ variant="ghost"
+ size="md"
+ disabled={props.download.busy()}
+ onClick={() =>
+ fireAndForget(props.download.start('share'), 'file-download')
+ }
+ >
+ <Show when={shareBusy()} fallback={<ShareIcon />}>
+ <SpinnerIcon class="animate-spin" />
+ </Show>
+ {shareBusy() ? preparing() : 'Share'}
+ </Button>
+ </Show>
+ <Show when={props.download.busy()}>
+ <Button variant="ghost" size="md" onClick={props.download.cancel}>
+ Cancel
+ </Button>
+ </Show>
+ </>
+ );
+}
diff --git a/apps/web/src/lib/core/component/FileDownload/browser-test/download.browser.e2e.ts b/apps/web/src/lib/core/component/FileDownload/browser-test/download.browser.e2e.ts
new file mode 100644
index 0000000000..b2e4915a82
--- /dev/null
+++ b/apps/web/src/lib/core/component/FileDownload/browser-test/download.browser.e2e.ts
@@ -0,0 +1,162 @@
+import { readFile } from 'node:fs/promises';
+import { expect, test } from '@playwright/test';
+
+const videoPath = new URL(
+ '../../../../../features/block-pptx/browser-test/fixtures/clip.webm',
+ import.meta.url
+);
+
+test.beforeEach(async ({ page }) => {
+ const video = await readFile(videoPath);
+ await page.route('**/file/download-video', (route) =>
+ route.fulfill({ body: video, contentType: 'video/webm' })
+ );
+ await page.route('**/api/file/metadata/download-video', (route) =>
+ route.fulfill({
+ json: {
+ file_id: 'download-video',
+ file_name: 'Team demo.webm',
+ content_type: 'video/webm',
+ is_uploaded: true,
+ owner_id: 'test-user',
+ s3_key: 'test-video',
+ },
+ })
+ );
+ await page.goto('/');
+});
+
+test('downloads the original video from the message and expanded viewer', async ({
+ page,
+}) => {
+ const action = 'Download';
+ const clickDownload = async () => {
+ await page
+ .getByRole('button', { name: action, exact: true })
+ .last()
+ .click();
+ };
+ const firstDownload = page.waitForEvent('download');
+ await clickDownload();
+ const first = await firstDownload;
+ await expect(page.getByRole('dialog')).toHaveCount(0);
+ expect(first.suggestedFilename()).toBe('Team demo.webm');
+ expect(await readFile((await first.path())!)).toEqual(
+ await readFile(videoPath)
+ );
+ await page
+ .getByRole('button', { name: 'Open video viewer', exact: true })
+ .first()
+ .click();
+ const secondDownload = page.waitForEvent('download');
+ await clickDownload();
+ expect((await secondDownload).suggestedFilename()).toBe('Team demo.webm');
+ await page.keyboard.press('Escape');
+ await expect(
+ page.getByRole('button', { name: 'Open video viewer', exact: true }).first()
+ ).toBeFocused();
+ await expect(page.locator('body')).toHaveJSProperty(
+ 'scrollWidth',
+ await page.locator('body').evaluate((body) => body.clientWidth)
+ );
+});
+
+test('recovers from a failed transfer and never opens the viewer when downloading', async ({
+ page,
+}) => {
+ let failed = false;
+ const video = await readFile(videoPath);
+ await page.route('**/file/download-video', (route) => {
+ if (route.request().resourceType() === 'media' || failed)
+ return route.fulfill({ body: video, contentType: 'video/webm' });
+ failed = true;
+ return route.fulfill({ status: 404 });
+ });
+ await page
+ .getByRole('button', {
+ name: 'Download',
+ exact: true,
+ })
+ .click();
+ await expect(page.locator('video[controls]')).toHaveCount(0);
+ const saved = page.waitForEvent('download');
+ await page
+ .getByRole('button', { name: 'Retry download', exact: true })
+ .click();
+ expect((await saved).suggestedFilename()).toBe('Team demo.webm');
+ await expect(
+ page.getByRole('button', {
+ name: 'Download',
+ exact: true,
+ })
+ ).toBeFocused();
+});
+
+test('the shared Drive and standalone header downloads through its visible action', async ({
+ page,
+}) => {
+ await page.goto('/?header');
+ const trigger = page.getByRole('button', {
+ name: 'Download',
+ exact: true,
+ });
+ const saved = page.waitForEvent('download');
+ await trigger.click();
+ const file = await saved;
+ expect(file.suggestedFilename()).toBe('Team demo.webm');
+ expect(await readFile((await file.path())!)).toEqual(
+ await readFile(videoPath)
+ );
+ await expect(trigger).toBeFocused();
+ await expect(page.locator('body')).toHaveJSProperty(
+ 'scrollWidth',
+ await page.locator('body').evaluate((body) => body.clientWidth)
+ );
+});
+
+test('shares from a separate action after a transfer outlives browser activation', async ({
+ page,
+}) => {
+ await page.addInitScript(() => {
+ Object.defineProperty(navigator, 'canShare', { value: () => true });
+ Object.defineProperty(navigator, 'userActivation', {
+ value: { isActive: false },
+ });
+ Object.defineProperty(navigator, 'share', {
+ value: async (data: ShareData) => {
+ Object.defineProperty(window, 'sharedFileName', {
+ configurable: true,
+ value: data.files?.[0]?.name,
+ });
+ },
+ });
+ });
+ await page.reload();
+ const share = page.getByRole('button', { name: 'Share', exact: true });
+ await share.click();
+ await expect(
+ page.getByText('File ready — tap Share', { exact: true })
+ ).toBeVisible();
+ expect(
+ await page.evaluate(() => Reflect.get(window, 'sharedFileName'))
+ ).toBeUndefined();
+ await expect(page.getByRole('dialog')).toHaveCount(0);
+ const saving = page.waitForEvent('download');
+ const download = page.getByRole('button', { name: 'Download', exact: true });
+ await download.click();
+ expect((await saving).suggestedFilename()).toBe('Team demo.webm');
+ await expect(download).toBeFocused();
+ await share.click();
+ await expect(
+ page.getByText('File ready — tap Share', { exact: true })
+ ).toBeVisible();
+ await share.click();
+ await expect
+ .poll(() => page.evaluate(() => Reflect.get(window, 'sharedFileName')))
+ .toBe('Team demo.webm');
+ await expect(share).toBeFocused();
+ await expect(page.locator('body')).toHaveJSProperty(
+ 'scrollWidth',
+ await page.locator('body').evaluate((body) => body.clientWidth)
+ );
+});
diff --git a/apps/web/src/lib/core/component/FileDownload/browser-test/index.html b/apps/web/src/lib/core/component/FileDownload/browser-test/index.html
new file mode 100644
index 0000000000..5537ee4d29
--- /dev/null
+++ b/apps/web/src/lib/core/component/FileDownload/browser-test/index.html
@@ -0,0 +1 @@
+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Download regression</title></head><body><div id="root"></div><script type="module" src="/main.tsx"></script></body></html>
\ No newline at end of file
diff --git a/apps/web/src/lib/core/component/FileDownload/browser-test/main.tsx b/apps/web/src/lib/core/component/FileDownload/browser-test/main.tsx
new file mode 100644
index 0000000000..d575f7dcd1
--- /dev/null
+++ b/apps/web/src/lib/core/component/FileDownload/browser-test/main.tsx
@@ -0,0 +1,63 @@
+import { MediaPreview } from '@channel/Message/MediaPreview';
+import { mediaDownloadSource } from '@channel/queries/static-media-download';
+import { FileDownloadHeader } from '@components/app/FileDownloadHeader';
+import { SidePanel } from '@components/app/side-panel/SidePanel';
+import { ToastRegion } from '@core/component/Toast/ToastRegion';
+import { staticFileIdEndpoint } from '@core/constant/servers';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { createFileDownload } from '@core/util/createFileDownload';
+import { Show } from 'solid-js';
+import { render } from 'solid-js/web';
+import '../../../../../index.css';
+
+document.documentElement.dataset.touchDevice = String(isTouchDevice());
+
+function HeaderFixture() {
+ const download = createFileDownload(() =>
+ mediaDownloadSource({
+ id: 'download-video',
+ kind: 'video',
+ src: staticFileIdEndpoint('download-video'),
+ fullSrc: staticFileIdEndpoint('download-video'),
+ })
+ );
+ return (
+ <SidePanel.Root floating>
+ <header class="flex items-center justify-between gap-2 border-b border-edge pb-2">
+ <span class="min-w-0 truncate">Team demo.webm</span>
+ <SidePanel.HeaderActionsOutlet />
+ </header>
+ <FileDownloadHeader download={download} />
+ </SidePanel.Root>
+ );
+}
+
+const root = document.getElementById('root');
+if (!root) throw new Error('Missing fixture root');
+render(
+ () => (
+ <main class="min-h-screen bg-page p-4 text-ink">
+ <Show
+ when={location.search.includes('header')}
+ fallback={
+ <MediaPreview
+ items={[
+ {
+ id: 'download-video',
+ kind: 'video',
+ width: 480,
+ height: 270,
+ src: staticFileIdEndpoint('download-video'),
+ fullSrc: staticFileIdEndpoint('download-video'),
+ },
+ ]}
+ />
+ }
+ >
+ <HeaderFixture />
+ </Show>
+ <ToastRegion />
+ </main>
+ ),
+ root
+);
diff --git a/apps/web/src/lib/core/component/FileDownload/browser-test/playwright.config.ts b/apps/web/src/lib/core/component/FileDownload/browser-test/playwright.config.ts
new file mode 100644
index 0000000000..b13b40dcd3
--- /dev/null
+++ b/apps/web/src/lib/core/component/FileDownload/browser-test/playwright.config.ts
@@ -0,0 +1,41 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig, devices } from '@playwright/test';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(
+ new URL('../../../../../../', import.meta.url)
+);
+const port = Number(process.env.DOWNLOAD_BROWSER_PORT ?? 3016);
+export default defineConfig({
+ testDir: directory,
+ testMatch: '*.browser.e2e.ts',
+ outputDir: `${directory}/test-results`,
+ timeout: 30_000,
+ workers: 1,
+ reporter: 'line',
+ use: {
+ launchOptions: {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ },
+ baseURL: `http://127.0.0.1:${port}`,
+ trace: 'retain-on-failure',
+ screenshot: 'only-on-failure',
+ },
+ webServer: {
+ command: `bunx vite --config src/lib/core/component/FileDownload/browser-test/vite.config.ts --port ${port}`,
+ cwd: webDirectory,
+ url: `http://127.0.0.1:${port}`,
+ reuseExistingServer: false,
+ },
+ projects: [
+ { name: 'desktop', use: { ...devices['Desktop Chrome'] } },
+ {
+ name: 'tablet',
+ use: { ...devices['iPad Mini'], browserName: 'chromium' },
+ },
+ {
+ name: 'mobile',
+ use: { ...devices['iPhone 13'], browserName: 'chromium' },
+ },
+ ],
+});
diff --git a/apps/web/src/lib/core/component/FileDownload/browser-test/vite.config.ts b/apps/web/src/lib/core/component/FileDownload/browser-test/vite.config.ts
new file mode 100644
index 0000000000..b588f734db
--- /dev/null
+++ b/apps/web/src/lib/core/component/FileDownload/browser-test/vite.config.ts
@@ -0,0 +1,26 @@
+import { fileURLToPath } from 'node:url';
+import tailwindcss from '@tailwindcss/vite';
+import { defineConfig } from 'vite';
+import solid from 'vite-plugin-solid';
+import solidSvg from 'vite-plugin-solid-svg';
+import tsconfigPaths from 'vite-tsconfig-paths';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(
+ new URL('../../../../../../', import.meta.url)
+);
+export default defineConfig({
+ root: directory,
+ plugins: [
+ tailwindcss(),
+ solid(),
+ solidSvg({ defaultAsComponent: true }),
+ tsconfigPaths({ projects: [`${webDirectory}/tsconfig.json`] }),
+ ],
+ resolve: {
+ dedupe: ['solid-js'],
+ alias: { 'loro-crdt': 'loro-crdt/base64' },
+ },
+ optimizeDeps: { esbuildOptions: { target: 'esnext' } },
+ server: { host: '127.0.0.1', strictPort: true },
+});
diff --git a/apps/web/src/lib/core/mobile/androidFiles.ts b/apps/web/src/lib/core/mobile/androidFiles.ts
index f7ff98324b..b7461cbb1c 100644
--- a/apps/web/src/lib/core/mobile/androidFiles.ts
+++ b/apps/web/src/lib/core/mobile/androidFiles.ts
@@ -1,53 +1,12 @@
-import { invoke } from '@tauri-apps/api/core';
+import { exportNativeFile, type NativeFileAction } from './nativeFileExport';
-const EXPORT_CHUNK_BYTES = 256 * 1024;
+export type AndroidFileAction = NativeFileAction;
-export type AndroidFileAction = 'save' | 'share' | 'copy';
-
-/**
- * Exports already-fetched bytes, including authenticated downloads and Blob
- * URLs. The native side owns the size limit and rejects at `beginExport`.
- */
-export async function exportAndroidFile(
+export function exportAndroidFile(
blob: Blob,
name: string,
action: AndroidFileAction = 'save',
options?: { signal?: AbortSignal; onProgress?: (fraction: number) => void }
): Promise<{ canceled: boolean }> {
- options?.signal?.throwIfAborted();
- const { token } = await invoke<{ token: string }>(
- 'plugin:android-mobile|beginExport',
- {
- name,
- mimeType: blob.type || 'application/octet-stream',
- size: blob.size,
- }
- );
- try {
- for (let offset = 0; offset < blob.size; offset += EXPORT_CHUNK_BYTES) {
- options?.signal?.throwIfAborted();
- const bytes = new Uint8Array(
- await blob.slice(offset, offset + EXPORT_CHUNK_BYTES).arrayBuffer()
- );
- let binary = '';
- for (const byte of bytes) binary += String.fromCharCode(byte);
- await invoke('plugin:android-mobile|appendExport', {
- token,
- data: btoa(binary),
- });
- options?.onProgress?.(
- Math.min(offset + bytes.length, blob.size) / blob.size
- );
- }
- options?.signal?.throwIfAborted();
- return await invoke('plugin:android-mobile|finishExport', {
- token,
- action,
- });
- } finally {
- // Cleanup failures must not mask the export result or its error.
- await invoke('plugin:android-mobile|discardExport', { token }).catch(
- (error) => console.error('Unable to discard Android export', error)
- );
- }
+ return exportNativeFile('android-mobile', blob, name, action, options);
}
diff --git a/apps/web/src/lib/core/mobile/exportAndroidFileWithProgress.test.ts b/apps/web/src/lib/core/mobile/exportAndroidFileWithProgress.test.ts
new file mode 100644
index 0000000000..9ea0742230
--- /dev/null
+++ b/apps/web/src/lib/core/mobile/exportAndroidFileWithProgress.test.ts
@@ -0,0 +1,49 @@
+import { beforeEach, expect, it, vi } from 'vitest';
+import { exportAndroidFileWithProgress } from './exportAndroidFileWithProgress';
+
+const mocks = vi.hoisted(() => ({ export: vi.fn(), dismiss: vi.fn() }));
+vi.mock('./androidFiles', () => ({ exportAndroidFile: mocks.export }));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { custom: () => 1, dismiss: mocks.dismiss },
+}));
+beforeEach(() => vi.clearAllMocks());
+
+it.each([10, 2 * 1024 * 1024])(
+ 'cancels a %i-byte native transfer when its owner closes',
+ async (size) => {
+ const controller = new AbortController();
+ mocks.export.mockImplementation(
+ (_blob, _name, _action, options) =>
+ new Promise((_resolve, reject) => {
+ options.signal.addEventListener(
+ 'abort',
+ () => reject(new DOMException('Cancelled', 'AbortError')),
+ { once: true }
+ );
+ })
+ );
+ const pending = exportAndroidFileWithProgress(
+ new Blob([new Uint8Array(size)]),
+ 'video.mp4',
+ 'share',
+ controller.signal
+ );
+ controller.abort();
+ await expect(pending).resolves.toEqual({ canceled: true });
+ expect(mocks.export.mock.calls[0][3].signal.aborted).toBe(true);
+ }
+);
+
+it('does not start a native export for an already cancelled request', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ await expect(
+ exportAndroidFileWithProgress(
+ new Blob(['video']),
+ 'video.mp4',
+ 'save',
+ controller.signal
+ )
+ ).resolves.toEqual({ canceled: true });
+ expect(mocks.export).not.toHaveBeenCalled();
+});
diff --git a/apps/web/src/lib/core/mobile/exportAndroidFileWithProgress.ts b/apps/web/src/lib/core/mobile/exportAndroidFileWithProgress.ts
index a9dd74cdb7..8a00af3948 100644
--- a/apps/web/src/lib/core/mobile/exportAndroidFileWithProgress.ts
+++ b/apps/web/src/lib/core/mobile/exportAndroidFileWithProgress.ts
@@ -6,10 +6,21 @@ import { type AndroidFileAction, exportAndroidFile } from './androidFiles';
export async function exportAndroidFileWithProgress(
blob: Blob,
name: string,
- action: AndroidFileAction = 'save'
+ action: AndroidFileAction = 'save',
+ signal?: AbortSignal
): Promise<{ canceled: boolean }> {
- if (blob.size < 1024 * 1024) return exportAndroidFile(blob, name, action);
+ if (signal?.aborted) return { canceled: true };
+ if (blob.size < 1024 * 1024) {
+ try {
+ return await exportAndroidFile(blob, name, action, { signal });
+ } catch (error) {
+ if (signal?.aborted) return { canceled: true };
+ throw error;
+ }
+ }
const controller = new AbortController();
+ const abort = () => controller.abort();
+ signal?.addEventListener('abort', abort, { once: true });
const [progress, setProgress] = createSignal(0);
const id = toast.custom(
{
@@ -33,6 +44,7 @@ export async function exportAndroidFileWithProgress(
if (controller.signal.aborted) return { canceled: true };
throw error;
} finally {
+ signal?.removeEventListener('abort', abort);
toast.dismiss(id);
}
}
diff --git a/apps/web/src/lib/core/mobile/iosFiles.test.ts b/apps/web/src/lib/core/mobile/iosFiles.test.ts
new file mode 100644
index 0000000000..6943239b24
--- /dev/null
+++ b/apps/web/src/lib/core/mobile/iosFiles.test.ts
@@ -0,0 +1,77 @@
+import { Blob as NodeBlob } from 'node:buffer';
+import { beforeEach, expect, it, vi } from 'vitest';
+import { hasIosFileExport } from './iosFiles';
+import { exportNativeFile } from './nativeFileExport';
+
+const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }));
+vi.mock('@tauri-apps/api/core', () => ({ invoke }));
+
+beforeEach(() => {
+ invoke.mockReset();
+ invoke.mockImplementation(async (command: string) => {
+ if (command.endsWith('available')) return true;
+ if (command.endsWith('beginExport')) return { token: 'ios-export' };
+ if (command.endsWith('finishExport')) return { canceled: false };
+ });
+});
+
+it('detects older native binaries without attempting an export', async () => {
+ invoke.mockRejectedValue('Plugin file-export not found');
+ expect(await hasIosFileExport()).toBe(false);
+ expect(invoke).toHaveBeenCalledOnce();
+});
+
+it('exports original file bytes to the iOS save picker', async () => {
+ const data = new Uint8Array(600_000).map((_, i) => i % 251);
+ vi.stubGlobal('Blob', NodeBlob);
+ try {
+ await exportNativeFile(
+ 'file-export',
+ new Blob([data], { type: 'video/mp4' }),
+ 'demo.mp4',
+ 'save'
+ );
+ const chunks = invoke.mock.calls.filter(([cmd]) =>
+ cmd.endsWith('appendExport')
+ );
+ expect(chunks).toHaveLength(3);
+ expect(
+ Uint8Array.from(chunks.map(([, args]) => atob(args.data)).join(''), (c) =>
+ c.charCodeAt(0)
+ )
+ ).toEqual(data);
+ expect(invoke).toHaveBeenCalledWith('plugin:file-export|finishExport', {
+ token: 'ios-export',
+ action: 'save',
+ });
+ } finally {
+ vi.unstubAllGlobals();
+ }
+});
+
+it('dismisses an open iOS chooser on cancellation and cleans staged bytes', async () => {
+ const opened = Promise.withResolvers<void>();
+ const result = Promise.withResolvers<{ canceled: boolean }>();
+ invoke.mockImplementation(async (command: string) => {
+ if (command.endsWith('beginExport')) return { token: 'ios-export' };
+ if (command.endsWith('finishExport')) {
+ opened.resolve();
+ return result.promise;
+ }
+ if (command.endsWith('discardExport')) result.resolve({ canceled: true });
+ });
+ const controller = new AbortController();
+ const exporting = exportNativeFile(
+ 'file-export',
+ new Blob([]),
+ 'empty.txt',
+ 'save',
+ { signal: controller.signal }
+ );
+ await opened.promise;
+ controller.abort();
+ expect(await exporting).toEqual({ canceled: true });
+ expect(invoke).toHaveBeenLastCalledWith('plugin:file-export|discardExport', {
+ token: 'ios-export',
+ });
+});
diff --git a/apps/web/src/lib/core/mobile/iosFiles.ts b/apps/web/src/lib/core/mobile/iosFiles.ts
new file mode 100644
index 0000000000..4fb8e840b7
--- /dev/null
+++ b/apps/web/src/lib/core/mobile/iosFiles.ts
@@ -0,0 +1,19 @@
+import { invoke } from '@tauri-apps/api/core';
+import { exportNativeFile } from './nativeFileExport';
+
+/** Older installed binaries keep Web Share until the native bridge ships. */
+export async function hasIosFileExport(): Promise<boolean> {
+ try {
+ return await invoke<boolean>('plugin:file-export|available');
+ } catch {
+ return false;
+ }
+}
+
+export function exportIosFile(
+ file: File,
+ action: 'save' | 'share',
+ options: { signal: AbortSignal; onProgress: (fraction: number) => void }
+) {
+ return exportNativeFile('file-export', file, file.name, action, options);
+}
diff --git a/apps/web/src/lib/core/mobile/nativeFileExport.ts b/apps/web/src/lib/core/mobile/nativeFileExport.ts
new file mode 100644
index 0000000000..296f0360b3
--- /dev/null
+++ b/apps/web/src/lib/core/mobile/nativeFileExport.ts
@@ -0,0 +1,95 @@
+import { fireAndForget } from '@core/util/fireAndForget';
+import { type Span, Telemetry } from '@macro-inc/observability';
+import { invoke } from '@tauri-apps/api/core';
+
+const EXPORT_CHUNK_BYTES = 256 * 1024;
+
+export type NativeFileAction = 'save' | 'share' | 'copy';
+
+/**
+ * Exports already-fetched bytes, including authenticated downloads and Blob
+ * URLs. The native side owns the size limit and rejects at `beginExport`.
+ */
+export async function exportNativeFile(
+ plugin: 'android-mobile' | 'file-export',
+ blob: Blob,
+ name: string,
+ action: NativeFileAction = 'save',
+ {
+ signal,
+ onProgress,
+ }: { signal?: AbortSignal; onProgress?: (fraction: number) => void } = {}
+): Promise<{ canceled: boolean }> {
+ return Telemetry.span('file.native.export', async (span) => {
+ span.setAttr('file.size', blob.size);
+ span.setAttr('file.action', action);
+ span.setAttr('file.native.plugin', plugin);
+ const transfer = span.span('file.native.transfer');
+ let chooser: Span | undefined;
+ try {
+ signal?.throwIfAborted();
+ const { token } = await invoke<{ token: string }>(
+ `plugin:${plugin}|beginExport`,
+ {
+ name,
+ mimeType: blob.type || 'application/octet-stream',
+ size: blob.size,
+ }
+ );
+ const discard = () =>
+ fireAndForget(
+ invoke(`plugin:${plugin}|discardExport`, { token }),
+ 'file-export-cancel'
+ );
+ if (plugin === 'file-export')
+ signal?.addEventListener('abort', discard, { once: true });
+ try {
+ signal?.throwIfAborted();
+ for (let offset = 0; offset < blob.size; offset += EXPORT_CHUNK_BYTES) {
+ signal?.throwIfAborted();
+ const bytes = new Uint8Array(
+ await blob.slice(offset, offset + EXPORT_CHUNK_BYTES).arrayBuffer()
+ );
+ let binary = '';
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ await invoke(`plugin:${plugin}|appendExport`, {
+ token,
+ data: btoa(binary),
+ });
+ onProgress?.(Math.min(offset + bytes.length, blob.size) / blob.size);
+ }
+ signal?.throwIfAborted();
+ transfer.end();
+ chooser = span.span('file.native.chooser');
+ const result = await invoke<{ canceled: boolean }>(
+ `plugin:${plugin}|finishExport`,
+ {
+ token,
+ action,
+ }
+ );
+ chooser.setAttr(
+ 'file.outcome',
+ result.canceled ? 'canceled' : 'handed_off'
+ );
+ return result;
+ } finally {
+ signal?.removeEventListener('abort', discard);
+ // Cleanup failures must not mask the export result or its error.
+ await invoke(`plugin:${plugin}|discardExport`, { token }).catch(
+ (error) => console.error('Unable to discard native export', error)
+ );
+ }
+ } catch (error) {
+ if (signal?.aborted) span.setAttr('file.outcome', 'canceled');
+ else {
+ (chooser ?? transfer).error(error);
+ span.error(error);
+ }
+ throw error;
+ } finally {
+ transfer.end();
+ chooser?.end();
+ }
+ });
+}
diff --git a/apps/web/src/lib/core/util/createFileDownload.test.ts b/apps/web/src/lib/core/util/createFileDownload.test.ts
new file mode 100644
index 0000000000..4ee2a6703d
--- /dev/null
+++ b/apps/web/src/lib/core/util/createFileDownload.test.ts
@@ -0,0 +1,294 @@
+import {
+ createFileDownload,
+ type DownloadSource,
+} from '@core/util/createFileDownload';
+import { err, ok } from 'neverthrow';
+import { createRoot, createSignal } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ touch: false,
+ platform: 'web',
+ save: vi.fn(),
+ android: vi.fn(),
+ ios: vi.fn(),
+ hasIos: vi.fn(),
+ custom: vi.fn(),
+ success: vi.fn(),
+ failure: vi.fn(),
+}));
+vi.mock('@core/mobile/isTouchDevice', () => ({
+ isTouchDevice: () => mocks.touch,
+}));
+vi.mock('@core/util/platform', () => ({
+ isPlatform: (platform: string) => mocks.platform === platform,
+}));
+vi.mock('@core/mobile/iosFiles', () => ({
+ exportIosFile: mocks.ios,
+ hasIosFileExport: mocks.hasIos,
+}));
+vi.mock('@filesystem/download', () => ({ downloadFile: mocks.save }));
+vi.mock('@core/mobile/exportAndroidFileWithProgress', () => ({
+ exportAndroidFileWithProgress: mocks.android,
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: {
+ success: mocks.success,
+ failure: mocks.failure,
+ custom: mocks.custom,
+ },
+}));
+
+type DownloadResult = Awaited<ReturnType<DownloadSource['load']>>;
+let dispose: () => void;
+beforeEach(() => {
+ mocks.touch = false;
+ mocks.platform = 'web';
+ vi.clearAllMocks();
+ mocks.save.mockResolvedValue({ saved: true });
+ mocks.hasIos.mockResolvedValue(true);
+ mocks.ios.mockResolvedValue({ canceled: false });
+ mocks.android.mockResolvedValue({ canceled: false });
+});
+afterEach(() => {
+ dispose?.();
+ vi.unstubAllGlobals();
+});
+
+describe('file download lifecycle', () => {
+ it('deduplicates preparation and saves the original bytes and filename', async () => {
+ const pending = Promise.withResolvers<DownloadResult>();
+ const load = vi.fn<DownloadSource['load']>(() => pending.promise);
+ const download = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createFileDownload(() => ({ id: 'video-1', name: 'Video', load }));
+ });
+ const first = download.start();
+ await download.start();
+ expect(load).toHaveBeenCalledTimes(1);
+ pending.resolve(
+ ok({
+ blob: new Blob(['original video'], { type: 'video/quicktime' }),
+ name: 'Demo.mov',
+ })
+ );
+ await first;
+ expect(mocks.save).toHaveBeenCalledTimes(1);
+ const saved = mocks.save.mock.calls[0][0];
+ expect(saved.name).toBe('Demo.mov');
+ expect(saved.type).toBe('video/quicktime');
+ expect(saved.size).toBe(14);
+ expect(download.busy()).toBe(false);
+ });
+
+ it('aborts on cancel and ignores a late result after a retry', async () => {
+ const old = Promise.withResolvers<DownloadResult>();
+ const next = Promise.withResolvers<DownloadResult>();
+ const load = vi
+ .fn()
+ .mockReturnValueOnce(old.promise)
+ .mockReturnValueOnce(next.promise);
+ const download = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createFileDownload(() => ({
+ id: 'video-1',
+ name: 'demo.mp4',
+ load,
+ }));
+ });
+ const first = download.start();
+ const signal = load.mock.calls[0][0].signal;
+ download.cancel();
+ expect(signal.aborted).toBe(true);
+ const retry = download.start();
+ old.resolve(ok({ blob: new Blob(['old']) }));
+ await first;
+ expect(mocks.save).not.toHaveBeenCalled();
+ expect(download.phase()).toBe('loading');
+ next.resolve(ok({ blob: new Blob(['new']) }));
+ await retry;
+ expect(mocks.save).toHaveBeenCalledTimes(1);
+ });
+
+ it('never downloads stale data after the selected file changes', async () => {
+ const pending = Promise.withResolvers<DownloadResult>();
+ const [id, setId] = createSignal('first');
+ const download = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createFileDownload(() => ({
+ id: id(),
+ name: 'demo.mp4',
+ load: () => pending.promise,
+ }));
+ });
+ const started = download.start();
+ setId('second');
+ pending.resolve(ok({ blob: new Blob(['first']) }));
+ await started;
+ expect(mocks.save).not.toHaveBeenCalled();
+ });
+
+ it('shares prepared files from a fresh tap when browser activation expired', async () => {
+ mocks.touch = true;
+ const share = vi.fn().mockResolvedValue(undefined);
+ vi.stubGlobal('navigator', {
+ canShare: () => true,
+ share,
+ userActivation: { isActive: false },
+ });
+ const download = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createFileDownload(() => ({
+ id: 'video',
+ name: 'demo.mp4',
+ load: async () =>
+ ok({
+ blob: new Blob(['video'], { type: 'video/mp4' }),
+ }),
+ }));
+ });
+ await download.start('share');
+ expect(download.phase()).toBe('ready');
+ expect(share).not.toHaveBeenCalled();
+ expect(mocks.save).not.toHaveBeenCalled();
+ const sharing = download.start('share');
+ expect(share).toHaveBeenCalledTimes(1);
+ await sharing;
+ expect(mocks.success).not.toHaveBeenCalled();
+ expect(download.file()).toBeUndefined();
+ });
+
+ it('keeps the prepared file after native cancellation without reporting success', async () => {
+ mocks.touch = true;
+ mocks.platform = 'android';
+ mocks.android.mockResolvedValue({ canceled: true });
+ const download = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createFileDownload(() => ({
+ id: 'video',
+ name: 'demo.mp4',
+ load: async () => ok({ blob: new Blob(['video']) }),
+ }));
+ });
+ await download.start();
+ expect(download.phase()).toBe('ready');
+ expect(download.file()?.name).toBe('demo.mp4');
+ expect(mocks.success).not.toHaveBeenCalled();
+ expect(mocks.failure).not.toHaveBeenCalled();
+ });
+
+ it.each(['web', 'android', 'ios'])(
+ 'downloads directly on %s without a confirmation step',
+ async (platform) => {
+ mocks.touch = true;
+ mocks.platform = platform;
+ const download = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createFileDownload(() => ({
+ id: 'video',
+ name: 'demo.mp4',
+ load: async () => ok({ blob: new Blob(['video']) }),
+ }));
+ });
+ await download.start();
+ expect(
+ platform === 'android'
+ ? mocks.android
+ : platform === 'ios'
+ ? mocks.ios
+ : mocks.save
+ ).toHaveBeenCalledTimes(1);
+ expect(download.phase()).toBe('idle');
+ }
+ );
+
+ it('opens browser sharing directly while the user gesture remains active', async () => {
+ const share = vi.fn().mockResolvedValue(undefined);
+ vi.stubGlobal('navigator', {
+ canShare: () => true,
+ share,
+ userActivation: { isActive: true },
+ });
+ const download = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createFileDownload(() => ({
+ id: 'video',
+ name: 'demo.mp4',
+ load: async () => ok({ blob: new Blob(['video']) }),
+ }));
+ });
+ await download.start('share');
+ expect(share).toHaveBeenCalledTimes(1);
+ expect(mocks.save).not.toHaveBeenCalled();
+ });
+
+ it('keeps older iOS builds usable through the system share sheet', async () => {
+ mocks.platform = 'ios';
+ mocks.hasIos.mockResolvedValue(false);
+ const share = vi.fn().mockResolvedValue(undefined);
+ vi.stubGlobal('navigator', {
+ canShare: () => true,
+ share,
+ userActivation: { isActive: false },
+ });
+ const load = vi.fn(async () => ok({ blob: new Blob(['video']) }));
+ const download = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createFileDownload(() => ({
+ id: 'video',
+ name: 'demo.mp4',
+ load,
+ }));
+ });
+ await download.start();
+ expect(download.phase()).toBe('ready');
+ const saving = download.start();
+ expect(share).toHaveBeenCalledTimes(1);
+ await saving;
+ expect(load).toHaveBeenCalledTimes(1);
+ expect(mocks.ios).not.toHaveBeenCalled();
+ expect(mocks.success).not.toHaveBeenCalled();
+ });
+
+ it('allows retry after a network failure', async () => {
+ const load = vi
+ .fn()
+ .mockResolvedValueOnce(
+ err([{ code: 'NETWORK_ERROR', message: 'offline' }])
+ )
+ .mockResolvedValueOnce(ok({ blob: new Blob(['video']) }));
+ const download = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createFileDownload(() => ({
+ id: 'video',
+ name: 'demo.mp4',
+ load,
+ }));
+ });
+ await download.start();
+ expect(download.phase()).toBe('error');
+ await download.start();
+ expect(mocks.save).toHaveBeenCalledTimes(1);
+ });
+
+ it('aborts a pending load on disposal and ignores its late result', async () => {
+ const pending = Promise.withResolvers<DownloadResult>();
+ const load = vi.fn<DownloadSource['load']>(() => pending.promise);
+ const download = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createFileDownload(() => ({
+ id: 'video',
+ name: 'demo.mp4',
+ load,
+ }));
+ });
+ const started = download.start();
+ const signal = load.mock.calls[0][0].signal;
+ expect(signal.aborted).toBe(false);
+ dispose();
+ expect(signal.aborted).toBe(true);
+ pending.resolve(ok({ blob: new Blob(['video']) }));
+ await started;
+ expect(mocks.save).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/lib/core/util/createFileDownload.ts b/apps/web/src/lib/core/util/createFileDownload.ts
new file mode 100644
index 0000000000..35087eccf7
--- /dev/null
+++ b/apps/web/src/lib/core/util/createFileDownload.ts
@@ -0,0 +1,306 @@
+import { toast } from '@core/component/Toast/Toast';
+import { exportAndroidFileWithProgress } from '@core/mobile/exportAndroidFileWithProgress';
+import { exportIosFile, hasIosFileExport } from '@core/mobile/iosFiles';
+import { isPlatform } from '@core/util/platform';
+import type { ResultError } from '@core/util/result';
+import { downloadFile } from '@filesystem/download';
+import { type Span, Telemetry } from '@macro-inc/observability';
+import type { FetchProgress } from '@service-storage/util/fetchPresigned';
+import type { Result } from 'neverthrow';
+import {
+ type Accessor,
+ batch,
+ createEffect,
+ createSignal,
+ on,
+ onCleanup,
+} from 'solid-js';
+
+export type DownloadSource = {
+ id: string;
+ name: string;
+ load: (options: {
+ signal: AbortSignal;
+ onProgress: (progress: FetchProgress) => void;
+ }) => Promise<Result<{ blob: Blob; name?: string }, ResultError<string>[]>>;
+};
+
+export function createFileDownload(
+ source: Accessor<DownloadSource | undefined>
+) {
+ const [phase, setPhase] = createSignal<
+ 'idle' | 'loading' | 'ready' | 'saving' | 'error'
+ >('idle');
+ const [action, setAction] = createSignal<'save' | 'share'>('save');
+ let nativeIos = false;
+ const [file, setFile] = createSignal<File>();
+ const [name, setName] = createSignal('');
+ const [progress, setProgress] = createSignal<FetchProgress>({
+ loaded: 0,
+ total: 0,
+ });
+ let controller: AbortController | undefined;
+ const isCurrent = (request: AbortController) =>
+ controller === request && !request.signal.aborted;
+ let selectedId: string | undefined;
+ let trace: Span | undefined;
+ const finishTrace = (outcome: string, error?: unknown) => {
+ if (error !== undefined) trace?.error(error);
+ trace?.setAttr('file.outcome', outcome);
+ trace?.end();
+ trace = undefined;
+ };
+ let opener: HTMLElement | undefined;
+ const restoreFocus = () => {
+ if (opener?.isConnected) opener.focus();
+ };
+
+ const cancel = () => {
+ finishTrace('canceled');
+ controller?.abort();
+ controller = undefined;
+ setFile(undefined);
+ setPhase('idle');
+ };
+ onCleanup(cancel);
+ // Abort the external transfer when the viewer changes file or version.
+ createEffect(on(() => source()?.id, cancel, { defer: true }));
+
+ const busy = () => phase() === 'loading' || phase() === 'saving';
+ const canOfferShare = () =>
+ isPlatform('android') ||
+ isPlatform('ios') ||
+ typeof navigator.share === 'function';
+ const canShare = () => {
+ const ready = file();
+ return (
+ !!ready &&
+ (isPlatform('android') ||
+ nativeIos ||
+ !!navigator.canShare?.({ files: [ready] }))
+ );
+ };
+
+ // A prepared Web Share file can be handed off from the original control on
+ // a fresh tap if loading outlived the browser's user activation.
+ const handOff = async (action: 'save' | 'share') => {
+ const ready = file();
+ const request = controller;
+ if (!ready || !request || request.signal.aborted || phase() === 'saving')
+ return;
+ if (source()?.id !== selectedId) {
+ cancel();
+ return;
+ }
+ setPhase('saving');
+ // A cancelled chooser can be retried with the already prepared bytes.
+ trace ??= Telemetry.span('file.download');
+ trace.setAttr('file.id', selectedId ?? '');
+ trace.setAttr('file.size', ready.size);
+ const span = trace.span(`file.${action}`);
+ try {
+ await span.run(async () => {
+ let canceled = false;
+ if (isPlatform('android')) {
+ ({ canceled } = await exportAndroidFileWithProgress(
+ ready,
+ ready.name,
+ action,
+ request.signal
+ ));
+ } else if (nativeIos) {
+ ({ canceled } = await exportIosFile(ready, action, {
+ signal: request.signal,
+ onProgress: (fraction) => {
+ if (controller === request)
+ setProgress({
+ loaded: fraction * ready.size,
+ total: ready.size,
+ });
+ },
+ }));
+ } else if (action === 'share' || isPlatform('ios')) {
+ await navigator.share({ files: [ready] });
+ } else {
+ const { saved } = await downloadFile(ready, ready.name);
+ if (!saved) {
+ span.error('Unable to save file');
+ if (controller === request) {
+ setPhase('ready');
+ finishTrace('failed', 'Unable to save file');
+ }
+ return;
+ }
+ }
+ span.setAttr('file.outcome', canceled ? 'canceled' : 'handed_off');
+ if (controller !== request) return;
+ if (canceled) {
+ finishTrace('canceled');
+ setPhase('ready');
+ return;
+ }
+ if (action === 'save' && (!isPlatform('ios') || nativeIos)) {
+ toast.success(
+ isPlatform('android') || nativeIos
+ ? 'File saved'
+ : 'Download started',
+ {
+ subtext:
+ isPlatform('android') || nativeIos
+ ? ready.name
+ : `${ready.name} — check your browser or device downloads.`,
+ }
+ );
+ }
+ finishTrace('handed_off');
+ cancel();
+ restoreFocus();
+ });
+ } catch (error) {
+ const canceled =
+ request.signal.aborted ||
+ (error instanceof Error && error.name === 'AbortError');
+ if (canceled) span.setAttr('file.outcome', 'canceled');
+ else span.error(error);
+ if (controller !== request) return;
+ setPhase('ready');
+ finishTrace(
+ canceled ? 'canceled' : 'failed',
+ canceled ? undefined : error
+ );
+ if (canceled) return;
+ Telemetry.error(error, { surface: 'file-download' });
+ toast.failure(
+ action === 'share' ? 'Unable to share file' : 'Unable to download file',
+ {
+ subtext: 'Please try again.',
+ }
+ );
+ } finally {
+ span.end();
+ }
+ };
+
+ const handOffWhenReady = async (nextAction: 'save' | 'share') => {
+ const usesWebShare =
+ !nativeIos &&
+ !isPlatform('android') &&
+ (nextAction === 'share' || isPlatform('ios'));
+ if (usesWebShare) {
+ if (!canShare()) {
+ setPhase('error');
+ finishTrace('unsupported');
+ toast.failure('This device can’t share this file');
+ return;
+ }
+ if (!navigator.userActivation?.isActive) {
+ toast.custom({
+ title:
+ nextAction === 'share'
+ ? 'File ready — tap Share'
+ : 'File ready — tap Save file',
+ });
+ return;
+ }
+ }
+ await handOff(nextAction);
+ };
+
+ const start = async (nextAction: 'save' | 'share' = 'save') => {
+ if (busy()) return;
+ if (document.activeElement instanceof HTMLElement)
+ opener = document.activeElement;
+ if (phase() === 'ready' && file() && source()?.id === selectedId) {
+ setAction(nextAction);
+ await handOff(nextAction);
+ return;
+ }
+ const snapshot = source();
+ if (!snapshot) return;
+ const request = new AbortController();
+ batch(() => {
+ cancel();
+ selectedId = snapshot.id;
+ controller = request;
+ setName(snapshot.name);
+ setProgress({ loaded: 0, total: 0 });
+ setPhase('loading');
+ setAction(nextAction);
+ });
+ trace = Telemetry.span('file.download');
+ trace.setAttr('file.id', snapshot.id);
+ trace.setAttr('file.action', nextAction);
+ const span = trace.span('file.load');
+ try {
+ nativeIos = isPlatform('ios') && (await hasIosFileExport());
+ if (!isCurrent(request)) {
+ span.end();
+ return;
+ }
+ const result = await span.run(async () => {
+ try {
+ const result = await snapshot.load({
+ signal: request.signal,
+ onProgress: (next) => {
+ if (controller === request) setProgress(next);
+ },
+ });
+ if (result.isErr() && !request.signal.aborted)
+ span.error(result.error);
+ return result;
+ } catch (error) {
+ if (request.signal.aborted) span.setAttr('file.outcome', 'canceled');
+ else span.error(error);
+ throw error;
+ } finally {
+ span.end();
+ }
+ });
+ if (!isCurrent(request)) return;
+ if (source()?.id !== snapshot.id) {
+ cancel();
+ return;
+ }
+ if (result.isErr()) {
+ setPhase('error');
+ finishTrace('failed', result.error);
+ toast.failure('Unable to download file', {
+ subtext: 'Try again. The file may no longer be available.',
+ });
+ return;
+ }
+ const filename = result.value.name || snapshot.name;
+ trace?.setAttr('file.size', result.value.blob.size);
+ setName(filename);
+ setFile(
+ new File([result.value.blob], filename, {
+ type: result.value.blob.type,
+ })
+ );
+ setPhase('ready');
+ await handOffWhenReady(nextAction);
+ } catch (error) {
+ if (!isCurrent(request)) return;
+ setPhase('error');
+ finishTrace('failed', error);
+ Telemetry.error(error, { surface: 'file-download' });
+ toast.failure('Unable to download file', {
+ subtext: 'Try again. The file may no longer be available.',
+ });
+ }
+ };
+
+ return {
+ start,
+ cancel,
+ action,
+ phase,
+ busy,
+ file,
+ name,
+ progress,
+ canOfferShare,
+ };
+}
+
+export type FileDownloadController = ReturnType<typeof createFileDownload>;
diff --git a/apps/web/src/lib/service-clients/service-static-files/client.ts b/apps/web/src/lib/service-clients/service-static-files/client.ts
index a1ce6110d3..7033fda258 100644
--- a/apps/web/src/lib/service-clients/service-static-files/client.ts
+++ b/apps/web/src/lib/service-clients/service-static-files/client.ts
@@ -1,4 +1,4 @@
-import { SERVER_HOSTS } from '@core/constant/servers';
+import { SERVER_HOSTS, staticFileIdEndpoint } from '@core/constant/servers';
import {
type FetchWithTokenErrorCode,
fetchWithToken,
@@ -6,6 +6,10 @@ import {
import { platformFetch } from '@core/util/platformFetch';
import type { ObjectLike, ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
+import {
+ type FetchProgress,
+ fetchPresignedBlobWithProgress,
+} from '@service-storage/util/fetchPresigned';
import type { Result } from 'neverthrow';
import type { FileMetadata } from './generated/schemas/fileMetadata';
import type { PutFileRequest } from './generated/schemas/putFileRequest';
@@ -33,6 +37,19 @@ function staticFetch<T extends ObjectLike = never>(
type WithFileId = { file_id: string };
export const staticFileClient = {
+ getFileBlob(
+ args: WithFileId,
+ options: {
+ signal: AbortSignal;
+ onProgress: (progress: FetchProgress) => void;
+ }
+ ) {
+ return fetchPresignedBlobWithProgress(
+ staticFileIdEndpoint(args.file_id),
+ options.onProgress,
+ { signal: options.signal }
+ );
+ },
async makePresignedUrl(args: PutFileRequest) {
return (
await staticFetch<PutFileResponse>('/api/file', {
diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lock
index 208bba81df..a34ad904f4 100644
--- a/apps/web/tauri/Cargo.lock
+++ b/apps/web/tauri/Cargo.lock
@@ -291,6 +291,7 @@ dependencies = [
"tauri-plugin-deep-link",
"tauri-plugin-device-info",
"tauri-plugin-edit-menu",
+ "tauri-plugin-file-export",
"tauri-plugin-haptics",
"tauri-plugin-http",
"tauri-plugin-input-accessory",
@@ -6928,6 +6929,14 @@ dependencies = [
"tauri-plugin",
]
+[[package]]
+name = "tauri-plugin-file-export"
+version = "0.1.0"
+dependencies = [
+ "tauri",
+ "tauri-plugin",
+]
+
[[package]]
name = "tauri-plugin-fs"
version = "2.5.1"
diff --git a/apps/web/tauri/Cargo.toml b/apps/web/tauri/Cargo.toml
index 0e54de8141..61d722d0f3 100644
--- a/apps/web/tauri/Cargo.toml
+++ b/apps/web/tauri/Cargo.toml
@@ -5,6 +5,7 @@ members = [
"android_push_plugin",
"callkit_plugin",
"edit_menu_plugin",
+ "file_export_plugin",
"graphql_cache_plugin",
"input_accessory_plugin",
"logger",
diff --git a/apps/web/tauri/file_export_plugin/AGENTS.md b/apps/web/tauri/file_export_plugin/AGENTS.md
new file mode 100644
index 0000000000..58c6edcfde
--- /dev/null
+++ b/apps/web/tauri/file_export_plugin/AGENTS.md
@@ -0,0 +1,38 @@
+# iOS file exports
+
+## What it is
+
+The shared file download controls use this optional iOS bridge to open UIKit's
+save picker or share sheet after loading authenticated file bytes.
+
+## Boundaries
+
+- Owns bounded temporary-file staging and native chooser lifecycle; receives
+ bytes already authorized by existing web service clients, never arbitrary paths.
+- `src/lib.rs` registers the Swift package; `build.rs` generates IPC permissions.
+- `ios/Sources/FileExportPlugin.swift` owns the serial staging queue and the
+ main-thread picker. All completion/cancellation paths settle once.
+- `src/lib/core/mobile/nativeFileExport.ts` (relative to `apps/web`) sends
+ 256 KiB chunks, checks cancellation, and discards staging in `finally`.
+
+## Checks
+
+- From the repo root: `nix develop .#tauri-linux --command cargo test
+ --manifest-path apps/web/tauri/Cargo.toml -p tauri-plugin-file-export`.
+- The host check covers Rust registration only. Build the iOS app on macOS and
+ exercise save, share, cancellation, background/foreground, and iPad popovers.
+- Run the `iosFiles.test.ts` and `createFileDownload.test.ts` suites in `apps/web`.
+
+## Gotchas
+
+- `available` is an optional capability probe; older installed binaries reject
+ it and retain Web Share. Do not remove that compatibility before raising the
+ native build floor through the iOS release workflow.
+- Native exports cap each file at 500 MB and four staged transfers, matching
+ Android's bounded transfer design. Successful shared files survive 24 hours
+ for asynchronous recipients; other completed/cancelled staging is removed.
+ Incomplete transfers expire after five idle minutes on the next export, so
+ WebContent reloads cannot permanently exhaust the staging slots.
+- Native changes need an App Store binary to reach devices. This additive bridge
+ leaves the existing native/web contract working, so the PR can use
+ `skip-ios-update`; shipping the picker still requires a later authorized release.
diff --git a/apps/web/tauri/file_export_plugin/CLAUDE.md b/apps/web/tauri/file_export_plugin/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/apps/web/tauri/file_export_plugin/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/apps/web/tauri/file_export_plugin/Cargo.toml b/apps/web/tauri/file_export_plugin/Cargo.toml
new file mode 100644
index 0000000000..dee305477e
--- /dev/null
+++ b/apps/web/tauri/file_export_plugin/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "tauri-plugin-file-export"
+version = "0.1.0"
+edition.workspace = true
+links = "tauri-plugin-file-export"
+
+[build-dependencies]
+tauri-plugin = { version = "2.4", features = ["build"] }
+
+[dependencies]
+tauri = { workspace = true }
diff --git a/apps/web/tauri/file_export_plugin/build.rs b/apps/web/tauri/file_export_plugin/build.rs
new file mode 100644
index 0000000000..467a9f91b9
--- /dev/null
+++ b/apps/web/tauri/file_export_plugin/build.rs
@@ -0,0 +1,11 @@
+fn main() {
+ tauri_plugin::Builder::new(&[
+ "available",
+ "beginExport",
+ "appendExport",
+ "finishExport",
+ "discardExport",
+ ])
+ .ios_path("ios")
+ .build();
+}
diff --git a/apps/web/tauri/file_export_plugin/ios/Package.swift b/apps/web/tauri/file_export_plugin/ios/Package.swift
new file mode 100644
index 0000000000..61efc170d7
--- /dev/null
+++ b/apps/web/tauri/file_export_plugin/ios/Package.swift
@@ -0,0 +1,29 @@
+// swift-tools-version:5.3
+import PackageDescription
+
+let package = Package(
+ name: "tauri-plugin-file-export",
+ platforms: [
+ .macOS(.v10_13),
+ .iOS(.v14),
+ ],
+ products: [
+ .library(
+ name: "tauri-plugin-file-export",
+ type: .static,
+ targets: ["tauri-plugin-file-export"]
+ )
+ ],
+ dependencies: [
+ .package(name: "Tauri", path: "../.tauri/tauri-api")
+ ],
+ targets: [
+ .target(
+ name: "tauri-plugin-file-export",
+ dependencies: [
+ .byName(name: "Tauri")
+ ],
+ path: "Sources"
+ )
+ ]
+)
diff --git a/apps/web/tauri/file_export_plugin/ios/Sources/FileExportPlugin.swift b/apps/web/tauri/file_export_plugin/ios/Sources/FileExportPlugin.swift
new file mode 100644
index 0000000000..c08fa3b174
--- /dev/null
+++ b/apps/web/tauri/file_export_plugin/ios/Sources/FileExportPlugin.swift
@@ -0,0 +1,249 @@
+import Foundation
+import UIKit
+import Tauri
+
+private struct BeginExport: Decodable {
+ let name: String
+ let size: Int64
+}
+
+private struct AppendExport: Decodable {
+ let token: String
+ let data: String
+}
+
+private struct ExportToken: Decodable {
+ let token: String
+}
+
+private struct FinishExport: Decodable {
+ let token: String
+ let action: String
+}
+
+private struct StagedExport {
+ let url: URL
+ let size: Int64
+ var written: Int64 = 0
+ var updatedAt = Date()
+}
+
+@available(iOS 14.0, *)
+class FileExportPlugin: Plugin, UIDocumentPickerDelegate, UIAdaptivePresentationControllerDelegate {
+ // Disk operations and transfer state stay on one queue, away from UIKit.
+ private let worker = DispatchQueue(label: "com.macro.file-export", qos: .userInitiated)
+ private let directory = FileManager.default.temporaryDirectory
+ .appendingPathComponent("macro-file-exports", isDirectory: true)
+ private var staged: [String: StagedExport] = [:]
+ private var presentingTokens: Set<String> = []
+ // The currently presented chooser is owned exclusively by the main queue.
+ private var current: (token: String, export: StagedExport, invoke: Invoke, action: String)?
+ private weak var chooser: UIViewController?
+
+ @objc public func available(_ invoke: Invoke) {
+ invoke.resolve(true)
+ }
+
+ @objc public func beginExport(_ invoke: Invoke) throws {
+ let args = try invoke.parseArgs(BeginExport.self)
+ worker.async {
+ self.cleanupStaleFiles()
+ guard args.size >= 0, args.size <= 500 * 1024 * 1024, self.staged.count < 4 else {
+ invoke.reject("File export exceeds the 500 MB or active-transfer limit")
+ return
+ }
+ let name = (args.name as NSString).lastPathComponent
+ guard !name.isEmpty, name != ".", name != "..", !name.contains("\0") else {
+ invoke.reject("Invalid filename")
+ return
+ }
+ let token = UUID().uuidString
+ let folder = self.directory.appendingPathComponent(token, isDirectory: true)
+ do {
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ let url = folder.appendingPathComponent(name)
+ try Data().write(to: url)
+ self.staged[token] = StagedExport(url: url, size: args.size)
+ invoke.resolve(["token": token])
+ } catch {
+ try? FileManager.default.removeItem(at: folder)
+ invoke.reject("Unable to prepare file: \(error.localizedDescription)")
+ }
+ }
+ }
+
+ @objc public func appendExport(_ invoke: Invoke) throws {
+ let args = try invoke.parseArgs(AppendExport.self)
+ worker.async {
+ guard var export = self.staged[args.token] else {
+ invoke.reject("Unknown file export")
+ return
+ }
+ guard args.data.utf8.count <= 350_000,
+ let data = Data(base64Encoded: args.data),
+ data.count <= 256 * 1024,
+ export.written + Int64(data.count) <= export.size else {
+ invoke.reject("Invalid file chunk")
+ return
+ }
+ do {
+ let handle = try FileHandle(forWritingTo: export.url)
+ defer { try? handle.close() }
+ try handle.seekToEnd()
+ try handle.write(contentsOf: data)
+ export.written += Int64(data.count)
+ export.updatedAt = Date()
+ self.staged[args.token] = export
+ invoke.resolve()
+ } catch {
+ invoke.reject("Unable to write file: \(error.localizedDescription)")
+ }
+ }
+ }
+
+ @objc public func finishExport(_ invoke: Invoke) throws {
+ let args = try invoke.parseArgs(FinishExport.self)
+ worker.async {
+ guard args.action == "save" || args.action == "share",
+ let export = self.staged[args.token], export.written == export.size else {
+ invoke.reject("Incomplete or invalid file export")
+ return
+ }
+ self.staged.removeValue(forKey: args.token)
+ self.presentingTokens.insert(args.token)
+ DispatchQueue.main.async {
+ guard self.current == nil,
+ let root = self.manager.viewController ?? UIApplication.shared.connectedScenes
+ .compactMap({ $0 as? UIWindowScene })
+ .filter({ $0.activationState == .foregroundActive })
+ .flatMap({ $0.windows })
+ .first(where: { $0.isKeyWindow })?.rootViewController else {
+ self.remove(export)
+ invoke.reject("A file chooser cannot be opened right now")
+ return
+ }
+ var presenter = root
+ while let presented = presenter.presentedViewController {
+ presenter = presented
+ }
+ guard presenter.viewIfLoaded?.window != nil,
+ !presenter.isBeingDismissed, !presenter.isBeingPresented else {
+ self.remove(export)
+ invoke.reject("The app is not ready to present a file chooser")
+ return
+ }
+ self.current = (args.token, export, invoke, args.action)
+ let controller: UIViewController
+ if args.action == "save" {
+ let picker = UIDocumentPickerViewController(forExporting: [export.url], asCopy: true)
+ picker.delegate = self
+ controller = picker
+ } else {
+ let sheet = UIActivityViewController(activityItems: [export.url], applicationActivities: nil)
+ sheet.completionWithItemsHandler = { [weak self] _, completed, _, error in
+ self?.complete(token: args.token, canceled: !completed, error: error)
+ }
+ if let popover = sheet.popoverPresentationController {
+ popover.sourceView = presenter.view
+ popover.sourceRect = CGRect(x: presenter.view.bounds.midX,
+ y: presenter.view.bounds.midY,
+ width: 1, height: 1)
+ popover.permittedArrowDirections = []
+ }
+ controller = sheet
+ }
+ self.chooser = controller
+ controller.presentationController?.delegate = self
+ presenter.present(controller, animated: true)
+ }
+ }
+ }
+
+ @objc public func discardExport(_ invoke: Invoke) throws {
+ let token = try invoke.parseArgs(ExportToken.self).token
+ worker.async {
+ if let export = self.staged.removeValue(forKey: token) {
+ try? FileManager.default.removeItem(at: export.url.deletingLastPathComponent())
+ }
+ DispatchQueue.main.async {
+ if self.current?.token == token {
+ self.chooser?.dismiss(animated: true)
+ self.complete(token: token, canceled: true)
+ }
+ invoke.resolve()
+ }
+ }
+ }
+
+ func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
+ guard chooser === controller, let token = current?.token else { return }
+ complete(token: token, canceled: urls.isEmpty)
+ }
+
+ func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
+ guard chooser === controller, let token = current?.token else { return }
+ complete(token: token, canceled: true)
+ }
+
+ func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
+ guard chooser === presentationController.presentedViewController,
+ let token = current?.token else { return }
+ complete(token: token, canceled: true)
+ }
+
+ private func complete(token: String, canceled: Bool, error: Error? = nil) {
+ guard let session = current, session.token == token else { return }
+ current = nil
+ chooser = nil
+ // Share extensions can read after handoff. Retain successful shares for
+ // the same 24-hour grace period as Android, then clean on the next export.
+ if session.action == "save" || canceled || error != nil {
+ remove(session.export)
+ } else {
+ worker.async { self.presentingTokens.remove(token) }
+ }
+ if let error = error {
+ session.invoke.reject("Unable to export file: \(error.localizedDescription)")
+ } else {
+ session.invoke.resolve(["canceled": canceled])
+ }
+ }
+
+ private func remove(_ export: StagedExport) {
+ worker.async {
+ self.presentingTokens.remove(export.url.deletingLastPathComponent().lastPathComponent)
+ try? FileManager.default.removeItem(at: export.url.deletingLastPathComponent())
+ }
+ }
+
+ private func cleanupStaleFiles() {
+ // WebContent can reload before JS's finally runs. Expire stalled
+ // transfers before counting slots so orphaned tokens cannot wedge exports.
+ let transferCutoff = Date().addingTimeInterval(-5 * 60)
+ for (token, export) in staged where export.updatedAt < transferCutoff {
+ staged.removeValue(forKey: token)
+ try? FileManager.default.removeItem(at: export.url.deletingLastPathComponent())
+ }
+ guard let folders = try? FileManager.default.contentsOfDirectory(
+ at: directory, includingPropertiesForKeys: [.contentModificationDateKey]
+ ) else { return }
+ let cutoff = Date().addingTimeInterval(-24 * 60 * 60)
+ for folder in folders {
+ if staged[folder.lastPathComponent] != nil || presentingTokens.contains(folder.lastPathComponent) { continue }
+ let modified = try? folder.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
+ if let modified = modified, modified < cutoff {
+ try? FileManager.default.removeItem(at: folder)
+ }
+ }
+ }
+}
+
+@_cdecl("init_plugin_file_export")
+func initPlugin() -> Plugin {
+ if #available(iOS 14.0, *) { return FileExportPlugin() }
+ return UnavailableFileExportPlugin()
+}
+
+private class UnavailableFileExportPlugin: Plugin {
+ @objc public func available(_ invoke: Invoke) { invoke.resolve(false) }
+}
diff --git a/apps/web/tauri/file_export_plugin/permissions/autogenerated/commands/appendExport.toml b/apps/web/tauri/file_export_plugin/permissions/autogenerated/commands/appendExport.toml
new file mode 100644
index 0000000000..e14f187e91
--- /dev/null
+++ b/apps/web/tauri/file_export_plugin/permissions/autogenerated/commands/appendExport.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-appendExport"
+description = "Enables the appendExport command without any pre-configured scope."
+commands.allow = ["appendExport"]
+
+[[permission]]
+identifier = "deny-appendExport"
+description = "Denies the appendExport command without any pre-configured scope."
+commands.deny = ["appendExport"]
diff --git a/apps/web/tauri/file_export_plugin/permissions/autogenerated/commands/available.toml b/apps/web/tauri/file_export_plugin/permissions/autogenerated/commands/available.toml
new file mode 100644
index 0000000000..c66874b662
--- /dev/null
+++ b/apps/web/tauri/file_export_plugin/permissions/autogenerated/commands/available.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-available"
+description = "Enables the available command without any pre-configured scope."
+commands.allow = ["available"]
+
+[[permission]]
+identifier = "deny-available"
+description = "Denies the available command without any pre-configured scope."
+commands.deny = ["available"]
diff --git a/apps/web/tauri/file_export_plugin/permissions/autogenerated/commands/beginExport.toml b/apps/web/tauri/file_export_plugin/permissions/autogenerated/commands/beginExport.toml
new file mode 100644
index 0000000000..e8912facca
--- /dev/null
+++ b/apps/web/tauri/file_export_plugin/permissions/autogenerated/commands/beginExport.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-beginExport"
+description = "Enables the beginExport command without any pre-configured scope."
+commands.allow = ["beginExport"]
+
+[[permission]]
+identifier = "deny-beginExport"
+description = "Denies the beginExport command without any pre-configured scope."
+commands.deny = ["beginExport"]
diff --git a/apps/web/tauri/file_export_plugin/permissions/autogenerated/commands/discardExport.toml b/apps/web/tauri/file_export_plugin/permissions/autogenerated/commands/discardExport.toml
new file mode 100644
index 0000000000..1712cc24e4
--- /dev/null
+++ b/apps/web/tauri/file_export_plugin/permissions/autogenerated/commands/discardExport.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-discardExport"
+description = "Enables the discardExport command without any pre-configured scope."
+commands.allow = ["discardExport"]
+
+[[permission]]
+identifier = "deny-discardExport"
+description = "Denies the discardExport command without any pre-configured scope."
+commands.deny = ["discardExport"]
diff --git a/apps/web/tauri/file_export_plugin/permissions/autogenerated/commands/finishExport.toml b/apps/web/tauri/file_export_plugin/permissions/autogenerated/commands/finishExport.toml
new file mode 100644
index 0000000000..1aac990863
--- /dev/null
+++ b/apps/web/tauri/file_export_plugin/permissions/autogenerated/commands/finishExport.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-finishExport"
+description = "Enables the finishExport command without any pre-configured scope."
+commands.allow = ["finishExport"]
+
+[[permission]]
+identifier = "deny-finishExport"
+description = "Denies the finishExport command without any pre-configured scope."
+commands.deny = ["finishExport"]
diff --git a/apps/web/tauri/file_export_plugin/permissions/autogenerated/reference.md b/apps/web/tauri/file_export_plugin/permissions/autogenerated/reference.md
new file mode 100644
index 0000000000..e4a0e2ea0b
--- /dev/null
+++ b/apps/web/tauri/file_export_plugin/permissions/autogenerated/reference.md
@@ -0,0 +1,139 @@
+## Permission Table
+
+<table>
+<tr>
+<th>Identifier</th>
+<th>Description</th>
+</tr>
+
+
+<tr>
+<td>
+
+`file-export:allow-appendExport`
+
+</td>
+<td>
+
+Enables the appendExport command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`file-export:deny-appendExport`
+
+</td>
+<td>
+
+Denies the appendExport command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`file-export:allow-available`
+
+</td>
+<td>
+
+Enables the available command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`file-export:deny-available`
+
+</td>
+<td>
+
+Denies the available command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`file-export:allow-beginExport`
+
+</td>
+<td>
+
+Enables the beginExport command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`file-export:deny-beginExport`
+
+</td>
+<td>
+
+Denies the beginExport command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`file-export:allow-discardExport`
+
+</td>
+<td>
+
+Enables the discardExport command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`file-export:deny-discardExport`
+
+</td>
+<td>
+
+Denies the discardExport command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`file-export:allow-finishExport`
+
+</td>
+<td>
+
+Enables the finishExport command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`file-export:deny-finishExport`
+
+</td>
+<td>
+
+Denies the finishExport command without any pre-configured scope.
+
+</td>
+</tr>
+</table>
diff --git a/apps/web/tauri/file_export_plugin/permissions/schemas/schema.json b/apps/web/tauri/file_export_plugin/permissions/schemas/schema.json
new file mode 100644
index 0000000000..53a7d2cb38
--- /dev/null
+++ b/apps/web/tauri/file_export_plugin/permissions/schemas/schema.json
@@ -0,0 +1,360 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "title": "PermissionFile",
+ "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
+ "type": "object",
+ "properties": {
+ "default": {
+ "description": "The default permission set for the plugin",
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DefaultPermission"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "set": {
+ "description": "A list of permissions sets defined",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionSet"
+ }
+ },
+ "permission": {
+ "description": "A list of inlined permissions",
+ "default": [],
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Permission"
+ }
+ }
+ },
+ "definitions": {
+ "DefaultPermission": {
+ "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
+ "type": "object",
+ "required": [
+ "permissions"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "PermissionSet": {
+ "description": "A set of direct permissions grouped together under a new name.",
+ "type": "object",
+ "required": [
+ "description",
+ "identifier",
+ "permissions"
+ ],
+ "properties": {
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does.",
+ "type": "string"
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionKind"
+ }
+ }
+ }
+ },
+ "Permission": {
+ "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
+ "type": "object",
+ "required": [
+ "identifier"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "commands": {
+ "description": "Allowed or denied commands when using this permission.",
+ "default": {
+ "allow": [],
+ "deny": []
+ },
+ "allOf": [
+ {
+ "$ref": "#/definitions/Commands"
+ }
+ ]
+ },
+ "scope": {
+ "description": "Allowed or denied scoped when using this permission.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Scopes"
+ }
+ ]
+ },
+ "platforms": {
+ "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Target"
+ }
+ }
+ }
+ },
+ "Commands": {
+ "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Allowed command.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "deny": {
+ "description": "Denied command, which takes priority.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "Scopes": {
+ "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Data that defines what is allowed by the scope.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ "deny": {
+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ }
+ },
+ "Value": {
+ "description": "All supported ACL values.",
+ "anyOf": [
+ {
+ "description": "Represents a null JSON value.",
+ "type": "null"
+ },
+ {
+ "description": "Represents a [`bool`].",
+ "type": "boolean"
+ },
+ {
+ "description": "Represents a valid ACL [`Number`].",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Number"
+ }
+ ]
+ },
+ {
+ "description": "Represents a [`String`].",
+ "type": "string"
+ },
+ {
+ "description": "Represents a list of other [`Value`]s.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ {
+ "description": "Represents a map of [`String`] keys to [`Value`]s.",
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ ]
+ },
+ "Number": {
+ "description": "A valid ACL number.",
+ "anyOf": [
+ {
+ "description": "Represents an [`i64`].",
+ "type": "integer",
+ "format": "int64"
+ },
+ {
+ "description": "Represents a [`f64`].",
+ "type": "number",
+ "format": "double"
+ }
+ ]
+ },
+ "Target": {
+ "description": "Platform target.",
+ "oneOf": [
+ {
+ "description": "MacOS.",
+ "type": "string",
+ "enum": [
+ "macOS"
+ ]
+ },
+ {
+ "description": "Windows.",
+ "type": "string",
+ "enum": [
+ "windows"
+ ]
+ },
+ {
+ "description": "Linux.",
+ "type": "string",
+ "enum": [
+ "linux"
+ ]
+ },
+ {
+ "description": "Android.",
+ "type": "string",
+ "enum": [
+ "android"
+ ]
+ },
+ {
+ "description": "iOS.",
+ "type": "string",
+ "enum": [
+ "iOS"
+ ]
+ }
+ ]
+ },
+ "PermissionKind": {
+ "type": "string",
+ "oneOf": [
+ {
+ "description": "Enables the appendExport command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-appendExport",
+ "markdownDescription": "Enables the appendExport command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the appendExport command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-appendExport",
+ "markdownDescription": "Denies the appendExport command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the available command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-available",
+ "markdownDescription": "Enables the available command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the available command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-available",
+ "markdownDescription": "Denies the available command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the beginExport command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-beginExport",
+ "markdownDescription": "Enables the beginExport command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the beginExport command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-beginExport",
+ "markdownDescription": "Denies the beginExport command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the discardExport command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-discardExport",
+ "markdownDescription": "Enables the discardExport command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the discardExport command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-discardExport",
+ "markdownDescription": "Denies the discardExport command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the finishExport command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-finishExport",
+ "markdownDescription": "Enables the finishExport command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the finishExport command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-finishExport",
+ "markdownDescription": "Denies the finishExport command without any pre-configured scope."
+ }
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/apps/web/tauri/file_export_plugin/src/lib.rs b/apps/web/tauri/file_export_plugin/src/lib.rs
new file mode 100644
index 0000000000..b7ab9aa93e
--- /dev/null
+++ b/apps/web/tauri/file_export_plugin/src/lib.rs
@@ -0,0 +1,19 @@
+//! Native iOS save and share adapters for already-authorized file bytes.
+#![deny(missing_docs)]
+
+use tauri::Runtime;
+use tauri::plugin::{Builder, TauriPlugin};
+
+#[cfg(target_os = "ios")]
+tauri::ios_plugin_binding!(init_plugin_file_export);
+
+/// Registers the iOS file export bridge.
+pub fn init<R: Runtime>() -> TauriPlugin<R> {
+ let builder = Builder::new("file-export");
+ #[cfg(target_os = "ios")]
+ let builder = builder.setup(|_app, api| {
+ api.register_ios_plugin(init_plugin_file_export)?;
+ Ok(())
+ });
+ builder.build()
+}
diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.toml
index 2873e7d178..52d5a94f9e 100644
--- a/apps/web/tauri/src-tauri/Cargo.toml
+++ b/apps/web/tauri/src-tauri/Cargo.toml
@@ -143,6 +143,7 @@ tauri-plugin-virtual-keyboard = { git = "https://github.com/voxelbee/tauri-plugi
tracing-oslog = { version = "0.3" }
tauri-plugin-call-kit = { path = "../callkit_plugin" }
tauri-plugin-edit-menu = { path = "../edit_menu_plugin" }
+tauri-plugin-file-export = { path = "../file_export_plugin" }
tauri-plugin-input-accessory = { path = "../input_accessory_plugin" }
tauri-plugin-network-status = { path = "../network_status_plugin" }
tauri-plugin-pasteboard = { path = "../pasteboard_plugin" }
diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.md
index 37c635172e..4c39c9aba1 100644
--- a/apps/web/tauri/src-tauri/README.md
+++ b/apps/web/tauri/src-tauri/README.md
@@ -5,6 +5,15 @@ single Vite build that runs identically for web, desktop, iOS, and Android — t
platform is detected at runtime via `getPlatform()` rather than baked into the
bundle.
+## File saving and sharing
+
+The optional `file_export_plugin` registers iOS save/share commands. The web
+client stages original bytes in bounded chunks, then UIKit opens the system
+save picker or share sheet without an intermediate Macro dialog. Android uses
+its existing `android_mobile_plugin` export commands. Older iOS installations
+retain Web Share until the next native release; see
+[the bridge guide](../file_export_plugin/AGENTS.md).
+
## Desktop app icons
Only desktop icons carry the ALPHA badge; iOS and Android icons are unbadged.
diff --git a/apps/web/tauri/src-tauri/capabilities/ios.json b/apps/web/tauri/src-tauri/capabilities/ios.json
index 262178a42f..b0f4044cfc 100644
--- a/apps/web/tauri/src-tauri/capabilities/ios.json
+++ b/apps/web/tauri/src-tauri/capabilities/ios.json
@@ -8,6 +8,12 @@
],
"permissions": [
"auth:allow-authenticate",
+ "file-export:allow-available",
+ "file-export:allow-beginExport",
+ "file-export:allow-appendExport",
+ "file-export:allow-finishExport",
+ "file-export:allow-discardExport",
+
"edit-menu:allow-set-native-menu-suppressed",
"pasteboard:allow-read-pasteboard-text",
"network-status:allow-watch-status",
diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rs
index 9f11f7c375..e0e897ab98 100644
--- a/apps/web/tauri/src-tauri/src/lib.rs
+++ b/apps/web/tauri/src-tauri/src/lib.rs
@@ -254,6 +254,7 @@ pub fn run_with(builder: tauri::Builder<AppRuntime>) {
.plugin(tauri_plugin_auth::init())
.plugin(tauri_plugin_virtual_keyboard::init())
.plugin(tauri_plugin_edit_menu::init())
+ .plugin(tauri_plugin_file_export::init())
.plugin(tauri_plugin_input_accessory::init())
.plugin(tauri_plugin_network_status::init())
.plugin(tauri_plugin_pasteboard::init())
diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.md
index b19c5f6141..3c22c8b6a0 100644
--- a/docs/agent-guide/channels.md
+++ b/docs/agent-guide/channels.md
@@ -1335,3 +1335,11 @@ Markdown options before Query and Database. Typing `/query` filters to the Query
action; `/database` creates a new database and inserts its editable card.
When Databases is enabled, type `/query` in a channel message or thread reply and choose **Query** to insert a live question. Ask with Enter or the Ask button, then accept the answer before sending the message. Enter in the question box belongs to the question and must not send the channel draft. Recipients can read the live answer subject to their database access. Database @ mentions in message composers remain compact; **Expand** turns one into an editable database card.
+
+## Downloading channel videos
+
+Video messages show **Download** below the player on desktop and touch devices. The expanded viewer has the same action. These retrieve the
+original bytes and filename from static-file metadata; they do not record or
+transcode playback. If the metadata is unavailable, the fallback extension comes
+from the response MIME type. See [Downloading files](files.md#downloading-files)
+for progress, cancellation, retries, and mobile save/share verification.
diff --git a/docs/agent-guide/files.md b/docs/agent-guide/files.md
index e98b5c2c69..0786289e69 100644
--- a/docs/agent-guide/files.md
+++ b/docs/agent-guide/files.md
@@ -156,3 +156,38 @@ switch via the header pills; on narrow desktop layouts the header keeps a plain
title and navigation goes through the hamburger overlay. Location, search,
filters, expanded folders, list focus, and scroll position are restored when
returning from an opened file.
+
+## Downloading files
+
+Open a video, image, code file, canvas, or other uploaded file in Drive. Its
+header exposes **Download** on desktop, phone, and tablet. The file menu uses
+the same action. Video routes also expose it in their header; channel videos
+expose it below the player and in the expanded viewer. Playing, downloading,
+and sharing a video are separate actions.
+
+- Click Download once. The control shows preparation progress when the server
+ provides a length, disables repeat clicks, and offers Cancel. Browser users
+ proceed directly to browser downloads. Android and iOS binaries with the
+ file-export bridge proceed directly to the system save picker.
+- **Download started** means the browser accepted the file; check its downloads
+ UI for the location and final completion. **File saved** is reserved for a
+ completed native save. Retry download remains available after a fetch failure.
+- **Share**, where supported, opens the system share sheet. If a browser's
+ user gesture expires during loading, a ready notice asks for another tap on
+ Share; that tap uses the prepared bytes without another network request.
+ No Macro download dialog appears. Cancelling a chooser keeps the file ready
+ for another attempt and does not report success.
+- Installed iOS binaries without the optional file-export bridge use the system
+ share sheet for saving too. After a slow preparation, tap **Save file** to open
+ it, then choose Save to Files or another available system action. The dedicated
+ save picker becomes available when the new native binary ships.
+- Change files or close the viewer during preparation: the old request must stop
+ and must not save a late response. Close the expanded viewer with Escape and
+ confirm focus returns to its opener.
+
+Verification: use an existing video in a channel and Drive. Check both message
+and expanded-viewer download actions; compare downloaded bytes, filename, and
+extension with the original. Repeat at 390px with touch enabled and at tablet
+width. Exercise a failed request, retry, cancellation, and changing selection.
+Native save/share dialogs require physical iOS/Android verification in addition
+to browser emulation.