Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(iOS): native iOS media attachments with staged uploads (#3441)
Peter Chinman4a7a86683a90
diff --git a/js/app/packages/app/component/ios-share-sheet/IosShareSheet.tsx b/js/app/packages/app/component/ios-share-sheet/IosShareSheet.tsxindex 3c924adada..7bddbf690a 100644--- a/js/app/packages/app/component/ios-share-sheet/IosShareSheet.tsx+++ b/js/app/packages/app/component/ios-share-sheet/IosShareSheet.tsx@@ -464,7 +464,7 @@ function IosShareSheetComposer(props: {<Input.Footer><Input.Actions><Input.Actions.Left>- <Input.AttachFilesAction />+ <Input.AttachNativeMediaAction /><Input.ToggleFormatAction /></Input.Actions.Left></Input.Actions>diff --git a/js/app/packages/block-channel/component/Compose.tsx b/js/app/packages/block-channel/component/Compose.tsxindex db6f6038db..30f4fa3772 100644--- a/js/app/packages/block-channel/component/Compose.tsx+++ b/js/app/packages/block-channel/component/Compose.tsx@@ -29,6 +29,7 @@ import {} from '@core/user';import { useSendMessageToPeople } from '@core/util/channels';import { getDestinationFromOptions } from '@core/util/destination';+import { isPlatform } from '@core/util/platform';import {chatRuleset,@@ -312,7 +313,12 @@ export function ChannelCompose() {<Input.Footer><Input.Actions><Input.Actions.Left>- <Input.AttachFilesAction />+ <Show+ when={!isPlatform('ios')}+ fallback={<Input.AttachNativeMediaAction />}+ >+ <Input.AttachFilesAction />+ </Show><Input.ToggleFormatAction /></Input.Actions.Left><Input.Actions.Right>diff --git a/js/app/packages/channel/Channel/Channel.tsx b/js/app/packages/channel/Channel/Channel.tsxindex 806527e2cd..06ebe6230d 100644--- a/js/app/packages/channel/Channel/Channel.tsx+++ b/js/app/packages/channel/Channel/Channel.tsx@@ -3,7 +3,7 @@ import { useSplitLayout } from '@app/component/split-layout/layout';import { createActivityTracker } from '@channel/activity-tracker';import { DebugSuspense } from '@channel/DebugSuspense';import type { ChannelInputProps } from '@channel/Input/ChannelInput';-import { buildPostMessageRequest } from '@channel/Input/message-payload';+import { buildPostMessageSendPayload } from '@channel/Input/message-payload';import {makeAttachmentTrackerPersistenceKey,makeInputValuePersistenceKey,@@ -361,16 +361,17 @@ export function Channel(props: ChannelProps) {const onSend: ChannelInputProps['onSend'] = (snapshot) => {const senderId = userId();if (!senderId) return;+ const payload = buildPostMessageSendPayload({+ snapshot,+ participantIds: participants.ids(),+ });sendMessageMutation.mutate({channelID: props.channelId,senderId,optimisticId: crypto.randomUUID(),- message: buildPostMessageRequest({- snapshot,- participantIds: participants.ids(),- }),+ ...payload,},{onError: () => {diff --git a/js/app/packages/channel/Input/ChannelInput.tsx b/js/app/packages/channel/Input/ChannelInput.tsxindex 3dc0fac6cb..ef371f39a5 100644--- a/js/app/packages/channel/Input/ChannelInput.tsx+++ b/js/app/packages/channel/Input/ChannelInput.tsx@@ -2,6 +2,7 @@ import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownSimport { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';import { isMobile } from '@core/mobile/isMobile';import type { IUser } from '@core/user/types';+import { isPlatform } from '@core/util/platform';import {chatRuleset,handleFileFolderDrop,@@ -47,7 +48,7 @@ export type ChannelInputProps = InputCallbacks & {autofocus?: boolean;};-function DefaultActions(props: { input: InputData }) {+function WebDefaultActions(props: { input: InputData }) {return (<Input.Actions><Input.Actions.Left>@@ -64,6 +65,34 @@ function DefaultActions(props: { input: InputData }) {);}+function IosDefaultActions(props: { input: InputData }) {+ return (+ <Input.Actions>+ <Input.Actions.Left>+ <Input.AttachNativeMediaAction />+ <Input.ToggleFormatAction />+ <Show when={isReplyInput(props.input)}>+ <Input.CloseReplyAction />+ </Show>+ </Input.Actions.Left>+ <Input.Actions.Right>+ <Input.SendAction />+ </Input.Actions.Right>+ </Input.Actions>+ );+}++function DefaultActions(props: { input: InputData }) {+ return (+ <Show+ when={isPlatform('ios')}+ fallback={<WebDefaultActions input={props.input} />}+ >+ <IosDefaultActions input={props.input} />+ </Show>+ );+}+export function ChannelInput(props: ChannelInputProps) {const [scrollContainer, setScrollContainer] = createSignal<HTMLElement>();const mentionsTracker = createMentionsTracker();diff --git a/js/app/packages/channel/Input/Input.ts b/js/app/packages/channel/Input/Input.tsindex 2483a80366..77e32f0b82 100644--- a/js/app/packages/channel/Input/Input.ts+++ b/js/app/packages/channel/Input/Input.ts@@ -8,6 +8,7 @@ import { Footer } from './Footer';import { FormatRibbon } from './FormatRibbon';import {AttachFilesAction,+ AttachNativeMediaAction,CloseReplyAction,DiscardDraftAction,ToggleFormatAction,@@ -28,6 +29,7 @@ export const Input = {Footer,Actions,AttachFilesAction,+ AttachNativeMediaAction,ToggleFormatAction,CloseReplyAction,DiscardDraftAction,diff --git a/js/app/packages/channel/Input/InputActions.tsx b/js/app/packages/channel/Input/InputActions.tsxindex fb2b55c8fa..f326126c7e 100644--- a/js/app/packages/channel/Input/InputActions.tsx+++ b/js/app/packages/channel/Input/InputActions.tsx@@ -1,5 +1,7 @@+import { pickNativePhotoLibraryMedia } from '@core/mobile/nativePhotoLibrary';import FormatIcon from '@phosphor/text-aa.svg';import TrashIcon from '@phosphor/trash.svg';+import ImageIcon from '@phosphor-icons/core/regular/image.svg?component-solid';import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';import type { JSX } from 'solid-js';import { InputActionButton } from './ActionButton';@@ -42,6 +44,26 @@ export function AttachFilesAction() {);}+export function AttachNativeMediaAction() {+ const commands = useInputCommands();++ const onAttachMedia = async () => {+ const files = await pickNativePhotoLibraryMedia();+ if (files.length > 0) {+ await commands.attachFiles(files);+ }+ };++ return (+ <InputActionButton+ label="Attach photos or videos"+ onClick={() => void onAttachMedia()}+ >+ <ImageIcon />+ </InputActionButton>+ );+}+export function ToggleFormatAction() {const input = useInput();const commands = useInputCommands();diff --git a/js/app/packages/channel/Input/PrimaryActions.tsx b/js/app/packages/channel/Input/PrimaryActions.tsxdeleted file mode 100644index ae4c82c9d2..0000000000--- a/js/app/packages/channel/Input/PrimaryActions.tsx+++ /dev/null@@ -1,98 +0,0 @@-import FormatIcon from '@phosphor/text-aa.svg';-import TrashIcon from '@phosphor/trash.svg';-import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';-import { Button, cn } from '@ui';-import { children, type JSX, Show, splitProps } from 'solid-js';-import { CHANNEL_FILE_PICKER_ACCEPT } from './accepted-file-types';-import { useInput, useInputCommands } from './context';-import { isReplyInput } from './types';--export function InputActionButton(props: {- label: string;- onClick?: (event: MouseEvent) => void;- active?: boolean;- children: JSX.Element;-}) {- return (- <Button- title={props.label}- aria-label={props.label}- label={props.label}- onClick={(event) => props.onClick?.(event)}- classList={{ 'bg-active': props.active }}- >- {props.children}- </Button>- );-}--export function PrimaryActions(props: JSX.HTMLAttributes<HTMLDivElement>) {- const input = useInput();- const commands = useInputCommands();- const [local, rest] = splitProps(props, ['class', 'children']);- const resolved = children(() => local.children);- let fileInputRef: HTMLInputElement | undefined;-- const openAttachPicker = () => {- fileInputRef?.click();- };-- const onAttachFiles: JSX.EventHandlerUnion<HTMLInputElement, Event> = (- event- ) => {- const files = Array.from(event.currentTarget.files ?? []);- event.currentTarget.value = '';- if (files.length === 0) return;- void commands.attachFiles(files);- };-- return (- <div- class={cn('flex flex-row items-center gap-2', local.class)}- data-input-primary-actions- {...rest}- >- <input- ref={(element) => {- fileInputRef = element;- }}- type="file"- class="hidden"- multiple- accept={CHANNEL_FILE_PICKER_ACCEPT}- onChange={onAttachFiles}- data-input-attach-file-picker- />- <Show- when={resolved()}- fallback={- <>- <InputActionButton- label="Attach files"- onClick={() => openAttachPicker()}- >- <PaperclipIcon class="size-5" />- </InputActionButton>- <InputActionButton- label="Format"- active={input().showFormatRibbon}- onClick={() => commands.toggleFormatRibbon()}- >- <FormatIcon class="size-5" />- </InputActionButton>- <Show when={isReplyInput(input())}>- <InputActionButton- label="Delete reply"- onClick={() => commands.close()}- >- <TrashIcon class="size-5" />- </InputActionButton>- </Show>- </>- }- >- {(children) => children()}- </Show>- </div>- );-}diff --git a/js/app/packages/channel/Input/index.ts b/js/app/packages/channel/Input/index.tsindex bf2d369b1a..c296dbcc34 100644--- a/js/app/packages/channel/Input/index.ts+++ b/js/app/packages/channel/Input/index.ts@@ -16,15 +16,21 @@ export { FormatRibbon } from './FormatRibbon';export { Input } from './Input';export {AttachFilesAction,+ AttachNativeMediaAction,CloseReplyAction,DiscardDraftAction,ToggleFormatAction,} from './InputActions';export { Layout } from './Layout';export { createMentionsTracker } from './mentions-tracker';+export type {+ OptimisticPostMessageAttachment,+ PostMessageSendPayload,+} from './message-payload';export {attachmentEntityType,buildPostMessageRequest,+ buildPostMessageSendPayload,} from './message-payload';export { Root } from './Root';export { SendAction } from './SendAction';diff --git a/js/app/packages/channel/Input/message-payload.ts b/js/app/packages/channel/Input/message-payload.tsindex 6e6d2c66fb..4d17cff9ff 100644--- a/js/app/packages/channel/Input/message-payload.ts+++ b/js/app/packages/channel/Input/message-payload.ts@@ -1,6 +1,7 @@import type { ItemMention } from '@core/component/LexicalMarkdown/plugins';import { STATIC_IMAGE, STATIC_VIDEO } from '@core/store/cacheChannelInput';import type { PostMessageRequest } from '@service-comms/generated/models';+import type { NewAttachment } from '@service-comms/generated/models/newAttachment';import type { SimpleMention } from '@service-comms/generated/models/simpleMention';import { match } from 'ts-pattern';import type { InputAttachmentData, InputSnapshot } from './types';@@ -75,20 +76,47 @@ type BuildPostMessageRequestOptions = {participantIds?: string[];};-export function buildPostMessageRequest(+export type OptimisticPostMessageAttachment = {+ attachment: NewAttachment;+ previewSrc?: string;+};++export type PostMessageSendPayload = {+ message: PostMessageRequest;+ optimisticAttachments: OptimisticPostMessageAttachment[];+};++export function buildPostMessageSendPayload(options: BuildPostMessageRequestOptions-): PostMessageRequest {+): PostMessageSendPayload {const { snapshot, threadId, participantIds } = options;-- return {- content: snapshot.value,- thread_id: threadId,- mentions: expandMentions(snapshot.mentions, participantIds ?? []),- attachments: snapshot.attachments.map((attachment) => ({+ const optimisticAttachments = snapshot.attachments.map((attachment) => {+ const postAttachment = {entity_id: attachment.id,entity_type: attachmentEntityType(attachment.kind),width: attachment.width ?? null,height: attachment.height ?? null,- })),+ };++ return {+ attachment: postAttachment,+ previewSrc: attachment.previewSrc,+ };+ });++ return {+ message: {+ content: snapshot.value,+ thread_id: threadId,+ mentions: expandMentions(snapshot.mentions, participantIds ?? []),+ attachments: optimisticAttachments.map((item) => item.attachment),+ },+ optimisticAttachments,};}++export function buildPostMessageRequest(+ options: BuildPostMessageRequestOptions+): PostMessageRequest {+ return buildPostMessageSendPayload(options).message;+}diff --git a/js/app/packages/channel/Input/tests/upload-attachments.test.ts b/js/app/packages/channel/Input/tests/upload-attachments.test.tsindex d0253e0978..b007ea91cb 100644--- a/js/app/packages/channel/Input/tests/upload-attachments.test.ts+++ b/js/app/packages/channel/Input/tests/upload-attachments.test.ts@@ -50,19 +50,38 @@ describe('uploadInputAttachments', () => {).toBe('document');});- it('replaces pending attachment with uploaded attachment', async () => {+ it('keeps the attachment pending until the upload promise resolves', async () => {const tracker = createInputAttachmentTracker();const file = new File(['abc'], 'image.png', { type: 'image/png' });+ let resolveUpload:+ | ((result: { failed: false; destination: 'static'; id: string }) => void)+ | undefined;- await uploadInputAttachments({+ const uploadPromise = uploadInputAttachments({files: [file],tracker,- uploadFile: async () => ({- failed: false,- destination: 'static',- id: 'uploaded-image-1',- }),+ uploadFile: () =>+ new Promise((resolve) => {+ resolveUpload = resolve;+ }),+ });++ await Promise.resolve();+ expect(tracker.attachments()).toEqual([+ {+ id: expect.any(String),+ name: 'image.png',+ kind: 'image',+ pending: true,+ },+ ]);++ resolveUpload?.({+ failed: false,+ destination: 'static',+ id: 'uploaded-image-1',});+ await uploadPromise;expect(tracker.attachments()).toEqual([{diff --git a/js/app/packages/channel/Input/upload-attachments.ts b/js/app/packages/channel/Input/upload-attachments.tsindex fc3d4c5425..21c68a9533 100644--- a/js/app/packages/channel/Input/upload-attachments.ts+++ b/js/app/packages/channel/Input/upload-attachments.ts@@ -1,6 +1,12 @@import { toast } from '@core/component/Toast/Toast';import { getImageDimensions, getVideoDimensions } from '@core/util/media';-import type { InputAttachmentTracker } from './types';+import {+ createUploadFile,+ createUploadFilePreviewUrl,+ getUploadFilePreviewSource,+ type UploadFile,+} from '@core/util/uploadFile';+import type { InputAttachmentData, InputAttachmentTracker } from './types';import {buildUploadedAttachment,getAttachmentKindFromFile,@@ -10,21 +16,55 @@ import {export { getAttachmentKindFromFile } from './utils/file-helpers';+function createAttachmentPreviewSrc(+ file: UploadFile,+ kind: 'image' | 'video' | 'document'+): string | undefined {+ if (kind === 'document') return undefined;++ try {+ return createUploadFilePreviewUrl(file);+ } catch {+ return undefined;+ }+}++function replacePendingAttachment(+ tracker: InputAttachmentTracker,+ pendingId: string,+ uploaded: InputAttachmentData+) {+ const current = tracker.attachments();+ const pendingIndex = current.findIndex(+ (attachment) => attachment.id === pendingId+ );++ if (pendingIndex === -1) {+ tracker.addAttachment(uploaded);+ return;+ }++ const next = [...current];+ next[pendingIndex] = uploaded;+ tracker.setAttachments(next);+}+/*** Resolve media dimensions from a File for image/video attachments.* Returns undefined for documents or on failure.*/async function resolveMediaDimensions(- file: File,+ file: UploadFile,kind: 'image' | 'video' | 'document'): Promise<{ width: number; height: number } | undefined> {if (kind === 'document') return undefined;try {+ const source = getUploadFilePreviewSource(file);const dims =kind === 'image'- ? await getImageDimensions(file)- : await getVideoDimensions(file);- if (dims.width > 0 && dims.height > 0) return dims;+ ? await getImageDimensions(source)+ : await getVideoDimensions(source);+ if (dims && dims.width > 0 && dims.height > 0) return dims;} catch {// Dimension extraction is best-effort}@@ -37,8 +77,10 @@ export async function uploadInputAttachments(options: {uploadFile: (file: File) => Promise<UploadResult>;}): Promise<void> {for (const file of options.files) {+ const uploadSource = createUploadFile(file);const pendingId = crypto.randomUUID();- const pendingKind = getAttachmentKindFromFile(file);+ const pendingKind = getAttachmentKindFromFile(uploadSource);+ const previewSrc = createAttachmentPreviewSrc(uploadSource, pendingKind);options.tracker.addAttachment({id: pendingId,@@ -49,13 +91,11 @@ export async function uploadInputAttachments(options: {? iconTypeFromFilename(file.name): undefined,pending: true,+ previewSrc,});try {- const [result, dims] = await Promise.all([- options.uploadFile(file),- resolveMediaDimensions(file, pendingKind),- ]);+ const result = await options.uploadFile(file);if (result.failed) {options.tracker.removeAttachment(pendingId);@@ -70,13 +110,24 @@ export async function uploadInputAttachments(options: {continue;}- if (dims) {- uploaded.width = dims.width;- uploaded.height = dims.height;+ if (previewSrc && uploaded.kind !== 'document') {+ uploaded.previewSrc = previewSrc;}- options.tracker.removeAttachment(pendingId);- options.tracker.addAttachment(uploaded);+ replacePendingAttachment(options.tracker, pendingId, uploaded);++ void resolveMediaDimensions(uploadSource, pendingKind).then((dims) => {+ if (!dims) return;+ options.tracker.setAttachments(+ options.tracker+ .attachments()+ .map((attachment) =>+ attachment.id === uploaded.id+ ? { ...attachment, width: dims.width, height: dims.height }+ : attachment+ )+ );+ });} catch (error) {console.error('failed to upload attachment', error);options.tracker.removeAttachment(pendingId);diff --git a/js/app/packages/channel/Input/utils/file-helpers.ts b/js/app/packages/channel/Input/utils/file-helpers.tsindex d59d33626f..53ffcdf6b1 100644--- a/js/app/packages/channel/Input/utils/file-helpers.ts+++ b/js/app/packages/channel/Input/utils/file-helpers.ts@@ -53,11 +53,14 @@ export function iconTypeFromFilename(filename: string) {return fileTypeToBlockName(fileExtension(filename), true);}-export function getAttachmentKindFromFile(- file: Pick<File, 'name' | 'type'>-): InputAttachmentKind {- if (file.type.startsWith('image/')) return 'image';- if (file.type.startsWith('video/')) return 'video';+export function getAttachmentKindFromFile(file: {+ name: string;+ mimeType?: string;+ type?: string;+}): InputAttachmentKind {+ const mimeType = file.mimeType ?? file.type ?? '';+ if (mimeType.startsWith('image/')) return 'image';+ if (mimeType.startsWith('video/')) return 'video';const extension = fileExtension(file.name);if (!extension) return 'document';@@ -68,7 +71,7 @@ export function getAttachmentKindFromFile(}export function buildUploadedAttachment(- file: File,+ file: { name: string },pendingKind: InputAttachmentKind,result: UploadSuccess): InputAttachmentData | undefined {diff --git a/js/app/packages/channel/Media/MediaGrid.tsx b/js/app/packages/channel/Media/MediaGrid.tsxindex 77cdcfa9c1..665e9de9dc 100644--- a/js/app/packages/channel/Media/MediaGrid.tsx+++ b/js/app/packages/channel/Media/MediaGrid.tsx@@ -34,6 +34,7 @@ function MessageImageTile(props: {><MediaImage.Imagesrc={props.item.src}+ previewSrc={props.item.previewSrc}class="max-h-[80vh] w-full select-none rounded-2xl border border-edge object-contain"width={dimensions()?.width ?? props.item.width ?? undefined}height={dimensions()?.height ?? props.item.height ?? undefined}@@ -58,6 +59,7 @@ function AttachmentImageTile(props: { item: MediaItem; onOpen?: () => void }) {<MediaImage.Root><MediaImage.Imagesrc={props.item.src}+ previewSrc={props.item.previewSrc}class={cn('size-25.5 select-none rounded-2xl border border-edge object-cover',props.onOpen && 'hover:opacity-80'diff --git a/js/app/packages/channel/Media/media-items.ts b/js/app/packages/channel/Media/media-items.tsindex e429460f74..1e1d6d798c 100644--- a/js/app/packages/channel/Media/media-items.ts+++ b/js/app/packages/channel/Media/media-items.ts@@ -14,6 +14,8 @@ export type MediaItem = {src: string;/** Full-resolution original — used when expanding */fullSrc: string;+ /** Local preview for optimistic media we just uploaded/sent. */+ previewSrc?: string;kind: 'image' | 'video';width?: number | null;height?: number | null;@@ -23,6 +25,7 @@ type AttachmentWithMediaFields = {id: string;entity_id: string;entity_type: string;+ previewSrc?: string;width?: number | null;height?: number | null;};@@ -71,6 +74,7 @@ function mapAttachmentToMediaItem(? staticFileSizedEndpoint(attachment.entity_id, 'medium'): fullSrc,fullSrc,+ previewSrc: attachment.previewSrc,kind,width: attachment.width ?? undefined,height: attachment.height ?? undefined,@@ -81,30 +85,41 @@ function mapAttachmentsToMediaItems<T extends AttachmentWithMediaFields>(attachments: T[],previousItems: MediaItem[] = []): MediaItem[] {- const previousByAttachmentId = new Map(- attachments.map((attachment, index) => [- attachment.id,- previousItems[index],- ])+ const previousByMediaId = new Map(+ previousItems.map((item) => [item.id, item]));- return attachments.flatMap((attachment) => {+ return attachments.flatMap((attachment, index) => {const item = mapAttachmentToMediaItem(attachment);if (!item) return [];- const previousItem = previousByAttachmentId.get(attachment.id);+ const previousItem =+ previousItems[index]?.id === item.id+ ? previousItems[index]+ : previousByMediaId.get(item.id);+ const nextItem =+ previousItem && previousItem.id === item.id+ ? {+ ...item,+ previewSrc: item.previewSrc ?? previousItem.previewSrc,+ width: item.width ?? previousItem.width,+ height: item.height ?? previousItem.height,+ }+ : item;+if (previousItem &&- previousItem.src === item.src &&- previousItem.fullSrc === item.fullSrc &&- previousItem.kind === item.kind &&- previousItem.width === item.width &&- previousItem.height === item.height+ previousItem.src === nextItem.src &&+ previousItem.fullSrc === nextItem.fullSrc &&+ previousItem.previewSrc === nextItem.previewSrc &&+ previousItem.kind === nextItem.kind &&+ previousItem.width === nextItem.width &&+ previousItem.height === nextItem.height) {return [previousItem];}- return [item];+ return [nextItem];});}diff --git a/js/app/packages/channel/Media/tests/media-image.test.tsx b/js/app/packages/channel/Media/tests/media-image.test.tsxnew file mode 100644index 0000000000..83fbf5b8c0--- /dev/null+++ b/js/app/packages/channel/Media/tests/media-image.test.tsx@@ -0,0 +1,43 @@+/**+ * @vitest-environment jsdom+ */++import { render, screen } from '@solidjs/testing-library';+import { describe, expect, it, vi } from 'vitest';+import { MediaImage } from '../MediaImage';++vi.mock(+ '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid',+ () => ({+ default: () => <span data-testid="spinner-icon" />,+ })+);++describe('MediaImage', () => {+ it('keeps rendering a local preview when the primary source fails', () => {+ render(() => (+ <MediaImage.Image+ src="https://static.example/file/image-id?size=1080"+ previewSrc="blob:local-preview"+ fallback={<MediaImage.Fallback square />}+ />+ ));++ const images = screen.getAllByAltText('preview') as HTMLImageElement[];+ expect(images.map((image) => image.getAttribute('src'))).toEqual([+ 'blob:local-preview',+ 'https://static.example/file/image-id?size=1080',+ ]);++ images[1]?.dispatchEvent(new Event('error'));++ expect(+ (screen.getAllByAltText('preview') as HTMLImageElement[]).map((image) =>+ image.getAttribute('src')+ )+ ).toEqual([+ 'blob:local-preview',+ 'https://static.example/file/image-id?size=1080',+ ]);+ });+});diff --git a/js/app/packages/channel/Media/tests/media-items.test.ts b/js/app/packages/channel/Media/tests/media-items.test.tsnew file mode 100644index 0000000000..e43e4bbee4--- /dev/null+++ b/js/app/packages/channel/Media/tests/media-items.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest';+import { mapMediaItems } from '../media-items';++describe('mapMediaItems', () => {+ it('preserves local preview metadata across optimistic attachment reconciliation', () => {+ const previousItems = mapMediaItems([+ {+ id: 'optimistic-attachment-id',+ entity_id: 'static-file-1',+ entity_type: 'static/image',+ created_at: '2026-05-22T00:00:00.000Z',+ previewSrc: 'blob:local-preview',+ width: 300,+ height: 200,+ },+ ]);++ expect(+ mapMediaItems(+ [+ {+ id: 'server-attachment-id',+ entity_id: 'static-file-1',+ entity_type: 'static/image',+ created_at: '2026-05-22T00:00:01.000Z',+ },+ ],+ previousItems+ )+ ).toEqual([+ expect.objectContaining({+ id: 'static-file-1',+ previewSrc: 'blob:local-preview',+ width: 300,+ height: 200,+ }),+ ]);+ });+});diff --git a/js/app/packages/channel/Thread/ThreadReplyInput.tsx b/js/app/packages/channel/Thread/ThreadReplyInput.tsxindex e9e552095f..d63ed4807b 100644--- a/js/app/packages/channel/Thread/ThreadReplyInput.tsx+++ b/js/app/packages/channel/Thread/ThreadReplyInput.tsx@@ -10,7 +10,7 @@ import { type Accessor, createSignal, onCleanup, type Setter } from 'solid-js';import { createEntityDropZone } from '../Channel/create-entity-drop-zone';import type { InputHandle, InputSnapshot } from '../Input';import { ChannelInput, createInputAttachmentTracker } from '../Input';-import { buildPostMessageRequest } from '../Input/message-payload';+import { buildPostMessageSendPayload } from '../Input/message-payload';import { hasSendableInputContent } from '../Input/utils/sendable-content';import { ThreadReplyInputConnector } from './ThreadReplyInputConnector';import { replyInputOffsetX } from './utils/thread-rail-geometry';@@ -101,17 +101,18 @@ export function ThreadReplyInput(props: ThreadReplyInputProps) {onSend={(snapshot) => {const senderId = userId();if (!senderId) return;+ const payload = buildPostMessageSendPayload({+ snapshot,+ threadId: props.messageId,+ participantIds: participants.ids(),+ });sendMessageMutation.mutate({channelID: props.channelId,senderId,optimisticId: crypto.randomUUID(),- message: buildPostMessageRequest({- snapshot,- threadId: props.messageId,- participantIds: participants.ids(),- }),+ ...payload,},{onSuccess: () => {diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/file-paste/filePastePlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/file-paste/filePastePlugin.tsindex db63b628c9..2df1557718 100644--- a/js/app/packages/core/component/LexicalMarkdown/plugins/file-paste/filePastePlugin.ts+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/file-paste/filePastePlugin.ts@@ -1,3 +1,7 @@+import {+ recoverMobileClipboardImageEntries,+ shouldUseMobileClipboardImageRecovery,+} from '@core/mobile/mobileClipboardImageRecovery';import { extractFileSystemEntries } from '@core/util/dataTransfer';import { mergeRegister } from '@lexical/utils';import {@@ -29,6 +33,21 @@ function registerFilePastePlugin(const { fileEntries, directoryEntries } =extractFileSystemEntries(data);+ if (+ directoryEntries.length === 0 &&+ shouldUseMobileClipboardImageRecovery(data)+ ) {+ event.preventDefault();+ void recoverMobileClipboardImageEntries().then((entries) => {+ if (entries.length > 0) {+ props.onPasteFilesAndDirs(entries, []);+ } else if (fileEntries.length > 0) {+ props.onPasteFilesAndDirs(fileEntries, []);+ }+ });+ return true;+ }+if (fileEntries.length === 0 && directoryEntries.length === 0) {return false;}diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.tsindex 4cfd48a16b..4bfa34e266 100644--- a/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts@@ -2,9 +2,14 @@ import { blockNameToFileExtensionSet } from '@core/constant/allBlocks';import { staticFileIdEndpoint } from '@core/constant/servers';import { heicConversionService } from '@core/heic/service';import type { FetchError } from '@core/service';-import { createStaticFile } from '@core/util/create';-import { contentHash } from '@core/util/hash';import type { ResultError } from '@core/util/result';+import {+ createStaticUploadFile,+ createUploadFile,+ createUploadFilePreviewUrl,+ getUploadFileCacheKey,+ type UploadFile,+} from '@core/util/uploadFile';import { mergeRegister } from '@lexical/utils';import {@@ -94,7 +99,7 @@ export const TRY_INSERT_MEDIA_UPLOAD_COMMAND: LexicalCommand<MediaType | 'all'> = createCommand('TRY_INSERT_MEDIA_UPLOAD_COMMAND');-function validateMediaFile(file: File, mediaType: MediaType): boolean {+function validateMediaFile(file: UploadFile, mediaType: MediaType): boolean {const ext = fileExtension(file.name);return ext != null && blockNameToFileExtensionSet[mediaType].has(ext);}@@ -105,12 +110,12 @@ export async function addMediaFromFile(mediaType: MediaType,constrainedMediaDimensions?: { width: number; height: number }) {- const processedFile = await processFile(file);+ const processedFile = await processFile(createUploadFile(file));if (!validateMediaFile(processedFile, mediaType)) return { success: false };editor.dispatchCommand(INSERT_MEDIA_COMMAND, {type: 'local',- url: URL.createObjectURL(processedFile),- file: processedFile,+ url: createUploadFilePreviewUrl(processedFile),+ file: processedFile.file,mediaType,constrainedMediaDimensions,});@@ -140,17 +145,13 @@ export async function getMediaUrl(src: {/*** Generate a unique key for a file to prevent duplicate uploads.*/-async function getFileKey(file: File, chunks = 8) {- const hash = await contentHash(- await file.slice(0, chunks * 1024).arrayBuffer()- );- return `${file.name}_${file.size}_${hash}`;+async function getFileKey(file: UploadFile, chunks = 8) {+ return getUploadFileCacheKey(file, chunks);}-async function processFile(file: File): Promise<File> {- if (heicConversionService.canConvert(file)) {- const convertedFile = await heicConversionService.convertFile(file);- return convertedFile;+async function processFile(file: UploadFile): Promise<UploadFile> {+ if (file.kind === 'browser' && heicConversionService.canConvert(file.file)) {+ return createUploadFile(await heicConversionService.convertFile(file.file));}return file;}@@ -165,8 +166,8 @@ async function uploadStaticFiles() {for (const file of files) {try {- const processedFile = await processFile(file);- const id = await createStaticFile(processedFile);+ const processedFile = await processFile(createUploadFile(file));+ const id = await createStaticUploadFile(processedFile);onUpload(id);} catch (_error) {onError?.();@@ -313,7 +314,7 @@ function registerMediaPlugin(editor: LexicalEditor) {localUrl: string,mediaType: MediaType) => {- const uploadKey = await getFileKey(file);+ const uploadKey = await getFileKey(createUploadFile(file));if (cachedUploads.has(uploadKey)) {const id = cachedUploads.get(uploadKey)!;diff --git a/js/app/packages/core/mobile/mobileClipboardImageRecovery.ts b/js/app/packages/core/mobile/mobileClipboardImageRecovery.tsnew file mode 100644index 0000000000..780c1f56ab--- /dev/null+++ b/js/app/packages/core/mobile/mobileClipboardImageRecovery.ts@@ -0,0 +1,79 @@+import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';+import { createSyntheticFileEntry } from '@core/util/dataTransfer';+import { isAndroid, isIOS } from '@solid-primitives/platform';+import { invoke, isTauri } from '@tauri-apps/api/core';+import {+ createNativeStagedUploadFile,+ type NativeStagedUploadData,+} from './nativeStagedUpload';++function isMobilePasteContext(): boolean {+ return isIOS || isAndroid || isNativeMobilePlatform();+}++function hasClipboardText(data: DataTransfer): boolean {+ const types = Array.from(data.types ?? []);+ if (types.includes('text/plain') || types.includes('text/html')) return true;++ return Array.from(data.items ?? []).some((item) => item.kind === 'string');+}++function hasClipboardImageOrFileHint(data: DataTransfer): boolean {+ const types = Array.from(data.types ?? []);+ if (+ types.includes('Files') ||+ types.some((type) => type.startsWith('image/'))+ )+ return true;++ if (+ Array.from(data.items ?? []).some(+ (item) =>+ item.kind === 'file' && (!item.type || item.type.startsWith('image/'))+ )+ ) {+ return true;+ }++ return Array.from(data.files ?? []).some((file) =>+ file.type.startsWith('image/')+ );+}++export function shouldUseMobileClipboardImageRecovery(+ data: DataTransfer+): boolean {+ if (!isMobilePasteContext()) return false;+ if (hasClipboardImageOrFileHint(data)) return true;++ // iOS WKWebView can expose an image paste with an empty ClipboardEvent+ // dataTransfer. Text pastes are still handled by the normal text plugins.+ return !hasClipboardText(data);+}++async function readImageEntryFromNativePasteboard(): Promise<FileSystemFileEntry | null> {+ if (!isTauri()) return null;++ try {+ const image = await invoke<NativeStagedUploadData>(+ 'plugin:pasteboard|stage_pasteboard_image'+ );+ const file = createNativeStagedUploadFile('pasteboard', image);+ return file ? createSyntheticFileEntry(file) : null;+ } catch {+ return null;+ }+}++/**+ * Recovers image paste entries through the native pasteboard plugin.+ *+ * Needed on mobile WKWebView where ClipboardEvent.clipboardData can omit image+ * files or expose an empty DataTransfer for image pastes.+ */+export async function recoverMobileClipboardImageEntries(): Promise<+ FileSystemFileEntry[]+> {+ const nativeEntry = await readImageEntryFromNativePasteboard();+ return nativeEntry ? [nativeEntry] : [];+}diff --git a/js/app/packages/core/mobile/nativePhotoLibrary.ts b/js/app/packages/core/mobile/nativePhotoLibrary.tsnew file mode 100644index 0000000000..ff5e489ace--- /dev/null+++ b/js/app/packages/core/mobile/nativePhotoLibrary.ts@@ -0,0 +1,23 @@+import { invoke, isTauri } from '@tauri-apps/api/core';+import {+ createNativeStagedUploadFile,+ type NativeStagedUploadData,+} from './nativeStagedUpload';++export async function pickNativePhotoLibraryMedia(): Promise<File[]> {+ if (!isTauri()) return [];++ let media: NativeStagedUploadData[];+ try {+ media = await invoke<NativeStagedUploadData[]>(+ 'plugin:photo-library|pick_photo_library_images'+ );+ } catch (error) {+ console.warn('Photo library picker failed', error);+ return [];+ }++ return media+ .map((item) => createNativeStagedUploadFile('photo-library', item))+ .filter((file): file is File => file !== null);+}diff --git a/js/app/packages/core/mobile/nativeStagedUpload.ts b/js/app/packages/core/mobile/nativeStagedUpload.tsnew file mode 100644index 0000000000..688e964b19--- /dev/null+++ b/js/app/packages/core/mobile/nativeStagedUpload.ts@@ -0,0 +1,75 @@+import { convertFileSrc, invoke } from '@tauri-apps/api/core';++/**+ * Native staged upload bridge.+ *+ * Some iOS sources, like pasteboard images and photo-library media, stage+ * bytes on disk and hand JS a placeholder `File`. Staging does not start a+ * network upload; the Rust upload starts later, after JS obtains a presigned+ * URL.+ */++export type NativeStagedUploadSource = 'pasteboard' | 'photo-library';++export type NativeStagedUploadData = {+ token: string | null;+ name: string | null;+ mimeType: string | null;+ size: number | null;+ previewPath: string | null;+};++export type NativeStagedUpload = {+ source: NativeStagedUploadSource;+ token: string;+ name: string;+ mimeType: string;+ size: number;+ previewSrc?: string;+};++const nativeStagedUploads = new WeakMap<File, NativeStagedUpload>();++export function createNativeStagedUploadFile(+ source: NativeStagedUploadSource,+ media: NativeStagedUploadData+): File | null {+ if (!media.token || !media.name || !media.mimeType || media.size == null) {+ return null;+ }++ const file = new File([], media.name, { type: media.mimeType });+ nativeStagedUploads.set(file, {+ source,+ token: media.token,+ name: media.name,+ mimeType: media.mimeType,+ size: media.size,+ previewSrc: media.previewPath+ ? convertFileSrc(media.previewPath)+ : undefined,+ });+ return file;+}++export function getNativeStagedUpload(+ file: File+): NativeStagedUpload | undefined {+ return nativeStagedUploads.get(file);+}++/**+ * Starts and awaits the Rust-side upload of a staged native file without+ * pulling the bytes through JS.+ */+export async function uploadNativeStagedFileToPresignedUrl(+ file: NativeStagedUpload,+ uploadUrl: string+): Promise<void> {+ await invoke('upload_staged_file_to_presigned_url', {+ source: file.source,+ token: file.token,+ uploadUrl,+ mimeType: file.mimeType,+ });+}diff --git a/js/app/packages/core/util/dataTransfer.ts b/js/app/packages/core/util/dataTransfer.tsindex f8f1eb159b..237633e4e7 100644--- a/js/app/packages/core/util/dataTransfer.ts+++ b/js/app/packages/core/util/dataTransfer.ts@@ -57,7 +57,7 @@ function partitionEntries(return { fileEntries, directoryEntries };}-function createSyntheticFileEntry(file: File): FileSystemFileEntry {+export function createSyntheticFileEntry(file: File): FileSystemFileEntry {return {isFile: true,isDirectory: false,diff --git a/js/app/packages/core/util/upload.ts b/js/app/packages/core/util/upload.tsindex af7f7ac2b6..da5e8635c2 100644--- a/js/app/packages/core/util/upload.ts+++ b/js/app/packages/core/util/upload.ts@@ -2,7 +2,9 @@* Unified Upload Module** Centralizes all upload operations to DSS and Static File Service- * with standardized validation, conversion, and error handling.+ * with standardized validation, conversion, and error handling. Browser `File`s+ * stay as the public API; upload internals normalize them into `UploadFile`s+ * where native staged files need special handling.*/import { analytics } from '@app/lib/analytics';@@ -18,7 +20,12 @@ import {blockAcceptsFileExtension,} from '@core/constant/allBlocks';import { heicConversionService } from '@core/heic/service';-import { createStaticFile } from '@core/util/create';+import {+ createStaticUploadFile,+ createUploadFile,+ isNativeStagedUpload,+ type UploadFile,+} from '@core/util/uploadFile';import {fileExtension,filenameWithoutExtension,@@ -172,7 +179,7 @@ type MaybeUploadResult = Success<DestinationUploadResult> | UploadFailure;type DestinationRuleset<D extends UploadDestination = UploadDestination> =| D- | ((file: File) => UploadDestination);+ | ((file: UploadFile) => UploadDestination);type ExtractDestination<T> = T extends UploadDestination? T@@ -194,28 +201,27 @@ type UploadFileEntry = {export type UploadInput = File | UploadFileEntry;-const getFileName = (file: File) =>+const getFileName = (file: { name: string }) =>filenameWithoutExtension(file.name) ?? file.name;-export const isFileUploadEntry = (- file: File | UploadFileEntry-): file is UploadFileEntry => 'isFolder' in file;+export const isFileUploadEntry = (file: UploadInput): file is UploadFileEntry =>+ 'isFolder' in file;-const getDestination = (file: File, ruleset: DestinationRuleset) => {+const getDestination = (file: UploadFile, ruleset: DestinationRuleset) => {return ruleset instanceof Function ? ruleset(file) : ruleset;};const DEFAULT_DESTINATION_RULESET: DestinationRuleset = 'dss';// Shared ruleset for chat input -> images/videos are static for inline display, everything else to DSS-export const chatRuleset: DestinationRuleset = (file: File) => {- const fileType = blockAcceptedMimetypeToFileExtension[file.type];+export const chatRuleset: DestinationRuleset = (file: UploadFile) => {+ const fileType = blockAcceptedMimetypeToFileExtension[file.mimeType];const ext = fileExtension(file.name);// Images go to static for inline displayif (- file.type.startsWith('image/') ||- file.type.startsWith('video/') ||+ file.mimeType.startsWith('image/') ||+ file.mimeType.startsWith('video/') ||blockAcceptsFileExtension('image', fileType) ||blockAcceptsFileExtension('video', fileType) ||(ext && blockAcceptsFileExtension('image', ext)) ||@@ -228,7 +234,7 @@ export const chatRuleset: DestinationRuleset = (file: File) => {};// Ruleset that forces an upload to dss.-export const forceDssRuleset: DestinationRuleset = (_: File) => 'dss';+export const forceDssRuleset: DestinationRuleset = (_: UploadFile) => 'dss';class FileSizeExceededError extends Error {public limit: number;@@ -277,7 +283,7 @@ class UnsupportedFileTypeError extends Error {class UploadError extends Error {constructor(- file: File,+ file: { name: string },destination?: UploadDestination,originalError?: Error | string) {@@ -327,35 +333,50 @@ function humanFileSize(bytes: number, si = true, dp = 1): string {return `${parseFloat(bytes.toFixed(dp))} ${units[u]}`;}-function validateFileSize(file: File): void {+function validateFileSize(file: UploadFile): void {if (file.size > MAX_FILE_BYTE_SIZE) {throw new FileSizeExceededError(getFileName(file));}}-// pre-upload processing (if needed). Currently only used for HEIC conversion-async function processFile(file: File): Promise<File> {- if (heicConversionService.canConvert(file)) {- return await heicConversionService.convertFile(file);+// Pre-upload processing for browser-backed files. Native staged uploads have+// already been encoded/staged by native code, and their JS `File` is only a+// placeholder, so browser-side conversions must not run on them.+async function processFile(file: UploadFile): Promise<UploadFile> {+ if (file.kind === 'browser' && heicConversionService.canConvert(file.file)) {+ return createUploadFile(await heicConversionService.convertFile(file.file));}return file;}async function uploadToDSS(- file: File,+ file: UploadFile,options: DssUploadFileOptions): Promise<DssUploadSuccessResult> {+ if (isNativeStagedUpload(file)) {+ throw new UploadError(+ file,+ 'dss',+ 'Native staged uploads require static upload'+ );+ }+try {- return dssUpload(file, options);+ return dssUpload(file.file, options);} catch (error) {throw new UploadError(file, 'dss', error);}}-async function uploadToStatic(file: File): Promise<StaticUploadSuccessResult> {+async function uploadToStatic(+ file: UploadFile+): Promise<StaticUploadSuccessResult> {const name = getFileName(file);try {- const id = await createStaticFile(file);+ // `createStaticUploadFile` is the single static-file path for UploadFile:+ // browser files are PUT from JS; native staged files are PUT from Rust using+ // the staged token and the presigned URL requested inside that helper.+ const id = await createStaticUploadFile(file);return {name,id,@@ -376,10 +397,11 @@ export async function uploadFile(destinationRuleset: DestinationRuleset,dssOptions: DssUploadFileOptions = {}): Promise<MaybeUploadResult> {+ const uploadSource = createUploadFile(file);try {- validateFileSize(file);+ validateFileSize(uploadSource);- const processedFile = await processFile(file);+ const processedFile = await processFile(uploadSource);const destination = destinationRuleset? getDestination(processedFile, destinationRuleset)@@ -404,11 +426,13 @@ export async function uploadFile(return { failed: false, pending, ...result };} catch (error) {- const name = getFileName(file);+ const name = getFileName(uploadSource);return {failed: true,error:- error instanceof Error ? error : new UploadError(file, 'dss', error),+ error instanceof Error+ ? error+ : new UploadError(uploadSource, 'dss', error),name,};}@@ -430,12 +454,14 @@ export async function uploadFiles(return [];}- const files = fileList.map((file) => {- return isFileUploadEntry(file) ? file.file : file;- });+ const entries = fileList.map((file) =>+ isFileUploadEntry(file) ? file : { file, isFolder: false }+ );+ const files = entries.map((entry) => entry.file);+ const uploadSources = files.map(createUploadFile);// validate all files before uploading- for (const file of files) {+ for (const file of uploadSources) {try {validateFileSize(file);} catch (error) {@@ -447,8 +473,7 @@ export async function uploadFiles(}const uploadPromises = files.map((file, index) => {- const isFolder =- isFileUploadEntry(fileList[index]) && fileList[index].isFolder;+ const isFolder = entries[index].isFolder;const uploadOptions: DssUploadFileOptions = isFolder? {...dssOptions,diff --git a/js/app/packages/core/util/uploadFile.ts b/js/app/packages/core/util/uploadFile.tsnew file mode 100644index 0000000000..fbd40de4e1--- /dev/null+++ b/js/app/packages/core/util/uploadFile.ts@@ -0,0 +1,127 @@+import {+ getNativeStagedUpload,+ type NativeStagedUploadSource,+ uploadNativeStagedFileToPresignedUrl,+} from '@core/mobile/nativeStagedUpload';+import { invalidateUserQuota } from '@queries/auth';+import { staticFileClient } from '@service-static-files/client';+import { contentHash } from './hash';++/**+ * App-level upload file model.+ *+ * In Tauri app file uploads are handled on the Rust-side. Paste/drop boundaries thus need to briefly carry native staged uploads as placeholder `Files`s.+ *+ * Immediately normalize those placeholders with `createUploadFile`.+ */++export type BrowserUploadFile = {+ kind: 'browser';+ file: File;+ name: string;+ mimeType: string;+ size: number;+};++export type NativeStagedUploadFile = {+ kind: 'native-staged';+ file: File;+ source: NativeStagedUploadSource;+ token: string;+ name: string;+ mimeType: string;+ size: number;+ previewSrc?: string;+};++export type UploadFile = BrowserUploadFile | NativeStagedUploadFile;++export function createUploadFile(file: File): UploadFile {+ const staged = getNativeStagedUpload(file);+ if (staged) {+ return {+ kind: 'native-staged',+ file,+ ...staged,+ };+ }++ return {+ kind: 'browser',+ file,+ name: file.name,+ mimeType: file.type,+ size: file.size,+ };+}++export function isNativeStagedUpload(+ file: UploadFile+): file is NativeStagedUploadFile {+ return file.kind === 'native-staged';+}++export async function createStaticUploadFile(+ file: UploadFile+): Promise<string> {+ const result = await staticFileClient.makePresignedUrl({+ file_name: file.name,+ content_type: file.mimeType,+ });+ invalidateUserQuota();+ if (result.isErr()) throw new Error('Failed to upload file');++ const { upload_url, id } = result.value;+ if (isNativeStagedUpload(file)) {+ await uploadNativeStagedFileToPresignedUrl(file, upload_url);+ return id;+ }++ const uploadResult = await staticFileClient.uploadToPresignedUrl({+ url: upload_url,+ blob: file.file,+ });+ if (!uploadResult.success) {+ throw new Error('Failed to upload file');+ }+ return id;+}++/**+ * Returns a browser-readable source for metadata extraction. For native staged+ * files this is the Tauri asset URL for the staged file; for regular files it+ * returns the File itself.+ */+export function getUploadFilePreviewSource(file: UploadFile): File | string {+ return isNativeStagedUpload(file)+ ? (file.previewSrc ?? file.file)+ : file.file;+}++/**+ * Creates the URL used for local media nodes. Native staged files already have+ * a Tauri asset URL, while regular files need an object URL.+ */+export function createUploadFilePreviewUrl(file: UploadFile): string {+ return isNativeStagedUpload(file) && file.previewSrc+ ? file.previewSrc+ : URL.createObjectURL(file.file);+}++/**+ * Builds a stable upload key without reading bytes from native staged files.+ * Their JS `File` is empty, so hashing `file.slice()` would hash the wrong data.+ */+export async function getUploadFileCacheKey(+ file: UploadFile,+ chunks = 8+): Promise<string> {+ if (isNativeStagedUpload(file)) {+ return `${file.name}_${file.size}_${file.token}`;+ }++ const hash = await contentHash(+ await file.file.slice(0, chunks * 1024).arrayBuffer()+ );+ return `${file.name}_${file.size}_${hash}`;+}diff --git a/js/app/packages/queries/channel/message.ts b/js/app/packages/queries/channel/message.tsindex a96b3bf773..a7c0d2131e 100644--- a/js/app/packages/queries/channel/message.ts+++ b/js/app/packages/queries/channel/message.ts@@ -1,4 +1,5 @@import { useAnalytics } from '@app/component/analytics-context';+import type { OptimisticPostMessageAttachment } from '@channel/Input/message-payload';import { toast } from '@core/component/Toast/Toast';import type { DateValue } from '@core/util/date';import { throwOnErr } from '@core/util/result';@@ -19,6 +20,7 @@ import type {} from '@service-comms/generated/models';import type { NewAttachment } from '@service-comms/generated/models/newAttachment';import type { SimpleMention } from '@service-comms/generated/models/simpleMention';+import type { ApiMessageAttachment } from '@service-storage/generated/schemas/apiMessageAttachment';import { useMutation } from '@tanstack/solid-query';import { queryClient } from '../client';import { createMutationNonce, registerNonce } from '../nonce';@@ -92,24 +94,28 @@ type UpdateMessageContext = {previousAttachments: Attachment[];};+type OptimisticApiMessageAttachment = ApiMessageAttachment & {+ previewSrc?: string;+};+function makeOptimisticAttachments(- channelId: string,- optimisticId: string,- attachments: PostMessageRequest['attachments'],+ attachments: readonly OptimisticPostMessageAttachment[],now: string-): Attachment[] {- return attachments.map((attachment) => ({+): OptimisticApiMessageAttachment[] {+ return attachments.map(({ attachment, previewSrc }) => ({id: crypto.randomUUID(),- channel_id: channelId,+ entity_id: attachment.entity_id,+ entity_type: attachment.entity_type,created_at: now,- message_id: optimisticId,- ...attachment,+ width: attachment.width ?? undefined,+ height: attachment.height ?? undefined,+ previewSrc,}));}function makeOptimisticTopLevelMessage(vars: WithChannelId<WithOptimisticId<WithSenderId<PostMessageRequest>>>,- attachments: Attachment[],+ attachments: OptimisticApiMessageAttachment[],now: string): ApiChannelMessage {return {@@ -121,14 +127,7 @@ function makeOptimisticTopLevelMessage(updated_at: now,deleted_at: undefined,edited_at: undefined,- attachments: attachments.map(- ({ id, entity_id, entity_type, created_at }) => ({- id,- entity_id,- entity_type,- created_at,- })- ),+ attachments,reactions: [],thread: {preview: [],@@ -140,7 +139,7 @@ function makeOptimisticTopLevelMessage(function makeOptimisticThreadReply(vars: WithChannelId<WithOptimisticId<WithSenderId<PostMessageRequest>>>,- attachments: Attachment[],+ attachments: OptimisticApiMessageAttachment[],now: string): ApiThreadReply {return {@@ -150,14 +149,7 @@ function makeOptimisticThreadReply(created_at: now,updated_at: now,edited_at: undefined,- attachments: attachments.map(- ({ id, entity_id, entity_type, created_at }) => ({- id,- entity_id,- entity_type,- created_at,- })- ),+ attachments,reactions: [],};}@@ -167,13 +159,20 @@ function makeOptimisticThreadReply(* Returns minimal context for rollback (just the optimistic ID).*/export function optimisticInsertChannelMessage(- vars: WithChannelId<WithOptimisticId<WithSenderId<PostMessageRequest>>>+ vars: WithChannelId<+ WithOptimisticId<+ WithSenderId<+ PostMessageRequest & {+ optimisticAttachments?: readonly OptimisticPostMessageAttachment[];+ }+ >+ >+ >): InsertMessageContext | undefined {const now = new Date().toISOString();const newAttachments = makeOptimisticAttachments(- vars.channelId,- vars.optimisticId,- vars.attachments,+ vars.optimisticAttachments ??+ vars.attachments.map((attachment) => ({ attachment })),now);const threadId = vars.thread_id ?? undefined;@@ -397,6 +396,7 @@ export function rollbackUpdateChannelMessage(type SendMessageParams = {channelID: string;message: PostMessageRequest;+ optimisticAttachments?: readonly OptimisticPostMessageAttachment[];optimisticId: string;senderId: string;};@@ -443,6 +443,7 @@ export function useSendMessageMutation(channelId: vars.channelID,optimisticId: vars.optimisticId,senderId: vars.senderId,+ optimisticAttachments: vars.optimisticAttachments,...vars.message,});},diff --git a/js/app/packages/queries/channel/tests/channel-optimistic.test.ts b/js/app/packages/queries/channel/tests/channel-optimistic.test.tsindex 50e1be72cb..1fc9b5c7c8 100644--- a/js/app/packages/queries/channel/tests/channel-optimistic.test.ts+++ b/js/app/packages/queries/channel/tests/channel-optimistic.test.ts@@ -180,6 +180,54 @@ describe('channel optimistic cache regressions', () => {]);});+ it('keeps local media metadata on optimistic top-level inserts', () => {+ seedChannelMessagesCache(+ 'channel-1',+ createChannelMessagesData([+ [createPaginatedMessage('existing-msg', '2024-01-03T00:00:00.000Z')],+ ])+ );++ optimisticInsertChannelMessage({+ channelId: 'channel-1',+ optimisticId: 'optimistic-top-level',+ senderId: 'user-2',+ content: 'Top level optimistic message',+ mentions: [],+ attachments: [+ {+ entity_id: 'static-file-1',+ entity_type: 'static/image',+ width: 300,+ height: 200,+ },+ ],+ optimisticAttachments: [+ {+ attachment: {+ entity_id: 'static-file-1',+ entity_type: 'static/image',+ width: 300,+ height: 200,+ },+ previewSrc: 'blob:local-preview',+ },+ ],+ });++ expect(+ getChannelMessagesFromCache('channel-1')?.pages[0].items[0].attachments[0]+ ).toEqual(+ expect.objectContaining({+ entity_id: 'static-file-1',+ entity_type: 'static/image',+ width: 300,+ height: 200,+ previewSrc: 'blob:local-preview',+ })+ );+ });+it('rolls back optimistic thread replies when only the new caches are warm', () => {seedChannelMessagesCache('channel-1',diff --git a/js/app/packages/tauri/src/ShareTargetProvider.tsx b/js/app/packages/tauri/src/ShareTargetProvider.tsxindex cbe49cba20..96222ec79b 100644--- a/js/app/packages/tauri/src/ShareTargetProvider.tsx+++ b/js/app/packages/tauri/src/ShareTargetProvider.tsx@@ -97,7 +97,8 @@ async function clearSharedFiles(tokens: string[]): Promise<void> {async function uploadPendingShareFile(args: UploadPendingShareFileArgs): Promise<void> {- await invoke('upload_shared_file_to_presigned_url', {+ await invoke('upload_staged_file_to_presigned_url', {+ source: 'share',token: args.token,uploadUrl: args.uploadUrl,mimeType: args.mimeType,diff --git a/js/app/tauri/Cargo.lock b/js/app/tauri/Cargo.lockindex 861aba7c5e..99d5bc6f4b 100644--- a/js/app/tauri/Cargo.lock+++ b/js/app/tauri/Cargo.lock@@ -103,6 +103,7 @@ dependencies = ["serde","serde_json","serde_qs",+ "staged_upload_constants","tauri","tauri-build","tauri-plugin-auth",@@ -117,6 +118,8 @@ dependencies = ["tauri-plugin-notifications","tauri-plugin-opener","tauri-plugin-os",+ "tauri-plugin-pasteboard",+ "tauri-plugin-photo-library","tauri-plugin-safe-area-insets","tauri-plugin-single-instance","tauri-plugin-virtual-keyboard",@@ -4992,6 +4995,10 @@ version = "1.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"+[[package]]+name = "staged_upload_constants"+version = "0.1.0"+[[package]]name = "string_cache"version = "0.8.9"@@ -5616,6 +5623,26 @@ dependencies = ["thiserror 2.0.18",]+[[package]]+name = "tauri-plugin-pasteboard"+version = "0.1.0"+dependencies = [+ "serde",+ "staged_upload_constants",+ "tauri",+ "tauri-plugin",+]++[[package]]+name = "tauri-plugin-photo-library"+version = "0.1.0"+dependencies = [+ "serde",+ "staged_upload_constants",+ "tauri",+ "tauri-plugin",+]+[[package]]name = "tauri-plugin-safe-area-insets"version = "0.1.0"diff --git a/js/app/tauri/Cargo.toml b/js/app/tauri/Cargo.tomlindex aab772040e..1b051fa9b4 100644--- a/js/app/tauri/Cargo.toml+++ b/js/app/tauri/Cargo.toml@@ -5,6 +5,9 @@ members = ["logger","macro_bundle_updater_plugin","navigation_plugin",+ "pasteboard_plugin",+ "photo_library_plugin",+ "staged_upload_constants","src-tauri",]package.edition = "2024"diff --git a/js/app/tauri/pasteboard_plugin/.gitignore b/js/app/tauri/pasteboard_plugin/.gitignorenew file mode 100644index 0000000000..a2ba4dd574--- /dev/null+++ b/js/app/tauri/pasteboard_plugin/.gitignore@@ -0,0 +1,6 @@+# Swift Package Manager build artifacts+ios/.build/+ios/Package.resolved++# Tauri-generated Swift API (placed here by `cargo tauri ios build`)+.tauri/diff --git a/js/app/tauri/pasteboard_plugin/Cargo.toml b/js/app/tauri/pasteboard_plugin/Cargo.tomlnew file mode 100644index 0000000000..cf13ae2948--- /dev/null+++ b/js/app/tauri/pasteboard_plugin/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "tauri-plugin-pasteboard"+version = "0.1.0"+edition = "2024"+links = "tauri-plugin-pasteboard"++[build-dependencies]+tauri-plugin = { version = "2.4", features = ["build"] }++[dependencies]+serde = { workspace = true, features = ["derive"] }+staged_upload_constants = { path = "../staged_upload_constants" }+tauri = { workspace = true }++[target.'cfg(target_os = "ios")'.dependencies]+tauri = { workspace = true, features = ["wry"] }diff --git a/js/app/tauri/pasteboard_plugin/build.rs b/js/app/tauri/pasteboard_plugin/build.rsnew file mode 100644index 0000000000..05e84a3e7d--- /dev/null+++ b/js/app/tauri/pasteboard_plugin/build.rs@@ -0,0 +1,6 @@+fn main() {+ tauri_plugin::Builder::new(&["stage_pasteboard_image"])+ .ios_path("ios")+ .try_build()+ .unwrap();+}diff --git a/js/app/tauri/pasteboard_plugin/ios/Package.swift b/js/app/tauri/pasteboard_plugin/ios/Package.swiftnew file mode 100644index 0000000000..fbc15b4c94--- /dev/null+++ b/js/app/tauri/pasteboard_plugin/ios/Package.swift@@ -0,0 +1,29 @@+// swift-tools-version:5.3+import PackageDescription++let package = Package(+ name: "tauri-plugin-pasteboard",+ platforms: [+ .macOS(.v10_13),+ .iOS(.v14),+ ],+ products: [+ .library(+ name: "tauri-plugin-pasteboard",+ type: .static,+ targets: ["tauri-plugin-pasteboard"]+ )+ ],+ dependencies: [+ .package(name: "Tauri", path: "../.tauri/tauri-api")+ ],+ targets: [+ .target(+ name: "tauri-plugin-pasteboard",+ dependencies: [+ .byName(name: "Tauri")+ ],+ path: "Sources"+ )+ ]+)diff --git a/js/app/tauri/pasteboard_plugin/ios/Sources/PasteboardPlugin.swift b/js/app/tauri/pasteboard_plugin/ios/Sources/PasteboardPlugin.swiftnew file mode 100644index 0000000000..d9ea7a186e--- /dev/null+++ b/js/app/tauri/pasteboard_plugin/ios/Sources/PasteboardPlugin.swift@@ -0,0 +1,152 @@+import UIKit+import Tauri++private struct StagePasteboardImagePayload: Decodable {+ let stagingDirectoryPath: String+ let tokenPrefix: String+}++class PasteboardPlugin: Plugin {+ @objc public func stagePasteboardImage(_ invoke: Invoke) throws {+ let payload = try invoke.parseArgs(StagePasteboardImagePayload.self)+ let stagingDirectory = URL(+ fileURLWithPath: payload.stagingDirectoryPath,+ isDirectory: true+ )++ DispatchQueue.main.async {+ guard let image = UIPasteboard.general.image else {+ invoke.resolve([+ "token": NSNull(),+ "name": NSNull(),+ "mimeType": NSNull(),+ "size": NSNull(),+ "previewPath": NSNull(),+ ])+ return+ }++ DispatchQueue.global(qos: .userInitiated).async {+ self.cleanupStalePasteboardImages(in: stagingDirectory)++ let encoded = encodedData(from: image)+ guard let data = encoded.data else {+ invoke.reject("Failed to encode pasteboard image")+ return+ }++ let token = payload.tokenPrefix+ + UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()+ let name = "pasted-image.\(encoded.fileExtension)"+ let fileURL = stagingDirectory.appendingPathComponent("\(token)-\(name)")++ do {+ try FileManager.default.createDirectory(+ at: stagingDirectory,+ withIntermediateDirectories: true+ )+ try data.write(to: fileURL, options: [.atomic])+ let size = try FileManager.default.attributesOfItem(+ atPath: fileURL.path+ )[.size] as? NSNumber++ invoke.resolve([+ "token": token,+ "name": name,+ "mimeType": encoded.mimeType,+ "size": size?.uint64Value ?? UInt64(data.count),+ "previewPath": fileURL.path,+ ])+ } catch {+ invoke.reject("Failed to stage pasteboard image: \(error.localizedDescription)")+ }+ }+ }+ }++ private func cleanupStalePasteboardImages(in directory: URL) {+ guard+ let entries = try? FileManager.default.contentsOfDirectory(+ at: directory,+ includingPropertiesForKeys: [.contentModificationDateKey]+ )+ else { return }++ let cutoff = Date().addingTimeInterval(-60 * 60 * 24)+ for url in entries {+ let modified = (try? url.resourceValues(+ forKeys: [.contentModificationDateKey]+ ).contentModificationDate) ?? Date.distantFuture+ if modified < cutoff {+ try? FileManager.default.removeItem(at: url)+ }+ }+ }+}++private struct EncodedImageData {+ let data: Data?+ let mimeType: String+ let fileExtension: String+}++private let maxImagePixelDimension: CGFloat = 4096++private func encodedData(from image: UIImage) -> EncodedImageData {+ let normalized = normalizedImage(image)+ if imageHasAlpha(image), let data = normalized.pngData() {+ return EncodedImageData(+ data: data,+ mimeType: "image/png",+ fileExtension: "png"+ )+ }++ return EncodedImageData(+ data: normalized.jpegData(compressionQuality: 0.92),+ mimeType: "image/jpeg",+ fileExtension: "jpg"+ )+}++private func imageHasAlpha(_ image: UIImage) -> Bool {+ guard let alphaInfo = image.cgImage?.alphaInfo else { return false }+ switch alphaInfo {+ case .first, .last, .premultipliedFirst, .premultipliedLast:+ return true+ default:+ return false+ }+}++private func normalizedImage(_ image: UIImage) -> UIImage {+ let widthPx = image.size.width * image.scale+ let heightPx = image.size.height * image.scale+ let longestPx = max(widthPx, heightPx)+ let needsDownscale = longestPx > maxImagePixelDimension++ if !needsDownscale && image.imageOrientation == .up {+ return image+ }++ let format = UIGraphicsImageRendererFormat()+ let targetSize: CGSize+ if needsDownscale {+ let ratio = maxImagePixelDimension / longestPx+ format.scale = 1+ targetSize = CGSize(width: widthPx * ratio, height: heightPx * ratio)+ } else {+ format.scale = image.scale+ targetSize = image.size+ }++ let renderer = UIGraphicsImageRenderer(size: targetSize, format: format)+ return renderer.image { _ in+ image.draw(in: CGRect(origin: .zero, size: targetSize))+ }+}++@_cdecl("init_plugin_pasteboard")+func initPlugin() -> Plugin {+ return PasteboardPlugin()+}diff --git a/js/app/tauri/pasteboard_plugin/permissions/autogenerated/commands/stage_pasteboard_image.toml b/js/app/tauri/pasteboard_plugin/permissions/autogenerated/commands/stage_pasteboard_image.tomlnew file mode 100644index 0000000000..68431c72d6--- /dev/null+++ b/js/app/tauri/pasteboard_plugin/permissions/autogenerated/commands/stage_pasteboard_image.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-stage-pasteboard-image"+description = "Enables the stage_pasteboard_image command without any pre-configured scope."+commands.allow = ["stage_pasteboard_image"]++[[permission]]+identifier = "deny-stage-pasteboard-image"+description = "Denies the stage_pasteboard_image command without any pre-configured scope."+commands.deny = ["stage_pasteboard_image"]diff --git a/js/app/tauri/pasteboard_plugin/permissions/autogenerated/reference.md b/js/app/tauri/pasteboard_plugin/permissions/autogenerated/reference.mdnew file mode 100644index 0000000000..0fccbd8bee--- /dev/null+++ b/js/app/tauri/pasteboard_plugin/permissions/autogenerated/reference.md@@ -0,0 +1,35 @@+## Permission Table++<table>+<tr>+<th>Identifier</th>+<th>Description</th>+</tr>+++<tr>+<td>++`pasteboard:allow-stage-pasteboard-image`++</td>+<td>++Enables the stage_pasteboard_image command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`pasteboard:deny-stage-pasteboard-image`++</td>+<td>++Denies the stage_pasteboard_image command without any pre-configured scope.++</td>+</tr>+</table>diff --git a/js/app/tauri/pasteboard_plugin/permissions/schemas/schema.json b/js/app/tauri/pasteboard_plugin/permissions/schemas/schema.jsonnew file mode 100644index 0000000000..1d57c8c12a--- /dev/null+++ b/js/app/tauri/pasteboard_plugin/permissions/schemas/schema.json@@ -0,0 +1,312 @@+{+ "$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 stage_pasteboard_image command without any pre-configured scope.",+ "type": "string",+ "const": "allow-stage-pasteboard-image",+ "markdownDescription": "Enables the stage_pasteboard_image command without any pre-configured scope."+ },+ {+ "description": "Denies the stage_pasteboard_image command without any pre-configured scope.",+ "type": "string",+ "const": "deny-stage-pasteboard-image",+ "markdownDescription": "Denies the stage_pasteboard_image command without any pre-configured scope."+ }+ ]+ }+ }+}\ No newline at end of filediff --git a/js/app/tauri/pasteboard_plugin/src/lib.rs b/js/app/tauri/pasteboard_plugin/src/lib.rsnew file mode 100644index 0000000000..df3cfeeb5a--- /dev/null+++ b/js/app/tauri/pasteboard_plugin/src/lib.rs@@ -0,0 +1,95 @@+use serde::{Deserialize, Serialize};+use tauri::{+ AppHandle, Manager, Runtime, command,+ plugin::{Builder, PluginHandle, TauriPlugin},+};++#[cfg(target_os = "ios")]+tauri::ios_plugin_binding!(init_plugin_pasteboard);++#[cfg(target_os = "ios")]+#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct StagePasteboardImagePayload {+ staging_directory_path: String,+ token_prefix: &'static str,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct StagedPasteboardImage {+ pub token: Option<String>,+ pub name: Option<String>,+ pub mime_type: Option<String>,+ pub size: Option<u64>,+ pub preview_path: Option<String>,+}++pub struct Pasteboard<R: Runtime>(PluginHandle<R>);++impl<R: Runtime> Pasteboard<R> {+ #[cfg(target_os = "ios")]+ fn stage_pasteboard_image(+ &self,+ staging_directory_path: String,+ ) -> Result<StagedPasteboardImage, String> {+ self.0+ .run_mobile_plugin(+ "stagePasteboardImage",+ StagePasteboardImagePayload {+ staging_directory_path,+ token_prefix: staged_upload_constants::PASTEBOARD_TOKEN_PREFIX,+ },+ )+ .map_err(|error| error.to_string())+ }+}++pub trait PasteboardExt<R: Runtime> {+ fn pasteboard(&self) -> &Pasteboard<R>;+}++impl<R: Runtime, T: Manager<R>> PasteboardExt<R> for T {+ fn pasteboard(&self) -> &Pasteboard<R> {+ self.state::<Pasteboard<R>>().inner()+ }+}++#[command]+async fn stage_pasteboard_image<R: Runtime>(+ app: AppHandle<R>,+) -> Result<StagedPasteboardImage, String> {+ #[cfg(not(target_os = "ios"))]+ {+ let _ = app;+ Err("pasteboard plugin is only available on iOS".to_string())+ }++ #[cfg(target_os = "ios")]+ {+ let staging_directory_path = app+ .path()+ .app_cache_dir()+ .map_err(|error| format!("failed to resolve app cache directory: {error}"))?+ .join(staged_upload_constants::PASTEBOARD_STAGING_DIRECTORY_NAME)+ .to_string_lossy()+ .into_owned();++ app.pasteboard()+ .stage_pasteboard_image(staging_directory_path)+ }+}++pub fn init<R: Runtime>() -> TauriPlugin<R> {+ Builder::new("pasteboard")+ .invoke_handler(tauri::generate_handler![stage_pasteboard_image])+ .setup(|_app, _api| {+ #[cfg(target_os = "ios")]+ {+ let handle = _api.register_ios_plugin(init_plugin_pasteboard)?;+ _app.manage(Pasteboard(handle));+ }+ Ok(())+ })+ .build()+}diff --git a/js/app/tauri/photo_library_plugin/.gitignore b/js/app/tauri/photo_library_plugin/.gitignorenew file mode 100644index 0000000000..2e256f5774--- /dev/null+++ b/js/app/tauri/photo_library_plugin/.gitignore@@ -0,0 +1,11 @@+# Swift Package Manager build artifacts+ios/.build/+ios/Package.resolved++# Tauri-generated Swift API (placed here by `cargo tauri ios build`)+.tauri/++target+dist-js+Cargo.lock+node_modulesdiff --git a/js/app/tauri/photo_library_plugin/Cargo.toml b/js/app/tauri/photo_library_plugin/Cargo.tomlnew file mode 100644index 0000000000..885c785ddd--- /dev/null+++ b/js/app/tauri/photo_library_plugin/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "tauri-plugin-photo-library"+version = "0.1.0"+edition = "2024"+links = "tauri-plugin-photo-library"++[build-dependencies]+tauri-plugin = { version = "2.4", features = ["build"] }++[dependencies]+serde = { workspace = true, features = ["derive"] }+staged_upload_constants = { path = "../staged_upload_constants" }+tauri = { workspace = true }++[target.'cfg(target_os = "ios")'.dependencies]+tauri = { workspace = true, features = ["wry"] }diff --git a/js/app/tauri/photo_library_plugin/build.rs b/js/app/tauri/photo_library_plugin/build.rsnew file mode 100644index 0000000000..13d5114f0a--- /dev/null+++ b/js/app/tauri/photo_library_plugin/build.rs@@ -0,0 +1,6 @@+fn main() {+ tauri_plugin::Builder::new(&["pick_photo_library_images"])+ .ios_path("ios")+ .try_build()+ .unwrap();+}diff --git a/js/app/tauri/photo_library_plugin/ios/Package.swift b/js/app/tauri/photo_library_plugin/ios/Package.swiftnew file mode 100644index 0000000000..927c6cb042--- /dev/null+++ b/js/app/tauri/photo_library_plugin/ios/Package.swift@@ -0,0 +1,29 @@+// swift-tools-version:5.3+import PackageDescription++let package = Package(+ name: "tauri-plugin-photo-library",+ platforms: [+ .macOS(.v10_13),+ .iOS(.v14),+ ],+ products: [+ .library(+ name: "tauri-plugin-photo-library",+ type: .static,+ targets: ["tauri-plugin-photo-library"]+ )+ ],+ dependencies: [+ .package(name: "Tauri", path: "../.tauri/tauri-api")+ ],+ targets: [+ .target(+ name: "tauri-plugin-photo-library",+ dependencies: [+ .byName(name: "Tauri")+ ],+ path: "Sources"+ )+ ]+)diff --git a/js/app/tauri/photo_library_plugin/ios/Sources/PhotoLibraryPlugin.swift b/js/app/tauri/photo_library_plugin/ios/Sources/PhotoLibraryPlugin.swiftnew file mode 100644index 0000000000..2bce21c61c--- /dev/null+++ b/js/app/tauri/photo_library_plugin/ios/Sources/PhotoLibraryPlugin.swift@@ -0,0 +1,568 @@+import ImageIO+import PhotosUI+import Tauri+import UIKit+import UniformTypeIdentifiers++private let maxPhotoLibrarySelectionCount = 10++private struct PickPhotoLibraryImagesPayload: Decodable {+ let stagingDirectoryPath: String+ let tokenPrefix: String+}++class UnavailablePhotoLibraryPlugin: Plugin {+ @objc public func pickPhotoLibraryImages(_ invoke: Invoke) {+ invoke.reject("Photo library media picker requires iOS 14 or newer")+ }+}++@available(iOS 14.0, *)+class PhotoLibraryPlugin: Plugin {+ private var pickerDelegate: PhotoLibraryPickerDelegate?++ @objc public func pickPhotoLibraryImages(_ invoke: Invoke) throws {+ let payload = try invoke.parseArgs(PickPhotoLibraryImagesPayload.self)+ let stagingDirectory = URL(+ fileURLWithPath: payload.stagingDirectoryPath,+ isDirectory: true+ )++ DispatchQueue.main.async {+ guard self.pickerDelegate == nil else {+ invoke.reject("Photo library picker is already open")+ return+ }++ guard let rootViewController = self.manager.viewController else {+ invoke.reject("No view controller available to present photo library")+ return+ }++ guard let viewController = topmostPresentableViewController(from: rootViewController) else {+ invoke.reject("Photo library picker cannot be presented right now")+ return+ }++ var configuration = PHPickerConfiguration(photoLibrary: .shared())+ configuration.filter = .any(of: [.images, .videos])+ configuration.preferredAssetRepresentationMode = .current+ configuration.selectionLimit = maxPhotoLibrarySelectionCount++ let picker = PHPickerViewController(configuration: configuration)+ let delegate = PhotoLibraryPickerDelegate(+ plugin: self,+ invoke: invoke,+ stagingDirectory: stagingDirectory,+ tokenPrefix: payload.tokenPrefix,+ onComplete: { [weak self] in+ self?.pickerDelegate = nil+ }+ )+ self.pickerDelegate = delegate+ picker.delegate = delegate++ viewController.present(picker, animated: true)+ }+ }++ fileprivate func stageMediaFile(+ sourceURL: URL,+ typeIdentifier: String?,+ suggestedName: String?,+ mediaKind: PhotoLibraryMediaKind,+ stagingDirectory: URL,+ tokenPrefix: String+ ) throws -> StagedPhotoLibraryMedia {+ let sourceType: UTType?+ if mediaKind == .image {+ sourceType = imageType(typeIdentifier: typeIdentifier, sourceURL: sourceURL)+ } else {+ sourceType = mediaType(typeIdentifier: typeIdentifier, sourceURL: sourceURL)+ }+ let shouldConvertToJpeg =+ mediaKind == .image && isHeicOrHeif(type: sourceType, sourceURL: sourceURL)+ let token = tokenPrefix+ + UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()+ let fileExtension = shouldConvertToJpeg+ ? "jpg"+ : preferredFilenameExtension(type: sourceType, sourceURL: sourceURL, mediaKind: mediaKind)+ let name = sanitizedMediaFilename(+ suggestedName,+ fileExtension: fileExtension,+ mediaKind: mediaKind+ )+ let targetURL = stagingDirectory.appendingPathComponent("\(token)-\(name)")++ try FileManager.default.createDirectory(+ at: stagingDirectory,+ withIntermediateDirectories: true+ )++ if FileManager.default.fileExists(atPath: targetURL.path) {+ try FileManager.default.removeItem(at: targetURL)+ }++ if shouldConvertToJpeg {+ try writeJpegImageUsingImageIO(from: sourceURL, to: targetURL)+ } else {+ try FileManager.default.copyItem(at: sourceURL, to: targetURL)+ }+ try FileManager.default.setAttributes(+ [.modificationDate: Date()],+ ofItemAtPath: targetURL.path+ )++ let size = try FileManager.default.attributesOfItem(+ atPath: targetURL.path+ )[.size] as? NSNumber++ return StagedPhotoLibraryMedia(+ token: token,+ name: name,+ mimeType: shouldConvertToJpeg+ ? "image/jpeg"+ : mimeType(+ type: sourceType,+ sourceURL: targetURL,+ mediaKind: mediaKind+ ),+ size: size?.uint64Value ?? 0,+ previewPath: targetURL.path+ )+ }++ fileprivate func cleanupStalePhotoLibraryMedia(in directory: URL) {+ guard+ let entries = try? FileManager.default.contentsOfDirectory(+ at: directory,+ includingPropertiesForKeys: [.contentModificationDateKey]+ )+ else { return }++ let cutoff = Date().addingTimeInterval(-60 * 60 * 24)+ for url in entries {+ let modified = (try? url.resourceValues(+ forKeys: [.contentModificationDateKey]+ ).contentModificationDate) ?? Date.distantFuture+ if modified < cutoff {+ try? FileManager.default.removeItem(at: url)+ }+ }+ }+}++private enum PhotoLibraryMediaKind {+ case image+ case video+}++private struct PhotoLibraryMediaType {+ let identifier: String+ let kind: PhotoLibraryMediaKind+}++private struct StagedPhotoLibraryMedia: Encodable {+ let token: String+ let name: String+ let mimeType: String+ let size: UInt64+ let previewPath: String+}++@available(iOS 14.0, *)+private class PhotoLibraryPickerDelegate: NSObject, PHPickerViewControllerDelegate {+ private weak var plugin: PhotoLibraryPlugin?+ private let invoke: Invoke+ private let stagingDirectory: URL+ private let tokenPrefix: String+ private let onComplete: () -> Void++ init(+ plugin: PhotoLibraryPlugin,+ invoke: Invoke,+ stagingDirectory: URL,+ tokenPrefix: String,+ onComplete: @escaping () -> Void+ ) {+ self.plugin = plugin+ self.invoke = invoke+ self.stagingDirectory = stagingDirectory+ self.tokenPrefix = tokenPrefix+ self.onComplete = onComplete+ }++ func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {+ picker.dismiss(animated: true)++ guard !results.isEmpty else {+ invoke.resolve([StagedPhotoLibraryMedia]())+ onComplete()+ return+ }++ guard let plugin = plugin else {+ invoke.reject("Photo library plugin was released")+ onComplete()+ return+ }++ DispatchQueue.global(qos: .userInitiated).async {+ plugin.cleanupStalePhotoLibraryMedia(in: self.stagingDirectory)++ let group = DispatchGroup()+ let lock = NSLock()+ var stagedMedia = Array<StagedPhotoLibraryMedia?>(+ repeating: nil,+ count: results.count+ )+ var firstError: String?++ for (index, result) in results.enumerated() {+ let provider = result.itemProvider+ guard let mediaType = mediaTypeIdentifier(from: provider) else {+ continue+ }++ group.enter()+ provider.loadFileRepresentation(forTypeIdentifier: mediaType.identifier) { url, error in+ defer { group.leave() }++ if let error = error {+ lock.lock()+ firstError = firstError ?? error.localizedDescription+ lock.unlock()+ return+ }++ guard let url = url else {+ lock.lock()+ firstError = firstError ?? "Selected media did not provide a file"+ lock.unlock()+ return+ }++ do {+ let staged = try plugin.stageMediaFile(+ sourceURL: url,+ typeIdentifier: mediaType.identifier,+ suggestedName: provider.suggestedName,+ mediaKind: mediaType.kind,+ stagingDirectory: self.stagingDirectory,+ tokenPrefix: self.tokenPrefix+ )+ lock.lock()+ stagedMedia[index] = staged+ lock.unlock()+ } catch {+ lock.lock()+ firstError = firstError ?? error.localizedDescription+ lock.unlock()+ }+ }+ }++ group.notify(queue: .main) {+ let orderedStagedMedia = stagedMedia.compactMap { $0 }+ if !orderedStagedMedia.isEmpty {+ self.invoke.resolve(orderedStagedMedia)+ } else if let firstError = firstError {+ self.invoke.reject("Failed to stage photo library media: \(firstError)")+ } else {+ self.invoke.resolve([StagedPhotoLibraryMedia]())+ }+ self.onComplete()+ }+ }+ }+}++@available(iOS 14.0, *)+private func topmostPresentableViewController(from root: UIViewController) -> UIViewController? {+ var current = root++ while let presented = current.presentedViewController {+ if presented.isBeingDismissed || presented.isBeingPresented {+ return nil+ }+ current = presented+ }++ if current.isBeingDismissed || current.isBeingPresented || current.view.window == nil {+ return nil+ }++ return current+}++@available(iOS 14.0, *)+private func mediaTypeIdentifier(from provider: NSItemProvider) -> PhotoLibraryMediaType? {+ if let typeIdentifier = videoTypeIdentifier(from: provider) {+ return PhotoLibraryMediaType(identifier: typeIdentifier, kind: .video)+ }++ if let typeIdentifier = imageTypeIdentifier(from: provider) {+ return PhotoLibraryMediaType(identifier: typeIdentifier, kind: .image)+ }++ return nil+}++@available(iOS 14.0, *)+private func imageTypeIdentifier(from provider: NSItemProvider) -> String? {+ preferredTypeIdentifier(+ from: provider,+ preferredTypes: preferredImageTypes(),+ fallbackTypes: [.image]+ )+}++@available(iOS 14.0, *)+private func videoTypeIdentifier(from provider: NSItemProvider) -> String? {+ preferredTypeIdentifier(+ from: provider,+ preferredTypes: preferredVideoTypes(),+ fallbackTypes: [.movie, .video]+ )+}++@available(iOS 14.0, *)+private func preferredImageTypes() -> [UTType] {+ ["jpg", "png", "heic", "heif", "webp", "gif"].compactMap {+ UTType(filenameExtension: $0)+ }+}++@available(iOS 14.0, *)+private func preferredVideoTypes() -> [UTType] {+ var types = ["mp4", "mov", "m4v"].compactMap {+ UTType(filenameExtension: $0)+ }+ types.append(contentsOf: [.mpeg4Movie, .quickTimeMovie, .movie])+ return types+}++@available(iOS 14.0, *)+private func preferredTypeIdentifier(+ from provider: NSItemProvider,+ preferredTypes: [UTType],+ fallbackTypes: [UTType]+) -> String? {+ let fallbackIdentifiers = Set(fallbackTypes.map(\.identifier))+ let concreteRegisteredTypes = provider.registeredTypeIdentifiers.compactMap { identifier -> (String, UTType)? in+ guard !fallbackIdentifiers.contains(identifier), let type = UTType(identifier) else {+ return nil+ }+ return (identifier, type)+ }++ for preferredType in preferredTypes {+ if let match = concreteRegisteredTypes.first(where: { $0.1.conforms(to: preferredType) }) {+ return match.0+ }+ if provider.hasItemConformingToTypeIdentifier(preferredType.identifier) {+ return preferredType.identifier+ }+ }++ for fallbackType in fallbackTypes {+ if let match = concreteRegisteredTypes.first(where: { $0.1.conforms(to: fallbackType) }) {+ return match.0+ }+ }++ for fallbackType in fallbackTypes {+ if provider.hasItemConformingToTypeIdentifier(fallbackType.identifier) {+ return fallbackType.identifier+ }+ }++ return nil+}++@available(iOS 14.0, *)+private func imageType(typeIdentifier: String?, sourceURL: URL) -> UTType? {+ if let sourceType = imageSourceType(from: sourceURL) {+ return sourceType+ }+ if let typeIdentifier = typeIdentifier, let type = UTType(typeIdentifier) {+ return type+ }+ if let type = UTType(filenameExtension: sourceURL.pathExtension) {+ return type+ }+ return nil+}++@available(iOS 14.0, *)+private func mediaType(typeIdentifier: String?, sourceURL: URL) -> UTType? {+ if let typeIdentifier = typeIdentifier, let type = UTType(typeIdentifier) {+ return type+ }+ if let type = UTType(filenameExtension: sourceURL.pathExtension) {+ return type+ }+ return nil+}++@available(iOS 14.0, *)+private func imageSourceType(from sourceURL: URL) -> UTType? {+ guard+ let source = CGImageSourceCreateWithURL(sourceURL as CFURL, nil),+ let typeIdentifier = CGImageSourceGetType(source)+ else {+ return nil+ }++ return UTType(typeIdentifier as String)+}++private func sanitizedMediaFilename(+ _ suggestedName: String?,+ fileExtension: String,+ mediaKind: PhotoLibraryMediaKind+) -> String {+ let fallback: String+ if mediaKind == .video {+ fallback = "photo-library-video"+ } else {+ fallback = "photo-library-image"+ }+ let rawName = suggestedName?.trimmingCharacters(in: .whitespacesAndNewlines)+ let basename = rawName?.isEmpty == false ? rawName! : fallback+ let filename = URL(fileURLWithPath: basename).lastPathComponent+ let nameWithoutExtension = URL(fileURLWithPath: filename)+ .deletingPathExtension()+ .lastPathComponent+ let normalizedName = nameWithoutExtension.isEmpty ? fallback : nameWithoutExtension+ let normalizedExtension = fileExtension.trimmingCharacters(in: .whitespacesAndNewlines)+ let fallbackExtension = mediaKind == .video ? "mov" : "jpg"++ return "\(normalizedName).\(normalizedExtension.isEmpty ? fallbackExtension : normalizedExtension)"+}++@available(iOS 14.0, *)+private func preferredFilenameExtension(+ type: UTType?,+ sourceURL: URL,+ mediaKind: PhotoLibraryMediaKind+) -> String {+ if let fileExtension = type?.preferredFilenameExtension, !fileExtension.isEmpty {+ return fileExtension+ }+ if !sourceURL.pathExtension.isEmpty {+ return sourceURL.pathExtension+ }+ return mediaKind == .video ? "mov" : "jpg"+}++@available(iOS 14.0, *)+private func mimeType(+ type: UTType?,+ sourceURL: URL,+ mediaKind: PhotoLibraryMediaKind+) -> String {+ if let mimeType = type?.preferredMIMEType {+ return mimeType+ }++ switch sourceURL.pathExtension.lowercased() {+ case "jpg", "jpeg":+ return "image/jpeg"+ case "png":+ return "image/png"+ case "gif":+ return "image/gif"+ case "heic", "heif":+ return "image/heic"+ case "webp":+ return "image/webp"+ case "mov", "qt":+ return "video/quicktime"+ case "mp4":+ return "video/mp4"+ case "m4v":+ return "video/x-m4v"+ default:+ return mediaKind == .video ? "video/quicktime" : "application/octet-stream"+ }+}++@available(iOS 14.0, *)+private func isHeicOrHeif(type: UTType?, sourceURL: URL) -> Bool {+ let heicType = UTType(filenameExtension: "heic")+ let heifType = UTType(filenameExtension: "heif")+ if let type = type {+ if let heicType = heicType, type.conforms(to: heicType) {+ return true+ }+ if let heifType = heifType, type.conforms(to: heifType) {+ return true+ }+ }++ switch sourceURL.pathExtension.lowercased() {+ case "heic", "heif":+ return true+ default:+ return false+ }+}++private func photoLibraryError(_ message: String, code: Int) -> NSError {+ NSError(+ domain: "PhotoLibraryPlugin",+ code: code,+ userInfo: [NSLocalizedDescriptionKey: message]+ )+}++@available(iOS 14.0, *)+private func writeJpegImageUsingImageIO(from sourceURL: URL, to targetURL: URL) throws {+ guard let source = CGImageSourceCreateWithURL(sourceURL as CFURL, nil) else {+ throw photoLibraryError("Failed to create image source", code: 1)+ }+ try writeJpegImageSourceUsingImageIO(source, to: targetURL)+}++@available(iOS 14.0, *)+private func writeJpegImageSourceUsingImageIO(_ source: CGImageSource, to targetURL: URL) throws {+ guard CGImageSourceGetCount(source) > 0 else {+ throw photoLibraryError("Selected photo did not contain an image", code: 2)+ }++ guard let destination = CGImageDestinationCreateWithURL(+ targetURL as CFURL,+ UTType.jpeg.identifier as CFString,+ 1,+ nil+ ) else {+ throw photoLibraryError("Failed to create JPEG destination", code: 3)+ }++ guard let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else {+ throw photoLibraryError("Failed to decode selected photo", code: 4)+ }++ let sourceProperties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]+ let destinationProperties: [CFString: Any] = [+ kCGImageDestinationLossyCompressionQuality: 0.92,+ ].merging(sourceProperties ?? [:]) { compressionQuality, _ in+ compressionQuality+ }++ CGImageDestinationAddImage(destination, image, destinationProperties as CFDictionary)++ guard CGImageDestinationFinalize(destination) else {+ throw photoLibraryError("Failed to encode selected photo as JPEG", code: 5)+ }+}++@_cdecl("init_plugin_photo_library")+func initPlugin() -> Plugin {+ if #available(iOS 14.0, *) {+ return PhotoLibraryPlugin()+ }++ return UnavailablePhotoLibraryPlugin()+}diff --git a/js/app/tauri/photo_library_plugin/permissions/autogenerated/commands/pick_photo_library_images.toml b/js/app/tauri/photo_library_plugin/permissions/autogenerated/commands/pick_photo_library_images.tomlnew file mode 100644index 0000000000..11edd8f3c7--- /dev/null+++ b/js/app/tauri/photo_library_plugin/permissions/autogenerated/commands/pick_photo_library_images.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-pick-photo-library-images"+description = "Enables the pick_photo_library_images command without any pre-configured scope."+commands.allow = ["pick_photo_library_images"]++[[permission]]+identifier = "deny-pick-photo-library-images"+description = "Denies the pick_photo_library_images command without any pre-configured scope."+commands.deny = ["pick_photo_library_images"]diff --git a/js/app/tauri/photo_library_plugin/permissions/autogenerated/reference.md b/js/app/tauri/photo_library_plugin/permissions/autogenerated/reference.mdnew file mode 100644index 0000000000..ce1350eeb4--- /dev/null+++ b/js/app/tauri/photo_library_plugin/permissions/autogenerated/reference.md@@ -0,0 +1,35 @@+## Permission Table++<table>+<tr>+<th>Identifier</th>+<th>Description</th>+</tr>+++<tr>+<td>++`photo-library:allow-pick-photo-library-images`++</td>+<td>++Enables the pick_photo_library_images command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`photo-library:deny-pick-photo-library-images`++</td>+<td>++Denies the pick_photo_library_images command without any pre-configured scope.++</td>+</tr>+</table>diff --git a/js/app/tauri/photo_library_plugin/permissions/schemas/schema.json b/js/app/tauri/photo_library_plugin/permissions/schemas/schema.jsonnew file mode 100644index 0000000000..d6c0511978--- /dev/null+++ b/js/app/tauri/photo_library_plugin/permissions/schemas/schema.json@@ -0,0 +1,312 @@+{+ "$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 pick_photo_library_images command without any pre-configured scope.",+ "type": "string",+ "const": "allow-pick-photo-library-images",+ "markdownDescription": "Enables the pick_photo_library_images command without any pre-configured scope."+ },+ {+ "description": "Denies the pick_photo_library_images command without any pre-configured scope.",+ "type": "string",+ "const": "deny-pick-photo-library-images",+ "markdownDescription": "Denies the pick_photo_library_images command without any pre-configured scope."+ }+ ]+ }+ }+}\ No newline at end of filediff --git a/js/app/tauri/photo_library_plugin/src/lib.rs b/js/app/tauri/photo_library_plugin/src/lib.rsnew file mode 100644index 0000000000..2bc8ce215f--- /dev/null+++ b/js/app/tauri/photo_library_plugin/src/lib.rs@@ -0,0 +1,95 @@+use serde::{Deserialize, Serialize};+use tauri::{+ AppHandle, Manager, Runtime, command,+ plugin::{Builder, PluginHandle, TauriPlugin},+};++#[cfg(target_os = "ios")]+tauri::ios_plugin_binding!(init_plugin_photo_library);++#[cfg(target_os = "ios")]+#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct PickPhotoLibraryImagesPayload {+ staging_directory_path: String,+ token_prefix: &'static str,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct StagedPhotoLibraryMedia {+ pub token: String,+ pub name: String,+ pub mime_type: String,+ pub size: u64,+ pub preview_path: String,+}++pub struct PhotoLibrary<R: Runtime>(PluginHandle<R>);++impl<R: Runtime> PhotoLibrary<R> {+ #[cfg(target_os = "ios")]+ fn pick_photo_library_images(+ &self,+ staging_directory_path: String,+ ) -> Result<Vec<StagedPhotoLibraryMedia>, String> {+ self.0+ .run_mobile_plugin(+ "pickPhotoLibraryImages",+ PickPhotoLibraryImagesPayload {+ staging_directory_path,+ token_prefix: staged_upload_constants::PHOTO_LIBRARY_TOKEN_PREFIX,+ },+ )+ .map_err(|error| error.to_string())+ }+}++pub trait PhotoLibraryExt<R: Runtime> {+ fn photo_library(&self) -> &PhotoLibrary<R>;+}++impl<R: Runtime, T: Manager<R>> PhotoLibraryExt<R> for T {+ fn photo_library(&self) -> &PhotoLibrary<R> {+ self.state::<PhotoLibrary<R>>().inner()+ }+}++#[command]+async fn pick_photo_library_images<R: Runtime>(+ app: AppHandle<R>,+) -> Result<Vec<StagedPhotoLibraryMedia>, String> {+ #[cfg(not(target_os = "ios"))]+ {+ let _ = app;+ Err("photo library plugin is only available on iOS".to_string())+ }++ #[cfg(target_os = "ios")]+ {+ let staging_directory_path = app+ .path()+ .app_cache_dir()+ .map_err(|error| format!("failed to resolve app cache directory: {error}"))?+ .join(staged_upload_constants::PHOTO_LIBRARY_STAGING_DIRECTORY_NAME)+ .to_string_lossy()+ .into_owned();++ app.photo_library()+ .pick_photo_library_images(staging_directory_path)+ }+}++pub fn init<R: Runtime>() -> TauriPlugin<R> {+ Builder::new("photo-library")+ .invoke_handler(tauri::generate_handler![pick_photo_library_images])+ .setup(|_app, _api| {+ #[cfg(target_os = "ios")]+ {+ let handle = _api.register_ios_plugin(init_plugin_photo_library)?;+ _app.manage(PhotoLibrary(handle));+ }+ Ok(())+ })+ .build()+}diff --git a/js/app/tauri/src-tauri/Cargo.toml b/js/app/tauri/src-tauri/Cargo.tomlindex c36a308ecb..667efd3d5a 100644--- a/js/app/tauri/src-tauri/Cargo.toml+++ b/js/app/tauri/src-tauri/Cargo.toml@@ -28,6 +28,7 @@ mime_guess = "2"rootcause = { workspace = true }serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"+staged_upload_constants = { path = "../staged_upload_constants" }tracing-oslog = { version = "0.3" }nom = "8.0.0"@@ -71,6 +72,8 @@ tauri-plugin-haptics = "2"[target.'cfg(target_os = "ios")'.dependencies]tauri-plugin-call-kit = { path = "../callkit_plugin" }tauri-plugin-input-accessory = { path = "../input_accessory_plugin" }+tauri-plugin-pasteboard = { path = "../pasteboard_plugin" }+tauri-plugin-photo-library = { path = "../photo_library_plugin" }# Used to call NSFileManager from Rust to get the App Group container path.# This version is already in the dependency tree via wry/tao.objc2 = "0.5"diff --git a/js/app/tauri/src-tauri/capabilities/mobile.json b/js/app/tauri/src-tauri/capabilities/mobile.jsonindex 6263532d1a..0ba3e5bbf3 100644--- a/js/app/tauri/src-tauri/capabilities/mobile.json+++ b/js/app/tauri/src-tauri/capabilities/mobile.json@@ -15,6 +15,8 @@"log:default","auth:allow-authenticate","device-info:default",+ "pasteboard:allow-stage-pasteboard-image",+ "photo-library:allow-pick-photo-library-images","call-kit:allow-get-voip-token","call-kit:allow-end-active-call"]diff --git a/js/app/tauri/src-tauri/gen/apple/ShareExtension/ShareViewController.swift b/js/app/tauri/src-tauri/gen/apple/ShareExtension/ShareViewController.swiftindex 10a15f8f01..8451551328 100644--- a/js/app/tauri/src-tauri/gen/apple/ShareExtension/ShareViewController.swift+++ b/js/app/tauri/src-tauri/gen/apple/ShareExtension/ShareViewController.swift@@ -1,3 +1,4 @@+import ImageIOimport UIKitimport UniformTypeIdentifiers@@ -5,6 +6,8 @@ class ShareViewController: UIViewController {private let appGroupId = "group.com.macro.app.prod"private let appURLScheme = "macro"+ private var timeoutWorkItem: DispatchWorkItem?+ private var didComplete = false// MARK: - Lifecycle@@ -14,10 +17,7 @@ class ShareViewController: UIViewController {// before it has a chance to do anything. Use a near-transparent scrim instead.view.backgroundColor = UIColor.black.withAlphaComponent(0.01)- DispatchQueue.main.asyncAfter(deadline: .now() + 15) { [weak self] in- self?.complete()- }-+ scheduleTimeout()processSharedItems()}@@ -34,80 +34,90 @@ class ShareViewController: UIViewController {}let group = DispatchGroup()- var savedFilenames: [String] = []+ var savedFilenames = Array<String?>(repeating: nil, count: attachments.count)let lock = NSLock()- for provider in attachments {- let imageType = UTType.image.identifier- let movieType = UTType.movie.identifier+ for (index, provider) in attachments.enumerated() {let urlType = UTType.url.identifier- if provider.hasItemConformingToTypeIdentifier(imageType) {+ if let imageType = mediaTypeIdentifier(from: provider, conformingTo: .image) {group.enter()- loadData(from: provider, typeIdentifier: imageType, defaultExt: "jpg") { [weak self] data, ext in+ loadImage(from: provider, typeIdentifier: imageType) { name indefer { group.leave() }- if let data, let name = self?.saveToAppGroup(data: data, ext: ext) {- lock.withLock { savedFilenames.append(name) }+ if let name = name {+ lock.withLock { savedFilenames[index] = name }}}- } else if provider.hasItemConformingToTypeIdentifier(movieType) {+ } else if let movieType = mediaTypeIdentifier(from: provider, conformingTo: .movie) {group.enter()- loadData(from: provider, typeIdentifier: movieType, defaultExt: "mp4") { [weak self] data, ext in+ loadMovie(from: provider, typeIdentifier: movieType) { name indefer { group.leave() }- if let data, let name = self?.saveToAppGroup(data: data, ext: ext) {- lock.withLock { savedFilenames.append(name) }+ if let name = name {+ lock.withLock { savedFilenames[index] = name }}}} else if provider.hasItemConformingToTypeIdentifier(urlType) {group.enter()loadURLData(from: provider, typeIdentifier: urlType) { [weak self] data indefer { group.leave() }- if let data, let name = self?.saveToAppGroup(data: data, ext: "url") {- lock.withLock { savedFilenames.append(name) }+ if let data = data, let name = self?.saveToAppGroup(data: data, ext: "url") {+ lock.withLock { savedFilenames[index] = name }}}}}group.notify(queue: .main) { [weak self] in- guard let self else { return }- if savedFilenames.isEmpty {+ guard let self = self else { return }+ let orderedFilenames = savedFilenames.compactMap { $0 }+ if orderedFilenames.isEmpty {self.complete()} else {- self.openMainApp(filenames: savedFilenames)+ self.openMainApp(filenames: orderedFilenames)}}}// MARK: - Data loading- /// Load raw data from an NSItemProvider.- /// Uses loadDataRepresentation (designed for Share Extensions) and falls back- /// to loadItem if that fails.- private func loadData(+ private func loadImage(from provider: NSItemProvider,typeIdentifier: String,- defaultExt: String,- completion: @escaping (Data?, String) -> Void+ completion: @escaping (String?) -> Void) {- provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { data, _ in- if let data {- completion(data, defaultExt)+ provider.loadFileRepresentation(forTypeIdentifier: typeIdentifier) { [weak self] url, _ in+ guard let self = self else {+ completion(nil)+ return+ }++ if let url = url {+ completion(self.saveImageToAppGroup(sourceURL: url, typeIdentifier: typeIdentifier))+ return+ }++ self.loadImageItemFallback(from: provider, typeIdentifier: typeIdentifier, completion: completion)+ }+ }++ private func loadMovie(+ from provider: NSItemProvider,+ typeIdentifier: String,+ completion: @escaping (String?) -> Void+ ) {+ provider.loadFileRepresentation(forTypeIdentifier: typeIdentifier) { [weak self] url, _ in+ guard let self = self else {+ completion(nil)+ return+ }++ if let url = url {+ completion(self.saveMovieToAppGroup(sourceURL: url, typeIdentifier: typeIdentifier))return}- // Fallback: loadItem covers UIImage / NSURL pathsprovider.loadItem(forTypeIdentifier: typeIdentifier, options: nil) { item, _ in- if let url = item as? URL, url.isFileURL {- let ext = url.pathExtension.isEmpty ? defaultExt : url.pathExtension- completion(try? Data(contentsOf: url), ext)- } else if let image = item as? UIImage {- completion(image.jpegData(compressionQuality: 0.9), "jpg")- } else if let rawData = item as? Data {- completion(rawData, defaultExt)- } else {- completion(nil, defaultExt)- }+ completion(self.saveMovieItemFallback(item, typeIdentifier: typeIdentifier))}}}@@ -136,18 +146,53 @@ class ShareViewController: UIViewController {// MARK: - App Group storage+ private func saveImageToAppGroup(sourceURL: URL, typeIdentifier: String) -> String? {+ let type = imageType(typeIdentifier: typeIdentifier, sourceURL: sourceURL)+ let shouldConvertToJpeg = isHeicOrHeif(type: type, sourceURL: sourceURL)+ let ext = shouldConvertToJpeg+ ? "jpg"+ : preferredFilenameExtension(type: type, sourceURL: sourceURL, fallback: "jpg")++ guard let target = makeAppGroupFileURL(ext: ext) else {+ return nil+ }++ do {+ if shouldConvertToJpeg {+ try writeJpegImageUsingImageIO(from: sourceURL, to: target.url)+ } else {+ try copyFile(sourceURL, to: target.url)+ }+ return target.filename+ } catch {+ return nil+ }+ }++ private func saveMovieToAppGroup(sourceURL: URL, typeIdentifier: String) -> String? {+ let type = mediaType(typeIdentifier: typeIdentifier, sourceURL: sourceURL)+ let ext = preferredFilenameExtension(type: type, sourceURL: sourceURL, fallback: "mov")++ guard let target = makeAppGroupFileURL(ext: ext) else {+ return nil+ }++ do {+ try copyFile(sourceURL, to: target.url)+ return target.filename+ } catch {+ return nil+ }+ }+private func saveToAppGroup(data: Data, ext: String) -> String? {- guard let container = FileManager.default.containerURL(- forSecurityApplicationGroupIdentifier: appGroupId- ) else {+ guard let target = makeAppGroupFileURL(ext: ext) else {return nil}- let filename = "share_\(UUID().uuidString).\(ext)"- let fileURL = container.appendingPathComponent(filename)do {- try data.write(to: fileURL)- return filename+ try data.write(to: target.url, options: [.atomic])+ return target.filename} catch {return nil}@@ -192,7 +237,315 @@ class ShareViewController: UIViewController {// MARK: - Helpers+ private func mediaTypeIdentifier(from provider: NSItemProvider, conformingTo type: UTType) -> String? {+ let preferredTypes = type.conforms(to: .image)+ ? preferredImageTypes()+ : preferredMovieTypes()+ return preferredTypeIdentifier(+ from: provider,+ preferredTypes: preferredTypes,+ fallbackType: type+ )+ }++ private func preferredImageTypes() -> [UTType] {+ ["jpg", "png", "heic", "heif", "webp", "gif"].compactMap {+ UTType(filenameExtension: $0)+ }+ }++ private func preferredMovieTypes() -> [UTType] {+ ["mov", "mp4"].compactMap {+ UTType(filenameExtension: $0)+ }+ }++ private func preferredTypeIdentifier(+ from provider: NSItemProvider,+ preferredTypes: [UTType],+ fallbackType: UTType+ ) -> String? {+ let concreteRegisteredTypes = provider.registeredTypeIdentifiers.compactMap { identifier -> (String, UTType)? in+ guard identifier != fallbackType.identifier, let type = UTType(identifier) else {+ return nil+ }+ return (identifier, type)+ }++ for preferredType in preferredTypes {+ if let match = concreteRegisteredTypes.first(where: { $0.1.conforms(to: preferredType) }) {+ return match.0+ }+ if provider.hasItemConformingToTypeIdentifier(preferredType.identifier) {+ return preferredType.identifier+ }+ }++ if let match = concreteRegisteredTypes.first(where: { $0.1.conforms(to: fallbackType) }) {+ return match.0+ }++ return provider.hasItemConformingToTypeIdentifier(fallbackType.identifier)+ ? fallbackType.identifier+ : nil+ }++ private func imageType(typeIdentifier: String, sourceURL: URL) -> UTType? {+ if let sourceType = imageSourceType(from: sourceURL) {+ return sourceType+ }+ return mediaType(typeIdentifier: typeIdentifier, sourceURL: sourceURL)+ }++ private func imageType(typeIdentifier: String, data: Data) -> UTType? {+ if let sourceType = imageSourceType(from: data) {+ return sourceType+ }+ return UTType(typeIdentifier)+ }++ private func mediaType(typeIdentifier: String, sourceURL: URL) -> UTType? {+ if let type = UTType(typeIdentifier) {+ return type+ }+ if let type = UTType(filenameExtension: sourceURL.pathExtension) {+ return type+ }+ return nil+ }++ private func imageSourceType(from sourceURL: URL) -> UTType? {+ guard+ let source = CGImageSourceCreateWithURL(sourceURL as CFURL, nil),+ let typeIdentifier = CGImageSourceGetType(source)+ else {+ return nil+ }++ return UTType(typeIdentifier as String)+ }++ private func imageSourceType(from data: Data) -> UTType? {+ guard+ let source = CGImageSourceCreateWithData(data as CFData, nil),+ let typeIdentifier = CGImageSourceGetType(source)+ else {+ return nil+ }++ return UTType(typeIdentifier as String)+ }++ private func preferredFilenameExtension(type: UTType?, sourceURL: URL, fallback: String) -> String {+ if let ext = type?.preferredFilenameExtension, !ext.isEmpty {+ return ext+ }+ if !sourceURL.pathExtension.isEmpty {+ return sourceURL.pathExtension+ }+ return fallback+ }++ private func isHeicOrHeif(type: UTType?, sourceURL: URL) -> Bool {+ let heicType = UTType(filenameExtension: "heic")+ let heifType = UTType(filenameExtension: "heif")+ if let type = type {+ if let heicType = heicType, type.conforms(to: heicType) {+ return true+ }+ if let heifType = heifType, type.conforms(to: heifType) {+ return true+ }+ }++ switch sourceURL.pathExtension.lowercased() {+ case "heic", "heif":+ return true+ default:+ return false+ }+ }++ private func loadImageItemFallback(+ from provider: NSItemProvider,+ typeIdentifier: String,+ completion: @escaping (String?) -> Void+ ) {+ provider.loadItem(forTypeIdentifier: typeIdentifier, options: nil) { [weak self] item, _ in+ completion(self?.saveImageItemFallback(item, typeIdentifier: typeIdentifier))+ }+ }++ private func saveImageItemFallback(_ item: NSSecureCoding?, typeIdentifier: String) -> String? {+ if let url = item as? URL, url.isFileURL {+ return saveImageToAppGroup(sourceURL: url, typeIdentifier: typeIdentifier)+ }++ if let image = item as? UIImage {+ return saveUIImageToAppGroup(image)+ }++ if let data = item as? Data {+ let type = imageType(typeIdentifier: typeIdentifier, data: data)+ if isHeicOrHeif(type: type, sourceURL: URL(fileURLWithPath: "")) {+ return saveHeicDataAsJpegToAppGroup(data)+ }++ let ext = preferredFilenameExtension(type: type, sourceURL: URL(fileURLWithPath: ""), fallback: "jpg")+ return saveToAppGroup(data: data, ext: ext)+ }++ return nil+ }++ private func saveMovieItemFallback(_ item: NSSecureCoding?, typeIdentifier: String) -> String? {+ if let url = item as? URL, url.isFileURL {+ return saveMovieToAppGroup(sourceURL: url, typeIdentifier: typeIdentifier)+ }++ if let data = item as? Data {+ let ext = preferredFilenameExtension(+ type: UTType(typeIdentifier),+ sourceURL: URL(fileURLWithPath: ""),+ fallback: "mov"+ )+ return saveToAppGroup(data: data, ext: ext)+ }++ return nil+ }++ private func saveUIImageToAppGroup(_ image: UIImage) -> String? {+ if imageHasAlpha(image), let data = image.pngData() {+ return saveToAppGroup(data: data, ext: "png")+ }++ guard let data = image.jpegData(compressionQuality: 0.92) else {+ return nil+ }+ return saveToAppGroup(data: data, ext: "jpg")+ }++ private func saveHeicDataAsJpegToAppGroup(_ data: Data) -> String? {+ guard let target = makeAppGroupFileURL(ext: "jpg") else {+ return nil+ }++ do {+ try writeJpegImageUsingImageIO(from: data, to: target.url)+ return target.filename+ } catch {+ return nil+ }+ }++ private func makeAppGroupFileURL(ext: String) -> (filename: String, url: URL)? {+ guard let container = FileManager.default.containerURL(+ forSecurityApplicationGroupIdentifier: appGroupId+ ) else {+ return nil+ }++ let normalizedExt = normalizedFilenameExtension(ext)+ let filename = "share_\(UUID().uuidString).\(normalizedExt)"+ return (filename, container.appendingPathComponent(filename))+ }++ private func normalizedFilenameExtension(_ ext: String) -> String {+ let raw = ext+ .trimmingCharacters(in: .whitespacesAndNewlines)+ .trimmingCharacters(in: CharacterSet(charactersIn: "."))+ .lowercased()+ let filtered = raw.filter { character in+ character.isLetter || character.isNumber+ }+ return filtered.isEmpty ? "bin" : String(filtered)+ }++ private func copyFile(_ sourceURL: URL, to targetURL: URL) throws {+ if FileManager.default.fileExists(atPath: targetURL.path) {+ try FileManager.default.removeItem(at: targetURL)+ }+ try FileManager.default.copyItem(at: sourceURL, to: targetURL)+ }++ private func writeJpegImageUsingImageIO(from sourceURL: URL, to targetURL: URL) throws {+ guard let source = CGImageSourceCreateWithURL(sourceURL as CFURL, nil) else {+ throw shareExtensionError("Failed to create image source", code: 1)+ }+ try writeJpegImageSourceUsingImageIO(source, to: targetURL)+ }++ private func writeJpegImageUsingImageIO(from data: Data, to targetURL: URL) throws {+ guard let source = CGImageSourceCreateWithData(data as CFData, nil) else {+ throw shareExtensionError("Failed to create image source", code: 2)+ }+ try writeJpegImageSourceUsingImageIO(source, to: targetURL)+ }++ private func writeJpegImageSourceUsingImageIO(_ source: CGImageSource, to targetURL: URL) throws {+ guard CGImageSourceGetCount(source) > 0 else {+ throw shareExtensionError("Shared image did not contain an image", code: 3)+ }++ guard let destination = CGImageDestinationCreateWithURL(+ targetURL as CFURL,+ UTType.jpeg.identifier as CFString,+ 1,+ nil+ ) else {+ throw shareExtensionError("Failed to create JPEG destination", code: 4)+ }++ guard let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else {+ throw shareExtensionError("Failed to decode shared image", code: 5)+ }++ let sourceProperties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]+ let destinationProperties: [CFString: Any] = [+ kCGImageDestinationLossyCompressionQuality: 0.92,+ ].merging(sourceProperties ?? [:]) { compressionQuality, _ in+ compressionQuality+ }++ CGImageDestinationAddImage(destination, image, destinationProperties as CFDictionary)++ guard CGImageDestinationFinalize(destination) else {+ throw shareExtensionError("Failed to encode shared image as JPEG", code: 6)+ }+ }++ private func shareExtensionError(_ message: String, code: Int) -> NSError {+ NSError(+ domain: "ShareExtension",+ code: code,+ userInfo: [NSLocalizedDescriptionKey: message]+ )+ }++ private func imageHasAlpha(_ image: UIImage) -> Bool {+ guard let alphaInfo = image.cgImage?.alphaInfo else { return false }+ switch alphaInfo {+ case .first, .last, .premultipliedFirst, .premultipliedLast:+ return true+ default:+ return false+ }+ }++ private func scheduleTimeout() {+ let workItem = DispatchWorkItem { [weak self] in+ self?.complete()+ }+ timeoutWorkItem = workItem+ DispatchQueue.main.asyncAfter(deadline: .now() + 30, execute: workItem)+ }+private func complete() {+ guard !didComplete else { return }+ didComplete = true+ timeoutWorkItem?.cancel()+ timeoutWorkItem = nilextensionContext?.completeRequest(returningItems: [], completionHandler: nil)}}diff --git a/js/app/tauri/src-tauri/src/lib.rs b/js/app/tauri/src-tauri/src/lib.rsindex 4c4665ddf0..e603e2158c 100644--- a/js/app/tauri/src-tauri/src/lib.rs+++ b/js/app/tauri/src-tauri/src/lib.rs@@ -7,10 +7,10 @@ use reqwest::header::{COOKIE, ORIGIN};use rootcause::{Report, report};use serde::Serialize;use share_target::{- PendingShareFilesState, cleanup_stale_staged_shared_files, clear_shared_files,- get_pending_share_filenames, maybe_handle_share_deep_link, pop_shared_files,- read_shared_file_text, upload_shared_file_to_presigned_url,+ PendingShareFilesState, clear_shared_files, get_pending_share_filenames,+ maybe_handle_share_deep_link, pop_shared_files, read_shared_file_text,};+use staged_upload::cleanup_stale_staged_files;use tauri::http::{HeaderMap, HeaderValue};use tauri::{AppHandle, Emitter, Manager, RunEvent, Runtime};@@ -23,6 +23,7 @@ use tracing_subscriber::util::SubscriberInitExt;use url::Url;mod share_target;+mod staged_upload;/// This module provides debuging utilities and should not be compiled in prodiction builds#[cfg(debug_assertions)] // do not remove this@@ -97,6 +98,8 @@ pub fn run() {builder = builder.plugin(tauri_plugin_haptics::init()).plugin(tauri_plugin_input_accessory::init())+ .plugin(tauri_plugin_pasteboard::init())+ .plugin(tauri_plugin_photo_library::init()).plugin(tauri_plugin_call_kit::init());}@@ -191,8 +194,8 @@ pub fn run() {get_pending_share_filenames,pop_shared_files,clear_shared_files,- upload_shared_file_to_presigned_url,read_shared_file_text,+ staged_upload::upload_staged_file_to_presigned_url,]).setup(|app| {// Restore persisted bundle root on startup@@ -219,7 +222,7 @@ pub fn run() {}app.chain(attach_deep_link_handler);- cleanup_stale_staged_shared_files(&app.handle());+ cleanup_stale_staged_files(&app.handle());Ok(())})diff --git a/js/app/tauri/src-tauri/src/share_target.rs b/js/app/tauri/src-tauri/src/share_target.rsindex a9e124b206..e871d8cf8a 100644--- a/js/app/tauri/src-tauri/src/share_target.rs+++ b/js/app/tauri/src-tauri/src/share_target.rs@@ -43,8 +43,6 @@ pub(crate) struct StagedSharedFile {}pub(crate) trait ShareTargetPlatform {- fn cleanup_stale_staged_shared_files(app: &AppHandle);-fn get_pending_share_filenames(app: AppHandle, state: &PendingShareFilesState) -> Vec<String>;fn pop_shared_files(@@ -55,13 +53,6 @@ pub(crate) trait ShareTargetPlatform {fn clear_shared_files(app: AppHandle, tokens: Vec<String>) -> Result<(), String>;- async fn upload_shared_file_to_presigned_url(- app: AppHandle,- token: String,- upload_url: String,- mime_type: String,- ) -> Result<(), String>;-async fn read_shared_file_text(app: AppHandle, token: String) -> Result<String, String>;fn maybe_handle_share_deep_link(handle: &AppHandle, url: &Url) -> bool;@@ -79,10 +70,6 @@ fn remaining_pending_share_filenames(.collect()}-pub(crate) fn cleanup_stale_staged_shared_files(app: &AppHandle) {- ShareTargetPlatformImpl::cleanup_stale_staged_shared_files(app);-}-#[tauri::command]pub(crate) fn get_pending_share_filenames(app: AppHandle,@@ -111,19 +98,6 @@ pub(crate) fn clear_shared_files(app: AppHandle, tokens: Vec<String>) -> Result<ShareTargetPlatformImpl::clear_shared_files(app, tokens)}-/// Tauri command: upload a staged shared file directly to a presigned URL-/// without copying the file through JS memory.-#[tauri::command]-pub(crate) async fn upload_shared_file_to_presigned_url(- app: AppHandle,- token: String,- upload_url: String,- mime_type: String,-) -> Result<(), String> {- ShareTargetPlatformImpl::upload_shared_file_to_presigned_url(app, token, upload_url, mime_type)- .await-}-#[tauri::command]pub(crate) async fn read_shared_file_text(app: AppHandle, token: String) -> Result<String, String> {ShareTargetPlatformImpl::read_shared_file_text(app, token).awaitdiff --git a/js/app/tauri/src-tauri/src/share_target/ios.rs b/js/app/tauri/src-tauri/src/share_target/ios.rsindex f1ab13edb3..c29986a0b2 100644--- a/js/app/tauri/src-tauri/src/share_target/ios.rs+++ b/js/app/tauri/src-tauri/src/share_target/ios.rs@@ -3,12 +3,16 @@ use super::shared::{sanitize_shared_filename, share_filenames_from_url,};use super::{PendingShareFilesState, ShareTargetPlatform, StagedSharedFile};-use crate::APP_SCHEME;+use crate::{+ APP_SCHEME,+ staged_upload::{+ StagedUploadSource, next_stage_token, staged_file_path, staged_file_path_for_name,+ },+};use serde::Serialize;use tauri::{AppHandle, Emitter, Manager};use tauri_plugin_deep_link::DeepLinkExt;use url::Url;-use uuid::Uuid;pub(super) struct ShareTargetPlatformImpl;@@ -17,8 +21,6 @@ struct ShareFilesReadyPayload {filenames: Vec<String>,}-const SHARED_FILE_STAGING_DIR_NAME: &str = "ios-share-staging";-const STALE_SHARED_FILE_TTL_SECS: u64 = 60 * 60 * 24;/// Returns the filesystem path of the shared App Group container used to/// exchange files between the Share Extension and the main app./// Calls NSFileManager directly via the objc2 runtime — no FFI to main.mm needed.@@ -60,70 +62,6 @@ fn ios_app_group_container_path() -> Option<String> {})}-fn shared_file_staging_dir(app: &AppHandle) -> Result<std::path::PathBuf, String> {- let dir = app- .path()- .app_cache_dir()- .map_err(|error| format!("failed to resolve app cache directory: {error}"))?- .join(SHARED_FILE_STAGING_DIR_NAME);- std::fs::create_dir_all(&dir)- .map_err(|error| format!("failed to create shared file staging directory: {error}"))?;- Ok(dir)-}--fn next_shared_file_stage_token() -> String {- format!("share-stage-{}", Uuid::new_v4().simple())-}--fn sanitize_shared_file_stage_token(token: &str) -> Option<&str> {- let valid = !token.is_empty()- && token.len() <= 128- && token.bytes().all(|byte| {- matches!(- byte,- b'0'..=b'9' | b'a'..=b'z' | b'A'..=b'Z' | b'-' | b'_'- )- });- valid.then_some(token)-}--fn staged_shared_file_path_for_name(- app: &AppHandle,- token: &str,- source_name: &str,-) -> Result<std::path::PathBuf, String> {- let token = sanitize_shared_file_stage_token(token)- .ok_or_else(|| "invalid shared file staging token".to_string())?;- let source_name = sanitize_shared_filename(source_name)- .ok_or_else(|| "invalid shared file staging source name".to_string())?;- Ok(shared_file_staging_dir(app)?.join(format!("{token}-{source_name}")))-}--fn staged_shared_file_path(app: &AppHandle, token: &str) -> Result<std::path::PathBuf, String> {- let token = sanitize_shared_file_stage_token(token)- .ok_or_else(|| "invalid shared file staging token".to_string())?;- let staging_dir = shared_file_staging_dir(app)?;- let legacy_path = staging_dir.join(token);- if legacy_path.is_file() {- return Ok(legacy_path);- }-- let prefix = format!("{token}-");- let entries = std::fs::read_dir(&staging_dir)- .map_err(|error| format!("failed to read shared file staging directory: {error}"))?;-- for entry in entries {- let entry =- entry.map_err(|error| format!("failed to inspect staged shared file: {error}"))?;- let file_name = entry.file_name();- if file_name.to_string_lossy().starts_with(&prefix) {- return Ok(entry.path());- }- }-- Err(STAGED_SHARED_FILE_NOT_FOUND_ERROR.to_string())-}-fn move_file_to_path(source: &std::path::Path, target: &std::path::Path) -> std::io::Result<()> {match std::fs::rename(source, target) {Ok(()) => Ok(()),@@ -139,8 +77,11 @@ fn stage_shared_file(source_path: &std::path::Path,source_name: &str,) -> Result<StagedSharedFile, String> {- let token = next_shared_file_stage_token();- let staged_path = staged_shared_file_path_for_name(app, &token, source_name)?;+ let token = next_stage_token(StagedUploadSource::Share);+ let source_name = sanitize_shared_filename(source_name)+ .ok_or_else(|| "invalid shared file staging source name".to_string())?;+ let staged_path =+ staged_file_path_for_name(app, StagedUploadSource::Share, &token, source_name)?;let mime_type = mime_type_from_path(source_path).to_string();let size = std::fs::metadata(source_path).map_err(|error| format!("failed to read shared file metadata: {error}"))?@@ -160,43 +101,6 @@ fn stage_shared_file(})}-fn cleanup_stale_staged_shared_files(app: &AppHandle) {- let Ok(staging_dir) = app- .path()- .app_cache_dir()- .map(|dir| dir.join(SHARED_FILE_STAGING_DIR_NAME))- else {- return;- };-- let Ok(entries) = std::fs::read_dir(&staging_dir) else {- return;- };-- let cutoff = std::time::SystemTime::now()- .checked_sub(std::time::Duration::from_secs(STALE_SHARED_FILE_TTL_SECS))- .unwrap_or(std::time::UNIX_EPOCH);-- for entry in entries.flatten() {- let Ok(metadata) = entry.metadata() else {- continue;- };-- if !metadata.is_file() {- continue;- }-- let modified = metadata.modified().or_else(|_| metadata.created());- let should_remove = modified.map(|time| time < cutoff).unwrap_or(false);-- if should_remove {- let _ = std::fs::remove_file(entry.path());- }- }-- let _ = std::fs::remove_dir(staging_dir);-}-fn consume_pending_share_filenames(container_path: &std::path::Path,state: &PendingShareFilesState,@@ -245,10 +149,6 @@ fn mime_type_from_path(path: &std::path::Path) -> &'static str {}impl ShareTargetPlatform for ShareTargetPlatformImpl {- fn cleanup_stale_staged_shared_files(app: &AppHandle) {- cleanup_stale_staged_shared_files(app);- }-fn get_pending_share_filenames(app: AppHandle, state: &PendingShareFilesState) -> Vec<String> {let pending = state.with_data(|f| f.clone());@@ -338,7 +238,7 @@ impl ShareTargetPlatform for ShareTargetPlatformImpl {fn clear_shared_files(app: AppHandle, tokens: Vec<String>) -> Result<(), String> {for token in tokens {- let path = match staged_shared_file_path(&app, &token) {+ let path = match staged_file_path(&app, StagedUploadSource::Share, &token) {Ok(path) => path,Err(error) if is_staged_shared_file_not_found_error(&error) => continue,Err(error) => return Err(error),@@ -352,77 +252,8 @@ impl ShareTargetPlatform for ShareTargetPlatformImpl {Ok(())}- async fn upload_shared_file_to_presigned_url(- app: AppHandle,- token: String,- upload_url: String,- mime_type: String,- ) -> Result<(), String> {- use reqwest::header::{CONTENT_LENGTH, CONTENT_TYPE};-- let upload_url = Url::parse(&upload_url)- .map_err(|error| format!("invalid shared file upload URL: {error}"))?;- if !matches!(upload_url.scheme(), "http" | "https") {- return Err("invalid shared file upload URL scheme".to_string());- }-- let path = staged_shared_file_path(&app, &token)?;- let file = tokio::fs::File::open(&path)- .await- .map_err(|error| format!("failed to open staged shared file: {error}"))?;- let size = file- .metadata()- .await- .map_err(|error| format!("failed to read staged shared file metadata: {error}"))?- .len();-- let body = reqwest::Body::wrap_stream(tokio_util::io::ReaderStream::new(file));- let client = reqwest::Client::builder()- .connect_timeout(std::time::Duration::from_secs(30))- .timeout(std::time::Duration::from_secs(300))- .build()- .map_err(|error| format!("failed to build HTTP client: {error}"))?;- let mut request = client.put(upload_url).body(body);-- if !mime_type.is_empty() {- request = request.header(CONTENT_TYPE, mime_type);- }-- let response = request- .header(CONTENT_LENGTH, size.to_string())- .send()- .await- .map_err(|error| format!("failed to upload staged shared file: {error}"))?;-- let status = response.status();- if !status.is_success() {- let detail = response.text().await.unwrap_or_default();- if detail.trim().is_empty() {- return Err(format!(- "failed to upload staged shared file: HTTP {status}"- ));- }- return Err(format!(- "failed to upload staged shared file: HTTP {status}: {}",- detail.trim()- ));- }-- if let Err(error) = tokio::fs::remove_file(&path).await- && error.kind() != std::io::ErrorKind::NotFound- {- tracing::warn!(- "failed to delete staged shared file after upload {}: {}",- path.display(),- error- );- }-- Ok(())- }-async fn read_shared_file_text(app: AppHandle, token: String) -> Result<String, String> {- let path = staged_shared_file_path(&app, &token)?;+ let path = staged_file_path(&app, StagedUploadSource::Share, &token)?;tokio::task::spawn_blocking(move || {std::fs::read_to_string(&path).map_err(|error| format!("failed to read staged shared text file: {error}"))diff --git a/js/app/tauri/src-tauri/src/share_target/noop.rs b/js/app/tauri/src-tauri/src/share_target/noop.rsindex 1ebda6be91..d8ed3843f3 100644--- a/js/app/tauri/src-tauri/src/share_target/noop.rs+++ b/js/app/tauri/src-tauri/src/share_target/noop.rs@@ -5,8 +5,6 @@ use url::Url;pub(super) struct ShareTargetPlatformImpl;impl ShareTargetPlatform for ShareTargetPlatformImpl {- fn cleanup_stale_staged_shared_files(_app: &AppHandle) {}-fn get_pending_share_filenames(_app: AppHandle, state: &PendingShareFilesState) -> Vec<String> {state.with_data(|d| d.clone())}@@ -23,15 +21,6 @@ impl ShareTargetPlatform for ShareTargetPlatformImpl {Ok(())}- async fn upload_shared_file_to_presigned_url(- _app: AppHandle,- _token: String,- _upload_url: String,- _mime_type: String,- ) -> Result<(), String> {- Ok(())- }-async fn read_shared_file_text(_app: AppHandle, _token: String) -> Result<String, String> {Ok(String::new())}diff --git a/js/app/tauri/src-tauri/src/staged_upload.rs b/js/app/tauri/src-tauri/src/staged_upload.rsnew file mode 100644index 0000000000..b1ffea0a7e--- /dev/null+++ b/js/app/tauri/src-tauri/src/staged_upload.rs@@ -0,0 +1,269 @@+use reqwest::header::{CONTENT_LENGTH, CONTENT_TYPE};+use serde::Deserialize;+use staged_upload_constants::{+ PASTEBOARD_STAGING_DIRECTORY_NAME, PASTEBOARD_TOKEN_PREFIX,+ PHOTO_LIBRARY_STAGING_DIRECTORY_NAME, PHOTO_LIBRARY_TOKEN_PREFIX,+};+use std::path::{Path, PathBuf};+use tauri::AppHandle;+use tauri::Manager;+use url::Url;+#[cfg(target_os = "ios")]+use uuid::Uuid;++const STAGED_FILE_TTL_SECS: u64 = 60 * 60 * 24;++#[derive(Clone, Copy, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub(crate) enum StagedUploadSource {+ Share,+ Pasteboard,+ PhotoLibrary,+}++impl StagedUploadSource {+ const ALL: [Self; 3] = [Self::Share, Self::Pasteboard, Self::PhotoLibrary];++ fn directory_name(self) -> &'static str {+ match self {+ Self::Share => "ios-share-staging",+ Self::Pasteboard => PASTEBOARD_STAGING_DIRECTORY_NAME,+ Self::PhotoLibrary => PHOTO_LIBRARY_STAGING_DIRECTORY_NAME,+ }+ }++ fn token_prefix(self) -> &'static str {+ match self {+ Self::Share => "share-stage-",+ Self::Pasteboard => PASTEBOARD_TOKEN_PREFIX,+ Self::PhotoLibrary => PHOTO_LIBRARY_TOKEN_PREFIX,+ }+ }++ fn description(self) -> &'static str {+ match self {+ Self::Share => "staged shared file",+ Self::Pasteboard => "staged pasteboard image",+ Self::PhotoLibrary => "staged photo library media",+ }+ }++ fn not_found_error(self) -> &'static str {+ match self {+ Self::Share => "staged shared file not found",+ Self::Pasteboard => "staged pasteboard image not found",+ Self::PhotoLibrary => "staged photo library media not found",+ }+ }+}++#[cfg(target_os = "ios")]+pub(crate) fn next_stage_token(source: StagedUploadSource) -> String {+ format!("{}{}", source.token_prefix(), Uuid::new_v4().simple())+}++fn is_valid_stage_token(source: StagedUploadSource, token: &str) -> bool {+ token.starts_with(source.token_prefix())+ && token.len() <= 128+ && token.bytes().all(|byte| {+ matches!(+ byte,+ b'0'..=b'9' | b'a'..=b'z' | b'A'..=b'Z' | b'-' | b'_'+ )+ })+}++pub(crate) fn staging_dir_path(+ app: &AppHandle,+ source: StagedUploadSource,+) -> Result<PathBuf, String> {+ Ok(app+ .path()+ .app_cache_dir()+ .map_err(|error| format!("failed to resolve app cache directory: {error}"))?+ .join(source.directory_name()))+}++pub(crate) fn cleanup_stale_staged_files(app: &AppHandle) {+ for source in StagedUploadSource::ALL {+ cleanup_stale_staged_files_for(app, source);+ }+}++fn cleanup_stale_staged_files_for(app: &AppHandle, source: StagedUploadSource) {+ let Ok(staging_dir) = staging_dir_path(app, source) else {+ return;+ };++ let Ok(entries) = std::fs::read_dir(&staging_dir) else {+ return;+ };++ let cutoff = std::time::SystemTime::now()+ .checked_sub(std::time::Duration::from_secs(STAGED_FILE_TTL_SECS))+ .unwrap_or(std::time::UNIX_EPOCH);++ for entry in entries.flatten() {+ let Ok(metadata) = entry.metadata() else {+ continue;+ };++ if !metadata.is_file() {+ continue;+ }++ let modified = metadata.modified().or_else(|_| metadata.created());+ let should_remove = modified.map(|time| time < cutoff).unwrap_or(false);++ if should_remove {+ let _ = std::fs::remove_file(entry.path());+ }+ }++ let _ = std::fs::remove_dir(staging_dir);+}++fn ensure_staging_dir(app: &AppHandle, source: StagedUploadSource) -> Result<PathBuf, String> {+ let dir = staging_dir_path(app, source)?;+ std::fs::create_dir_all(&dir).map_err(|error| {+ format!(+ "failed to create {} directory: {error}",+ source.description()+ )+ })?;+ Ok(dir)+}++#[cfg(target_os = "ios")]+pub(crate) fn staged_file_path_for_name(+ app: &AppHandle,+ source: StagedUploadSource,+ token: &str,+ source_name: &str,+) -> Result<PathBuf, String> {+ if !is_valid_stage_token(source, token) {+ return Err(format!("invalid {} token", source.description()));+ }++ let file_name = std::path::Path::new(source_name)+ .file_name()+ .and_then(|file_name| file_name.to_str())+ .filter(|file_name| *file_name == source_name)+ .ok_or_else(|| format!("invalid {} source name", source.description()))?;++ Ok(ensure_staging_dir(app, source)?.join(format!("{token}-{file_name}")))+}++pub(crate) fn staged_file_path(+ app: &AppHandle,+ source: StagedUploadSource,+ token: &str,+) -> Result<PathBuf, String> {+ if !is_valid_stage_token(source, token) {+ return Err(format!("invalid {} token", source.description()));+ }++ let staging_dir = ensure_staging_dir(app, source)?;+ let legacy_path = staging_dir.join(token);+ if legacy_path.is_file() {+ return Ok(legacy_path);+ }++ let prefix = format!("{token}-");+ let entries = std::fs::read_dir(&staging_dir)+ .map_err(|error| format!("failed to read {} directory: {error}", source.description()))?;++ for entry in entries {+ let entry = entry+ .map_err(|error| format!("failed to inspect {}: {error}", source.description()))?;+ let file_name = entry.file_name();+ if file_name.to_string_lossy().starts_with(&prefix) {+ let path = entry.path();+ if path.is_file() {+ return Ok(path);+ }+ }+ }++ Err(source.not_found_error().to_string())+}++#[tauri::command]+pub(crate) async fn upload_staged_file_to_presigned_url(+ app: AppHandle,+ source: StagedUploadSource,+ token: String,+ upload_url: String,+ mime_type: String,+) -> Result<(), String> {+ let path = staged_file_path(&app, source, &token)?;+ let description = source.description();+ upload_file_to_presigned_url(&path, &upload_url, &mime_type, description).await?;++ if let Err(error) = tokio::fs::remove_file(&path).await+ && error.kind() != std::io::ErrorKind::NotFound+ {+ tracing::warn!(+ "failed to delete {} after upload {}: {}",+ description,+ path.display(),+ error+ );+ }++ Ok(())+}++pub(crate) async fn upload_file_to_presigned_url(+ path: &Path,+ upload_url: &str,+ mime_type: &str,+ description: &str,+) -> Result<(), String> {+ let upload_url = Url::parse(upload_url)+ .map_err(|error| format!("invalid {description} upload URL: {error}"))?;+ if !matches!(upload_url.scheme(), "http" | "https") {+ return Err(format!("invalid {description} upload URL scheme"));+ }++ let file = tokio::fs::File::open(path)+ .await+ .map_err(|error| format!("failed to open {description}: {error}"))?;+ let size = file+ .metadata()+ .await+ .map_err(|error| format!("failed to read {description} metadata: {error}"))?+ .len();++ let body = reqwest::Body::wrap_stream(tokio_util::io::ReaderStream::new(file));+ let client = reqwest::Client::builder()+ .connect_timeout(std::time::Duration::from_secs(30))+ .timeout(std::time::Duration::from_secs(300))+ .build()+ .map_err(|error| format!("failed to build HTTP client: {error}"))?;++ let mut request = client.put(upload_url).body(body);+ if !mime_type.is_empty() {+ request = request.header(CONTENT_TYPE, mime_type);+ }++ let response = request+ .header(CONTENT_LENGTH, size.to_string())+ .send()+ .await+ .map_err(|error| format!("failed to upload {description}: {error}"))?;++ let status = response.status();+ if status.is_success() {+ return Ok(());+ }++ let detail = response.text().await.unwrap_or_default();+ if detail.trim().is_empty() {+ return Err(format!("failed to upload {description}: HTTP {status}"));+ }+ Err(format!(+ "failed to upload {description}: HTTP {status}: {}",+ detail.trim()+ ))+}diff --git a/js/app/tauri/src-tauri/tauri.conf.json b/js/app/tauri/src-tauri/tauri.conf.jsonindex 573a8555a1..8b689d5f4d 100644--- a/js/app/tauri/src-tauri/tauri.conf.json+++ b/js/app/tauri/src-tauri/tauri.conf.json@@ -25,7 +25,9 @@"enable": true,"scope": {"allow": [- "$APPCACHE/ios-share-staging/**"+ "$APPCACHE/ios-share-staging/**",+ "$APPCACHE/ios-pasteboard-staging/**",+ "$APPCACHE/ios-photo-library-staging/**"],"deny": []}diff --git a/js/app/tauri/staged_upload_constants/Cargo.toml b/js/app/tauri/staged_upload_constants/Cargo.tomlnew file mode 100644index 0000000000..6bde5620ca--- /dev/null+++ b/js/app/tauri/staged_upload_constants/Cargo.toml@@ -0,0 +1,6 @@+[package]+name = "staged_upload_constants"+version = "0.1.0"+edition.workspace = true++[dependencies]diff --git a/js/app/tauri/staged_upload_constants/src/lib.rs b/js/app/tauri/staged_upload_constants/src/lib.rsnew file mode 100644index 0000000000..5dc42a2ab2--- /dev/null+++ b/js/app/tauri/staged_upload_constants/src/lib.rs@@ -0,0 +1,5 @@+pub const PASTEBOARD_STAGING_DIRECTORY_NAME: &str = "ios-pasteboard-staging";+pub const PASTEBOARD_TOKEN_PREFIX: &str = "paste-stage-";++pub const PHOTO_LIBRARY_STAGING_DIRECTORY_NAME: &str = "ios-photo-library-staging";+pub const PHOTO_LIBRARY_TOKEN_PREFIX: &str = "photo-stage-";