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(android): Android input, navigation, attachments, and sharing (#7237)
Peter Chinmana462c37fdfb6
diff --git a/apps/web/knip.ts b/apps/web/knip.tsindex 12df2c9d45..47a5d72ad0 100644--- a/apps/web/knip.ts+++ b/apps/web/knip.ts@@ -39,7 +39,6 @@ const config: KnipConfig = {ignoreDependencies: ['@fontsource-variable/inter','@fontsource-variable/roboto-mono',- 'tauri-plugin-safe-area-insets','@inkibra/tauri-plugins','@types/facebook-pixel','@types/gtag.js',diff --git a/apps/web/package.json b/apps/web/package.jsonindex c8bc862118..b234ae7573 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -161,7 +161,6 @@"tabbable": "^6.2.0","tailwind-merge": "^3.4.0","tailwindcss": "^4.2.4",- "tauri-plugin-safe-area-insets": "^0.1.0","ts-pattern": "^5.9.0","unicode-emoji-json": "^0.8.0","uuid": "^10.0.0",diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsxindex ce66d912b2..dbd33a3c32 100644--- a/apps/web/src/components/app/Layout.tsx+++ b/apps/web/src/components/app/Layout.tsx@@ -28,7 +28,7 @@ import { ReminderComposerModal } from '@app/features/reminders/ReminderComposerMimport { MobileSettingsProvider } from '@app/features/settings/context/mobile-settings';import { MobileSettings } from '@app/features/settings/MobileSettings';import { useOnboardingV4Flag } from '@app/features/setup/flow/useOnboardingV4Flag';-import { IosShareSheet } from '@app/features/sharing/ios-share-sheet/IosShareSheet';+import { NativeShareSheet } from '@app/features/sharing/native-share-sheet/NativeShareSheet';import { ShowFeatureFlag } from '@app/lib/analytics/posthog';import { mountGlobalFocusListener } from '@app/signal/focus';import { AutomationComposer } from '@block-automation/component';@@ -221,7 +221,7 @@ function LayoutInner(props: RouteSectionProps) {<PropertyEditorModal /></Suspense><GlobalBulkEditEntityModal />- <IosShareSheet />+ <NativeShareSheet /><MacroMcpSetupModal /><CreateChannelModal /><CreateCompanyModal />diff --git a/apps/web/src/components/app/mobile/float-regions/FloatRegionHost.tsx b/apps/web/src/components/app/mobile/float-regions/FloatRegionHost.tsxindex 48b01f96a4..a81ce28a3d 100644--- a/apps/web/src/components/app/mobile/float-regions/FloatRegionHost.tsx+++ b/apps/web/src/components/app/mobile/float-regions/FloatRegionHost.tsx@@ -1,5 +1,6 @@import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';+import { isPlatform } from '@core/util/platform';import { createElementSize } from '@solid-primitives/resize-observer';import { cn, Layer } from '@ui';import { createEffect, createSignal, For, onCleanup } from 'solid-js';@@ -45,6 +46,8 @@ export function FloatRegionHost() {// reply bars) keep rem sizing.'pointer-events-none absolute inset-x-0 bottom-0 z-mobile-nav-bar flex flex-col gap-(--mobile-chrome-gutter) pb-(--mobile-chrome-gutter)',isNativeMobilePlatform() && 'pb-[28px]',+ isPlatform('android') &&+ 'pb-[calc(var(--safe-bottom,0px)+var(--mobile-chrome-gutter))]',virtualKeyboardVisible() && 'pb-(--mobile-chrome-gutter)')}>diff --git a/apps/web/src/components/app/split-layout/mobile/MobileSplitContainer.tsx b/apps/web/src/components/app/split-layout/mobile/MobileSplitContainer.tsxindex 9115a244fa..a1338a8784 100644--- a/apps/web/src/components/app/split-layout/mobile/MobileSplitContainer.tsx+++ b/apps/web/src/components/app/split-layout/mobile/MobileSplitContainer.tsx@@ -1,4 +1,5 @@import { ContentLoading } from '@components/app/ContentLoading';+import { useAndroidBackNavigation } from '@core/mobile/androidBack';import { type Accessor, createMemo, Show, Suspense } from 'solid-js';import { SplitPanel } from '../components/SplitPanel';import type {@@ -20,6 +21,12 @@ export type MobileSplitContainerProps = {export function MobileSplitContainer(props: MobileSplitContainerProps) {const { splitManager, mobileSwipeLayout } = props;+ useAndroidBackNavigation(() => {+ if (!mobileSwipeLayout.canGoBack()) return false;+ mobileSwipeLayout.swipeBack();+ return true;+ });+const motion = createMobileSplitMotion({mobileSwipeLayout,});diff --git a/apps/web/src/components/app/useAppSquishHandlers.ts b/apps/web/src/components/app/useAppSquishHandlers.tsindex e590c6c3c0..6295ff929c 100644--- a/apps/web/src/components/app/useAppSquishHandlers.ts+++ b/apps/web/src/components/app/useAppSquishHandlers.ts@@ -5,6 +5,7 @@ import {virtualKeyboardVisible,} from '@core/mobile/virtualKeyboard';import { isEditableInput } from '@core/util/isEditableInput';+import { isPlatform } from '@core/util/platform';import { isIOS } from '@solid-primitives/platform';import { onCleanup, onMount } from 'solid-js';@@ -74,6 +75,10 @@ function createActiveElementPolling(onActiveElementLost: () => void) {* Functionality for responding to virtual keyboard appearance in web app and native mobile app.*/export function useAppSquishHandlers() {+ if (isPlatform('android')) {+ // Native Android insets are owned by TauriProvider, including login routes.+ return;+ }if (isNativeMobilePlatform()) {let activeElementPolling: ReturnType<typeof createActiveElementPolling>;diff --git a/apps/web/src/features/block-md/component/MarkdownEditor.tsx b/apps/web/src/features/block-md/component/MarkdownEditor.tsxindex ff05bfd6d9..cd0b90ad2b 100644--- a/apps/web/src/features/block-md/component/MarkdownEditor.tsx+++ b/apps/web/src/features/block-md/component/MarkdownEditor.tsx@@ -999,6 +999,10 @@ export function MarkdownEditor(props: {});}}contentEditable={isContentEditable()}+ role="textbox"+ aria-multiline="true"+ aria-readonly={!isContentEditable()}+ aria-label="Document content"class="ph-no-capture w-full max-w-full min-h-52"classList={{'select-auto': !canEdit(),diff --git a/apps/web/src/features/block-md/component/useMarkdownDocumentDownload.ts b/apps/web/src/features/block-md/component/useMarkdownDocumentDownload.tsindex d3a83039ca..11e82f1c40 100644--- a/apps/web/src/features/block-md/component/useMarkdownDocumentDownload.ts+++ b/apps/web/src/features/block-md/component/useMarkdownDocumentDownload.ts@@ -2,6 +2,7 @@ import {editorStateAsMarkdown,getSaveState,} from '@core/component/LexicalMarkdown/utils';+import { downloadFile } from '@filesystem/download';import { createCallback } from '@solid-primitives/rootless';import { useMarkdownDocument } from '../context/markdown-document-context';@@ -16,13 +17,8 @@ export function useDownloadDocumentAsMarkdownText() {const fileNameWithExtension = `${fileName()}.md`;const markdownString = editorStateAsMarkdown(editor, 'external');- const blob = new Blob([markdownString], { type: 'text/plain' });- const url = URL.createObjectURL(blob);- const link = document.createElement('a');- link.href = url;- link.download = fileNameWithExtension;- link.click();- URL.revokeObjectURL(url);+ const blob = new Blob([markdownString], { type: 'text/markdown' });+ downloadFile(blob, fileNameWithExtension);});}@@ -40,11 +36,6 @@ export function useDownloadDocumentAsJson() {const blob = new Blob([JSON.stringify(json, null, 2)], {type: 'application/json',});- const url = URL.createObjectURL(blob);- const link = document.createElement('a');- link.href = url;- link.download = fileNameWithExtension;- link.click();- URL.revokeObjectURL(url);+ downloadFile(blob, fileNameWithExtension);});}diff --git a/apps/web/src/features/block-pdf/util/pdf-file-actions.ts b/apps/web/src/features/block-pdf/util/pdf-file-actions.tsindex 692a10e346..afa9df58d3 100644--- a/apps/web/src/features/block-pdf/util/pdf-file-actions.ts+++ b/apps/web/src/features/block-pdf/util/pdf-file-actions.ts@@ -47,24 +47,25 @@ export async function downloadPdfDocument(const blob = await pdfBytes(proxy);const fileNameWithExtension = `${auth.fileName}.pdf`;- try {- // No need to export if there are no modifications.- // Comments live outside the modification data, so they are handled separately.- if (!auth.hasModifications && !auth.hasComments)- return downloadFile(blob, fileNameWithExtension);+ // No need to export if there are no modifications.+ // Comments live outside the modification data, so they are handled separately.+ if (!auth.hasModifications && !auth.hasComments) {+ await downloadFile(blob, fileNameWithExtension);+ return;+ }- const exportFile = await exportPdf({+ let exportFile: Blob;+ try {+ exportFile = await exportPdf({documentId: auth.documentId,fileName: auth.fileName,});- downloadFile(exportFile, fileNameWithExtension);- } catch (_) {- try {- downloadFile(blob, fileNameWithExtension);- } catch (_) {- toast.failure('Unable to download file');- }+ } catch (error) {+ // Fall back to the unmodified bytes rather than downloading nothing.+ console.error('Unable to export PDF modifications', error);+ exportFile = blob;}+ await downloadFile(exportFile, fileNameWithExtension);}export async function downloadDocxDocument(@@ -76,8 +77,8 @@ export async function downloadDocxDocument(try {const blob = await fetchExportedDocx(auth.documentId);- downloadFile(blob, fileNameWithExtension);- toast.success('File downloaded successfully');+ const { saved } = await downloadFile(blob, fileNameWithExtension);+ if (saved) toast.success('File downloaded successfully');} catch (error) {console.error('Download failed:', error);toast.failure('Failed to download file');diff --git a/apps/web/src/features/block-video/component/TopBar.tsx b/apps/web/src/features/block-video/component/TopBar.tsxindex 2a94409f6a..2e67ef53bd 100644--- a/apps/web/src/features/block-video/component/TopBar.tsx+++ b/apps/web/src/features/block-video/component/TopBar.tsx@@ -60,9 +60,9 @@ export function TopBar() {try {const blob = await getBlob({ onProgress: setProgress });- downloadFile(blob, fileName);toast.dismiss(toastId);- toast.success(`Downloaded ${fileName}`);+ const { saved } = await downloadFile(blob, fileName);+ if (saved) toast.success(`Downloaded ${fileName}`);} catch (e) {toast.dismiss(toastId);console.error('error downloading file', e);diff --git a/apps/web/src/features/channel/Input/InputActions.tsx b/apps/web/src/features/channel/Input/InputActions.tsxindex 8cb0e40788..80af2154e9 100644--- a/apps/web/src/features/channel/Input/InputActions.tsx+++ b/apps/web/src/features/channel/Input/InputActions.tsx@@ -1,4 +1,5 @@import { pickNativePhotoLibraryMedia } from '@core/mobile/nativePhotoLibrary';+import { isPlatform } from '@core/util/platform';import PaperclipIcon from '@phosphor/paperclip.svg';import FormatIcon from '@phosphor/text-aa.svg';import TrashIcon from '@phosphor/trash.svg';@@ -64,6 +65,9 @@ export function AttachFilesAction(}export function AttachNativeMediaAction() {+ // Android's WebView picker supports documents and media. Open it directly+ // inside the click gesture instead of awaiting an unavailable iOS plugin.+ if (isPlatform('android')) return <AttachFilesAction />;const commands = useInputCommands();let fileInputRef: HTMLInputElement | undefined;diff --git a/apps/web/src/features/channel/Input/upload-attachments.ts b/apps/web/src/features/channel/Input/upload-attachments.tsindex 0e9f8d1fac..d672a7d89a 100644--- a/apps/web/src/features/channel/Input/upload-attachments.ts+++ b/apps/web/src/features/channel/Input/upload-attachments.ts@@ -119,7 +119,7 @@ export async function uploadInputAttachments(options: {uploaded.previewSrc = previewSrc;}if (file.type) uploaded.mimeType = file.type;- uploaded.size = file.size;+ uploaded.size = uploadSource.size;if (dimensions) {uploaded.width = dimensions.width;uploaded.height = dimensions.height;diff --git a/apps/web/src/features/companies/views/CrmExport.tsx b/apps/web/src/features/companies/views/CrmExport.tsxindex 4219bb8867..3e4132ce96 100644--- a/apps/web/src/features/companies/views/CrmExport.tsx+++ b/apps/web/src/features/companies/views/CrmExport.tsx@@ -1,5 +1,6 @@import { idToEmail } from '@core/user/util';import { type CrmCompanyEntity, getCompanyOwnerId } from '@entity';+import { downloadFile } from '@filesystem/download';import { SYSTEM_PROPERTY_IDS } from '@property/constants';import { useListPropertiesQuery } from '@queries/properties/definitions';import { Button, Dialog, Panel } from '@ui';@@ -150,21 +151,15 @@ export function CrmExport(props: {if (!signal.aborted) setPending(false);}}- function download() {+ async function download() {const data = rows();if (!data || !selectedColumns().length) return;const blob = new Blob([createCrmCsv(selectedColumns(), data)], {type: 'text/csv;charset=utf-8',});- const url = URL.createObjectURL(blob);- const link = document.createElement('a');- link.href = url;- link.download = filename();- document.body.append(link);- link.click();- link.remove();- setTimeout(() => URL.revokeObjectURL(url), 1000);- props.onClose();+ // Keep the dialog open when the Android save dialog is canceled.+ const { saved } = await downloadFile(blob, filename());+ if (saved) props.onClose();}return (<Dialog@@ -401,7 +396,7 @@ export function CrmExport(props: {metadataLoading() ||metadataError()}- onClick={() => (rows() ? download() : void prepare())}+ onClick={() => void (rows() ? download() : prepare())}>{pending()? 'Preparing…'diff --git a/apps/web/src/features/drive-view/util/download-with-progress.tsx b/apps/web/src/features/drive-view/util/download-with-progress.tsxindex 7ab1fd6739..e1857ee18e 100644--- a/apps/web/src/features/drive-view/util/download-with-progress.tsx+++ b/apps/web/src/features/drive-view/util/download-with-progress.tsx@@ -1,4 +1,5 @@import { toast } from '@core/component/Toast/Toast';+import { isPlatform } from '@core/util/platform';import { downloadFile } from '@filesystem/download';import Spinner from '@phosphor/spinner.svg';import type { FetchProgress } from '@service-storage/util/fetchPresigned';@@ -65,9 +66,13 @@ export async function downloadWithProgress(try {const blob = await load(setProgress);- downloadFile(blob, fileName);toast.dismiss(toastId);- toast.success(`Downloaded ${fileName}`);+ const { saved } = await downloadFile(blob, fileName);+ if (saved) {+ toast.success(+ isPlatform('android') ? `Saved ${fileName}` : `Downloaded ${fileName}`+ );+ }} catch (error) {toast.dismiss(toastId);console.error('error downloading file', error);diff --git a/apps/web/src/features/email-compose/primitives/reply-composer.ts b/apps/web/src/features/email-compose/primitives/reply-composer.tsindex b60776df97..6c815e2b48 100644--- a/apps/web/src/features/email-compose/primitives/reply-composer.ts+++ b/apps/web/src/features/email-compose/primitives/reply-composer.ts@@ -5,6 +5,7 @@ import {import type { EmailMessage } from '@app/features/email-message/core/email-message';import type { UserMentionRecord } from '@core/component/LexicalMarkdown/utils/mentionsUtils';import { setEditorStateFromHtml } from '@core/component/LexicalMarkdown/utils/setEditorStateFromHtml';+import { getUploadFileSize } from '@core/mobile/nativeStagedUpload';import { plural } from '@core/util/string';import { $generateHtmlFromNodes } from '@lexical/html';import {@@ -1127,7 +1128,10 @@ export function createReplyComposer(return;const currentAttachments = form.attachments.list();- const attachmentsToAddByteSize = files.reduce((sum, f) => sum + f.size, 0);+ const attachmentsToAddByteSize = files.reduce(+ (sum, f) => sum + getUploadFileSize(f),+ 0+ );if (attachmentsToAddByteSize >= MAX_ATTACHMENTS_BYTES_SIZE) {props.notices.feedback.failure(@@ -1137,7 +1141,8 @@ export function createReplyComposer(}const currentAttachmentsByteSize = currentAttachments.reduce(- (sum, a) => sum + (a.type === 'local' ? a.file.size : a.fileSize),+ (sum, a) =>+ sum + (a.type === 'local' ? getUploadFileSize(a.file) : a.fileSize),0);diff --git a/apps/web/src/features/email-compose/views/compose-toolbar.tsx b/apps/web/src/features/email-compose/views/compose-toolbar.tsxindex 917eb96756..a0fd265b44 100644--- a/apps/web/src/features/email-compose/views/compose-toolbar.tsx+++ b/apps/web/src/features/email-compose/views/compose-toolbar.tsx@@ -11,6 +11,7 @@ import {type NodeTransformType,} from '@core/component/LexicalMarkdown/plugins/node-transform/nodeTransformPlugin';import { fileSelector } from '@core/directive/fileSelector';+import { getUploadFileSize } from '@core/mobile/nativeStagedUpload';import { plural } from '@core/util/string';import PaperclipIcon from '@phosphor/paperclip.svg?component-solid';import TextAa from '@phosphor/text-aa.svg';@@ -30,7 +31,10 @@ export function EmailComposeToolbar(props: {const handleAddAttachments = (files: File[]) => {const currentAttachments = ctx.attachments();- const attachmentsToAddByteSize = files.reduce((sum, f) => sum + f.size, 0);+ const attachmentsToAddByteSize = files.reduce(+ (sum, f) => sum + getUploadFileSize(f),+ 0+ );if (attachmentsToAddByteSize >= MAX_ATTACHMENTS_BYTES_SIZE) {ctx.attachmentFailure(@@ -40,7 +44,8 @@ export function EmailComposeToolbar(props: {}const currentAttachmentsByteSize = currentAttachments.reduce(- (sum, a) => sum + (a.type === 'local' ? a.file.size : a.fileSize),+ (sum, a) =>+ sum + (a.type === 'local' ? getUploadFileSize(a.file) : a.fileSize),0);diff --git a/apps/web/src/features/sharing/ios-share-sheet/IosShareSheet.tsx b/apps/web/src/features/sharing/native-share-sheet/NativeShareSheet.tsxsimilarity index 71%rename from apps/web/src/features/sharing/ios-share-sheet/IosShareSheet.tsxrename to apps/web/src/features/sharing/native-share-sheet/NativeShareSheet.tsxindex 9c788b2b3c..63d21d78d3 100644--- a/apps/web/src/features/sharing/ios-share-sheet/IosShareSheet.tsx+++ b/apps/web/src/features/sharing/native-share-sheet/NativeShareSheet.tsx@@ -7,16 +7,13 @@ import {createMentionsTracker,FormatButtons,Input,- type InputAttachmentData,- type InputAttachmentKind,- type InputAttachmentTracker,type InputSnapshot,uploadInputAttachments,} from '@channel/Input';import { ChannelInputContainer } from '@channel/Input/ChannelInputContainer';import { buildPostMessageRequest } from '@channel/Input/message-payload';-import { getAttachmentKindFromFile } from '@channel/Input/utils/file-helpers';import { hasSendableInputContent } from '@channel/Input/utils/sendable-content';+import { ConfirmDrawer } from '@components/app/mobile/ConfirmDrawer';import { MobileDrawer } from '@components/app/mobile/MobileDrawer';import { useMacroMentionLinkResolver } from '@components/app/split-layout/split-router/mention-links';import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';@@ -28,27 +25,23 @@ import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';import type { WithCustomUserInput } from '@core/user';import { invalidateContacts } from '@core/user/contactService';import { getDestinationFromOptions } from '@core/util/destination';-import { throwOnErr } from '@core/util/result';import {chatRuleset,handleFileFolderDrop,uploadFile,} from '@core/util/upload';-import type {- PendingShareFile,- UploadPendingShareFileArgs,-} from '@macro/tauri';+import type { PendingShareFile } from '@macro/tauri';import { useShareTarget, useTauri } from '@macro/tauri';import { invalidateListChannels } from '@queries/channel/channels';import {useGetOrCreateDirectMessageMutation,useGetOrCreatePrivateChannelMutation,} from '@queries/channel/get-or-create-dm';+import { usePrepareSharedMediaMutation } from '@queries/channel/share-upload';import {newMessageId,useSendMessageMutation,} from '@queries/messages/mutations';-import { staticFileClient } from '@service-static-files/client';import { isIOS } from '@solid-primitives/platform';import { Button } from '@ui';import {@@ -58,9 +51,13 @@ import {ErrorBoundary,on,onCleanup,+ onMount,Show,} from 'solid-js';+import { createNativeShareSend } from './createNativeShareSend';+import { uploadPendingShareAttachment } from './uploadPendingShareAttachment';+// Use the current staged file tokens as the share-session identity.function pendingShareBatchKey(files: readonly PendingShareFile[]): string {return files.map((file) => file.token).join('|');@@ -79,102 +76,6 @@ function pendingShareInitialText(files: readonly PendingShareFile[]): string {.join('\n');}-function getPendingShareAttachmentKind(- file: Pick<PendingShareFile, 'name' | 'mimeType'>-): InputAttachmentKind {- return getAttachmentKindFromFile({- name: file.name,- type: file.mimeType,- });-}--type ShareSheetAttachmentKind = Extract<InputAttachmentKind, 'image' | 'video'>;--function buildPendingAttachment(- file: PendingShareFile,- pendingId: string,- kind: ShareSheetAttachmentKind-): InputAttachmentData {- return {- id: pendingId,- name: file.name,- kind,- pending: true,- previewSrc: kind === 'image' ? file.previewSrc : undefined,- };-}--function buildUploadedAttachment(- file: PendingShareFile,- staticFileId: string,- kind: ShareSheetAttachmentKind-): InputAttachmentData {- return {- id: staticFileId,- name: file.name,- kind,- previewSrc: file.previewSrc,- };-}--async function uploadPendingShareAttachment(options: {- file: PendingShareFile;- tracker: InputAttachmentTracker;- uploadPendingShareFile:- | ((args: UploadPendingShareFileArgs) => Promise<void>)- | undefined;- isActive: () => boolean;-}) {- const kind = getPendingShareAttachmentKind(options.file);- // The iOS share extension only hands the app images and videos today, and- // this upload path only creates static-file attachments for those media types.- if (kind === 'document') {- toast.failure(`Can't share ${options.file.name} from iOS yet`);- return;- }-- const pendingId = `pending-share:${options.file.token}`;-- options.tracker.addAttachment(- buildPendingAttachment(options.file, pendingId, kind)- );-- try {- const result = await throwOnErr(() =>- staticFileClient.makePresignedUrl({- file_name: options.file.name,- content_type: options.file.mimeType,- })- );-- if (!options.uploadPendingShareFile) {- throw new Error('Missing native shared file uploader');- }-- await options.uploadPendingShareFile({- token: options.file.token,- uploadUrl: result.upload_url,- mimeType: options.file.mimeType,- });-- if (!options.isActive()) return;-- options.tracker.removeAttachment(pendingId);- options.tracker.addAttachment(- buildUploadedAttachment(options.file, result.id, kind)- );- } catch (error) {- if (!options.isActive()) return;-- options.tracker.removeAttachment(pendingId);- console.error('failed to upload iOS shared file', {- file: options.file,- error,- });- toast.failure(`Failed to upload ${options.file.name}`);- }-}-function ShareSheetHeaderActions(props: {canSend: Accessor<boolean>;handleCancel: () => void;@@ -217,15 +118,16 @@ function ShareSheetComposerError(_props: { error: unknown }) {);}-function IosShareSheetComposer(props: {- batchKey: string;- handleCancel: () => void;-}) {+function NativeShareSheetComposer(props: { handleCancel: () => void }) {const shareTarget = useShareTarget();+ const batchTokens = (shareTarget?.pendingShareFiles() ?? []).map(+ (file) => file.token+ );const userId = useUserId();const sendMessage = useSendMessageMutation();const { all: destinationOptions } = useCombinedRecipients();const attachmentTracker = createInputAttachmentTracker();+ const prepareMedia = usePrepareSharedMediaMutation();const composerId = crypto.randomUUID();const mentionsTracker = createMentionsTracker();const [scrollContainer, setScrollContainer] = createSignal<HTMLElement>();@@ -238,45 +140,47 @@ function IosShareSheetComposer(props: {WithCustomUserInput<'user' | 'contact' | 'channel'>[]>([]);- createEffect(- on(- () => props.batchKey,- () => {- const files = shareTarget?.pendingShareFiles() ?? [];- if (files.length === 0) return;-- let active = true;- onCleanup(() => {- active = false;- });-- void (async () => {- await Promise.allSettled(- files- .filter(- (file) =>- !file.isSharedText && normalizedSharedText(file).length === 0- )- .map((file) =>- uploadPendingShareAttachment({- file,- tracker: attachmentTracker,- uploadPendingShareFile: shareTarget?.uploadPendingShareFile,- isActive: () => active,- })- )- );- })();- }- )- );+ const [failedFiles, setFailedFiles] = createSignal<PendingShareFile[]>([]);+ const [uploading, setUploading] = createSignal(false);+ let active = true;+ onCleanup(() => {+ active = false;+ });+ const uploadSharedFiles = async (files: PendingShareFile[]) => {+ if (uploading()) return;+ setUploading(true);+ const failed: PendingShareFile[] = [];+ // Bound simultaneous native uploads and retain failures for an explicit retry.+ for (const file of files) {+ if (!active) break;+ const result = await uploadPendingShareAttachment({+ file,+ tracker: attachmentTracker,+ prepareMedia: prepareMedia.mutateAsync,+ uploadPendingShareFile: shareTarget?.uploadPendingShareFile,+ isActive: () => active,+ });+ if (result === 'failed') failed.push(file);+ }+ if (active) {+ setFailedFiles(failed);+ setUploading(false);+ }+ };+ onMount(() => {+ void uploadSharedFiles(+ (shareTarget?.pendingShareFiles() ?? []).filter(+ (file) => !file.isSharedText && normalizedSharedText(file).length === 0+ )+ );+ });const resolveDestinationChannelId = async () => {const options = selectedOptions();if (options.length === 0) {toast.failure('Select a recipient');- throw new Error('No recipient selected for iOS share sheet');+ throw new Error('No recipient selected for native share sheet');}const destination = getDestinationFromOptions(options);@@ -287,7 +191,7 @@ function IosShareSheetComposer(props: {if (destination.users.length === 0) {toast.failure('Select a valid recipient');- throw new Error('No valid recipients selected for iOS share sheet');+ throw new Error('No valid recipients selected for native share sheet');}try {@@ -306,33 +210,40 @@ function IosShareSheetComposer(props: {}};- const handleSend = async (snapshot: InputSnapshot) => {- const senderId = userId();- if (!senderId) {- toast.failure('Failed to send message');- throw new Error('Missing sender id for iOS share sheet send');- }-- const channelId = await resolveDestinationChannelId();- const message = buildPostMessageRequest({ snapshot });-- await sendMessage.mutateAsync({- parent: { type: 'channel', id: channelId },- message,- senderId,- optimisticId: newMessageId(),- });+ const sendShare = createNativeShareSend<InputSnapshot>({+ clear: async () => {+ invalidateListChannels();+ invalidateContacts();+ await shareTarget?.clearPendingShareFiles(batchTokens);+ },+ send: async (snapshot) => {+ if (uploading() || failedFiles().length > 0) {+ throw new Error(+ 'Finish uploading the shared attachments before sending'+ );+ }+ const senderId = userId();+ if (!senderId) {+ toast.failure('Failed to send message');+ throw new Error('Missing sender id for native share sheet send');+ }- invalidateListChannels();- invalidateContacts();+ const channelId = await resolveDestinationChannelId();+ const message = buildPostMessageRequest({ snapshot });- void shareTarget?.clearPendingShareFiles();- };+ await sendMessage.mutateAsync({+ parent: { type: 'channel', id: channelId },+ message,+ senderId,+ optimisticId: newMessageId(),+ });+ },+ });const inputState = createInputState({initialInput: {mode: 'channel',- id: `ios-share-input-${composerId}`,+ id: `native-share-input-${composerId}`,placeholder: 'Add a message',value: pendingShareInitialText(shareTarget?.pendingShareFiles() ?? []),},@@ -348,11 +259,11 @@ function IosShareSheetComposer(props: {});},clearInput: () => markdownEditor.controls.clear(),- callbacks: { onSend: handleSend },+ callbacks: { onSend: sendShare.send },});const markdownEditor = createConfiguredChannelMarkdownEditor({- namespace: `ios-share-input-${composerId}`,+ namespace: `native-share-input-${composerId}`,resolveAppLink: useMacroMentionLinkResolver(),enableMentions: true,scrollContainer,@@ -389,13 +300,19 @@ function IosShareSheetComposer(props: {};const canSend = () =>+ sendShare.canSend() &&+ !uploading() &&+ failedFiles().length === 0 &&selectedOptions().length > 0 &&!inputState.view().hasPendingAttachments &&hasSendableInputContent(inputState.view());const handleHeaderSend = () => {void inputState.commands.send().catch((error) => {- console.error('failed to send from iOS share sheet header action', error);+ console.error(+ 'failed to send from native share sheet header action',+ error+ );});};@@ -409,6 +326,21 @@ function IosShareSheetComposer(props: {handleCancel={props.handleCancel}handleSend={handleHeaderSend}/>+ <Show when={failedFiles().length > 0}>+ <div+ role="alert"+ class="mx-6 mb-3 flex items-center justify-between gap-3 text-sm text-failure"+ >+ <span>{failedFiles().length} attachment(s) couldn't upload.</span>+ <Button+ variant="ghost"+ disabled={uploading()}+ onClick={() => void uploadSharedFiles(failedFiles())}+ >+ {uploading() ? 'Retrying…' : 'Retry'}+ </Button>+ </div>+ </Show><MobileDrawer.Label>Recipients</MobileDrawer.Label><MobileDrawer.Section><div class="shrink-0 p-2">@@ -486,19 +418,23 @@ function IosShareSheetComposer(props: {);}-export function IosShareSheet() {+export function NativeShareSheet() {const tauri = useTauri();const shareTarget = useShareTarget();+ const [confirmDiscard, setConfirmDiscard] = createSignal(false);const pendingFiles = () => shareTarget?.pendingShareFiles() ?? [];const shareBatchKey = () => pendingShareBatchKey(pendingFiles());- const isOpen = () => pendingFiles().length > 0 && tauri?.os === 'ios';+ const isOpen = () =>+ pendingFiles().length > 0 &&+ (tauri?.os === 'ios' || tauri?.os === 'android');const [awaitingFirstInteraction, setAwaitingFirstInteraction] =createSignal(false);createEffect(on(isOpen, (open) => {if (!open) {+ setConfirmDiscard(false);setAwaitingFirstInteraction(false);return;}@@ -520,11 +456,12 @@ export function IosShareSheet() {);const handleCancel = () => {+ setConfirmDiscard(false);void shareTarget?.clearPendingShareFiles();};return (- <Show when={tauri?.os === 'ios'}>+ <Show when={tauri?.os === 'ios' || tauri?.os === 'android'}><MobileDrawerside="bottom"open={isOpen()}@@ -540,24 +477,38 @@ export function IosShareSheet() {if (closeGuardActive) return;- if (!open && isOpen()) handleCancel();+ if (!open && isOpen()) {+ if (tauri?.os === 'android') setConfirmDiscard(true);+ else handleCancel();+ }}}><MobileDrawer.Portal><MobileDrawer.Overlay /><MobileDrawer.Content aria-label="Share to Macro" targetHeight={80}><MobileDrawer.Handle />+ {/* Keyed on the batch so each incoming share remounts the composer. */}<Show when={isOpen() ? shareBatchKey() : undefined} keyed>- {(batchKey) => (- <IosShareSheetComposer- batchKey={batchKey}- handleCancel={handleCancel}- />+ {(_batchKey) => (+ <NativeShareSheetComposer handleCancel={handleCancel} />)}</Show></MobileDrawer.Content></MobileDrawer.Portal></MobileDrawer>+ <ConfirmDrawer+ open={confirmDiscard()}+ onOpenChange={setConfirmDiscard}+ title="Discard this share?"+ body="Your message and shared attachments will be removed."+ cancelLabel="Keep editing"+ confirmLabel="Discard"+ tone="danger"+ onConfirm={() => {+ setConfirmDiscard(false);+ handleCancel();+ }}+ /></Show>);}diff --git a/apps/web/src/features/sharing/native-share-sheet/createNativeShareSend.test.ts b/apps/web/src/features/sharing/native-share-sheet/createNativeShareSend.test.tsnew file mode 100644index 0000000000..7d9e4510cc--- /dev/null+++ b/apps/web/src/features/sharing/native-share-sheet/createNativeShareSend.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it, vi } from 'vitest';+import { createNativeShareSend } from './createNativeShareSend';++describe('native share sending', () => {+ it('joins repeated sends while posting and awaiting native acknowledgement', async () => {+ const posted = Promise.withResolvers<void>();+ const acknowledged = Promise.withResolvers<void>();+ const post = vi.fn(() => posted.promise);+ const clear = vi.fn(() => acknowledged.promise);+ const share = createNativeShareSend({ send: post, clear });++ const first = share.send('draft');+ expect(share.canSend()).toBe(false);+ expect(share.send('second tap')).toBe(first);+ expect(post).toHaveBeenCalledTimes(1);+ posted.resolve();+ await vi.waitFor(() => expect(clear).toHaveBeenCalledOnce());+ expect(share.send('tap during cleanup')).toBe(first);+ expect(share.canSend()).toBe(false);+ acknowledged.resolve();+ await first;++ await share.send('tap after cleanup');+ expect(post).toHaveBeenCalledOnce();+ expect(clear).toHaveBeenCalledOnce();+ expect(share.canSend()).toBe(false);+ });++ it('keeps a delivered batch locked when native acknowledgement fails', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const post = vi.fn().mockResolvedValue(undefined);+ const share = createNativeShareSend({+ send: post,+ clear: vi.fn().mockRejectedValue(new Error('Unable to clear')),+ });+ // The message was delivered, so the composer must not see a send error.+ await expect(share.send('draft')).resolves.toBeUndefined();+ expect(share.canSend()).toBe(false);+ await share.send('second tap');+ expect(post).toHaveBeenCalledOnce();+ });++ it('allows a failed send to be retried without clearing its batch', async () => {+ const post = vi+ .fn()+ .mockRejectedValueOnce(new Error('Offline'))+ .mockResolvedValue(undefined);+ const clear = vi.fn().mockResolvedValue(undefined);+ const share = createNativeShareSend({ send: post, clear });+ await expect(share.send('draft')).rejects.toThrow('Offline');+ expect(share.canSend()).toBe(true);+ expect(clear).not.toHaveBeenCalled();+ await share.send('draft');+ expect(post).toHaveBeenCalledTimes(2);+ expect(clear).toHaveBeenCalledOnce();+ });+});diff --git a/apps/web/src/features/sharing/native-share-sheet/createNativeShareSend.ts b/apps/web/src/features/sharing/native-share-sheet/createNativeShareSend.tsnew file mode 100644index 0000000000..978b65f37d--- /dev/null+++ b/apps/web/src/features/sharing/native-share-sheet/createNativeShareSend.ts@@ -0,0 +1,37 @@+import { createSignal } from 'solid-js';++/** One successful send per mounted share batch, regardless of native cleanup. */+export function createNativeShareSend<T>(options: {+ send: (snapshot: T) => Promise<void>;+ clear: () => Promise<void>;+}) {+ const [state, setState] = createSignal<'idle' | 'sending' | 'sent'>('idle');+ let pending: Promise<void> | undefined;++ const send = (snapshot: T): Promise<void> => {+ if (pending) return pending;+ if (state() === 'sent') return Promise.resolve();+ setState('sending');+ pending = (async () => {+ try {+ await options.send(snapshot);+ } catch (error) {+ setState('idle');+ throw error;+ }+ // A failed acknowledgement must never make a delivered message sendable,+ // nor report the delivered message as a failed send.+ setState('sent');+ try {+ await options.clear();+ } catch (error) {+ console.error('Unable to acknowledge the shared batch', error);+ }+ })().finally(() => {+ pending = undefined;+ });+ return pending;+ };++ return { send, canSend: () => state() === 'idle' };+}diff --git a/apps/web/src/features/sharing/native-share-sheet/uploadPendingShareAttachment.test.ts b/apps/web/src/features/sharing/native-share-sheet/uploadPendingShareAttachment.test.tsnew file mode 100644index 0000000000..2b0ce7a9f7--- /dev/null+++ b/apps/web/src/features/sharing/native-share-sheet/uploadPendingShareAttachment.test.ts@@ -0,0 +1,141 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const { uploadFile, makePresignedUrl, toastFailure } = vi.hoisted(() => ({+ uploadFile: vi.fn(),+ makePresignedUrl: vi.fn(),+ toastFailure: vi.fn(),+}));+vi.mock('@core/constant/allBlocks', () => ({+ fileTypeToBlockName: (type: string) => type,+}));+vi.mock('@core/util/upload', () => ({ uploadFile, chatRuleset: {} }));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { failure: toastFailure },+}));++import { createInputAttachmentTracker } from '@channel/Input/attachment-tracker';+import { getNativeStagedUpload } from '@core/mobile/nativeStagedUpload';+import type { PendingShareFile } from '@macro/tauri';+import { uploadPendingShareAttachment } from './uploadPendingShareAttachment';++const file: PendingShareFile = {+ token: 'share-stage-fixture',+ name: 'photo.png',+ mimeType: 'image/png',+ size: 32 * 1024 * 1024,+ sha256: 'ab'.repeat(32),+ previewSrc: 'asset://fixture',+};+beforeEach(() => {+ vi.resetAllMocks();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ makePresignedUrl.mockResolvedValue({+ id: 'static-fixture',+ upload_url: 'https://example.com/upload',+ });+});+afterEach(() => vi.restoreAllMocks());++it('reports a failed native upload and can retry it without duplicate attachments', async () => {+ const tracker = createInputAttachmentTracker();+ const nativeUpload = vi+ .fn()+ .mockRejectedValueOnce(new Error('Offline'))+ .mockResolvedValueOnce(undefined);+ const options = {+ file,+ tracker,+ prepareMedia: makePresignedUrl,+ uploadPendingShareFile: nativeUpload,+ isActive: () => true,+ };+ expect(await uploadPendingShareAttachment(options)).toBe('failed');+ expect(tracker.attachments()).toEqual([]);+ expect(await uploadPendingShareAttachment(options)).toBe('uploaded');+ expect(tracker.attachments()).toEqual([+ expect.objectContaining({+ id: 'static-fixture',+ name: file.name,+ size: file.size,+ }),+ ]);+});++it('keeps the file pending until native bytes finish uploading', async () => {+ const tracker = createInputAttachmentTracker();+ let finish: (() => void) | undefined;+ const nativeUpload = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ })+ );+ const result = uploadPendingShareAttachment({+ file,+ tracker,+ prepareMedia: makePresignedUrl,+ uploadPendingShareFile: nativeUpload,+ isActive: () => true,+ });+ await vi.waitFor(() => expect(nativeUpload).toHaveBeenCalledOnce());+ expect(tracker.hasPending()).toBe(true);+ finish?.();+ expect(await result).toBe('uploaded');+ expect(tracker.hasPending()).toBe(false);+});++it('preserves document staging metadata instead of uploading an empty placeholder', async () => {+ const tracker = createInputAttachmentTracker();+ uploadFile.mockResolvedValue({+ failed: false,+ destination: 'dss',+ type: 'document',+ documentId: 'doc-fixture',+ fileType: 'pdf',+ });+ expect(+ await uploadPendingShareAttachment({+ file: { ...file, name: 'manual.pdf', mimeType: 'application/pdf' },+ tracker,+ prepareMedia: makePresignedUrl,+ uploadPendingShareFile: vi.fn(),+ isActive: () => true,+ })+ ).toBe('uploaded');+ const uploaded = uploadFile.mock.calls[0][0];+ expect(getNativeStagedUpload(uploaded)).toMatchObject({+ token: file.token,+ size: file.size,+ sha256: file.sha256,+ });+ expect(tracker.attachments()).toEqual([+ expect.objectContaining({+ id: 'doc-fixture',+ kind: 'document',+ size: file.size,+ }),+ ]);+});++it('skips an iOS document without a staged digest instead of failing the share', async () => {+ const tracker = createInputAttachmentTracker();+ expect(+ await uploadPendingShareAttachment({+ file: {+ ...file,+ name: 'manual.pdf',+ mimeType: 'application/pdf',+ sha256: undefined,+ },+ tracker,+ prepareMedia: makePresignedUrl,+ uploadPendingShareFile: vi.fn(),+ isActive: () => true,+ })+ ).toBe('skipped');+ expect(uploadFile).not.toHaveBeenCalled();+ expect(tracker.attachments()).toEqual([]);+ expect(toastFailure).toHaveBeenCalledWith(+ "Can't share manual.pdf from iOS yet"+ );+});diff --git a/apps/web/src/features/sharing/native-share-sheet/uploadPendingShareAttachment.ts b/apps/web/src/features/sharing/native-share-sheet/uploadPendingShareAttachment.tsnew file mode 100644index 0000000000..3affa3ba3c--- /dev/null+++ b/apps/web/src/features/sharing/native-share-sheet/uploadPendingShareAttachment.ts@@ -0,0 +1,100 @@+import type {+ InputAttachmentData,+ InputAttachmentTracker,+} from '@channel/Input';+import {+ buildUploadedAttachment as buildInputUploadedAttachment,+ getAttachmentKindFromFile,+} from '@channel/Input/utils/file-helpers';+import { toast } from '@core/component/Toast/Toast';+import { createNativeStagedUploadFile } from '@core/mobile/nativeStagedUpload';+import { chatRuleset, uploadFile } from '@core/util/upload';+import type {+ PendingShareFile,+ UploadPendingShareFileArgs,+} from '@macro/tauri';++export type PendingShareUploadResult = 'uploaded' | 'skipped' | 'failed';++async function uploadDocument(file: PendingShareFile) {+ const staged = createNativeStagedUploadFile('share', {+ ...file,+ previewPath: null,+ });+ if (!staged) throw new Error('This shared document is unavailable');+ const result = await uploadFile(staged, chatRuleset, {+ hideProgressIndicator: true,+ });+ if (result.failed) throw result.error;+ const attachment = buildInputUploadedAttachment(staged, 'document', result);+ if (!attachment) throw new Error('Unable to prepare shared attachment');+ return attachment;+}++export async function uploadPendingShareAttachment(options: {+ file: PendingShareFile;+ tracker: InputAttachmentTracker;+ prepareMedia: (file: {+ name: string;+ mimeType: string;+ }) => Promise<{ id: string; upload_url: string }>;+ uploadPendingShareFile:+ | ((args: UploadPendingShareFileArgs) => Promise<void>)+ | undefined;+ isActive: () => boolean;+}): Promise<PendingShareUploadResult> {+ const { file, tracker } = options;+ const kind = getAttachmentKindFromFile({+ name: file.name,+ type: file.mimeType,+ });+ // Documents stream from native staging, which needs the staged digest. The+ // iOS share extension does not supply one, so skip the file and keep the+ // rest of the share sendable.+ if (kind === 'document' && !file.sha256) {+ toast.failure(`Can't share ${file.name} from iOS yet`);+ return 'skipped';+ }+ const pendingId = `pending-share:${file.token}`;+ tracker.addAttachment({+ id: pendingId,+ name: file.name,+ kind,+ pending: true,+ previewSrc: kind === 'image' ? file.previewSrc : undefined,+ });+ try {+ let attachment: InputAttachmentData;+ if (kind === 'document') {+ attachment = await uploadDocument(file);+ } else {+ const result = await options.prepareMedia(file);+ if (!options.uploadPendingShareFile)+ throw new Error('Missing native shared file uploader');+ await options.uploadPendingShareFile({+ token: file.token,+ uploadUrl: result.upload_url,+ mimeType: file.mimeType,+ });+ attachment = {+ id: result.id,+ name: file.name,+ kind,+ previewSrc: file.previewSrc,+ };+ }+ if (!options.isActive()) return 'failed';+ tracker.removeAttachment(pendingId);+ tracker.addAttachment({+ ...attachment,+ mimeType: file.mimeType,+ size: file.size,+ });+ return 'uploaded';+ } catch (error) {+ if (!options.isActive()) return 'failed';+ tracker.removeAttachment(pendingId);+ console.error('Failed to upload shared attachment', error);+ return 'failed';+ }+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsxindex b70b2cf4b6..9e768bf070 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx@@ -233,7 +233,7 @@ export const MarkdownShell: Component<MarkdownShellProps> = (props) => {}}disabled={!!props.disabled}showPlaceholder={showPlaceholder()}- placeholder={props.placeholder ?? '...'}+ placeholder={props.placeholder}/><DecoratorRenderer editor={editor} />diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShellContent.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShellContent.tsxindex 95c2a4d511..a5b8fb04ea 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShellContent.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShellContent.tsx@@ -5,7 +5,7 @@ export function MarkdownShellContent(props: {connectRoot: (element: HTMLDivElement) => void;disabled: boolean;showPlaceholder: boolean;- placeholder: string;+ placeholder: string | undefined;}) {return (<>@@ -13,13 +13,17 @@ export function MarkdownShellContent(props: {data-markdown-editableref={props.connectRoot}contentEditable={!props.disabled}+ role="textbox"+ aria-multiline="true"+ aria-readonly={props.disabled}+ aria-label={props.placeholder || 'Message'}/><Show when={props.showPlaceholder}><divdata-markdown-placeholderclass="pointer-events-none text-ink-placeholder absolute top-0">- <p class="my-1.5 pointer-events-none">{props.placeholder}</p>+ <p class="my-1.5 pointer-events-none">{props.placeholder ?? '...'}</p></div></Show></>diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsxindex 0cc98564f7..9901c4e19e 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx@@ -382,6 +382,10 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {});}}contentEditable={props.editable()}+ role="textbox"+ aria-multiline="true"+ aria-readonly={!props.editable()}+ aria-label={props.placeholder || 'Message'}/><DecoratorRenderer editor={editor} />diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/directive/iosFloatingMiddleware.ts b/apps/web/src/lib/core/component/LexicalMarkdown/directive/iosFloatingMiddleware.tsindex e67d6700cc..71c0f6eb0f 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/directive/iosFloatingMiddleware.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/directive/iosFloatingMiddleware.ts@@ -1,15 +1,22 @@+import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { getSafeAreaInset } from '@core/mobile/safeAreaInsets';import { virtualKeyboardHeight } from '@core/mobile/virtualKeyboard';import { type Placement, size } from '@floating-ui/dom';import { isIOS } from '@solid-primitives/platform';+// iOS web, and both native apps, keep the viewport under the keyboard and+// publish its height instead of shrinking the visual viewport.+function keyboardOverlaysViewport() {+ return isIOS || isNativeMobilePlatform();+}+/**- * Returns iOS-aware safe-padding, incorporating the safe area insets and virtual keyboard height.+ * Returns keyboard-aware safe-padding, incorporating the safe area insets and virtual keyboard height.*/export function iosSafePadding(spacing: number): number | { top: number; right: number; bottom: number; left: number } {- if (!isIOS) return spacing;+ if (!keyboardOverlaysViewport()) return spacing;return {top: spacing + getSafeAreaInset('top'),right: spacing + getSafeAreaInset('right'),@@ -19,7 +26,7 @@ export function iosSafePadding(}/**- * Returns a size middleware that accounts for the iOS keyboard height and safe+ * Returns a size middleware that accounts for the overlaid keyboard height and safe* area insets when computing available height, and calls onAvailableHeight with* the usable height.* (which can be used to, e.g. set a signal with available height)@@ -43,7 +50,9 @@ export function iosSizeMiddleware(? getSafeAreaInset('top'): 0;const kbHeight =- isIOS && placement.startsWith('bottom') ? virtualKeyboardHeight() : 0;+ keyboardOverlaysViewport() && placement.startsWith('bottom')+ ? virtualKeyboardHeight()+ : 0;const h = Math.max(0, availableHeight - safeAreaTop - kbHeight);Object.assign(elements.floating.style, {maxHeight: `${h}px`,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actionsPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actionsPlugin.tsindex ee75348395..aa2ac7cdba 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actionsPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actionsPlugin.ts@@ -22,6 +22,7 @@ import {type LexicalEditor,} from 'lexical';import type { MenuOperations } from '../../shared/inlineMenu';+import { registerInlineMenuTrigger } from '../../shared/registerInlineMenuTrigger';const TYPE_SLASH_COMMAND: LexicalCommand<void> =createCommand('TYPE_SLASH_COMMAND');@@ -57,28 +58,10 @@ function registerActionsPlugin(const { menu } = props;- /**- * Register a manual DOM listener for the / symbol.- */- function registerSymbolListener() {- const listener = (e: KeyboardEvent) => {- if (e.key === '/') {- editor.dispatchCommand(TYPE_SLASH_COMMAND, undefined);- }- };-- return editor.registerRootListener((root, prev) => {- if (root) {- root.addEventListener('keydown', listener);- }- if (prev) {- prev.removeEventListener('keydown', listener);- }- });- }-return mergeRegister(- registerSymbolListener(),+ registerInlineMenuTrigger(editor, '/', () => {+ editor.dispatchCommand(TYPE_SLASH_COMMAND, undefined);+ }),editor.registerCommand(TYPE_SLASH_COMMAND,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/emojis/emojisPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/emojis/emojisPlugin.tsindex 437c9a0d74..945f0c00d6 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/emojis/emojisPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/emojis/emojisPlugin.ts@@ -22,6 +22,7 @@ import {type LexicalEditor,} from 'lexical';import type { MenuOperations } from '../../shared/inlineMenu';+import { registerInlineMenuTrigger } from '../../shared/registerInlineMenuTrigger';const TYPE_EMOJI_SYMBOL_COMMAND: LexicalCommand<void> = createCommand('EMOJI_SYMBOL_COMMAND'@@ -41,23 +42,6 @@ type EmojiPluginProps = {};function registerEmojisPlugin(editor: LexicalEditor, props: EmojiPluginProps) {- function registerSymbolListener() {- const listener = (e: KeyboardEvent) => {- if (e.key === ':') {- editor.dispatchCommand(TYPE_EMOJI_SYMBOL_COMMAND, undefined);- }- };-- return editor.registerRootListener((root, prev) => {- if (root) {- root.addEventListener('keydown', listener);- }- if (prev) {- prev.removeEventListener('keydown', listener);- }- });- }-const { menu } = props;function typeSymbolCommand() {@@ -72,7 +56,9 @@ function registerEmojisPlugin(editor: LexicalEditor, props: EmojiPluginProps) {}return mergeRegister(- registerSymbolListener(),+ registerInlineMenuTrigger(editor, ':', () => {+ editor.dispatchCommand(TYPE_EMOJI_SYMBOL_COMMAND, undefined);+ }),// When you type :editor.registerCommand(TYPE_EMOJI_SYMBOL_COMMAND,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.tsindex 374b95f9ac..135d3eb7e5 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts@@ -76,6 +76,7 @@ import {import type { Setter } from 'solid-js';import { match } from 'ts-pattern';import type { MenuOperations } from '../../shared/inlineMenu';+import { registerInlineMenuTrigger } from '../../shared/registerInlineMenuTrigger';import { $collapseSelection, $traverseNodes, nodeByKey } from '../../utils';import { mapRegisterDelete } from '../shared';@@ -376,27 +377,6 @@ function registerMentionsPlugin(*/let consumeDelete = false;- /**- * Register a manual DOM listener for the @ symbol.- * TODO (seamus) : Find a more Lexical-y way to do this.- */- function registerSymbolListener() {- const listener = (e: KeyboardEvent) => {- if (e.key === '@') {- editor.dispatchCommand(TYPE_AT_SYMBOL_COMMAND, undefined);- }- };-- return editor.registerRootListener((root, prev) => {- if (root) {- root.addEventListener('keydown', listener);- }- if (prev) {- prev.removeEventListener('keydown', listener);- }- });- }-function updateMentionsSignal() {if (props.setMentions === undefined) return;const mentions: ItemMention[] = [];@@ -640,7 +620,9 @@ function registerMentionsPlugin(COMMAND_PRIORITY_NORMAL),- registerSymbolListener(),+ registerInlineMenuTrigger(editor, '@', () => {+ editor.dispatchCommand(TYPE_AT_SYMBOL_COMMAND, undefined);+ }),editor.registerCommand(TYPE_AT_SYMBOL_COMMAND,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/skills/skillsPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/skills/skillsPlugin.tsindex 7be6563aab..c8b578309c 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/skills/skillsPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/skills/skillsPlugin.ts@@ -22,6 +22,7 @@ import {type LexicalEditor,} from 'lexical';import type { MenuOperations } from '../../shared/inlineMenu';+import { registerInlineMenuTrigger } from '../../shared/registerInlineMenuTrigger';const TYPE_SKILL_SYMBOL_COMMAND: LexicalCommand<void> = createCommand('SKILL_SYMBOL_COMMAND'@@ -56,23 +57,6 @@ const afterRegex = /^\s/;* menu is disabled — AI chat inputs.*/function registerSkillsPlugin(editor: LexicalEditor, props: SkillsPluginProps) {- function registerSymbolListener() {- const listener = (e: KeyboardEvent) => {- if (e.key === '/') {- editor.dispatchCommand(TYPE_SKILL_SYMBOL_COMMAND, undefined);- }- };-- return editor.registerRootListener((root, prev) => {- if (root) {- root.addEventListener('keydown', listener);- }- if (prev) {- prev.removeEventListener('keydown', listener);- }- });- }-const { menu } = props;function typeSymbolCommand() {@@ -87,7 +71,9 @@ function registerSkillsPlugin(editor: LexicalEditor, props: SkillsPluginProps) {}return mergeRegister(- registerSymbolListener(),+ registerInlineMenuTrigger(editor, '/', () => {+ editor.dispatchCommand(TYPE_SKILL_SYMBOL_COMMAND, undefined);+ }),// When you type /editor.registerCommand(TYPE_SKILL_SYMBOL_COMMAND,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/snippets/snippetsPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/snippets/snippetsPlugin.tsindex ae9045e19d..13e53a8b0c 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/snippets/snippetsPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/snippets/snippetsPlugin.ts@@ -34,6 +34,7 @@ import {import { nanoid } from 'nanoid';import { createLexicalWrapper } from '../../context/LexicalWrapperContext';import type { MenuOperations } from '../../shared/inlineMenu';+import { registerInlineMenuTrigger } from '../../shared/registerInlineMenuTrigger';import {editorStateAsMarkdown,initializeEditorWithState,@@ -116,23 +117,6 @@ function registerSnippetsPlugin(editor: LexicalEditor,props: SnippetsPluginProps) {- function registerSymbolListener() {- const listener = (e: KeyboardEvent) => {- if (e.key === ';') {- editor.dispatchCommand(TYPE_SNIPPET_SYMBOL_COMMAND, undefined);- }- };-- return editor.registerRootListener((root, prev) => {- if (root) {- root.addEventListener('keydown', listener);- }- if (prev) {- prev.removeEventListener('keydown', listener);- }- });- }-const { menu } = props;const parseEditor = createEditor({namespace: 'snippet-parser',@@ -230,7 +214,9 @@ function registerSnippetsPlugin(}const cleanup = mergeRegister(- registerSymbolListener(),+ registerInlineMenuTrigger(editor, ';', () => {+ editor.dispatchCommand(TYPE_SNIPPET_SYMBOL_COMMAND, undefined);+ }),// When you type ;editor.registerCommand(TYPE_SNIPPET_SYMBOL_COMMAND,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tags/tagsPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tags/tagsPlugin.tsindex 7341034541..7f1c258b3b 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tags/tagsPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tags/tagsPlugin.ts@@ -31,6 +31,7 @@ import {type LexicalEditor,} from 'lexical';import type { MenuOperations } from '../../shared/inlineMenu';+import { registerInlineMenuTrigger } from '../../shared/registerInlineMenuTrigger';import { $collapseSelection, $traverseNodes, nodeByKey } from '../../utils';import {CLOSE_INLINE_SEARCH_COMMAND,@@ -72,22 +73,15 @@ function registerHashSymbolListener(editor: LexicalEditor,props: TagsPluginProps) {- const listener = (e: KeyboardEvent) => {- if (e.key === '#') {- if (props.menu?.isOpen()) {- editor.update(() => {- $collapseInlineSearch(props.peerIdValidator);- });- props.menu.closeMenu();- return;- }- editor.dispatchCommand(TYPE_HASH_SYMBOL_COMMAND, undefined);+ return registerInlineMenuTrigger(editor, '#', () => {+ if (props.menu?.isOpen()) {+ editor.update(() => {+ $collapseInlineSearch(props.peerIdValidator);+ });+ props.menu.closeMenu();+ return;}- };-- return editor.registerRootListener((root, prev) => {- if (root) root.addEventListener('keydown', listener);- if (prev) prev.removeEventListener('keydown', listener);+ editor.dispatchCommand(TYPE_HASH_SYMBOL_COMMAND, undefined);});}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/shared/registerInlineMenuTrigger.ts b/apps/web/src/lib/core/component/LexicalMarkdown/shared/registerInlineMenuTrigger.tsnew file mode 100644index 0000000000..5380120b42--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/shared/registerInlineMenuTrigger.ts@@ -0,0 +1,45 @@+import type { LexicalEditor } from 'lexical';++/** Trigger before text insertion, including Android's Unidentified key events. */+export function registerInlineMenuTrigger(+ editor: LexicalEditor,+ symbol: string,+ onTrigger: () => void+) {+ let handledKeyDown = false;+ const keyDown = (event: KeyboardEvent) => {+ handledKeyDown = event.key === symbol;+ if (handledKeyDown) onTrigger();+ };+ const reset = () => {+ handledKeyDown = false;+ };+ const beforeInput = (event: InputEvent) => {+ const alreadyHandled = handledKeyDown;+ reset();+ if (+ !alreadyHandled &&+ event.inputType === 'insertText' &&+ event.data === symbol &&+ !event.isComposing &&+ !event.defaultPrevented+ ) {+ onTrigger();+ }+ };++ return editor.registerRootListener((root, previous) => {+ reset();+ if (previous) {+ previous.removeEventListener('keydown', keyDown);+ previous.removeEventListener('keyup', reset);+ previous.removeEventListener('beforeinput', beforeInput, true);+ }+ if (root) {+ root.addEventListener('keydown', keyDown);+ root.addEventListener('keyup', reset);+ // Validate the caret before Lexical inserts the trigger character.+ root.addEventListener('beforeinput', beforeInput, true);+ }+ });+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionTrigger.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionTrigger.test.tsindex 85f732179c..8d19db2f8e 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionTrigger.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionTrigger.test.ts@@ -22,11 +22,24 @@ vi.mock('@core/signal/mention', () => ({vi.mock('@service-storage/client', () => ({blockNameToItemType: (name: string) => name,}));+vi.mock('@core/constant/featureFlags', () => ({+ enableSnippets: {},+ isFeatureEnabled: () => true,+}));+vi.mock('../context/LexicalWrapperContext', async () => {+ const { createEditor } = await import('lexical');+ return {+ createLexicalWrapper: () => ({ editor: createEditor(), cleanup: vi.fn() }),+ };+});vi.mock('../utils', async () => {const { $getNodeByKey } = await import('lexical');return {$collapseSelection: vi.fn(),$traverseNodes: vi.fn(),+ editorStateAsMarkdown: vi.fn(),+ initializeEditorWithState: vi.fn(),+ setEditorStateFromMarkdown: vi.fn(),nodeByKey: (editorOrState: any, key: string) => {let node: any;editorOrState.read(() => {@@ -52,17 +65,22 @@ import {type TextNode,} from 'lexical';import { createSignal } from 'solid-js';+import { actionsPlugin } from '../plugins/actions/actionsPlugin';+import { emojisPlugin } from '../plugins/emojis/emojisPlugin';import {INSERT_USER_MENTION_COMMAND,mentionsPlugin,REMOVE_INLINE_SEARCH_COMMAND,} from '../plugins/mentions/mentionsPlugin';+import { skillsPlugin } from '../plugins/skills/skillsPlugin';+import { snippetsPlugin } from '../plugins/snippets/snippetsPlugin';+import { tagsPlugin } from '../plugins/tags/tagsPlugin';import type { MenuOperations } from '../shared/inlineMenu';type Harness = {editor: LexicalEditor;- /** Types `text` the way a keyboard would: keydown first, then the character. */- type: (text: string) => void;+ /** Sends keydown and beforeinput, then inserts the character. */+ type: (text: string, softwareKeyboard?: boolean) => void;/** `type:"text"` for every child of the first paragraph. */children: () => string[];searchTerms: string[];@@ -79,7 +97,12 @@ beforeEach(() => {};});-function setup(withParagraph: (text: typeof $createTextNode) => void): Harness {+function setup(+ withParagraph: (text: typeof $createTextNode) => void,+ plugin: (props: {+ menu: MenuOperations;+ }) => (editor: LexicalEditor) => () => void = mentionsPlugin+): Harness {const editor = createEditor({namespace: 'mention-trigger-test',nodes: [...SupportedNodeTypes],@@ -112,15 +135,28 @@ function setup(withParagraph: (text: typeof $createTextNode) => void): Harness {setIsOpen,};- cleanups.push(mentionsPlugin({ menu })(editor));+ cleanups.push(plugin({ menu })(editor));editor.update(() => withParagraph($createTextNode), { discrete: true });editor.read(() => {});- const type = (text: string) => {+ const type = (text: string, softwareKeyboard = false) => {for (const character of text) {rootElement.dispatchEvent(- new KeyboardEvent('keydown', { key: character, bubbles: true })+ new KeyboardEvent('keydown', {+ key: softwareKeyboard ? 'Unidentified' : character,+ keyCode: softwareKeyboard ? 229 : 0,+ bubbles: true,+ })+ );+ editor.read(() => {});+ rootElement.dispatchEvent(+ new InputEvent('beforeinput', {+ inputType: 'insertText',+ data: character,+ bubbles: true,+ cancelable: true,+ }));editor.read(() => {});editor.update(@@ -168,6 +204,59 @@ function paragraphWithCaret(text: string, offset: number) {}describe('@ trigger position', () => {+ test('opens and filters from software-keyboard input without an @ keydown', () => {+ const harness = setup(paragraphWithCaret('hello ', 6));++ harness.type('@jo', true);++ expect(harness.opened()).toBe(1);+ expect(harness.searchTerms.at(-1)).toBe('jo');+ expect(harness.children()).toEqual(['text:hello ', 'inline-search:@jo']);+ });++ test('keeps software-keyboard @ literal inside a word', () => {+ const harness = setup(paragraphWithCaret('hello', 3));++ harness.type('@', true);++ expect(harness.opened()).toBe(0);+ expect(harness.children()).toEqual(['text:hel@lo']);+ });++ test('opens from software input in an empty paragraph', () => {+ const harness = setup(() => {+ const paragraph = $createParagraphNode();+ $getRoot().clear().append(paragraph);+ paragraph.select();+ });++ harness.type('@', true);++ expect(harness.opened()).toBe(1);+ expect(harness.children()).toEqual(['inline-search:@']);+ });++ test.each([+ { inputType: 'insertFromPaste', isComposing: false },+ { inputType: 'insertCompositionText', isComposing: true },+ { inputType: 'insertText', isComposing: true },+ ])('does not intercept $inputType (composing: $isComposing)', (input) => {+ const harness = setup(paragraphWithCaret('hello ', 6));++ harness.editor.getRootElement()!.dispatchEvent(+ new InputEvent('beforeinput', {+ ...input,+ data: '@',+ bubbles: true,+ cancelable: true,+ })+ );+ harness.editor.read(() => {});++ expect(harness.opened()).toBe(0);+ expect(harness.children()).toEqual(['text:hello ']);+ });+test('opens a blank menu at the start of a word, leaving the word alone', () => {const harness = setup(paragraphWithCaret('hello world', 6));@@ -263,3 +352,48 @@ describe('@ trigger position', () => {expect(harness.children()).toEqual(['inline-search:@']);});});++describe.each([+ { name: 'emoji', symbol: ':', plugin: emojisPlugin },+ { name: 'actions', symbol: '/', plugin: actionsPlugin },+ { name: 'skills', symbol: '/', plugin: skillsPlugin },+ { name: 'snippets', symbol: ';', plugin: snippetsPlugin },+ { name: 'tags', symbol: '#', plugin: tagsPlugin },+])('$name menu input', ({ symbol, plugin }) => {+ test.each([true, false])(+ 'opens once and filters (software keyboard: %s)',+ (softwareKeyboard) => {+ const harness = setup(paragraphWithCaret('hello ', 6), plugin);++ harness.type(`${symbol}test`, softwareKeyboard);++ expect(harness.opened()).toBe(1);+ expect(harness.searchTerms.at(-1)).toBe('test');+ expect(harness.children()).toEqual([+ 'text:hello ',+ `inline-search:${symbol}test`,+ ]);+ }+ );++ test('keeps the software-keyboard trigger literal inside a word', () => {+ const harness = setup(paragraphWithCaret('hello', 3), plugin);++ harness.type(symbol, true);++ expect(harness.opened()).toBe(0);+ expect(harness.children()).toEqual([`text:hel${symbol}lo`]);+ });+});++test.each([true, false])(+ 'a second # closes the tags menu (software keyboard: %s)',+ (softwareKeyboard) => {+ const harness = setup(paragraphWithCaret('hello ', 6), tagsPlugin);++ harness.type('##', softwareKeyboard);++ expect(harness.opened()).toBe(1);+ expect(harness.children()).toEqual(['text:hello ##']);+ }+);diff --git a/apps/web/src/lib/core/mobile/androidBack.test.tsx b/apps/web/src/lib/core/mobile/androidBack.test.tsxnew file mode 100644index 0000000000..0bff07142c--- /dev/null+++ b/apps/web/src/lib/core/mobile/androidBack.test.tsx@@ -0,0 +1,114 @@+import { createRoot } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';++vi.mock('@core/util/platform', () => ({ isPlatform: () => true }));++import { useAndroidBack, useAndroidBackNavigation } from './androidBack';++// Dispose here too, so a failing test cannot leak its listeners into the next.+let dispose = () => {};+afterEach(() => {+ dispose();+ dispose = () => {};+ document.body.innerHTML = '';+});++async function mountBack(navigate: () => boolean) {+ createRoot((cleanup) => {+ dispose = cleanup;+ useAndroidBack();+ useAndroidBackNavigation(navigate);+ });+ await Promise.resolve();+ return dispose;+}++describe('Android committed Back', () => {+ it.each([+ 'data-kb-top-layer',+ 'data-corvu-dialog-content',+ 'data-corvu-drawer-content',+ ])(+ 'dismisses %s before navigation and retains the composer draft',+ async (marker) => {+ const input = document.createElement('textarea');+ input.value = 'Unsent draft';+ document.body.append(input);+ input.focus();+ const overlay = document.createElement('div');+ overlay.setAttribute(marker, '');+ overlay.setAttribute('data-open', '');+ document.body.append(overlay);+ const navigate = vi.fn(() => true);+ const dispose = await mountBack(navigate);+ const onEscape = (event: KeyboardEvent) => {+ if (event.key === 'Escape') {+ event.preventDefault();+ overlay.remove();+ }+ };+ document.addEventListener('keydown', onEscape);+ expect(+ window.dispatchEvent(new Event('android-back', { cancelable: true }))+ ).toBe(false);+ expect(navigate).not.toHaveBeenCalled();+ expect(input.value).toBe('Unsent draft');+ document.removeEventListener('keydown', onEscape);+ expect(+ window.dispatchEvent(new Event('android-back', { cancelable: true }))+ ).toBe(false);+ expect(navigate).toHaveBeenCalledOnce();+ dispose();+ }+ );++ it('sends Escape to a focused editor so its popups can claim Back', async () => {+ const editor = document.createElement('div');+ editor.setAttribute('contenteditable', 'true');+ editor.tabIndex = 0;+ document.body.append(editor);+ editor.focus();+ const onEscape = vi.fn((event: KeyboardEvent) => {+ if (event.key === 'Escape') event.preventDefault();+ });+ editor.addEventListener('keydown', onEscape);+ const navigate = vi.fn(() => true);+ const dispose = await mountBack(navigate);+ expect(+ window.dispatchEvent(new Event('android-back', { cancelable: true }))+ ).toBe(false);+ expect(onEscape).toHaveBeenCalledOnce();+ expect(navigate).not.toHaveBeenCalled();+ dispose();+ });++ it('does not send Escape when nothing dismissible is open or focused', async () => {+ const button = document.createElement('button');+ document.body.append(button);+ button.focus();+ const onEscape = vi.fn();+ document.addEventListener('keydown', onEscape);+ const navigate = vi.fn(() => true);+ const dispose = await mountBack(navigate);+ window.dispatchEvent(new Event('android-back', { cancelable: true }));+ expect(onEscape).not.toHaveBeenCalled();+ expect(navigate).toHaveBeenCalledOnce();+ document.removeEventListener('keydown', onEscape);+ dispose();+ });++ it('leaves root Back to Android and removes listeners on cleanup', async () => {+ const toasts = document.createElement('div');+ toasts.setAttribute('data-kb-top-layer', '');+ toasts.setAttribute('role', 'region');+ document.body.append(toasts);+ const navigate = vi.fn(() => false);+ const dispose = await mountBack(navigate);+ expect(+ window.dispatchEvent(new Event('android-back', { cancelable: true }))+ ).toBe(true);+ dispose();+ window.dispatchEvent(new Event('android-back', { cancelable: true }));+ expect(navigate).toHaveBeenCalledOnce();+ });+});diff --git a/apps/web/src/lib/core/mobile/androidBack.ts b/apps/web/src/lib/core/mobile/androidBack.tsnew file mode 100644index 0000000000..63e75211e0--- /dev/null+++ b/apps/web/src/lib/core/mobile/androidBack.ts@@ -0,0 +1,78 @@+import { isPlatform } from '@core/util/platform';+import { onCleanup, onMount } from 'solid-js';++declare global {+ interface WindowEventMap {+ 'android-back': Event;+ 'android-navigate-back': Event;+ }+}++function isEditable(element: Element | null): boolean {+ return (+ element?.closest(+ 'input, textarea, [contenteditable]:not([contenteditable="false"])'+ ) != null+ );+}++/**+ * Use the same Escape handlers as touch sheets, menus and editor popups.+ * Editor popups carry no top-layer marker, so a focused editor also receives+ * Escape; nothing else does, keeping Back away from unrelated Escape hotkeys.+ */+function dismissAndroidBackOverlay(): boolean {+ // Kobalte and corvu mark their top layers with these library attributes.+ const overlay = [+ ...document.querySelectorAll(+ '[data-kb-top-layer], [data-corvu-dialog-content][data-open], [data-corvu-drawer-content][data-open]'+ ),+ ].find((element) => {+ // Always-mounted toast regions also carry Kobalte's top-layer marker.+ if (element.matches('[role="region"], [role="tooltip"]')) return false;+ const style = getComputedStyle(element);+ return style.display !== 'none' && style.visibility !== 'hidden';+ });+ const target = document.activeElement;+ if (!overlay && !isEditable(target)) return false;+ const escapeEvent = new KeyboardEvent('keydown', {+ key: 'Escape',+ code: 'Escape',+ bubbles: true,+ cancelable: true,+ });+ (target ?? document.body).dispatchEvent(escapeEvent);+ // A non-dismissible/pending dialog also owns Back: do not navigate underneath it.+ return !!overlay || escapeEvent.defaultPrevented;+}++export function useAndroidBack() {+ if (!isPlatform('android')) return;+ onMount(() => {+ const onBack = (event: Event) => {+ if (dismissAndroidBackOverlay()) {+ event.preventDefault();+ return;+ }+ const navigation = new Event('android-navigate-back', {+ cancelable: true,+ });+ if (!window.dispatchEvent(navigation)) event.preventDefault();+ };+ window.addEventListener('android-back', onBack);+ onCleanup(() => window.removeEventListener('android-back', onBack));+ });+}++export function useAndroidBackNavigation(navigateBack: () => boolean) {+ if (!isPlatform('android')) return;+ onMount(() => {+ const onBack = (event: Event) => {+ if (!event.defaultPrevented && navigateBack()) event.preventDefault();+ };+ window.addEventListener('android-navigate-back', onBack);+ onCleanup(() =>+ window.removeEventListener('android-navigate-back', onBack)+ );+ });+}diff --git a/apps/web/src/lib/core/mobile/androidFiles.test.ts b/apps/web/src/lib/core/mobile/androidFiles.test.tsnew file mode 100644index 0000000000..e118940419--- /dev/null+++ b/apps/web/src/lib/core/mobile/androidFiles.test.ts@@ -0,0 +1,110 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }));+vi.mock('@tauri-apps/api/core', () => ({ invoke }));++import { exportAndroidFile } from './androidFiles';++beforeEach(() => {+ invoke.mockReset();+ invoke.mockImplementation(async (command: string) => {+ if (command.endsWith('beginExport')) return { token: 'test-token' };+ if (command.endsWith('finishExport')) return { canceled: false };+ });+});++describe('Android Blob export', () => {+ it('transfers the original bytes in bounded ordered chunks before opening a save dialog', async () => {+ const bytes = new Uint8Array(600_000).map((_, i) => i % 251);+ // Node Blob supplies arrayBuffer, unlike jsdom Blob.+ const { Blob } = await import('node:buffer');+ await exportAndroidFile(+ new Blob([bytes], { type: 'image/png' }) as unknown as globalThis.Blob,+ 'drawing.png'+ );+ const chunks = invoke.mock.calls.filter(([command]) =>+ command.endsWith('appendExport')+ );+ expect(chunks).toHaveLength(3);+ const copied = chunks.map(([, args]) => atob(args.data)).join('');+ expect(Uint8Array.from(copied, (char) => char.charCodeAt(0))).toEqual(+ bytes+ );+ expect(invoke).toHaveBeenLastCalledWith(+ 'plugin:android-mobile|discardExport',+ { token: 'test-token' }+ );+ expect(invoke).toHaveBeenCalledWith('plugin:android-mobile|finishExport', {+ token: 'test-token',+ action: 'save',+ });+ });++ it('declares the total size up front so native can reject oversized exports before streaming', async () => {+ invoke.mockImplementation(async (command: string) => {+ if (command.endsWith('beginExport'))+ throw new Error('Attachments exceed the 500 MB limit');+ });+ const { Blob } = await import('node:buffer');+ await expect(+ exportAndroidFile(+ new Blob([new Uint8Array(600_000)], {+ type: 'video/mp4',+ }) as unknown as globalThis.Blob,+ 'video.mp4'+ )+ ).rejects.toThrow('500 MB');+ expect(invoke).toHaveBeenCalledWith('plugin:android-mobile|beginExport', {+ name: 'video.mp4',+ mimeType: 'video/mp4',+ size: 600_000,+ });+ expect(invoke).toHaveBeenCalledOnce();+ });++ it('discards partial staging after an IPC failure without opening a chooser', async () => {+ invoke.mockImplementation(async (command: string) => {+ if (command.endsWith('beginExport')) return { token: 'test-token' };+ if (command.endsWith('appendExport')) throw new Error('Disk full');+ });+ const { Blob } = await import('node:buffer');+ await expect(+ exportAndroidFile(+ new Blob(['draft']) as unknown as globalThis.Blob,+ 'draft.txt'+ )+ ).rejects.toThrow('Disk full');+ expect(+ invoke.mock.calls.some(([command]) => command.endsWith('finishExport'))+ ).toBe(false);+ expect(invoke).toHaveBeenLastCalledWith(+ 'plugin:android-mobile|discardExport',+ { token: 'test-token' }+ );+ });+ it('cancels between chunks and deletes staging without opening a chooser', async () => {+ const controller = new AbortController();+ const { Blob } = await import('node:buffer');+ await expect(+ exportAndroidFile(+ new Blob([new Uint8Array(600_000)]) as unknown as globalThis.Blob,+ 'video.mp4',+ 'share',+ {+ signal: controller.signal,+ onProgress: () => controller.abort(),+ }+ )+ ).rejects.toThrow();+ expect(+ invoke.mock.calls.filter(([command]) => command.endsWith('appendExport'))+ ).toHaveLength(1);+ expect(+ invoke.mock.calls.some(([command]) => command.endsWith('finishExport'))+ ).toBe(false);+ expect(invoke).toHaveBeenLastCalledWith(+ 'plugin:android-mobile|discardExport',+ { token: 'test-token' }+ );+ });+});diff --git a/apps/web/src/lib/core/mobile/androidFiles.ts b/apps/web/src/lib/core/mobile/androidFiles.tsnew file mode 100644index 0000000000..f7ff98324b--- /dev/null+++ b/apps/web/src/lib/core/mobile/androidFiles.ts@@ -0,0 +1,53 @@+import { invoke } from '@tauri-apps/api/core';++const EXPORT_CHUNK_BYTES = 256 * 1024;++export type AndroidFileAction = 'save' | 'share' | 'copy';++/**+ * Exports already-fetched bytes, including authenticated downloads and Blob+ * URLs. The native side owns the size limit and rejects at `beginExport`.+ */+export async function exportAndroidFile(+ blob: Blob,+ name: string,+ action: AndroidFileAction = 'save',+ options?: { signal?: AbortSignal; onProgress?: (fraction: number) => void }+): Promise<{ canceled: boolean }> {+ options?.signal?.throwIfAborted();+ const { token } = await invoke<{ token: string }>(+ 'plugin:android-mobile|beginExport',+ {+ name,+ mimeType: blob.type || 'application/octet-stream',+ size: blob.size,+ }+ );+ try {+ for (let offset = 0; offset < blob.size; offset += EXPORT_CHUNK_BYTES) {+ options?.signal?.throwIfAborted();+ const bytes = new Uint8Array(+ await blob.slice(offset, offset + EXPORT_CHUNK_BYTES).arrayBuffer()+ );+ let binary = '';+ for (const byte of bytes) binary += String.fromCharCode(byte);+ await invoke('plugin:android-mobile|appendExport', {+ token,+ data: btoa(binary),+ });+ options?.onProgress?.(+ Math.min(offset + bytes.length, blob.size) / blob.size+ );+ }+ options?.signal?.throwIfAborted();+ return await invoke('plugin:android-mobile|finishExport', {+ token,+ action,+ });+ } finally {+ // Cleanup failures must not mask the export result or its error.+ await invoke('plugin:android-mobile|discardExport', { token }).catch(+ (error) => console.error('Unable to discard Android export', error)+ );+ }+}diff --git a/apps/web/src/lib/core/mobile/androidWindowInsets.test.ts b/apps/web/src/lib/core/mobile/androidWindowInsets.test.tsnew file mode 100644index 0000000000..554bdf4de5--- /dev/null+++ b/apps/web/src/lib/core/mobile/androidWindowInsets.test.ts@@ -0,0 +1,134 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { applyAndroidWindowInsets } from './androidWindowInsets';+import {+ virtualKeyboardHeight,+ virtualKeyboardVisible,+} from './virtualKeyboard';++afterEach(() => {+ document.documentElement.removeAttribute('style');+ vi.restoreAllMocks();+});++describe('Android window insets', () => {+ it('shrinks the layout root by the keyboard and lifts fixed sheets, like iOS', () => {+ applyAndroidWindowInsets(+ {+ top: 24,+ right: 0,+ bottom: 0,+ left: 0,+ imeHeight: 300,+ imeVisible: true,+ viewportWidth: 400,+ viewportHeight: 500,+ },+ 400+ );+ // The WebView is not resized: 500 - 300 = 200 CSS px of layout root.+ expect(document.documentElement.style.getPropertyValue('--dvh')).toBe(+ '2px'+ );+ expect(virtualKeyboardHeight()).toBe(300);+ expect(+ document.documentElement.style.getPropertyValue(+ '--virtual-keyboard-height'+ )+ ).toBe('300px');+ expect(virtualKeyboardVisible()).toBe(true);+ });++ it('updates every safe edge on rotation and restores the navigation inset after hiding', () => {+ applyAndroidWindowInsets(+ {+ top: 0,+ right: 24,+ bottom: 20,+ left: 32,+ imeHeight: 0,+ imeVisible: false,+ viewportWidth: 800,+ viewportHeight: 380,+ },+ 800+ );+ const style = document.documentElement.style;+ expect(style.getPropertyValue('--dvh')).toBe('1dvh');+ expect(style.getPropertyValue('--tauri-inset-right')).toBe('24px');+ expect(style.getPropertyValue('--tauri-inset-left')).toBe('32px');+ expect(style.getPropertyValue('--tauri-inset-bottom')).toBe('20px');+ expect(virtualKeyboardVisible()).toBe(false);+ });++ it('converts native safe areas into CSS pixels during display-density changes', () => {+ applyAndroidWindowInsets(+ {+ top: 48,+ right: 0,+ bottom: 32,+ left: 24,+ imeHeight: 0,+ imeVisible: false,+ viewportWidth: 800,+ viewportHeight: 1000,+ },+ 400+ );+ const style = document.documentElement.style;+ expect(style.getPropertyValue('--tauri-inset-top')).toBe('24px');+ expect(style.getPropertyValue('--tauri-inset-bottom')).toBe('16px');+ expect(style.getPropertyValue('--tauri-inset-left')).toBe('12px');+ expect(style.getPropertyValue('--dvh')).toBe('1dvh');+ });++ it('keeps the safe areas when a keyboard resize shrinks only the height', () => {+ const closed = {+ top: 36,+ right: 0,+ bottom: 27,+ left: 0,+ imeHeight: 0,+ imeVisible: false,+ viewportWidth: 384,+ viewportHeight: 832,+ };+ applyAndroidWindowInsets(closed, 384);+ const style = document.documentElement.style;+ expect(style.getPropertyValue('--tauri-inset-top')).toBe('36px');+ // The window resize event fires before the next insets event; the stale+ // insets must not be rescaled by the shorter viewport.+ const setProperty = vi.spyOn(style, 'setProperty');+ applyAndroidWindowInsets(closed, 384);+ expect(style.getPropertyValue('--tauri-inset-top')).toBe('36px');+ expect(setProperty).not.toHaveBeenCalled();+ });++ it('writes only the root properties whose value changed', () => {+ const style = document.documentElement.style;+ const closed = {+ top: 36,+ right: 0,+ bottom: 27,+ left: 0,+ imeHeight: 0,+ imeVisible: false,+ viewportWidth: 384,+ viewportHeight: 832,+ };+ applyAndroidWindowInsets(closed, 384);+ const setProperty = vi.spyOn(style, 'setProperty');+ applyAndroidWindowInsets(+ { ...closed, bottom: 0, imeHeight: 358, imeVisible: true },+ 384+ );+ // Only the values the keyboard changes: no top/left/right rewrite.+ expect(setProperty).toHaveBeenCalledTimes(3);+ expect(setProperty).toHaveBeenCalledWith('--tauri-inset-bottom', '0px');+ expect(setProperty).toHaveBeenCalledWith('--dvh', '4.74px');+ expect(setProperty).toHaveBeenCalledWith(+ '--virtual-keyboard-height',+ '358px'+ );+ expect(virtualKeyboardHeight()).toBe(358);+ });+});diff --git a/apps/web/src/lib/core/mobile/androidWindowInsets.ts b/apps/web/src/lib/core/mobile/androidWindowInsets.tsnew file mode 100644index 0000000000..998283b423--- /dev/null+++ b/apps/web/src/lib/core/mobile/androidWindowInsets.ts@@ -0,0 +1,121 @@+import { isPlatform } from '@core/util/platform';+import { addPluginListener, invoke } from '@tauri-apps/api/core';+import { onCleanup, onMount } from 'solid-js';+import {+ setVirtualKeyboardHeight,+ setVirtualKeyboardVisible,+ virtualKeyboardHeight,+} from './virtualKeyboard';++export type AndroidWindowInsets = {+ top: number;+ right: number;+ bottom: number;+ left: number;+ imeVisible: boolean;+ imeHeight: number;+ viewportWidth: number;+ viewportHeight: number;+};++/**+ * Native dp to CSS px. Android can publish a new display density before+ * Chromium updates its viewport, so native dp is not always CSS px. Width is+ * the reference because the keyboard only changes height: a keyboard resize+ * must never rescale the safe-area insets.+ */+function cssScale(insets: AndroidWindowInsets, cssViewportWidth: number) {+ return insets.viewportWidth > 0 ? cssViewportWidth / insets.viewportWidth : 1;+}++// Every root custom-property write recalculates style for the whole document.+function setRootPropertyIfChanged(name: string, value: string) {+ const style = document.documentElement.style;+ if (style.getPropertyValue(name) !== value) style.setProperty(name, value);+}++export function applyAndroidWindowInsets(+ insets: AndroidWindowInsets,+ cssViewportWidth = window.innerWidth+) {+ const scale = cssScale(insets, cssViewportWidth);+ const keyboardHeight = insets.imeVisible ? insets.imeHeight * scale : 0;+ for (const side of ['top', 'right', 'bottom', 'left'] as const) {+ setRootPropertyIfChanged(+ `--tauri-inset-${side}`,+ `${insets[side] * scale}px`+ );+ }+ // The WebView keeps its full height under the keyboard, as on iOS: the+ // layout root shrinks through --dvh and fixed sheets lift by the keyboard+ // height, so nothing subtracts the keyboard twice.+ setRootPropertyIfChanged(+ '--dvh',+ insets.imeVisible+ ? `${(insets.viewportHeight * scale - keyboardHeight) * 0.01}px`+ : '1dvh'+ );+ setRootPropertyIfChanged('--virtual-keyboard-height', `${keyboardHeight}px`);+ setVirtualKeyboardHeight(keyboardHeight);+ setVirtualKeyboardVisible(insets.imeVisible);+}++export function useAndroidWindowInsets() {+ if (!isPlatform('android')) return;+ onMount(() => {+ let disposed = false;+ let remove: (() => Promise<void>) | undefined;+ let receivedEvent = false;+ let currentInsets: AndroidWindowInsets | undefined;+ const applyInsets = (insets: AndroidWindowInsets) => {+ const wasVisible = currentInsets?.imeVisible ?? false;+ currentInsets = insets;+ applyAndroidWindowInsets(insets);+ // Same window events the iOS keyboard bridge dispatches, for behaviours+ // such as keeping a channel scrolled to its latest message.+ if (insets.imeVisible !== wasVisible) {+ window.dispatchEvent(+ new CustomEvent(+ insets.imeVisible ? 'keyboardWillShow' : 'keyboardWillHide',+ { detail: { height: virtualKeyboardHeight() } }+ )+ );+ }+ };+ // Re-applies after Chromium catches up with a density change; a keyboard+ // resize leaves the width-based scale alone, so it writes nothing.+ const onResize = () => {+ if (currentInsets) applyAndroidWindowInsets(currentInsets);+ };+ window.addEventListener('resize', onResize);+ const initialize = async () => {+ try {+ const listener = await addPluginListener<AndroidWindowInsets>(+ 'android-mobile',+ 'insets',+ (insets) => {+ receivedEvent = true;+ if (!disposed) applyInsets(insets);+ }+ );+ if (disposed) {+ await listener.unregister();+ return;+ }+ remove = () => listener.unregister();+ const insets = await invoke<AndroidWindowInsets>(+ 'plugin:android-mobile|getInsets'+ );+ if (!disposed && !receivedEvent) applyInsets(insets);+ } catch (error) {+ console.error('Unable to initialize Android window insets', error);+ }+ };+ void initialize();+ onCleanup(() => {+ disposed = true;+ window.removeEventListener('resize', onResize);+ if (remove) void remove();+ });+ });+}diff --git a/apps/web/src/lib/core/mobile/exportAndroidFileWithProgress.ts b/apps/web/src/lib/core/mobile/exportAndroidFileWithProgress.tsnew file mode 100644index 0000000000..a9dd74cdb7--- /dev/null+++ b/apps/web/src/lib/core/mobile/exportAndroidFileWithProgress.ts@@ -0,0 +1,38 @@+import { toast } from '@core/component/Toast/Toast';+import { createSignal } from 'solid-js';+import { type AndroidFileAction, exportAndroidFile } from './androidFiles';++/** Keep long Blob transfers visible and cancelable before launching a file action. */+export async function exportAndroidFileWithProgress(+ blob: Blob,+ name: string,+ action: AndroidFileAction = 'save'+): Promise<{ canceled: boolean }> {+ if (blob.size < 1024 * 1024) return exportAndroidFile(blob, name, action);+ const controller = new AbortController();+ const [progress, setProgress] = createSignal(0);+ const id = toast.custom(+ {+ get title() {+ return `Preparing file… ${Math.round(progress() * 100)}%`;+ },+ actions: [{ label: 'Cancel', onClick: () => controller.abort() }],+ },+ { persistent: true }+ );+ try {+ return await exportAndroidFile(blob, name, action, {+ signal: controller.signal,+ onProgress: (fraction) => {+ setProgress(fraction);+ // The transfer is done before the native chooser opens over the app.+ if (fraction === 1) toast.dismiss(id);+ },+ });+ } catch (error) {+ if (controller.signal.aborted) return { canceled: true };+ throw error;+ } finally {+ toast.dismiss(id);+ }+}diff --git a/apps/web/src/lib/core/mobile/haptics.ts b/apps/web/src/lib/core/mobile/haptics.tsindex df492b45b1..235e63da61 100644--- a/apps/web/src/lib/core/mobile/haptics.ts+++ b/apps/web/src/lib/core/mobile/haptics.ts@@ -1,9 +1,17 @@-import { isTauri } from '@tauri-apps/api/core';import { impactFeedback } from '@tauri-apps/plugin-haptics';+import { isNativeMobilePlatform } from './isNativeMobilePlatform';type ImpactStyle = Parameters<typeof impactFeedback>[0];export function hapticImpact(style: ImpactStyle): void {- if (!isTauri()) return;- void impactFeedback(style);+ if (!isNativeMobilePlatform()) return;+ void performImpact(style);+}++async function performImpact(style: ImpactStyle) {+ try {+ await impactFeedback(style);+ } catch {+ // Haptics are optional on tablets and devices without a vibrator.+ }}diff --git a/apps/web/src/lib/core/mobile/mobileClipboardImageRecovery.ts b/apps/web/src/lib/core/mobile/mobileClipboardImageRecovery.tsindex 780c1f56ab..beaa2c06cf 100644--- a/apps/web/src/lib/core/mobile/mobileClipboardImageRecovery.ts+++ b/apps/web/src/lib/core/mobile/mobileClipboardImageRecovery.ts@@ -1,5 +1,6 @@import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { createSyntheticFileEntry } from '@core/util/dataTransfer';+import { isPlatform } from '@core/util/platform';import { isAndroid, isIOS } from '@solid-primitives/platform';import { invoke, isTauri } from '@tauri-apps/api/core';import {@@ -56,7 +57,9 @@ async function readImageEntryFromNativePasteboard(): Promise<FileSystemFileEntrytry {const image = await invoke<NativeStagedUploadData>(- 'plugin:pasteboard|stage_pasteboard_image'+ isPlatform('android')+ ? 'plugin:android-mobile|stageClipboardImage'+ : 'plugin:pasteboard|stage_pasteboard_image');const file = createNativeStagedUploadFile('pasteboard', image);return file ? createSyntheticFileEntry(file) : null;diff --git a/apps/web/src/lib/core/mobile/nativePhotoLibrary.ts b/apps/web/src/lib/core/mobile/nativePhotoLibrary.tsindex 677f2df73b..721347a059 100644--- a/apps/web/src/lib/core/mobile/nativePhotoLibrary.ts+++ b/apps/web/src/lib/core/mobile/nativePhotoLibrary.ts@@ -1,3 +1,4 @@+import { isPlatform } from '@core/util/platform';import { invoke, isTauri } from '@tauri-apps/api/core';import {createNativeStagedUploadFile,@@ -11,7 +12,7 @@ import {* native picker is unavailable so callers can fall back to a file input.*/export async function pickNativePhotoLibraryMedia(): Promise<File[] | null> {- if (!isTauri()) return null;+ if (!isTauri() || !isPlatform('ios')) return null;let media: NativeStagedUploadData[];try {diff --git a/apps/web/src/lib/core/mobile/nativeStagedUpload.ts b/apps/web/src/lib/core/mobile/nativeStagedUpload.tsindex 688e964b19..c128626f92 100644--- a/apps/web/src/lib/core/mobile/nativeStagedUpload.ts+++ b/apps/web/src/lib/core/mobile/nativeStagedUpload.ts@@ -1,3 +1,4 @@+import { contentHash } from '@core/util/hash';import { convertFileSrc, invoke } from '@tauri-apps/api/core';/**@@ -9,7 +10,7 @@ import { convertFileSrc, invoke } from '@tauri-apps/api/core';* URL.*/-export type NativeStagedUploadSource = 'pasteboard' | 'photo-library';+export type NativeStagedUploadSource = 'pasteboard' | 'photo-library' | 'share';export type NativeStagedUploadData = {token: string | null;@@ -17,6 +18,7 @@ export type NativeStagedUploadData = {mimeType: string | null;size: number | null;previewPath: string | null;+ sha256?: string;};export type NativeStagedUpload = {@@ -26,6 +28,7 @@ export type NativeStagedUpload = {mimeType: string;size: number;previewSrc?: string;+ sha256?: string;};const nativeStagedUploads = new WeakMap<File, NativeStagedUpload>();@@ -45,6 +48,7 @@ export function createNativeStagedUploadFile(name: media.name,mimeType: media.mimeType,size: media.size,+ sha256: media.sha256,previewSrc: media.previewPath? convertFileSrc(media.previewPath): undefined,@@ -64,12 +68,72 @@ export function getNativeStagedUpload(*/export async function uploadNativeStagedFileToPresignedUrl(file: NativeStagedUpload,- uploadUrl: string+ uploadUrl: string,+ checksumSha256?: string): Promise<void> {await invoke('upload_staged_file_to_presigned_url', {source: file.source,token: file.token,uploadUrl,mimeType: file.mimeType,+ checksumSha256,});}++/** Native placeholders have no JS bytes; use their staged byte count for limits. */+export function getUploadFileSize(file: File): number {+ return getNativeStagedUpload(file)?.size ?? file.size;+}++/**+ * Android staging supplies a digest. The iOS plugins stage the original bytes+ * but no digest, so hash them through the asset protocol; this pulls the file+ * into JS memory once and caches the result for retries.+ */+export async function getNativeStagedUploadChecksum(+ file: NativeStagedUpload+): Promise<string> {+ if (file.sha256) return file.sha256;+ if (!file.previewSrc) throw new Error('Native attachment bytes unavailable');+ // Use the WebView's asset protocol, not the native HTTP client, for local files.+ const response = await fetch(file.previewSrc);+ if (!response.ok) throw new Error('Unable to read native attachment');+ const bytes = await response.arrayBuffer();+ if (bytes.byteLength !== file.size)+ throw new Error('Native attachment size mismatch');+ file.sha256 = await contentHash(bytes);+ return file.sha256;+}++/** Either JS bytes or a native staged file, with the fields uploads need. */+export type UploadSource =+ | { kind: 'bytes'; buffer: ArrayBuffer; sha: string; size: number }+ | { kind: 'staged'; staged: NativeStagedUpload; sha: string; size: number };++export async function resolveUploadSource(file: File): Promise<UploadSource> {+ const staged = getNativeStagedUpload(file);+ if (staged) {+ const sha = await getNativeStagedUploadChecksum(staged);+ return { kind: 'staged', staged, sha, size: staged.size };+ }+ const buffer = await file.arrayBuffer();+ return {+ kind: 'bytes',+ buffer,+ sha: await contentHash(buffer),+ size: file.size,+ };+}++/** S3 expects the native SHA-256 digest as base64 rather than hexadecimal. */+export function nativeUploadChecksum(sha256: string): string {+ if (!/^[a-f0-9]{64}$/i.test(sha256))+ throw new Error('Invalid staged file checksum');+ let binary = '';+ for (let index = 0; index < sha256.length; index += 2) {+ binary += String.fromCharCode(+ Number.parseInt(sha256.slice(index, index + 2), 16)+ );+ }+ return btoa(binary);+}diff --git a/apps/web/src/lib/core/util/imageActions.ts b/apps/web/src/lib/core/util/imageActions.tsindex 816a90e76c..5d7377ca31 100644--- a/apps/web/src/lib/core/util/imageActions.ts+++ b/apps/web/src/lib/core/util/imageActions.ts@@ -1,5 +1,7 @@import { toast } from '@core/component/Toast/Toast';+import { exportAndroidFileWithProgress } from '@core/mobile/exportAndroidFileWithProgress';import { isTouchDevice } from '@core/mobile/isTouchDevice';+import { isPlatform } from './platform';function extensionForImageBlob(blob: Blob): string {const t = (blob.type || '').toLowerCase().split(';')[0].trim();@@ -54,6 +56,16 @@ export async function copyImageToClipboard(const blob = await getBlob();if (!blob) throw new Error('No blob');+ if (isPlatform('android')) {+ const { canceled } = await exportAndroidFileWithProgress(+ blob,+ `image.${extensionForImageBlob(blob)}`,+ 'copy'+ );+ if (!canceled) toast.success('Copied to clipboard');+ return;+ }+if (isTouchDevice() && navigator.share) {try {await navigator.share({@@ -111,6 +123,11 @@ export async function downloadImage(const filename = `image-${imageId}.${extensionForImageBlob(blob)}`;+ if (isPlatform('android')) {+ await exportAndroidFileWithProgress(blob, filename, 'share');+ return;+ }+// iOS: Use the native share sheet instead — the user can save to Photos, AirDrop, etc.if (isTouchDevice() && navigator.share) {try {diff --git a/apps/web/src/lib/core/util/upload.ts b/apps/web/src/lib/core/util/upload.tsindex e9a99b7461..33b979ccae 100644--- a/apps/web/src/lib/core/util/upload.ts+++ b/apps/web/src/lib/core/util/upload.ts@@ -359,7 +359,7 @@ async function uploadToDSS(file: UploadFile,options: DssUploadFileOptions): Promise<DssUploadSuccessResult> {- if (isNativeStagedUpload(file)) {+ if (isNativeStagedUpload(file) && !file.sha256) {throw new UploadError(file,'dss',diff --git a/apps/web/src/lib/core/util/uploadFile.ts b/apps/web/src/lib/core/util/uploadFile.tsindex 092a6b6ca3..e67521fcb1 100644--- a/apps/web/src/lib/core/util/uploadFile.ts+++ b/apps/web/src/lib/core/util/uploadFile.ts@@ -33,6 +33,7 @@ export type NativeStagedUploadFile = {mimeType: string;size: number;previewSrc?: string;+ sha256?: string;};export type UploadFile = BrowserUploadFile | NativeStagedUploadFile;diff --git a/apps/web/src/lib/filesystem/download.ts b/apps/web/src/lib/filesystem/download.tsindex d92f888001..99ae99c823 100644--- a/apps/web/src/lib/filesystem/download.ts+++ b/apps/web/src/lib/filesystem/download.ts@@ -1,4 +1,32 @@-export function downloadFile(blob: Blob, name: string): void {+import { toast } from '@core/component/Toast/Toast';+import { exportAndroidFileWithProgress } from '@core/mobile/exportAndroidFileWithProgress';+import { isPlatform } from '@core/util/platform';++/**+ * Hands a Blob to the platform's save flow. Browsers download immediately;+ * Android opens a save dialog. `saved` is false when the user cancels or the+ * save fails; failures are already reported with a toast, so callers only+ * need the outcome to decide what happens next.+ */+export async function downloadFile(+ blob: Blob,+ name: string+): Promise<{ saved: boolean }> {+ try {+ if (isPlatform('android')) {+ const { canceled } = await exportAndroidFileWithProgress(blob, name);+ return { saved: !canceled };+ }+ downloadWithAnchor(blob, name);+ return { saved: true };+ } catch (error) {+ console.error('Unable to save file', error);+ toast.failure('Unable to save file');+ return { saved: false };+ }+}++function downloadWithAnchor(blob: Blob, name: string) {const url = URL.createObjectURL(blob);let anchor: HTMLAnchorElement | null = null;try {diff --git a/apps/web/src/lib/queries/channel/share-upload.ts b/apps/web/src/lib/queries/channel/share-upload.tsnew file mode 100644index 0000000000..8b2421b0f5--- /dev/null+++ b/apps/web/src/lib/queries/channel/share-upload.ts@@ -0,0 +1,16 @@+import { throwOnErr } from '@core/util/result';+import { staticFileClient } from '@service-static-files/client';+import { useMutation } from '@tanstack/solid-query';++export function usePrepareSharedMediaMutation() {+ return useMutation(() => ({+ gcTime: 0,+ mutationFn: (file: { name: string; mimeType: string }) =>+ throwOnErr(() =>+ staticFileClient.makePresignedUrl({+ file_name: file.name,+ content_type: file.mimeType,+ })+ ),+ }));+}diff --git a/apps/web/src/lib/queries/email/attachment.test.tsx b/apps/web/src/lib/queries/email/attachment.test.tsxindex ee0e42f0b0..043d30bfe6 100644--- a/apps/web/src/lib/queries/email/attachment.test.tsx+++ b/apps/web/src/lib/queries/email/attachment.test.tsx@@ -1,12 +1,21 @@+import { createNativeStagedUploadFile } from '@core/mobile/nativeStagedUpload';import { err, ok, type Result } from 'neverthrow';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { useUploadDraftAttachmentsMutation } from './attachment';import { mountEmailMutation } from './tests/mutation';+const invokeMock = vi.hoisted(() => vi.fn());+vi.mock('@tauri-apps/api/core', () => ({+ invoke: invokeMock,+ convertFileSrc: (path: string) => `asset://${path}`,+}));+const addDraftAttachmentMock = vi.hoisted(() => vi.fn());const removeDraftAttachmentMock = vi.hoisted(() => vi.fn());const uploadToPresignedUrlMock = vi.hoisted(() => vi.fn());const toastFailureMock = vi.hoisted(() => vi.fn());+const fetchMock = vi.hoisted(() => vi.fn());+const contentHashMock = vi.hoisted(() => vi.fn(async () => 'a'.repeat(64)));vi.mock('@service-email/client', () => ({emailClient: {@@ -20,7 +29,7 @@ vi.mock('@service-storage/util/uploadToPresignedUrl', () => ({}));vi.mock('@core/util/hash', () => ({- contentHash: vi.fn(async () => 'a'.repeat(64)),+ contentHash: contentHashMock,}));vi.mock('@core/component/Toast/Toast', () => ({@@ -40,6 +49,8 @@ const file = () => {beforeEach(() => {vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ fetchMock.mockReset();addDraftAttachmentMock.mockResolvedValue(ok({attachment_id: 'att-1',@@ -49,6 +60,7 @@ beforeEach(() => {);removeDraftAttachmentMock.mockResolvedValue(ok(undefined));});+afterEach(() => vi.unstubAllGlobals());describe('useUploadDraftAttachmentsMutation', () => {it('assigns the attachment id before the content upload completes', async () => {@@ -144,4 +156,117 @@ describe('useUploadDraftAttachmentsMutation', () => {expect(onAttachmentUploadFailed).toHaveBeenCalledWith(attachment);expect(toastFailureMock).toHaveBeenCalledWith('Failed to save attachments');});+ it('uploads native clipboard bytes with the real size and checksum', async () => {+ const attachment = createNativeStagedUploadFile('pasteboard', {+ token: 'paste-stage-fixture',+ name: 'photo.png',+ mimeType: 'image/png',+ size: 1024,+ previewPath: null,+ sha256: 'ab'.repeat(32),+ })!;+ invokeMock.mockResolvedValue(undefined);+ const mutation = mountEmailMutation(useUploadDraftAttachmentsMutation);+ await mutation.mutateAsync({+ draftID: 'draft-1',+ attachments: [attachment],+ });+ expect(addDraftAttachmentMock).toHaveBeenCalledWith(+ {+ draftID: 'draft-1',+ attachment: {+ file_name: 'photo.png',+ size: 1024,+ sha: 'ab'.repeat(32),+ },+ },+ undefined+ );+ expect(uploadToPresignedUrlMock).not.toHaveBeenCalled();+ expect(fetchMock).not.toHaveBeenCalled();+ expect(invokeMock).toHaveBeenCalledWith(+ 'upload_staged_file_to_presigned_url',+ {+ source: 'pasteboard',+ token: 'paste-stage-fixture',+ uploadUrl: 'https://bucket/att-1',+ mimeType: 'application/pdf',+ checksumSha256: btoa(+ String.fromCharCode(...new Uint8Array(32).fill(171))+ ),+ }+ );+ });++ it.each(['pasteboard', 'photo-library'] as const)(+ 'hashes the real staged %s bytes when the iOS plugin supplies no digest',+ async (source) => {+ const bytes = new Uint8Array([1, 2, 3]).buffer;+ fetchMock.mockResolvedValue({ ok: true, arrayBuffer: async () => bytes });+ const attachment = createNativeStagedUploadFile(source, {+ token: 'native-fixture',+ name: 'photo.png',+ mimeType: 'image/png',+ size: 3,+ previewPath: '/staging/photo.png',+ })!;+ Object.defineProperty(attachment, 'arrayBuffer', {+ value: () => {+ throw new Error('Must not hash the empty placeholder');+ },+ });+ invokeMock.mockResolvedValue(undefined);+ const mutation = mountEmailMutation(useUploadDraftAttachmentsMutation);+ await mutation.mutateAsync({+ draftID: 'draft-1',+ attachments: [attachment],+ });++ expect(fetchMock).toHaveBeenCalledWith('asset:///staging/photo.png');+ expect(contentHashMock).toHaveBeenCalledWith(bytes);+ expect(addDraftAttachmentMock).toHaveBeenCalledWith(+ {+ draftID: 'draft-1',+ attachment: { file_name: 'photo.png', size: 3, sha: 'a'.repeat(64) },+ },+ undefined+ );+ expect(invokeMock).toHaveBeenCalledWith(+ 'upload_staged_file_to_presigned_url',+ {+ source,+ token: 'native-fixture',+ uploadUrl: 'https://bucket/att-1',+ mimeType: 'application/pdf',+ checksumSha256: btoa(+ String.fromCharCode(...new Uint8Array(32).fill(170))+ ),+ }+ );+ expect(uploadToPresignedUrlMock).not.toHaveBeenCalled();+ }+ );++ it.each([+ { ok: false, bytes: new Uint8Array([1, 2, 3]).buffer },+ { ok: true, bytes: new ArrayBuffer(0) },+ ])(+ 'does not create a record when the staged bytes cannot be read intact: $ok',+ async ({ ok, bytes }) => {+ fetchMock.mockResolvedValue({ ok, arrayBuffer: async () => bytes });+ const attachment = createNativeStagedUploadFile('pasteboard', {+ token: 'native-fixture',+ name: 'photo.png',+ mimeType: 'image/png',+ size: 3,+ previewPath: '/staging/photo.png',+ })!;+ const mutation = mountEmailMutation(useUploadDraftAttachmentsMutation);+ await expect(+ mutation.mutateAsync({ draftID: 'draft-1', attachments: [attachment] })+ ).rejects.toThrow();+ expect(addDraftAttachmentMock).not.toHaveBeenCalled();+ expect(invokeMock).not.toHaveBeenCalled();+ }+ );});diff --git a/apps/web/src/lib/queries/email/attachment.ts b/apps/web/src/lib/queries/email/attachment.tsindex 8978dfbbbf..ed18c9f437 100644--- a/apps/web/src/lib/queries/email/attachment.ts+++ b/apps/web/src/lib/queries/email/attachment.ts@@ -1,5 +1,9 @@import { toast } from '@core/component/Toast/Toast';-import { contentHash } from '@core/util/hash';+import {+ nativeUploadChecksum,+ resolveUploadSource,+ uploadNativeStagedFileToPresignedUrl,+} from '@core/mobile/nativeStagedUpload';import { throwOnErr } from '@core/util/result';import { type MutationCallbacks, withCallbacks } from '@queries/utils';import { emailClient } from '@service-email/client';@@ -43,8 +47,7 @@ export const useUploadDraftAttachmentsMutation = (return useMutation(() => ({mutationFn: async (params: UploadDraftAttachmentsParams) => {for (const attachment of params.attachments) {- const arrayBuffer = await attachment.arrayBuffer();- const sha = await contentHash(arrayBuffer);+ const source = await resolveUploadSource(attachment);const result = await throwOnErr(async () =>@@ -53,8 +56,8 @@ export const useUploadDraftAttachmentsMutation = (draftID: params.draftID,attachment: {file_name: attachment.name,- size: attachment.size,- sha,+ size: source.size,+ sha: source.sha,},},params.linkId@@ -67,37 +70,42 @@ export const useUploadDraftAttachmentsMutation = (// so onError removes the record and clears the id -- a plain throw from// the fetch (network drop, abort) would otherwise leave the id in// place and the broken record would never be retried.- let uploadedResponse: Awaited<ReturnType<typeof uploadToPresignedUrl>>;+ const context = {+ attachmentID: result.attachment_id,+ file: attachment,+ };try {- uploadedResponse = await uploadToPresignedUrl({- presignedUrl: result.upload_url,- sha,- buffer: arrayBuffer,- type: result.content_type,- });+ if (source.kind === 'staged') {+ await uploadNativeStagedFileToPresignedUrl(+ { ...source.staged, mimeType: result.content_type },+ result.upload_url,+ nativeUploadChecksum(source.sha)+ );+ } else {+ const uploaded = await uploadToPresignedUrl({+ presignedUrl: result.upload_url,+ sha: source.sha,+ buffer: source.buffer,+ type: result.content_type,+ });+ if (uploaded.isErr()) {+ const uploadError = uploaded.error[0] ?? {+ code: 'SERVER_ERROR',+ message: 'Upload failed',+ };+ throw new UploadDraftAttachmentError(+ uploadError.message,+ { cause: uploadError.code },+ context+ );+ }+ }} catch (cause) {+ if (cause instanceof UploadDraftAttachmentError) throw cause;throw new UploadDraftAttachmentError('Upload failed',{ cause },- {- attachmentID: result.attachment_id,- file: attachment,- }- );- }-- if (uploadedResponse.isErr()) {- const uploadError = uploadedResponse.error[0] ?? {- code: 'SERVER_ERROR',- message: 'Upload failed',- };- throw new UploadDraftAttachmentError(- uploadError.message,- { cause: uploadError.code },- {- attachmentID: result.attachment_id,- file: attachment,- }+ context);}}diff --git a/apps/web/src/lib/service-clients/service-storage/util/upload-native.test.ts b/apps/web/src/lib/service-clients/service-storage/util/upload-native.test.tsnew file mode 100644index 0000000000..8c36bc5875--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/util/upload-native.test.ts@@ -0,0 +1,228 @@+import { ok } from 'neverthrow';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ invoke: vi.fn(),+ createDocument: vi.fn(),+ deleteDocument: vi.fn(),+ browserPut: vi.fn(),+ ready: vi.fn(),+ createUploadZipRequest: vi.fn(),+ bulkUploadStatus: vi.fn(),+ createUploadToast: vi.fn(),+ dismissToast: vi.fn(),+ contentHash: vi.fn(),+ fetch: vi.fn(),+}));+vi.mock('@tauri-apps/api/core', () => ({+ invoke: mocks.invoke,+ convertFileSrc: (path: string) => path,+}));+vi.mock('@app/lib/analytics', () => ({ analytics: { track: vi.fn() } }));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { success: vi.fn(), failure: vi.fn() },+ createUploadToast: mocks.createUploadToast,+}));+vi.mock('@core/constant/allBlocks', () => ({+ blockAcceptedMimetypeToFileExtension: { 'application/pdf': 'pdf' },+}));+vi.mock('@core/constant/PaywallState', () => ({+ usePaywallState: () => ({ showPaywall: vi.fn() }),+ PaywallKey: {},+}));+vi.mock('@core/util/hash', () => ({ contentHash: mocks.contentHash }));+vi.mock('@kobalte/core/toast', () => ({+ toaster: { dismiss: mocks.dismissToast },+}));+vi.mock('@queries/storage/document-location', () => ({+ waitForDocumentContentReady: mocks.ready,+}));+vi.mock('@service-connection/bulkUpload', () => ({+ waitBulkUploadStatus: mocks.bulkUploadStatus,+}));+vi.mock('@service-storage/client', () => ({+ DOCUMENT_NAME_TOO_LONG_CODE: 'name-too-long',+ storageServiceClient: {+ createDocument: mocks.createDocument,+ deleteDocument: mocks.deleteDocument,+ projects: { createUploadZipRequest: mocks.createUploadZipRequest },+ },+}));+vi.mock('@service-storage/util/uploadToPresignedUrl', () => ({+ uploadToPresignedUrl: mocks.browserPut,+}));+vi.mock('@service-storage/websocket', () => ({ storageWS: {} }));+vi.mock('./uploadDocx', () => ({ uploadDocx: vi.fn() }));++import { createNativeStagedUploadFile } from '@core/mobile/nativeStagedUpload';+import { upload } from './upload';++function stagedPdf() {+ const file = createNativeStagedUploadFile('share', {+ token: 'share-stage-test',+ name: 'manual.pdf',+ mimeType: 'application/pdf',+ size: 400_000_000,+ previewPath: null,+ sha256: 'ab'.repeat(32),+ })!;+ Object.defineProperty(file, 'arrayBuffer', {+ value: () => {+ throw new Error('Must not read the empty JS placeholder');+ },+ });+ return file;+}+beforeEach(() => {+ vi.resetAllMocks();+ vi.stubGlobal('fetch', mocks.fetch);+ mocks.contentHash.mockResolvedValue('cd'.repeat(32));+ mocks.createUploadToast.mockReturnValue(42);+ mocks.browserPut.mockResolvedValue(ok(undefined));+ mocks.createUploadZipRequest.mockResolvedValue(+ ok({ presignedUrl: 'https://example.com/zip', requestId: 'zip-request' })+ );+ mocks.bulkUploadStatus.mockResolvedValue('project');+ mocks.createDocument.mockResolvedValue(+ ok({+ metadata: { documentId: 'doc', documentVersionId: 1 },+ presignedUrl: 'https://example.com/upload',+ contentType: 'application/pdf',+ fileType: 'pdf',+ })+ );+ mocks.ready.mockResolvedValue({ content: { state: 'ready' } });+});+afterEach(() => vi.unstubAllGlobals());+describe('native shared document upload', () => {+ it('uses the staged checksum and streams native bytes without reading the JS placeholder', async () => {+ const result = await upload(stagedPdf(), { hideProgressIndicator: true });+ expect(result).toMatchObject({ type: 'document', documentId: 'doc' });+ expect(mocks.createDocument).toHaveBeenCalledWith(+ expect.objectContaining({+ sha: 'ab'.repeat(32),+ documentName: 'manual.pdf',+ })+ );+ expect(mocks.invoke).toHaveBeenCalledWith(+ 'upload_staged_file_to_presigned_url',+ {+ source: 'share',+ token: 'share-stage-test',+ uploadUrl: 'https://example.com/upload',+ mimeType: 'application/pdf',+ checksumSha256: btoa(+ String.fromCharCode(...new Uint8Array(32).fill(171))+ ),+ }+ );+ expect(mocks.browserPut).not.toHaveBeenCalled();+ expect(mocks.deleteDocument).not.toHaveBeenCalled();+ expect(mocks.fetch).not.toHaveBeenCalled();+ expect(mocks.contentHash).not.toHaveBeenCalled();+ });+ it('removes the newly created document if the native PUT fails', async () => {+ mocks.invoke.mockRejectedValue(new Error('Upload failed'));+ await expect(+ upload(stagedPdf(), { hideProgressIndicator: true })+ ).rejects.toThrow('Failed to upload file');+ expect(mocks.deleteDocument).toHaveBeenCalledWith({ documentId: 'doc' });+ expect(mocks.ready).not.toHaveBeenCalled();+ });+});++describe.each(['pdf', 'zip'])('%s upload checksums', (extension) => {+ function stagedWithoutChecksum() {+ const file = createNativeStagedUploadFile('pasteboard', {+ token: 'ios-stage-test',+ name: `attachment.${extension}`,+ mimeType: `application/${extension}`,+ size: 3,+ previewPath: 'https://asset.localhost/attachment',+ })!;+ Object.defineProperty(file, 'arrayBuffer', {+ value: () => {+ throw new Error('Must not read the empty JS placeholder');+ },+ });+ return file;+ }++ it('hashes staged bytes when the native source provides no checksum', async () => {+ const bytes = new Uint8Array([1, 2, 3]).buffer;+ mocks.fetch.mockResolvedValue({+ ok: true,+ arrayBuffer: async () => bytes,+ });++ await upload(stagedWithoutChecksum(), { unzipFolder: true });++ expect(mocks.fetch).toHaveBeenCalledWith(+ 'https://asset.localhost/attachment'+ );+ expect(mocks.contentHash).toHaveBeenCalledWith(bytes);+ const createRequest =+ extension === 'zip' ? mocks.createUploadZipRequest : mocks.createDocument;+ expect(createRequest).toHaveBeenCalledWith(+ expect.objectContaining({ sha: 'cd'.repeat(32) })+ );+ expect(mocks.invoke).toHaveBeenCalledWith(+ 'upload_staged_file_to_presigned_url',+ expect.objectContaining({+ token: 'ios-stage-test',+ checksumSha256: btoa(+ String.fromCharCode(...new Uint8Array(32).fill(205))+ ),+ })+ );+ expect(mocks.browserPut).not.toHaveBeenCalled();+ });++ it('dismisses the toast and creates no upload request if staged checksum calculation fails', async () => {+ mocks.fetch.mockRejectedValue(new Error('Native bytes unavailable'));++ await expect(+ upload(stagedWithoutChecksum(), { unzipFolder: true })+ ).rejects.toThrow('Native bytes unavailable');++ expect(mocks.dismissToast).toHaveBeenCalledWith(42);+ expect(mocks.createDocument).not.toHaveBeenCalled();+ expect(mocks.createUploadZipRequest).not.toHaveBeenCalled();+ expect(mocks.invoke).not.toHaveBeenCalled();+ expect(mocks.browserPut).not.toHaveBeenCalled();+ });+});++describe('browser upload checksums', () => {+ it('still hashes and uploads the original file bytes', async () => {+ const bytes = new Uint8Array([1, 2, 3]).buffer;+ const file = new File([], 'browser.pdf', { type: 'application/pdf' });+ Object.defineProperty(file, 'arrayBuffer', { value: async () => bytes });++ await upload(file);++ expect(mocks.contentHash).toHaveBeenCalledWith(bytes);+ expect(mocks.browserPut).toHaveBeenCalledWith({+ presignedUrl: 'https://example.com/upload',+ buffer: bytes,+ sha: 'cd'.repeat(32),+ type: 'application/pdf',+ });+ expect(mocks.fetch).not.toHaveBeenCalled();+ expect(mocks.invoke).not.toHaveBeenCalled();+ });++ it('dismisses the toast before creating a document if hashing fails', async () => {+ const file = new File([], 'browser.pdf', { type: 'application/pdf' });+ Object.defineProperty(file, 'arrayBuffer', {+ value: async () => new ArrayBuffer(0),+ });+ mocks.contentHash.mockRejectedValue(new Error('Hash failed'));++ await expect(upload(file)).rejects.toThrow('Hash failed');++ expect(mocks.dismissToast).toHaveBeenCalledWith(42);+ expect(mocks.createDocument).not.toHaveBeenCalled();+ expect(mocks.browserPut).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/service-clients/service-storage/util/upload.ts b/apps/web/src/lib/service-clients/service-storage/util/upload.tsindex bcfa9f870b..7c75b521f6 100644--- a/apps/web/src/lib/service-clients/service-storage/util/upload.ts+++ b/apps/web/src/lib/service-clients/service-storage/util/upload.ts@@ -3,7 +3,13 @@ import type { FileTypeString, MimeType } from '@core/block';import { createUploadToast, toast } from '@core/component/Toast/Toast';import { blockAcceptedMimetypeToFileExtension } from '@core/constant/allBlocks';import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';-import { contentHash } from '@core/util/hash';+import {+ getUploadFileSize,+ nativeUploadChecksum,+ resolveUploadSource,+ type UploadSource,+ uploadNativeStagedFileToPresignedUrl,+} from '@core/mobile/nativeStagedUpload';import type { ResultError } from '@core/util/result';import { toaster } from '@kobalte/core/toast';import { waitForDocumentContentReady } from '@queries/storage/document-location';@@ -133,7 +139,7 @@ export async function upload(analytics.track('upload_file', {fileType: fileTypeOrExtension,fileName: file.name,- fileSize: file.size,+ fileSize: getUploadFileSize(file),destination: 'dss',folder: isZip,});@@ -146,8 +152,37 @@ export async function upload(? createUploadToast(`Uploading ${name}`): null;- const buffer = await file.arrayBuffer();- const sha = await contentHash(buffer);+ let source: UploadSource;+ try {+ source = await resolveUploadSource(file);+ } catch (error) {+ return handleUploadError(+ error instanceof Error ? error : String(error),+ toastId+ );+ }+ const { sha } = source;+ const putFile = async (presignedUrl: string, type: MimeType) => {+ if (source.kind === 'bytes') {+ return uploadWithPresignedUrl({+ presignedUrl,+ buffer: source.buffer,+ sha,+ type,+ });+ }+ try {+ await uploadNativeStagedFileToPresignedUrl(+ { ...source.staged, mimeType: type },+ presignedUrl,+ nativeUploadChecksum(sha)+ );+ return true;+ } catch (error) {+ console.error('Native staged upload failed', error);+ return false;+ }+ };if (isZip && options?.unzipFolder) {const res = await storageServiceClient.projects.createUploadZipRequest({@@ -164,12 +199,7 @@ export async function upload(if (!presignedUrl ||!requestId ||- !(await uploadWithPresignedUrl({- presignedUrl,- buffer,- sha,- type: 'application/zip',- }))+ !(await putFile(presignedUrl, 'application/zip'))) {return handleUploadError('Failed to upload zip file', toastId);}@@ -236,14 +266,7 @@ export async function upload(fallbackMime ||'application/octet-stream') as MimeType;- if (- !(await uploadWithPresignedUrl({- presignedUrl,- buffer,- sha,- type: resolvedContentType,- }))- ) {+ if (!(await putFile(presignedUrl, resolvedContentType))) {console.error('failed to upload', documentId, 'removing...');await storageServiceClient.deleteDocument({ documentId });return handleUploadError('Failed to upload file', toastId);diff --git a/apps/web/src/lib/tauri/ShareTargetProvider.test.tsx b/apps/web/src/lib/tauri/ShareTargetProvider.test.tsxnew file mode 100644index 0000000000..d4be452cf7--- /dev/null+++ b/apps/web/src/lib/tauri/ShareTargetProvider.test.tsx@@ -0,0 +1,111 @@+import { createNativeShareSend } from '@app/features/sharing/native-share-sheet/createNativeShareSend';+import { cleanup, render } from '@solidjs/testing-library';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ type PendingShareFile,+ ShareTargetProvider,+ useShareTarget,+} from './ShareTargetProvider';++const invoke = vi.hoisted(() => vi.fn());+let setAndroidFiles: (files: PendingShareFile[]) => void;+let onIosFilesReady:+ | ((event: { payload: { filenames: string[] } }) => void)+ | undefined;++vi.mock('@tauri-apps/api/core', () => ({+ invoke,+ convertFileSrc: (path: string) => `asset://${path}`,+}));+vi.mock('@tauri-apps/api/event', () => ({+ listen: vi.fn((_name, listener) => {+ onIosFilesReady = listener;+ return Promise.resolve(vi.fn());+ }),+}));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { failure: vi.fn() },+}));+vi.mock('./androidShares', () => ({+ useAndroidShares: (setFiles: (files: PendingShareFile[]) => void) => {+ setAndroidFiles = setFiles;+ },+}));++beforeEach(() => {+ onIosFilesReady = undefined;+ invoke.mockReset();+ invoke.mockImplementation(async (command, args) => {+ if (command === 'get_pending_share_filenames') return [];+ if (command === 'pop_shared_files') {+ return args.filenames.map((name: string) => ({+ token: name,+ name,+ mime_type: 'image/png',+ size: 3,+ }));+ }+ });+});+afterEach(cleanup);++describe('share batch acknowledgement', () => {+ it.each(['android', 'ios'] as const)(+ 'keeps the next %s batch when a canceled composer finishes sending',+ async (os) => {+ let context: ReturnType<typeof useShareTarget>;+ function CaptureContext() {+ context = useShareTarget();+ return null;+ }+ render(() => (+ <ShareTargetProvider os={os}>+ <CaptureContext />+ </ShareTargetProvider>+ ));+ if (!context) throw new Error('Missing share target context');+ const target = context;+ const loadBatch = async (token: string) => {+ if (os === 'android') {+ setAndroidFiles([+ { token, name: token, mimeType: 'image/png', size: 3 },+ ]);+ } else {+ onIosFilesReady?.({ payload: { filenames: [token] } });+ }+ await vi.waitFor(() =>+ expect(target.pendingShareFiles().map((file) => file.token)).toEqual([+ token,+ ])+ );+ };++ await loadBatch('batch-a');+ const tokens = target.pendingShareFiles().map((file) => file.token);+ const posted = Promise.withResolvers<void>();+ const share = createNativeShareSend({+ send: () => posted.promise,+ clear: () => target.clearPendingShareFiles(tokens),+ });+ const sending = share.send('draft');+ await target.clearPendingShareFiles();+ await loadBatch('batch-b');+ posted.resolve();+ await sending;++ expect(target.pendingShareFiles().map((file) => file.token)).toEqual([+ 'batch-b',+ ]);+ const clearCommand =+ os === 'android'+ ? 'plugin:android-mobile|clearShares'+ : 'clear_shared_files';+ expect(+ invoke.mock.calls.filter(([command]) => command === clearCommand)+ ).toEqual([+ [clearCommand, { tokens: ['batch-a'] }],+ [clearCommand, { tokens: ['batch-a'] }],+ ]);+ }+ );+});diff --git a/apps/web/src/lib/tauri/ShareTargetProvider.tsx b/apps/web/src/lib/tauri/ShareTargetProvider.tsxindex 96222ec79b..1aab432dc2 100644--- a/apps/web/src/lib/tauri/ShareTargetProvider.tsx+++ b/apps/web/src/lib/tauri/ShareTargetProvider.tsx@@ -1,3 +1,4 @@+import { toast } from '@core/component/Toast/Toast';import { convertFileSrc, invoke } from '@tauri-apps/api/core';import { listen } from '@tauri-apps/api/event';import type { OsType } from '@tauri-apps/plugin-os';@@ -10,6 +11,7 @@ import {onMount,useContext,} from 'solid-js';+import { useAndroidShares } from './androidShares';interface StagedSharedFileData {token: string;@@ -27,6 +29,7 @@ export interface PendingShareFile {previewSrc?: string;isSharedText?: boolean;sharedText?: string;+ sha256?: string;}export interface UploadPendingShareFileArgs {@@ -90,7 +93,7 @@ async function readSharedFileText(token: string): Promise<string> {return invoke<string>('read_shared_file_text', { token });}-async function clearSharedFiles(tokens: string[]): Promise<void> {+async function clearSharedFiles(tokens: readonly string[]): Promise<void> {await invoke('clear_shared_files', { tokens });}@@ -108,7 +111,7 @@ async function uploadPendingShareFile(interface ShareTargetContextValue {pendingShareFiles: Accessor<PendingShareFile[]>;uploadPendingShareFile: (args: UploadPendingShareFileArgs) => Promise<void>;- clearPendingShareFiles: () => Promise<void>;+ clearPendingShareFiles: (tokens?: readonly string[]) => Promise<void>;}const ShareTargetContext = createContext<ShareTargetContextValue | undefined>(@@ -126,22 +129,36 @@ export function ShareTargetProvider(props: {string[]>([]);- const clearPendingShareFiles = async () => {- const files = pendingShareFiles();- setPendingShareFiles([]);- setPendingShareFileNames([]);+ const clearPendingShareFiles = async (+ tokens: readonly string[] = pendingShareFiles().map((file) => file.token)+ ) => {+ if (tokens.length === 0) return;- if (files.length === 0) {- return;- }+ const clearMatchingFiles = () => {+ setPendingShareFiles((current) =>+ current.filter((file) => !tokens.includes(file.token))+ );+ if (pendingShareFiles().length === 0) setPendingShareFileNames([]);+ };+ if (props.os !== 'android') clearMatchingFiles();try {- await clearSharedFiles(files.map((file) => file.token));+ if (props.os === 'android') {+ await invoke('plugin:android-mobile|clearShares', { tokens });+ // A queue notification may already have loaded the next batch.+ clearMatchingFiles();+ } else {+ await clearSharedFiles(tokens);+ }} catch (error) {console.error('failed to clear shared files', error);+ if (props.os === 'android')+ toast.failure('Unable to clear this share. Please try again.');}};+ if (props.os === 'android') useAndroidShares(setPendingShareFiles);+const clearLoadedPendingShare = (files: readonly PendingShareFile[]) => {setPendingShareFiles([]);setPendingShareFileNames([]);diff --git a/apps/web/src/lib/tauri/TauriProvider.tsx b/apps/web/src/lib/tauri/TauriProvider.tsxindex 58dd13e775..244e03c2e3 100644--- a/apps/web/src/lib/tauri/TauriProvider.tsx+++ b/apps/web/src/lib/tauri/TauriProvider.tsx@@ -1,5 +1,7 @@import { NativeCallProvider } from '@channel/Call/native-call-state';import { useCallKitSetup } from '@channel/Call/use-callkit';+import { useAndroidBack } from '@core/mobile/androidBack';+import { useAndroidWindowInsets } from '@core/mobile/androidWindowInsets';import { NativeAppUpdateRequiredDialog } from '@core/mobile/NativeAppUpdateRequiredDialog';import { isPlatform, isTauri } from '@core/util/platform';import { PlatformNotificationProvider } from '@notifications';@@ -17,13 +19,10 @@ import {onMount,useContext,} from 'solid-js';-import { getInsets, type Insets } from 'tauri-plugin-safe-area-insets';import { useTauriNavigationEffect } from './navigation';import { MaybePushNotificationRegistration } from './PushNotification';import { ShareTargetProvider } from './ShareTargetProvider';-type NotAndroid = 'not-android';-export type BundleUpdateStatus =| { status: 'Idle' }| { status: 'CheckingForUpdate' }@@ -42,7 +41,6 @@ export type BundleUpdateStatus =interface TauriContextValue {os: OsType;- runtimeInsets: Accessor<Insets | NotAndroid>;bundleUpdateStatus: Accessor<BundleUpdateStatus>;}@@ -68,10 +66,8 @@ function shouldShowNativeAppUpdateRequiredDialog(status: BundleUpdateStatus) {}function TauriProvider(props: { children: JSX.Element }) {- // we only care about this value on android.- // ios should use the env(safe-area-inset-top) css properties- // this css is not reliably set on android- const [insets, setInsets] = createSignal<NotAndroid | Insets>('not-android');+ useAndroidWindowInsets();+ useAndroidBack();const [bundleUpdateStatus, setBundleUpdateStatus] =createSignal<BundleUpdateStatus>({ status: 'Idle' });const [@@ -101,7 +97,6 @@ function TauriProvider(props: { children: JSX.Element }) {if (isTauri() && isPlatform('ios')) useCallKitSetup();const value: TauriContextValue = {- runtimeInsets: insets,os: osType(),bundleUpdateStatus,};@@ -128,29 +123,6 @@ function TauriProvider(props: { children: JSX.Element }) {unlistenPromise.then((unlisten) => unlisten());});- if (value.os === 'android') {- getInsets().then((insets) => {- setInsets(insets);- // Set CSS variables for Tauri insets- document.documentElement.style.setProperty(- '--tauri-inset-top',- `${insets.top}px`- );- document.documentElement.style.setProperty(- '--tauri-inset-bottom',- `${insets.bottom}px`- );- document.documentElement.style.setProperty(- '--tauri-inset-left',- `${insets.left}px`- );- document.documentElement.style.setProperty(- '--tauri-inset-right',- `${insets.right}px`- );- });- }-document.body.classList.add('tauri');document.body.classList.add(`tauri-${value.os}`);diff --git a/apps/web/src/lib/tauri/androidShares.ts b/apps/web/src/lib/tauri/androidShares.tsnew file mode 100644index 0000000000..9867312fee--- /dev/null+++ b/apps/web/src/lib/tauri/androidShares.ts@@ -0,0 +1,78 @@+import { toast } from '@core/component/Toast/Toast';+import {+ addPluginListener,+ convertFileSrc,+ invoke,+} from '@tauri-apps/api/core';+import { onCleanup, onMount } from 'solid-js';+import type { PendingShareFile } from './ShareTargetProvider';++type AndroidSharedFile = Omit<PendingShareFile, 'previewSrc'> & {+ previewPath?: string;+};++/** The native queue is acknowledged only after cancel/send, including across login. */+export function useAndroidShares(+ setFiles: (files: PendingShareFile[]) => void+) {+ onMount(() => {+ let disposed = false;+ let loading = false;+ let reload = false;+ let remove: (() => Promise<void>) | undefined;+ const refresh = async () => {+ reload = true;+ if (loading) return;+ loading = true;+ try {+ while (reload && !disposed) {+ reload = false;+ const { files, error } = await invoke<{+ files: AndroidSharedFile[];+ error?: string;+ }>('plugin:android-mobile|getPendingShares');+ if (!disposed && error) toast.failure(error);+ if (!disposed)+ setFiles(+ files.map(({ previewPath, ...file }) => ({+ ...file,+ previewSrc: previewPath+ ? convertFileSrc(previewPath)+ : undefined,+ }))+ );+ }+ } catch (error) {+ console.error('Unable to load Android shares', error);+ toast.failure('Unable to load shared attachments');+ } finally {+ loading = false;+ }+ };+ const initialize = async () => {+ try {+ const listener = await addPluginListener<{ error?: string }>(+ 'android-mobile',+ 'shares',+ ({ error }) => {+ if (error) toast.failure(error);+ void refresh();+ }+ );+ if (disposed) {+ await listener.unregister();+ return;+ }+ remove = () => listener.unregister();+ await refresh();+ } catch (error) {+ console.error('Unable to listen for Android shares', error);+ }+ };+ void initialize();+ onCleanup(() => {+ disposed = true;+ if (remove) void remove();+ });+ });+}diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lockindex edacd6f3b9..42ff168631 100644--- a/apps/web/tauri/Cargo.lock+++ b/apps/web/tauri/Cargo.lock@@ -215,6 +215,7 @@ dependencies = ["tauri","tauri-build","tauri-plugin-android-auth",+ "tauri-plugin-android-mobile","tauri-plugin-android-push","tauri-plugin-auth","tauri-plugin-call-kit",@@ -232,7 +233,6 @@ dependencies = ["tauri-plugin-os","tauri-plugin-pasteboard","tauri-plugin-photo-library",- "tauri-plugin-safe-area-insets","tauri-plugin-single-instance","tauri-plugin-virtual-keyboard","tauri-plugin-websocket",@@ -6575,6 +6575,14 @@ dependencies = ["tauri-plugin",]+[[package]]+name = "tauri-plugin-android-mobile"+version = "0.1.0"+dependencies = [+ "tauri",+ "tauri-plugin",+]+[[package]]name = "tauri-plugin-android-push"version = "0.1.0"@@ -6844,18 +6852,6 @@ dependencies = ["tauri-plugin",]-[[package]]-name = "tauri-plugin-safe-area-insets"-version = "0.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "653b425316a0e9563995286eb5b0fa44490583486b7a0925859b33ec5be07f0e"-dependencies = [- "serde",- "tauri",- "tauri-plugin",- "thiserror 2.0.18",-]-[[package]]name = "tauri-plugin-single-instance"version = "2.3.6"diff --git a/apps/web/tauri/Cargo.toml b/apps/web/tauri/Cargo.tomlindex 897cfbbcef..51311194f5 100644--- a/apps/web/tauri/Cargo.toml+++ b/apps/web/tauri/Cargo.toml@@ -1,6 +1,7 @@[workspace]members = ["android_auth_plugin",+ "android_mobile_plugin","android_push_plugin","callkit_plugin","edit_menu_plugin",diff --git a/apps/web/tauri/android_mobile_plugin/.gitignore b/apps/web/tauri/android_mobile_plugin/.gitignorenew file mode 100644index 0000000000..9eeb46b3a4--- /dev/null+++ b/apps/web/tauri/android_mobile_plugin/.gitignore@@ -0,0 +1,5 @@+/android/build+/android/.gradle+/android/.tauri+/permissions/autogenerated+/permissions/schemasdiff --git a/apps/web/tauri/android_mobile_plugin/Cargo.toml b/apps/web/tauri/android_mobile_plugin/Cargo.tomlnew file mode 100644index 0000000000..098d53fa68--- /dev/null+++ b/apps/web/tauri/android_mobile_plugin/Cargo.toml@@ -0,0 +1,11 @@+[package]+name = "tauri-plugin-android-mobile"+version = "0.1.0"+edition.workspace = true+links = "tauri-plugin-android-mobile"++[build-dependencies]+tauri-plugin = { version = "2.4", features = ["build"] }++[dependencies]+tauri = { workspace = true }diff --git a/apps/web/tauri/android_mobile_plugin/android/build.gradle.kts b/apps/web/tauri/android_mobile_plugin/android/build.gradle.ktsnew file mode 100644index 0000000000..0ca3557209--- /dev/null+++ b/apps/web/tauri/android_mobile_plugin/android/build.gradle.kts@@ -0,0 +1,30 @@+plugins {+ id("com.android.library")+ id("org.jetbrains.kotlin.android")+}++android {+ namespace = "com.macro.mobile"+ compileSdk = 36+ defaultConfig {+ minSdk = 24+ targetSdk = 36+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"+ }+ compileOptions {+ sourceCompatibility = JavaVersion.VERSION_1_8+ targetCompatibility = JavaVersion.VERSION_1_8+ }+ kotlinOptions { jvmTarget = "1.8" }+}++dependencies {+ implementation(project(":tauri-android"))+ implementation("androidx.activity:activity-ktx:1.10.1")+ implementation("androidx.appcompat:appcompat:1.7.1")+ implementation("androidx.core:core-ktx:1.13.1")+ testImplementation("junit:junit:4.13.2")+ androidTestImplementation("androidx.test:runner:1.6.2")+ androidTestImplementation("androidx.test:rules:1.6.1")+ androidTestImplementation("androidx.test.ext:junit:1.2.1")+}diff --git a/apps/web/tauri/android_mobile_plugin/android/src/androidTest/AndroidManifest.xml b/apps/web/tauri/android_mobile_plugin/android/src/androidTest/AndroidManifest.xmlnew file mode 100644index 0000000000..d54a81d127--- /dev/null+++ b/apps/web/tauri/android_mobile_plugin/android/src/androidTest/AndroidManifest.xml@@ -0,0 +1,6 @@+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <application>+ <activity android:name="com.macro.mobile.ShareTestActivity" android:exported="false" />+ <provider android:name="com.macro.mobile.ShareTestProvider" android:authorities="com.macro.mobile.test.provider" android:exported="false" android:grantUriPermissions="true" />+ </application>+</manifest>diff --git a/apps/web/tauri/android_mobile_plugin/android/src/androidTest/java/com/macro/mobile/MobileFilesInstrumentedTest.kt b/apps/web/tauri/android_mobile_plugin/android/src/androidTest/java/com/macro/mobile/MobileFilesInstrumentedTest.ktnew file mode 100644index 0000000000..3d4da7d572--- /dev/null+++ b/apps/web/tauri/android_mobile_plugin/android/src/androidTest/java/com/macro/mobile/MobileFilesInstrumentedTest.kt@@ -0,0 +1,171 @@+package com.macro.mobile++import android.app.Activity+import android.content.ClipData+import android.content.ContentProvider+import android.content.ContentValues+import android.content.Intent+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import android.os.ParcelFileDescriptor+import android.provider.OpenableColumns+import androidx.test.core.app.ActivityScenario+import androidx.test.ext.junit.runners.AndroidJUnit4+import org.junit.After+import org.junit.Assert.*+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.json.JSONArray+import java.io.ByteArrayInputStream+import java.io.File+import java.io.FileNotFoundException+import java.security.MessageDigest+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit++class ShareTestActivity : Activity()++/** Isolated instrumentation-only provider: no production bridge/test commands. */+class ShareTestProvider : ContentProvider() {+ override fun onCreate() = true+ override fun getType(uri: Uri): String? = if (uri.lastPathSegment == "unknown") null else "application/octet-stream"+ override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor {+ if (uri.lastPathSegment == "denied") throw SecurityException("Provider refused access")+ return MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE)).apply {+ addRow(arrayOf(if (uri.lastPathSegment == "unknown") "manual.pdf" else "../../漢字😀.bin", Long.MAX_VALUE))+ }+ }+ override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor {+ if (uri.lastPathSegment == "missing") throw FileNotFoundException("Provider item removed")+ val pipe = ParcelFileDescriptor.createReliablePipe()+ Thread {+ try {+ ParcelFileDescriptor.AutoCloseOutputStream(pipe[1]).use { output ->+ val bytes = ByteArray(64 * 1024) { (it % 251).toByte() }+ val chunks = if (uri.lastPathSegment == "large") 512 else 1+ repeat(chunks) { output.write(bytes) }+ }+ } catch (_: Exception) { pipe[1].closeWithError("Provider disconnected") }+ }.start()+ return pipe[0]+ }+ override fun insert(uri: Uri, values: ContentValues?): Uri? = null+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?) = 0+ override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?) = 0+}++@RunWith(AndroidJUnit4::class)+class MobileFilesInstrumentedTest {+ private lateinit var scenario: ActivityScenario<ShareTestActivity>+ private lateinit var activity: Activity+ private lateinit var files: MobileFiles+ private fun uri(name: String) = Uri.parse("content://com.macro.mobile.test.provider/$name")+ private fun receive(intent: Intent) {+ val done = CountDownLatch(1)+ files.receive(intent) { done.countDown() }+ assertTrue("Provider copy timed out", done.await(30, TimeUnit.SECONDS))+ }+ private fun send(name: String) = Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, uri(name))+ private fun pending() = files.readPendingShares().getJSONArray("files")+ private fun tokens(items: JSONArray) = (0 until items.length()).map { items.getJSONObject(it).getString("token") }.toSet()++ @Before fun setup() {+ scenario = ActivityScenario.launch(ShareTestActivity::class.java)+ scenario.onActivity { activity = it }+ for (name in listOf("android-share-inbox", "ios-share-staging", "ios-pasteboard-staging")) File(activity.cacheDir, name).deleteRecursively()+ files = MobileFiles(activity)+ }+ @After fun cleanup() { files.close(); scenario.close() }++ @Test fun multipleStreamsDeduplicateClipDataAndKeepText() {+ val first = uri("one")+ val second = uri("two")+ val intent = Intent(Intent.ACTION_SEND_MULTIPLE).apply {+ putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayListOf(first, second))+ clipData = ClipData.newUri(activity.contentResolver, "files", first).apply { addItem(ClipData.Item(second)) }+ putExtra(Intent.EXTRA_TEXT, "https://example.com/漢字 😀")+ }+ receive(intent)+ val items = pending()+ assertEquals(3, items.length())+ assertEquals(3, tokens(items).size)+ for (index in 0..1) {+ val item = items.getJSONObject(index)+ assertEquals("漢字😀.bin", item.getString("name"))+ assertEquals(65536, item.getLong("size"))+ val bytes = File(item.getString("previewPath")).readBytes()+ assertArrayEquals(ByteArray(65536) { (it % 251).toByte() }, bytes)+ assertEquals(MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }, item.getString("sha256"))+ }+ assertEquals("https://example.com/漢字 😀", items.getJSONObject(2).getString("sharedText"))+ files.acknowledge(tokens(items))+ assertEquals(0, pending().length())+ assertTrue(File(activity.cacheDir, "ios-share-staging").listFiles()!!.isEmpty())+ }++ @Test fun keepsQueueAcrossRecreationAndDelayedConsumption() {+ receive(send("one"))+ val first = pending()+ receive(Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_TEXT, "second"))+ files.close()+ files = MobileFiles(activity)+ assertEquals(tokens(first), tokens(pending()))+ files.acknowledge(tokens(first))+ val next = pending()+ assertEquals("second", next.getJSONObject(0).getString("sharedText"))+ files.acknowledge(tokens(next))+ assertEquals(0, pending().length())+ }++ @Test fun providerFailureIsAtomicAndSurvivesDelayedFrontendStartup() {+ receive(Intent(Intent.ACTION_SEND_MULTIPLE).putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayListOf(uri("one"), uri("missing"))))+ files.close()+ files = MobileFiles(activity)+ val snapshot = files.readPendingShares()+ assertTrue(snapshot.has("error"))+ assertEquals(0, snapshot.getJSONArray("files").length())+ assertTrue(File(activity.cacheDir, "ios-share-staging").listFiles()!!.isEmpty())+ assertFalse(files.readPendingShares().has("error"))+ receive(send("denied"))+ assertTrue(files.readPendingShares().has("error"))+ }++ @Test fun missingOrCorruptFirstBatchDoesNotBlockNextShare() {+ receive(send("one"))+ val first = pending().getJSONObject(0)+ File(first.getString("previewPath")).delete()+ receive(Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_TEXT, "next"))+ val snapshot = files.readPendingShares()+ assertTrue(snapshot.has("error"))+ assertEquals("next", snapshot.getJSONArray("files").getJSONObject(0).getString("sharedText"))+ files.acknowledge(tokens(snapshot.getJSONArray("files")))+ File(activity.cacheDir, "android-share-inbox/broken.json").writeText("{")+ receive(Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_TEXT, "after corruption"))+ assertEquals("after corruption", pending().getJSONObject(0).getString("sharedText"))+ }++ @Test fun streamsLargeProviderWithUntrustedSizeAndInfersMissingMime() {+ receive(send("large"))+ val item = pending().getJSONObject(0)+ assertEquals(32L * 1024 * 1024, item.getLong("size"))+ assertEquals(item.getLong("size"), File(item.getString("previewPath")).length())+ files.acknowledge(setOf(item.getString("token")))+ receive(send("unknown"))+ assertEquals("application/pdf", pending().getJSONObject(0).getString("mimeType"))+ }++ @Test fun rejectsUnsafeSchemesAndDeletesPartialOversizedCopies() {+ receive(Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/private.txt")))+ assertTrue(files.readPendingShares().has("error"))+ val output = File(activity.cacheDir, "oversized.bin")+ assertThrows(IllegalArgumentException::class.java) {+ MobileFiles.copyBounded(ByteArrayInputStream(ByteArray(4097)), output, 4096)+ }+ assertFalse(output.exists())+ val name = MobileFiles.safeName("漢😀".repeat(100))+ assertTrue(name.toByteArray().size <= 180)+ assertFalse(name.contains('�'))+ }+}diff --git a/apps/web/tauri/android_mobile_plugin/android/src/main/java/com/macro/mobile/MobileExports.kt b/apps/web/tauri/android_mobile_plugin/android/src/main/java/com/macro/mobile/MobileExports.ktnew file mode 100644index 0000000000..c27f002ac8--- /dev/null+++ b/apps/web/tauri/android_mobile_plugin/android/src/main/java/com/macro/mobile/MobileExports.kt@@ -0,0 +1,169 @@+package com.macro.mobile++import android.app.Activity+import android.content.ClipData+import android.content.ClipboardManager+import android.content.Context+import android.content.Intent+import android.util.Base64+import android.util.Log+import androidx.activity.result.ActivityResult+import androidx.core.content.FileProvider+import app.tauri.annotation.InvokeArg+import app.tauri.plugin.Invoke+import app.tauri.plugin.JSObject+import java.io.File+import java.util.UUID+import java.util.concurrent.Executors++@InvokeArg class BeginExportArgs {+ var name: String = "download"+ var mimeType: String = "application/octet-stream"+ var size: Long = 0+}+@InvokeArg class ExportTokenArgs { lateinit var token: String }+@InvokeArg class AppendExportArgs {+ lateinit var token: String+ lateinit var data: String+}+@InvokeArg class FinishExportArgs {+ lateinit var token: String+ var action: String = "save"+}++/** Chunked JS Blob transfer keeps large exports out of a single IPC message. */+class MobileExports(private val activity: Activity) {+ private companion object {+ const val TAG = "MacroMobile"+ // JS sends 256 KiB Blob slices; this is that slice base64-encoded.+ const val EXPORT_CHUNK_BYTES = 256 * 1024+ const val MAX_CHUNK_BASE64_CHARS = (EXPORT_CHUNK_BYTES + 2) / 3 * 4+ }+ private data class Export(val file: File, val mimeType: String)+ private val worker = Executors.newSingleThreadExecutor()+ private val active = mutableMapOf<String, Export>()+ private val directory = File(activity.cacheDir, "android-exports")+ private var saving: Export? = null++ fun begin(invoke: Invoke) {+ val args = invoke.parseArgs(BeginExportArgs::class.java)+ worker.execute {+ try {+ require(args.size <= MobileFiles.MAX_FILE_BYTES) { MobileFiles.SIZE_LIMIT_MESSAGE }+ directory.mkdirs()+ val cutoff = System.currentTimeMillis() - 24L * 60 * 60 * 1000+ directory.listFiles()?.filter { it.isDirectory && it.lastModified() < cutoff }+ ?.forEach { it.deleteRecursively() }+ val token = UUID.randomUUID().toString()+ val folder = File(directory, token).apply { mkdirs() }+ val file = File(folder, MobileFiles.safeName(args.name))+ file.createNewFile()+ active[token] = Export(file, args.mimeType.ifBlank { "application/octet-stream" })+ invoke.resolve(JSObject().apply { put("token", token) })+ } catch (error: IllegalArgumentException) {+ Log.w(TAG, "Rejected export", error)+ invoke.reject(error.message ?: "Unable to create export")+ } catch (error: Exception) {+ Log.w(TAG, "Unable to create export", error)+ invoke.reject("Unable to create export")+ }+ }+ }++ fun append(invoke: Invoke) {+ val args = invoke.parseArgs(AppendExportArgs::class.java)+ worker.execute {+ try {+ val export = active[args.token] ?: error("Unknown export")+ require(args.data.length <= MAX_CHUNK_BASE64_CHARS) { "Export chunk is too large" }+ val bytes = Base64.decode(args.data, Base64.DEFAULT)+ require(export.file.length() + bytes.size <= MobileFiles.MAX_FILE_BYTES) {+ MobileFiles.SIZE_LIMIT_MESSAGE+ }+ export.file.appendBytes(bytes)+ invoke.resolve()+ } catch (error: IllegalArgumentException) {+ Log.w(TAG, "Rejected export chunk", error)+ invoke.reject(error.message ?: "Unable to write export")+ } catch (error: Exception) {+ Log.w(TAG, "Unable to write export", error)+ invoke.reject("Unable to write export")+ }+ }+ }++ fun discard(invoke: Invoke) {+ val token = invoke.parseArgs(ExportTokenArgs::class.java).token+ worker.execute {+ active.remove(token)?.file?.parentFile?.deleteRecursively()+ invoke.resolve()+ }+ }++ fun finish(invoke: Invoke, launchSave: (Intent) -> Unit) {+ val args = invoke.parseArgs(FinishExportArgs::class.java)+ worker.execute {+ val export = active.remove(args.token)+ if (export == null) { invoke.reject("Unknown export"); return@execute }+ activity.runOnUiThread {+ try {+ if (args.action == "save") {+ check(saving == null) { "A save dialog is already open" }+ saving = export+ launchSave(Intent(Intent.ACTION_CREATE_DOCUMENT).apply {+ addCategory(Intent.CATEGORY_OPENABLE)+ type = export.mimeType+ putExtra(Intent.EXTRA_TITLE, export.file.name)+ })+ } else {+ val uri = FileProvider.getUriForFile(activity, "${activity.packageName}.fileprovider", export.file)+ val clip = ClipData.newUri(activity.contentResolver, export.file.name, uri)+ if (args.action == "copy") {+ val clipboard = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager+ clipboard.setPrimaryClip(clip)+ } else {+ require(args.action == "share") { "Unknown file action ${args.action}" }+ val intent = Intent(Intent.ACTION_SEND).apply {+ type = export.mimeType+ putExtra(Intent.EXTRA_STREAM, uri)+ clipData = clip+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+ }+ activity.startActivity(Intent.createChooser(intent, null))+ }+ // Receivers may read asynchronously; retain until the 24-hour cleanup.+ invoke.resolve(JSObject().apply { put("canceled", false) })+ }+ } catch (error: Exception) {+ Log.w(TAG, "Unable to complete file action ${args.action}", error)+ if (saving == export) saving = null+ export.file.parentFile?.deleteRecursively()+ invoke.reject("No application could complete this file action")+ }+ }+ }+ }++ fun close() = worker.shutdown()++ fun saved(invoke: Invoke, result: ActivityResult) {+ val export = saving+ saving = null+ if (export == null) { invoke.reject("Export is no longer available"); return }+ worker.execute {+ try {+ val uri = result.data?.data+ val canceled = result.resultCode != Activity.RESULT_OK || uri == null+ if (!canceled) {+ val output = activity.contentResolver.openOutputStream(uri!!, "wt")+ ?: error("Destination is unavailable")+ output.use { destination -> export.file.inputStream().use { it.copyTo(destination) } }+ }+ invoke.resolve(JSObject().apply { put("canceled", canceled) })+ } catch (error: Exception) {+ Log.w(TAG, "Unable to save file", error)+ invoke.reject("Unable to save file")+ } finally { export.file.parentFile?.deleteRecursively() }+ }+ }+}diff --git a/apps/web/tauri/android_mobile_plugin/android/src/main/java/com/macro/mobile/MobileFiles.kt b/apps/web/tauri/android_mobile_plugin/android/src/main/java/com/macro/mobile/MobileFiles.ktnew file mode 100644index 0000000000..95afc917e6--- /dev/null+++ b/apps/web/tauri/android_mobile_plugin/android/src/main/java/com/macro/mobile/MobileFiles.kt@@ -0,0 +1,306 @@+package com.macro.mobile++import android.app.Activity+import android.content.ClipboardManager+import android.content.Context+import android.content.Intent+import android.net.Uri+import android.provider.OpenableColumns+import android.util.Log+import android.webkit.MimeTypeMap+import androidx.core.content.IntentCompat+import app.tauri.annotation.InvokeArg+import app.tauri.plugin.Invoke+import app.tauri.plugin.JSObject+import org.json.JSONArray+import org.json.JSONObject+import java.io.File+import java.io.InputStream+import java.security.DigestInputStream+import java.security.MessageDigest+import java.util.UUID+import java.util.concurrent.Executors++@InvokeArg+class TokensArgs { var tokens: List<String> = emptyList() }++/** Copies granted content URIs while their grant is alive. Never resolves a URI+ * to an external filesystem path, nor trusts provider names or reported sizes. */+class MobileFiles(private val activity: Activity) {+ private val worker = Executors.newSingleThreadExecutor()+ private val inbox = File(activity.cacheDir, "android-share-inbox")+ // These directories/token prefixes are the existing Rust streaming-upload contract.+ private val shares = File(activity.cacheDir, "ios-share-staging")+ private val pasteboard = File(activity.cacheDir, "ios-pasteboard-staging")+ private val errorFile = File(inbox, "last-error.txt")++ companion object {+ private const val TAG = "MacroMobile"+ // One budget for a whole share batch, a single export or a pasted image.+ const val MAX_FILE_BYTES = 500L * 1024 * 1024+ const val SIZE_LIMIT_MESSAGE = "Attachments exceed the 500 MB limit"+ private const val MAX_TEXT_CHARS = 1024 * 1024+ private const val MAX_FILES = 100+ private const val TTL_MS = 24L * 60 * 60 * 1000++ fun safeName(name: String): String {+ val clean = name.substringAfterLast('/').substringAfterLast('\\')+ .replace(Regex("[\\p{Cntrl}]"), "_")+ if (clean.isBlank() || clean == "." || clean == "..") return "attachment"+ // Android filenames are byte-limited; keep Unicode code points intact.+ val result = StringBuilder()+ var index = 0+ var bytes = 0+ while (index < clean.length) {+ val point = clean.codePointAt(index)+ val next = String(Character.toChars(point))+ bytes += next.toByteArray(Charsets.UTF_8).size+ if (bytes > 180) break+ result.append(next)+ index += Character.charCount(point)+ }+ return result.toString()+ }++ fun copyBounded(input: InputStream, destination: File, maxBytes: Long = MAX_FILE_BYTES) {+ try {+ destination.outputStream().use { output ->+ val buffer = ByteArray(64 * 1024)+ var total = 0L+ while (true) {+ val count = input.read(buffer)+ if (count < 0) break+ total += count+ require(total <= maxBytes) { SIZE_LIMIT_MESSAGE }+ output.write(buffer, 0, count)+ }+ }+ } catch (error: Exception) {+ destination.delete()+ throw error+ }+ }+ }++ private fun stage(uri: Uri, directory: File, prefix: String, maxBytes: Long = MAX_FILE_BYTES): JSONObject {+ require(uri.scheme == "content") { "Only content attachments are supported" }+ val resolver = activity.contentResolver+ val displayName = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)+ ?.use { cursor -> if (cursor.moveToFirst()) cursor.getString(0) else null }+ val name = safeName(displayName ?: "attachment")+ val type = resolver.getType(uri)?.takeIf { it.isNotBlank() }+ ?: MimeTypeMap.getSingleton().getMimeTypeFromExtension(name.substringAfterLast('.', "").lowercase())+ ?: "application/octet-stream"+ val token = prefix + UUID.randomUUID().toString().replace("-", "")+ directory.mkdirs()+ val file = File(directory, "$token-$name")+ val input = resolver.openInputStream(uri) ?: error("Attachment is unavailable")+ val digest = MessageDigest.getInstance("SHA-256")+ DigestInputStream(input, digest).use { copyBounded(it, file, maxBytes) }+ return JSONObject().apply {+ put("token", token)+ put("name", name)+ put("mimeType", type)+ put("size", file.length())+ put("previewPath", file.absolutePath)+ put("sha256", digest.digest().joinToString("") { "%02x".format(it) })+ }+ }++ fun receive(intent: Intent, done: (String?) -> Unit) {+ worker.execute {+ val staged = mutableListOf<JSONObject>()+ try {+ cleanup()+ val uris = linkedSetOf<Uri>()+ if (intent.action == Intent.ACTION_SEND_MULTIPLE) {+ IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)+ ?.let { uris.addAll(it) }+ } else {+ IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)+ ?.let { uris.add(it) }+ }+ intent.clipData?.let { clip ->+ for (index in 0 until clip.itemCount) clip.getItemAt(index).uri?.let { uris.add(it) }+ }+ require(uris.size <= MAX_FILES) { "Too many attachments" }+ var remainingBytes = MAX_FILE_BYTES+ for (uri in uris) {+ val item = stage(uri, shares, "share-stage-", remainingBytes)+ staged.add(item)+ remainingBytes -= item.getLong("size")+ }+ intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString()?.takeIf { it.isNotBlank() }?.let { text ->+ require(text.length <= MAX_TEXT_CHARS) { "Shared text is too large" }+ val token = "share-stage-" + UUID.randomUUID().toString().replace("-", "")+ staged.add(JSONObject().apply {+ put("token", token)+ put("name", "Shared text")+ put("mimeType", "text/plain")+ put("size", text.toByteArray().size)+ put("isSharedText", true)+ put("sharedText", text)+ })+ }+ require(staged.isNotEmpty()) { "The share contains no readable content" }+ inbox.mkdirs()+ // One atomic manifest per incoming batch; readers never see partial copies.+ val batch = UUID.randomUUID().toString()+ val temporary = File(inbox, "$batch.tmp")+ temporary.writeText(JSONArray(staged).toString())+ check(temporary.renameTo(File(inbox, "$batch.json")))+ done(null)+ } catch (error: Exception) {+ Log.w(TAG, "Unable to receive share", error)+ staged.forEach { item -> stagedPath(item)?.delete() }+ val message = error.message ?: "Unable to read shared attachments"+ // A cold-start failure can precede the JS listener or login.+ // Keep it until the frontend has a chance to display it.+ try {+ recordError(message)+ done(null)+ } catch (persistError: Exception) {+ Log.w(TAG, "Unable to record share error", persistError)+ done(message)+ }+ }+ }+ }++ private fun stagedPath(item: JSONObject): File? {+ if (item.optBoolean("isSharedText")) return null+ val token = item.getString("token")+ require(Regex("share-stage-[a-f0-9]{32}").matches(token)) { "Invalid shared attachment" }+ return File(shares, "$token-${safeName(item.getString("name"))}")+ }++ private fun manifests(): List<File> = inbox.listFiles()+ ?.filter { it.extension == "json" }?.sortedBy { it.lastModified() } ?: emptyList()++ private fun cleanup() {+ val cutoff = System.currentTimeMillis() - TTL_MS+ for (directory in listOf(inbox, shares, pasteboard)) {+ directory.listFiles()?.filter { it.isFile && it.lastModified() < cutoff }?.forEach { it.delete() }+ }+ }++ private fun recordError(message: String) {+ inbox.mkdirs()+ errorFile.writeText(message)+ }++ /** Called on the serial worker; never expose half of a missing batch. */+ internal fun readPendingShares(): JSObject {+ cleanup()+ var files = JSONArray()+ for (manifest in manifests()) {+ var items: JSONArray? = null+ try {+ items = JSONArray(manifest.readText())+ check(items.length() > 0)+ for (index in 0 until items.length()) {+ val item = items.getJSONObject(index)+ check(item.optBoolean("isSharedText") || stagedPath(item)?.isFile == true)+ }+ files = items+ break+ } catch (error: Exception) {+ // Cache eviction or an interrupted write must not strand later shares.+ Log.w(TAG, "Discarding unreadable share manifest ${manifest.name}", error)+ manifest.delete()+ items?.let { batch ->+ for (index in 0 until batch.length()) {+ runCatching { stagedPath(batch.getJSONObject(index))?.delete() }+ }+ }+ recordError("A shared attachment is no longer available. Please share it again.")+ }+ }+ return JSObject().apply {+ put("files", files)+ if (errorFile.isFile) {+ put("error", errorFile.readText())+ errorFile.delete()+ }+ }+ }++ fun getPendingShares(invoke: Invoke) = worker.execute {+ try { invoke.resolve(readPendingShares()) }+ catch (error: Exception) {+ Log.w(TAG, "Unable to read pending shares", error)+ invoke.reject("Unable to read pending shares")+ }+ }++ internal fun acknowledge(tokens: Set<String>) {+ for (manifest in manifests()) {+ val items = try { JSONArray(manifest.readText()) } catch (error: Exception) {+ Log.w(TAG, "Discarding unreadable share manifest ${manifest.name}", error)+ manifest.delete()+ continue+ }+ val retained = JSONArray()+ val removed = mutableListOf<JSONObject>()+ for (index in 0 until items.length()) {+ val item = items.getJSONObject(index)+ if (item.getString("token") in tokens) removed.add(item)+ else retained.put(item)+ }+ if (removed.isEmpty()) continue+ // Acknowledge the manifest before unlinking bytes: failed persistence+ // keeps a retryable, intact batch instead of leaving missing attachments.+ if (retained.length() == 0) check(manifest.delete())+ else {+ val temporary = File(inbox, "${manifest.name}.tmp")+ temporary.writeText(retained.toString())+ check(temporary.renameTo(manifest))+ }+ removed.forEach { stagedPath(it)?.delete() }+ }+ }++ fun clearShares(invoke: Invoke, done: () -> Unit) {+ val tokens = invoke.parseArgs(TokensArgs::class.java).tokens.toSet()+ worker.execute {+ try {+ acknowledge(tokens)+ invoke.resolve()+ done()+ } catch (error: Exception) {+ Log.w(TAG, "Unable to clear shared files", error)+ invoke.reject("Unable to clear shared files")+ }+ }+ }++ fun close() = worker.shutdown()++ fun stageClipboardImage(invoke: Invoke) {+ // Clipboard access happens only on an explicit paste, while focused.+ val uri = try {+ val clipboard = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager+ clipboard.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.uri+ } catch (_: SecurityException) {+ invoke.reject("Unable to read clipboard image")+ return+ }+ if (uri == null || uri.scheme != "content") {+ invoke.resolve(JSObject())+ return+ }+ worker.execute {+ try {+ if (activity.contentResolver.getType(uri)?.startsWith("image/") != true) {+ invoke.resolve(JSObject())+ return@execute+ }+ cleanup()+ invoke.resolve(JSObject(stage(uri, pasteboard, "paste-stage-").toString()))+ } catch (error: Exception) {+ Log.w(TAG, "Unable to read clipboard image", error)+ invoke.reject("Unable to read clipboard image")+ }+ }+ }+}diff --git a/apps/web/tauri/android_mobile_plugin/android/src/main/java/com/macro/mobile/MobilePlugin.kt b/apps/web/tauri/android_mobile_plugin/android/src/main/java/com/macro/mobile/MobilePlugin.ktnew file mode 100644index 0000000000..8524057ee2--- /dev/null+++ b/apps/web/tauri/android_mobile_plugin/android/src/main/java/com/macro/mobile/MobilePlugin.kt@@ -0,0 +1,153 @@+package com.macro.mobile++import android.app.Activity+import android.content.Intent+import android.content.res.Configuration+import android.webkit.WebView+import androidx.activity.ComponentActivity+import androidx.activity.OnBackPressedCallback+import androidx.activity.result.ActivityResult+import androidx.appcompat.app.AppCompatActivity+import androidx.core.view.ViewCompat+import androidx.core.view.WindowInsetsCompat+import androidx.core.view.WindowInsetsControllerCompat+import app.tauri.annotation.Command+import app.tauri.annotation.ActivityCallback+import app.tauri.annotation.TauriPlugin+import app.tauri.plugin.Invoke+import app.tauri.plugin.JSObject+import app.tauri.plugin.Plugin++@TauriPlugin+class MobilePlugin(private val activity: Activity) : Plugin(activity) {+ private lateinit var webView: WebView+ private val files = MobileFiles(activity)+ private val exports = MobileExports(activity)+ private var insets = JSObject()+ private var backPending = false+ // A page that reloads mid-dispatch never answers; let the next press through.+ private val releaseBack = Runnable { backPending = false }++ private companion object {+ const val BACK_ANSWER_TIMEOUT_MS = 2_000L+ }++ override fun load(webView: WebView) {+ this.webView = webView+ // Listen on the WebView, leaving the window's own inset dispatch intact.+ ViewCompat.setOnApplyWindowInsetsListener(webView) { _, value ->+ updateInsets(value)+ value+ }+ webView.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->+ ViewCompat.getRootWindowInsets(webView)?.let { updateInsets(it) }+ }+ ViewCompat.requestApplyInsets(webView)+ (activity as ComponentActivity).onBackPressedDispatcher.addCallback(+ activity,+ object : OnBackPressedCallback(true) {+ override fun handleOnBackPressed() {+ val value = ViewCompat.getRootWindowInsets(webView)+ if (value?.isVisible(WindowInsetsCompat.Type.ime()) == true) {+ WindowInsetsControllerCompat(activity.window, webView)+ .hide(WindowInsetsCompat.Type.ime())+ return+ }+ if (backPending) return+ backPending = true+ webView.postDelayed(releaseBack, BACK_ANSWER_TIMEOUT_MS)+ // Only a committed Back reaches JS. Canceled predictive gestures+ // must never dismiss a sheet or navigate away from a draft.+ webView.evaluateJavascript(+ "window.dispatchEvent(new Event('android-back', {cancelable:true}))"+ ) { unhandled ->+ webView.removeCallbacks(releaseBack)+ backPending = false+ // "false" means JS claimed it; "null" means no page is loaded yet.+ if (unhandled != "false") activity.moveTaskToBack(true)+ }+ }+ }+ )+ receiveShare(activity.intent)+ }++ private fun updateInsets(value: WindowInsetsCompat) {+ val scale = activity.resources.displayMetrics.density+ val bars = value.getInsets(+ WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout()+ )+ val imeVisible = value.isVisible(WindowInsetsCompat.Type.ime())+ val ime = value.getInsets(WindowInsetsCompat.Type.ime())+ // The WebView keeps its full edge-to-edge size under the keyboard, as on+ // iOS. Resizing it here made Chromium relayout the whole document on top+ // of the CSS work; instead JS shrinks the layout root through --dvh and+ // lifts fixed sheets by the published keyboard height.+ val next = JSObject().apply {+ put("top", bars.top / scale)+ put("right", bars.right / scale)+ // The keyboard covers the navigation bar, so its inset no longer applies.+ put("bottom", if (ime.bottom > 0) 0 else bars.bottom / scale)+ put("left", bars.left / scale)+ put("imeVisible", imeVisible)+ put("imeHeight", if (imeVisible) ime.bottom / scale else 0)+ // Width is what JS scales by: a keyboard never changes it, a density change does.+ put("viewportWidth", webView.width / scale)+ put("viewportHeight", webView.height / scale)+ }+ if (next.toString() != insets.toString()) {+ insets = next+ trigger("insets", next)+ }+ }++ override fun onConfigurationChanged(newConfig: Configuration) {+ if (::webView.isInitialized) ViewCompat.requestApplyInsets(webView)+ }++ override fun onResume(activity: AppCompatActivity) {+ if (::webView.isInitialized) ViewCompat.requestApplyInsets(webView)+ }++ override fun onDestroy(activity: AppCompatActivity) {+ files.close()+ exports.close()+ }++ override fun onNewIntent(intent: Intent) = receiveShare(intent)++ private fun receiveShare(intent: Intent?) {+ if (intent == null || intent.action !in listOf(Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE)) return+ if (intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0) return+ // Do not re-ingest the launch intent on activity recreation. The queue is+ // durable, so it survives an authentication detour and process restart.+ val incoming = Intent(intent)+ intent.action = Intent.ACTION_MAIN+ files.receive(incoming) { error ->+ activity.runOnUiThread {+ trigger("shares", JSObject().apply { put("error", error) })+ }+ }+ }++ @Command+ fun getInsets(invoke: Invoke) {+ ViewCompat.getRootWindowInsets(webView)?.let { updateInsets(it) }+ invoke.resolve(insets)+ }++ @Command fun getPendingShares(invoke: Invoke) = files.getPendingShares(invoke)+ @Command fun register_listener(invoke: Invoke) = super.registerListener(invoke)+ @Command fun remove_listener(invoke: Invoke) = super.removeListener(invoke)+ @Command fun clearShares(invoke: Invoke) = files.clearShares(invoke) {+ activity.runOnUiThread { trigger("shares", JSObject()) }+ }+ @Command fun stageClipboardImage(invoke: Invoke) = files.stageClipboardImage(invoke)+ @Command fun beginExport(invoke: Invoke) = exports.begin(invoke)+ @Command fun appendExport(invoke: Invoke) = exports.append(invoke)+ @Command fun discardExport(invoke: Invoke) = exports.discard(invoke)+ @Command fun finishExport(invoke: Invoke) = exports.finish(invoke) { intent ->+ startActivityForResult(invoke, intent, "exportSaved")+ }+ @ActivityCallback fun exportSaved(invoke: Invoke, result: ActivityResult) = exports.saved(invoke, result)+}diff --git a/apps/web/tauri/android_mobile_plugin/android/src/test/java/com/macro/mobile/MobileFilesTest.kt b/apps/web/tauri/android_mobile_plugin/android/src/test/java/com/macro/mobile/MobileFilesTest.ktnew file mode 100644index 0000000000..cb4fa7e68d--- /dev/null+++ b/apps/web/tauri/android_mobile_plugin/android/src/test/java/com/macro/mobile/MobileFilesTest.kt@@ -0,0 +1,37 @@+package com.macro.mobile++import org.junit.Assert.*+import org.junit.Test+import java.io.ByteArrayInputStream+import java.io.File+import java.io.InputStream++class MobileFilesTest {+ @Test fun providerNamesCannotEscapeStaging() {+ assertEquals("photo.png", MobileFiles.safeName("../../photo.png"))+ assertEquals("file.pdf", MobileFiles.safeName("folder\\file.pdf"))+ assertEquals("attachment", MobileFiles.safeName(".."))+ assertEquals("a_b.txt", MobileFiles.safeName("a\nb.txt"))+ assertEquals(180, MobileFiles.safeName("a".repeat(1000)).length)+ }++ @Test fun copiesExactBytesIncludingEmptyFiles() {+ val file = File.createTempFile("macro-share-test", ".bin")+ try {+ val bytes = ByteArray(150_000) { (it % 251).toByte() }+ MobileFiles.copyBounded(ByteArrayInputStream(bytes), file)+ assertArrayEquals(bytes, file.readBytes())+ MobileFiles.copyBounded(ByteArrayInputStream(byteArrayOf()), file)+ assertEquals(0, file.length())+ } finally { file.delete() }+ }++ @Test fun providerFailureRemovesPartialFile() {+ val file = File.createTempFile("macro-share-test", ".bin")+ val failing = object : InputStream() {+ override fun read(): Int = throw java.io.IOException("Provider disconnected")+ }+ assertThrows(java.io.IOException::class.java) { MobileFiles.copyBounded(failing, file) }+ assertFalse(file.exists())+ }+}diff --git a/apps/web/tauri/android_mobile_plugin/build.rs b/apps/web/tauri/android_mobile_plugin/build.rsnew file mode 100644index 0000000000..dbaf587262--- /dev/null+++ b/apps/web/tauri/android_mobile_plugin/build.rs@@ -0,0 +1,16 @@+fn main() {+ tauri_plugin::Builder::new(&[+ "register_listener",+ "remove_listener",+ "getInsets",+ "getPendingShares",+ "clearShares",+ "stageClipboardImage",+ "beginExport",+ "appendExport",+ "finishExport",+ "discardExport",+ ])+ .android_path("android")+ .build();+}diff --git a/apps/web/tauri/android_mobile_plugin/permissions/default.toml b/apps/web/tauri/android_mobile_plugin/permissions/default.tomlnew file mode 100644index 0000000000..aaaa7923f4--- /dev/null+++ b/apps/web/tauri/android_mobile_plugin/permissions/default.toml@@ -0,0 +1,3 @@+[default]+description = "Android window insets, share intake, clipboard staging and file exports."+permissions = ["allow-register-listener", "allow-remove-listener", "allow-getInsets", "allow-getPendingShares", "allow-clearShares", "allow-stageClipboardImage", "allow-beginExport", "allow-appendExport", "allow-finishExport", "allow-discardExport"]diff --git a/apps/web/tauri/android_mobile_plugin/src/lib.rs b/apps/web/tauri/android_mobile_plugin/src/lib.rsnew file mode 100644index 0000000000..eeedab7ab8--- /dev/null+++ b/apps/web/tauri/android_mobile_plugin/src/lib.rs@@ -0,0 +1,16 @@+//! Android window, navigation, and file adapters for the shared web client.+#![deny(missing_docs)]++use tauri::Runtime;+use tauri::plugin::{Builder, TauriPlugin};++/// Registers native Android commands; the web client retains composer policy.+pub fn init<R: Runtime>() -> TauriPlugin<R> {+ let builder = Builder::new("android-mobile");+ #[cfg(target_os = "android")]+ let builder = builder.setup(|_app, api| {+ api.register_android_plugin("com.macro.mobile", "MobilePlugin")?;+ Ok(())+ });+ builder.build()+}diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.tomlindex 660543a9d4..5c7c82600c 100644--- a/apps/web/tauri/src-tauri/Cargo.toml+++ b/apps/web/tauri/src-tauri/Cargo.toml@@ -48,7 +48,6 @@ tauri-plugin-http = { git = "https://github.com/macro-inc/plugins-workspace", re] }tauri-plugin-log = { version = "2", features = ["tracing"] }tauri-plugin-opener = "2"-tauri-plugin-safe-area-insets = "0.1.0"tauri-plugin-websocket = { git = "https://github.com/macro-inc/plugins-workspace", rev = "06474e4c446600627cf37a11f0c22c27bcf764ca" }thiserror = "2.0.14"tokio = { version = "1.47.1", features = ["full"] }@@ -78,6 +77,7 @@ tauri-plugin-haptics = "2"jni = "0.21"rustls-platform-verifier = "0.6"tauri-plugin-android-auth = { path = "../android_auth_plugin" }+tauri-plugin-android-mobile = { path = "../android_mobile_plugin" }tauri-plugin-android-push = { path = "../android_push_plugin" }[target.'cfg(target_os = "ios")'.dependencies]diff --git a/apps/web/tauri/src-tauri/capabilities/android.json b/apps/web/tauri/src-tauri/capabilities/android.jsonindex f3e1cf1182..0201053f4d 100644--- a/apps/web/tauri/src-tauri/capabilities/android.json+++ b/apps/web/tauri/src-tauri/capabilities/android.json@@ -8,6 +8,7 @@],"permissions": ["android-auth:allow-authenticate",+ "android-mobile:default","android-push:default"]}diff --git a/apps/web/tauri/src-tauri/capabilities/default.json b/apps/web/tauri/src-tauri/capabilities/default.jsonindex ab8275f9f1..8632c6cee6 100644--- a/apps/web/tauri/src-tauri/capabilities/default.json+++ b/apps/web/tauri/src-tauri/capabilities/default.json@@ -46,7 +46,6 @@"opener:default","deep-link:default","websocket:default",- "safe-area-insets:default","notification:default","notifications:default","os:default",diff --git a/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml b/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xmlindex 5461d8ed8b..f8e612805b 100644--- a/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml+++ b/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml@@ -1,9 +1,13 @@<?xml version="1.0" encoding="utf-8"?>-<manifest xmlns:android="http://schemas.android.com/apk/res/android">+<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"><uses-permission android:name="android.permission.INTERNET" />+ <!-- Device-info contributes legacy permissions; SAF/content grants and+ app-private exports need none of them. BATTERY_STATS is privileged. -->+ <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" tools:node="remove" />+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="remove" />+ <uses-permission android:name="android.permission.BATTERY_STATS" tools:node="remove" />- <!-- AndroidTV support -->- <uses-feature android:name="android.software.leanback" android:required="false" />+ <uses-feature android:name="android.hardware.touchscreen" android:required="false" /><applicationandroid:icon="@mipmap/ic_launcher"@@ -11,16 +15,22 @@android:theme="@style/Theme.app"android:usesCleartextTraffic="${usesCleartextTraffic}"><activity- android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"+ android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|fontScale|density|layoutDirection|navigation"android:launchMode="singleTask"android:label="@string/main_activity_title"android:name=".MainActivity"- android:exported="true">+ android:exported="true"+ android:windowSoftInputMode="adjustResize"+ android:enableOnBackInvokedCallback="true"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" />- <!-- AndroidTV support -->- <category android:name="android.intent.category.LEANBACK_LAUNCHER" />+ </intent-filter>+ <intent-filter>+ <action android:name="android.intent.action.SEND" />+ <action android:name="android.intent.action.SEND_MULTIPLE" />+ <category android:name="android.intent.category.DEFAULT" />+ <data android:mimeType="*/*" /></intent-filter><!-- DEEP LINK PLUGIN. AUTO-GENERATED. DO NOT REMOVE. --><intent-filter >@@ -41,9 +51,9 @@<data android:scheme="https" /><data android:scheme="http" /><data android:host="macro.com" />+ <data android:path="/app" />-- <data android:pathPrefix="/app" />+ <data android:pathPrefix="/app/" /></intent-filter><intent-filter android:autoVerify="true" >@@ -53,9 +63,9 @@<data android:scheme="https" /><data android:scheme="http" /><data android:host="dev.macro.com" />+ <data android:path="/app" />-- <data android:pathPrefix="/app" />+ <data android:pathPrefix="/app/" /></intent-filter><intent-filter android:autoVerify="true" >@@ -65,9 +75,9 @@<data android:scheme="https" /><data android:scheme="http" /><data android:host="staging.macro.com" />+ <data android:path="/app" />-- <data android:pathPrefix="/app" />+ <data android:pathPrefix="/app/" /></intent-filter><!-- DEEP LINK PLUGIN. AUTO-GENERATED. DO NOT REMOVE. -->diff --git a/apps/web/tauri/src-tauri/gen/android/app/src/main/res/drawable/ic_macro_alpha_foreground.xml b/apps/web/tauri/src-tauri/gen/android/app/src/main/res/drawable/ic_macro_alpha_foreground.xmlnew file mode 100644index 0000000000..4ff3f7caf9--- /dev/null+++ b/apps/web/tauri/src-tauri/gen/android/app/src/main/res/drawable/ic_macro_alpha_foreground.xml@@ -0,0 +1,24 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Shared by adaptive and legacy icons. Keep artwork inside the central 66dp circle. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="72dp"+ android:height="72dp"+ android:viewportWidth="72"+ android:viewportHeight="72">+ <group android:translateX="10" android:translateY="18.75" android:scaleX="0.281" android:scaleY="0.281">+ <path+ android:fillColor="#FFFFFF"+ android:pathData="m48.143,0 -17.297,6.7832v44.893l-13.547,-12.793 -17.299,6.7812v51.516c0,0.98 0.20089,1.9496 0.58789,2.8496 0.388,0.9 0.95402,1.7108 1.666,2.3848l21.559,20.387 17.312,-6.7812v-44.891l54.654,51.672 17.313,-6.7812v-44.891l54.672,51.674 17.299,-6.7812v-51.516c0,-0.98 -0.20089,-1.9496 -0.58789,-2.8496 -0.388,-0.9 -0.95402,-1.7118 -1.666,-2.3848l-62.682,-59.271 -17.316,6.7832v44.893z" />+ </group>+ <!-- Overlay the centered logo; the badge does not reserve space or shift it.+ Fill: Macro Dark accent oklch(0.7 0.12 250deg), converted to sRGB. -->+ <path+ android:fillColor="#61A3E6"+ android:strokeColor="#000000"+ android:strokeWidth="1"+ android:pathData="M30,43 H60 A3,3 0,0 1,63 46 V53 A3,3 0,0 1,60 56 H30 A3,3 0,0 1,27 53 V46 A3,3 0,0 1,30 43 Z" />+ <!-- ALPHA: Arial Bold (Arial-BoldMT), shaped with CoreText and converted to outlines.+ Uniformly scaled to 29dp wide and centered at (45, 49.5). -->+ <path android:fillColor="#000000"+ android:pathData="M36.554,52.517 L35.229,52.517 L34.702,51.146 L32.290,51.146 L31.792,52.517 L30.500,52.517 L32.850,46.483 L34.138,46.483 Z M34.311,50.130 L33.480,47.891 L32.665,50.130 Z M37.233,52.517 L37.233,46.533 L38.452,46.533 L38.452,51.500 L41.481,51.500 L41.481,52.517 Z M42.349,52.517 L42.349,46.483 L44.304,46.483 Q45.416,46.483 45.753,46.574 Q46.272,46.709 46.622,47.164 Q46.971,47.619 46.971,48.339 Q46.971,48.895 46.770,49.274 Q46.568,49.652 46.257,49.868 Q45.947,50.084 45.626,50.154 Q45.189,50.241 44.362,50.241 L43.568,50.241 L43.568,52.517 Z M43.568,47.504 L43.568,49.216 L44.234,49.216 Q44.955,49.216 45.198,49.121 Q45.440,49.027 45.578,48.825 Q45.716,48.623 45.716,48.356 Q45.716,48.027 45.523,47.813 Q45.329,47.598 45.033,47.545 Q44.815,47.504 44.156,47.504 Z M47.976,52.517 L47.976,46.483 L49.194,46.483 L49.194,48.858 L51.581,48.858 L51.581,46.483 L52.799,46.483 L52.799,52.517 L51.581,52.517 L51.581,49.879 L49.194,49.879 L49.194,52.517 Z M59.500,52.517 L58.175,52.517 L57.648,51.146 L55.236,51.146 L54.738,52.517 L53.446,52.517 L55.796,46.483 L57.084,46.483 Z M57.257,50.130 L56.425,47.891 L55.611,50.130 Z" />+</vector>diff --git a/apps/web/tauri/src-tauri/gen/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/apps/web/tauri/src-tauri/gen/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xmlindex 2ffbf24b68..a660ef143e 100644--- a/apps/web/tauri/src-tauri/gen/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml+++ b/apps/web/tauri/src-tauri/gen/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml@@ -1,5 +1,8 @@<?xml version="1.0" encoding="utf-8"?><adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">- <foreground android:drawable="@mipmap/ic_launcher_foreground"/>+ <foreground>+ <!-- The 72dp artwork occupies the central 72dp of the 108dp adaptive layer. -->+ <inset android:drawable="@drawable/ic_macro_alpha_foreground" android:inset="16.6667%"/>+ </foreground><background android:drawable="@color/ic_launcher_background"/>-</adaptive-icon>\ No newline at end of file+</adaptive-icon>diff --git a/apps/web/tauri/src-tauri/gen/android/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/apps/web/tauri/src-tauri/gen/android/app/src/main/res/mipmap-anydpi/ic_launcher.xmlnew file mode 100644index 0000000000..12a174087e--- /dev/null+++ b/apps/web/tauri/src-tauri/gen/android/app/src/main/res/mipmap-anydpi/ic_launcher.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<layer-list xmlns:android="http://schemas.android.com/apk/res/android">+ <item android:drawable="@color/ic_launcher_background" />+ <item android:drawable="@drawable/ic_macro_alpha_foreground" />+</layer-list>diff --git a/apps/web/tauri/src-tauri/gen/android/app/src/main/res/values/ic_launcher_background.xml b/apps/web/tauri/src-tauri/gen/android/app/src/main/res/values/ic_launcher_background.xmlindex ea9c223a6c..61bce4c57b 100644--- a/apps/web/tauri/src-tauri/gen/android/app/src/main/res/values/ic_launcher_background.xml+++ b/apps/web/tauri/src-tauri/gen/android/app/src/main/res/values/ic_launcher_background.xml@@ -1,4 +1,4 @@<?xml version="1.0" encoding="utf-8"?><resources>- <color name="ic_launcher_background">#fff</color>-</resources>\ No newline at end of file+ <color name="ic_launcher_background">#000000</color>+</resources>diff --git a/apps/web/tauri/src-tauri/gen/android/app/src/main/res/xml/file_paths.xml b/apps/web/tauri/src-tauri/gen/android/app/src/main/res/xml/file_paths.xmlindex 782d63b993..a4506c8d2e 100644--- a/apps/web/tauri/src-tauri/gen/android/app/src/main/res/xml/file_paths.xml+++ b/apps/web/tauri/src-tauri/gen/android/app/src/main/res/xml/file_paths.xml@@ -1,5 +1,6 @@<?xml version="1.0" encoding="utf-8"?><paths xmlns:android="http://schemas.android.com/apk/res/android">- <external-path name="my_images" path="." />- <cache-path name="my_cache_images" path="." />+ <cache-path name="exports" path="android-exports/" />+ <!-- Wry's existing capture="environment" file-input fallback. -->+ <external-files-path name="captured_photos" path="Pictures/" /></paths>diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rsindex 049a30920a..bdd8d27e10 100644--- a/apps/web/tauri/src-tauri/src/lib.rs+++ b/apps/web/tauri/src-tauri/src/lib.rs@@ -175,6 +175,7 @@ pub fn run() {{builder = builder.plugin(tauri_plugin_android_auth::init())+ .plugin(tauri_plugin_android_mobile::init()).plugin(tauri_plugin_android_push::init());}@@ -222,9 +223,7 @@ pub fn run() {#[cfg(mobile)]{// register mobile specific plugins- builder = builder- .plugin(tauri_plugin_haptics::init())- .plugin(tauri_plugin_safe_area_insets::init());+ builder = builder.plugin(tauri_plugin_haptics::init());}// Window origin differs by platform:diff --git a/apps/web/tauri/src-tauri/src/staged_upload.rs b/apps/web/tauri/src-tauri/src/staged_upload.rsindex b1ffea0a7e..faf62369c1 100644--- a/apps/web/tauri/src-tauri/src/staged_upload.rs+++ b/apps/web/tauri/src-tauri/src/staged_upload.rs@@ -195,10 +195,26 @@ pub(crate) async fn upload_staged_file_to_presigned_url(token: String,upload_url: String,mime_type: String,+ checksum_sha256: Option<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?;+ upload_file_to_presigned_url(+ &path,+ &upload_url,+ &mime_type,+ description,+ checksum_sha256.as_deref(),+ )+ .await?;++ // Android keeps a durable incoming-share queue until the composer sends or+ // cancels. An eager attachment upload must not invalidate that queue during+ // an auth detour, a second incoming share, or a process restart.+ #[cfg(target_os = "android")]+ if matches!(source, StagedUploadSource::Share) {+ return Ok(());+ }if let Err(error) = tokio::fs::remove_file(&path).await&& error.kind() != std::io::ErrorKind::NotFound@@ -219,6 +235,7 @@ pub(crate) async fn upload_file_to_presigned_url(upload_url: &str,mime_type: &str,description: &str,+ checksum_sha256: Option<&str>,) -> Result<(), String> {let upload_url = Url::parse(upload_url).map_err(|error| format!("invalid {description} upload URL: {error}"))?;@@ -246,6 +263,9 @@ pub(crate) async fn upload_file_to_presigned_url(if !mime_type.is_empty() {request = request.header(CONTENT_TYPE, mime_type);}+ if let Some(checksum) = checksum_sha256 {+ request = request.header("x-amz-checksum-sha256", checksum);+ }let response = request.header(CONTENT_LENGTH, size.to_string())diff --git a/apps/web/tauri/src-tauri/tauri.conf.json b/apps/web/tauri/src-tauri/tauri.conf.jsonindex 30c098e9c3..bc6a520abd 100644--- a/apps/web/tauri/src-tauri/tauri.conf.json+++ b/apps/web/tauri/src-tauri/tauri.conf.json@@ -66,20 +66,29 @@},{"host": "macro.com",- "pathPrefix": [+ "path": ["/app"+ ],+ "pathPrefix": [+ "/app/"]},{"host": "dev.macro.com",- "pathPrefix": [+ "path": ["/app"+ ],+ "pathPrefix": [+ "/app/"]},{"host": "staging.macro.com",- "pathPrefix": [+ "path": ["/app"+ ],+ "pathPrefix": [+ "/app/"]}],diff --git a/apps/web/tests/native/android/smoke-utils.mjs b/apps/web/tests/native/android/smoke-utils.mjsnew file mode 100644index 0000000000..c82979d9f2--- /dev/null+++ b/apps/web/tests/native/android/smoke-utils.mjs@@ -0,0 +1,49 @@+import assert from 'node:assert/strict';++export function screenPointForInput(+ hierarchy,+ packageName,+ { rect, viewport }+) {+ // UIAutomator lists the native container before Chromium's nested virtual+ // WebView node. Use the container's screen bounds, not page content bounds.+ const webView = (hierarchy.match(/<node\b[^>]*>/g) ?? []).find(+ (node) =>+ node.includes('class="android.webkit.WebView"') &&+ node.includes(`package="${packageName}"`)+ );+ assert.ok(webView, 'Macro WebView is unavailable');+ const bounds = webView.match(+ /bounds="\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]"/+ );+ assert.ok(bounds, 'WebView screen bounds are unavailable');+ const [left, top, right, bottom] = bounds.slice(1).map(Number);+ assert.ok(right > left && bottom > top);+ assert.ok(viewport.width > 0 && viewport.height > 0);+ const cssX = rect.left + rect.width / 2 - viewport.left;+ const cssY = rect.top + rect.height / 2 - viewport.top;+ assert.ok(+ cssX > 0 && cssX < viewport.width,+ 'Input center is outside the viewport'+ );+ assert.ok(+ cssY > 0 && cssY < viewport.height,+ 'Input center is outside the viewport'+ );+ return {+ x: Math.round(left + (cssX * (right - left)) / viewport.width),+ y: Math.round(top + (cssY * (bottom - top)) / viewport.height),+ };+}++export function testShareTokens(files, { imageName, sharedText }) {+ return files+ .filter(+ (file) =>+ /^share-stage-[a-f0-9]{32}$/.test(file.token) &&+ (file.isSharedText+ ? file.sharedText === sharedText+ : file.name === imageName)+ )+ .map((file) => file.token);+}diff --git a/apps/web/tests/native/android/smoke-utils.test.ts b/apps/web/tests/native/android/smoke-utils.test.tsnew file mode 100644index 0000000000..1d8c00bfab--- /dev/null+++ b/apps/web/tests/native/android/smoke-utils.test.ts@@ -0,0 +1,61 @@+import { describe, expect, test } from 'bun:test';+import { screenPointForInput, testShareTokens } from './smoke-utils.mjs';++describe('Android smoke fixture isolation', () => {+ test.each([1, 1.5, 2.625])(+ 'maps CSS input bounds at scale %s with a window offset',+ (scale) => {+ const hierarchy = `<node class="android.webkit.WebView" package="com.macro.app.prod" bounds="[30,60][${30 + 400 * scale},${60 + 800 * scale}]"/>`;+ expect(+ screenPointForInput(hierarchy, 'com.macro.app.prod', {+ rect: { left: 20, top: 100, width: 300, height: 80 },+ viewport: { left: 10, top: 20, width: 400, height: 800 },+ })+ ).toEqual({+ x: Math.round(30 + 160 * scale),+ y: Math.round(60 + 120 * scale),+ });+ }+ );++ test('refuses to tap when the input is outside the visible viewport', () => {+ expect(() =>+ screenPointForInput(+ '<node class="android.webkit.WebView" package="com.macro.app.prod" bounds="[0,0][1080,2400]"/>',+ 'com.macro.app.prod',+ {+ rect: { left: 500, top: 100, width: 100, height: 80 },+ viewport: { left: 0, top: 0, width: 400, height: 800 },+ }+ )+ ).toThrow('Input center is outside');+ });++ test('uses native container bounds when Chromium exposes a nested WebView', () => {+ const hierarchy =+ '<node class="android.webkit.WebView" package="com.macro.app.prod" bounds="[30,60][830,1660]"><node class="android.webkit.WebView" package="com.macro.app.prod" bounds="[30,80][830,1640]"/></node>';+ expect(+ screenPointForInput(hierarchy, 'com.macro.app.prod', {+ rect: { left: 20, top: 100, width: 300, height: 80 },+ viewport: { left: 0, top: 0, width: 400, height: 800 },+ })+ ).toEqual({ x: 370, y: 340 });+ });++ test('selects only this run’s image and text tokens from mixed queued batches', () => {+ const token = (id: string) => `share-stage-${id.repeat(32)}`;+ const fixture = {+ imageName: 'smoke-current-run.png',+ sharedText: 'https://example.com/android-smoke/current-run',+ };+ const files = [+ { token: token('a'), name: 'personal.png' },+ { token: token('b'), name: fixture.imageName },+ { token: token('c'), isSharedText: true, sharedText: fixture.sharedText },+ { token: token('d'), isSharedText: true, sharedText: 'personal text' },+ { token: token('e'), name: 'smoke-previous-run.png' },+ ];+ expect(testShareTokens(files, fixture)).toEqual([token('b'), token('c')]);+ expect(testShareTokens(files.slice(0, 1), fixture)).toEqual([]);+ });+});diff --git a/apps/web/tests/native/android/smoke.mjs b/apps/web/tests/native/android/smoke.mjsnew file mode 100644index 0000000000..f6345dec96--- /dev/null+++ b/apps/web/tests/native/android/smoke.mjs@@ -0,0 +1,543 @@+// Run with ANDROID_SERIAL=<dedicated emulator> bun tests/native/android/smoke.mjs.+// Uses the installed debug APK and its real native bridge; sends no messages.+import assert from 'node:assert/strict';+import { mkdir, writeFile } from 'node:fs/promises';+import { screenPointForInput, testShareTokens } from './smoke-utils.mjs';++const serial = process.env.ANDROID_SERIAL;+if (!serial)+ throw new Error('Set ANDROID_SERIAL to the dedicated test emulator');+const adb =+ process.env.ADB ??+ `${process.env.HOME}/Library/Android/sdk/platform-tools/adb`;+const output = process.env.ANDROID_SMOKE_OUTPUT ?? '/tmp/macro-task03-smoke';+const packageName = 'com.macro.app.prod';+const port = 9236;+const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));+async function adbRun(...args) {+ const process = Bun.spawn([adb, '-s', serial, ...args], {+ stdout: 'pipe',+ stderr: 'pipe',+ });+ const result = await new Response(process.stdout).arrayBuffer();+ if ((await process.exited) !== 0)+ throw new Error(await new Response(process.stderr).text());+ return new Uint8Array(result);+}+const text = (bytes) => new TextDecoder().decode(bytes).trim();+let socket;+let seq = 0;+const pending = new Map();+async function connect(waitForApp = false) {+ socket?.close();+ for (let attempt = 0; attempt < 60; attempt++) {+ try {+ const pid = text(await adbRun('shell', 'pidof', packageName));+ await adbRun(+ 'forward',+ `tcp:${port}`,+ `localabstract:webview_devtools_remote_${pid}`+ );+ const pages = await (+ await fetch(`http://127.0.0.1:${port}/json/list`)+ ).json();+ const page = pages.find((page) => page.type === 'page');+ if (!page) throw new Error('WebView not ready');+ socket = new WebSocket(page.webSocketDebuggerUrl);+ await new Promise((resolve, reject) => {+ socket.onopen = resolve;+ socket.onerror = reject;+ });+ socket.onmessage = ({ data }) => {+ const response = JSON.parse(data);+ if (response.id) {+ pending.get(response.id)?.(response);+ pending.delete(response.id);+ }+ };+ for (let ready = 0; ready < 120; ready++) {+ if (+ await evaluate(+ `!!window.__TAURI_INTERNALS__ && !!document.documentElement.style.getPropertyValue('--dvh') && (${!waitForApp} || document.body.innerText.trim().length > 30)`+ )+ )+ return;+ await pause(500);+ }+ throw new Error('Macro did not initialize its native inset listener');+ } catch {+ socket?.close();+ await pause(500);+ }+ }+ throw new Error('Unable to connect to the debug WebView');+}+async function evaluate(expression, awaitPromise = true) {+ const id = ++seq;+ const response = await new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ pending.delete(id);+ reject(new Error('CDP timeout'));+ }, 30_000);+ pending.set(id, (response) => {+ clearTimeout(timer);+ resolve(response);+ });+ socket.send(+ JSON.stringify({+ id,+ method: 'Runtime.evaluate',+ params: { expression, returnByValue: true, awaitPromise },+ })+ );+ });+ if (response.error || response.result?.exceptionDetails)+ throw new Error(JSON.stringify(response));+ return response.result.result.value;+}+const invoke = (command, args = {}) =>+ evaluate(+ `window.__TAURI_INTERNALS__.invoke(${JSON.stringify(`plugin:android-mobile|${command}`)},${JSON.stringify(args)})`+ );+const results = {};+const runId = crypto.randomUUID();+const imageName = `smoke-${runId}.png`;+const sharedText = `https://example.com/android-smoke/${runId}`;+const shareTokens = new Set();+let sharesStarted = false;+let exportToken;+let clipboardPath;++function trackShares(files) {+ for (const token of testShareTokens(files, { imageName, sharedText })) {+ shareTokens.add(token);+ }+ return files;+}++async function pendingShares() {+ return trackShares((await invoke('getPendingShares')).files);+}++async function discoverTestShares() {+ // The second batch may still be behind another share, or an assertion may+ // fail before its tokens reach JS. Read atomic manifests without dequeuing.+ // Wait for already-dispatched intents on the plugin's serial worker.+ await pendingShares();+ const directory = 'cache/android-share-inbox';+ const names = text(+ await adbRun('shell', 'run-as', packageName, 'ls', directory)+ );+ for (const name of names.split('\n')) {+ if (!/^[a-f0-9-]+\.json$/.test(name)) continue;+ const files = JSON.parse(+ text(+ await adbRun(+ 'shell',+ 'run-as',+ packageName,+ 'cat',+ `${directory}/${name}`+ )+ )+ );+ trackShares(files);+ }+}++await mkdir(output, { recursive: true });+await connect(true);+const keyboardSetting = text(+ await adbRun(+ 'shell',+ 'settings',+ 'get',+ 'secure',+ 'show_ime_with_hard_keyboard'+ )+);+await adbRun(+ 'shell',+ 'settings',+ 'put',+ 'secure',+ 'show_ime_with_hard_keyboard',+ '1'+);+const fontScale = text(+ await adbRun('shell', 'settings', 'get', 'system', 'font_scale')+);+const originalDensity = text(await adbRun('shell', 'wm', 'density'));+const densityOverride = originalDensity.match(/Override density: (\d+)/)?.[1];+const initialDensity = Number(+ densityOverride ?? originalDensity.match(/Physical density: (\d+)/)?.[1]+);+const originalSize = text(await adbRun('shell', 'wm', 'size'));+const sizeOverride = originalSize.match(/Override size: (\d+x\d+)/)?.[1];+const handwritingSetting = text(+ await adbRun(+ 'shell',+ 'settings',+ 'get',+ 'secure',+ 'stylus_handwriting_enabled'+ )+);+await adbRun(+ 'shell',+ 'settings',+ 'put',+ 'secure',+ 'stylus_handwriting_enabled',+ '0'+);+try {+ assert.equal(+ (await invoke('getPendingShares')).files.length,+ 0,+ 'Do not run with a pending personal share'+ );+ assert.equal(+ await evaluate(`document.querySelectorAll('[role=dialog]').length`),+ 0,+ 'Close open dialogs before the keyboard probe'+ );+ const start = await invoke('getInsets');+ assert.ok(start.viewportHeight > 0);+ await evaluate(`(() => {+ const field = document.createElement('textarea'); field.id='android-smoke-input';+ field.setAttribute('aria-label','Android smoke test');+ field.value='Unsent Android draft';+ field.style.cssText='position:fixed;top:100px;left:20px;width:300px;height:80px;z-index:2147483647;background:white;color:black;font-size:20px';+ document.body.append(field);+ })()`);+ const geometry = await evaluate(`(() => {+ const rect = document.getElementById('android-smoke-input').getBoundingClientRect();+ const viewport = window.visualViewport;+ return {rect: {left:rect.left,top:rect.top,width:rect.width,height:rect.height},+ viewport: {left:viewport?.offsetLeft ?? 0,top:viewport?.offsetTop ?? 0,+ width:viewport?.width ?? innerWidth,height:viewport?.height ?? innerHeight}};+ })()`);+ const hierarchyPath = `/data/local/tmp/macro-android-smoke-${runId}.xml`;+ let hierarchy;+ try {+ await adbRun('shell', 'uiautomator', 'dump', hierarchyPath);+ hierarchy = text(await adbRun('shell', 'cat', hierarchyPath));+ } finally {+ await adbRun('shell', 'rm', '-f', hierarchyPath);+ }+ const { x, y } = screenPointForInput(hierarchy, packageName, geometry);+ await adbRun('shell', 'input', 'tap', String(x), String(y));+ let shown;+ for (let attempt = 0; attempt < 40; attempt++) {+ shown = await invoke('getInsets');+ if (shown.imeVisible && shown.imeHeight > 0) break;+ await pause(500);+ }+ await writeFile(+ `${output}/keyboard.png`,+ await adbRun('exec-out', 'screencap', '-p')+ );+ assert.equal(shown.imeVisible, true);+ assert.ok(+ Math.abs(shown.viewportHeight - start.viewportHeight) < 1,+ 'IME must not resize the WebView; the layout root shrinks through --dvh'+ );+ const css = await evaluate(+ `(() => {+ const probe = document.createElement('div');+ probe.style.cssText = 'position:fixed;height:calc(var(--dvh)*100);pointer-events:none';+ document.body.append(probe);+ const dvh = probe.getBoundingClientRect().height;+ probe.remove();+ return {dvh,offset:document.documentElement.style.getPropertyValue('--virtual-keyboard-height')};+ })()`+ );+ assert.ok(+ Math.abs(css.dvh - (shown.viewportHeight - shown.imeHeight)) < 1,+ 'The layout root must shrink by exactly the keyboard height'+ );+ assert.ok(+ Math.abs(Number.parseFloat(css.offset) - shown.imeHeight) < 1,+ 'Fixed sheets lift by the keyboard height'+ );+ await adbRun('shell', 'input', 'keyevent', '4');+ for (let attempt = 0; attempt < 40; attempt++) {+ if (!(await invoke('getInsets')).imeVisible) break;+ await pause(500);+ }+ assert.equal((await invoke('getInsets')).imeVisible, false);+ assert.equal(+ await evaluate(`document.getElementById('android-smoke-input').value`),+ 'Unsent Android draft'+ );+ results.keyboard = { start, shown, css, backPreservedDraft: true };+ console.log('Keyboard overlay and Back passed');++ // Font/display settings previously recreated the Activity while the native+ // plugin retained the old WebView, stranding its insets and the open draft.+ await adbRun(+ 'shell',+ 'settings',+ 'put',+ 'system',+ 'font_scale',+ fontScale === '1.3' ? '1.0' : '1.3'+ );+ await pause(1500);+ assert.equal(+ await evaluate(`document.getElementById('android-smoke-input')?.value`),+ 'Unsent Android draft'+ );+ const configured = await invoke('getInsets');+ const actualHeight = await evaluate('innerHeight');+ assert.ok(+ Math.abs(configured.viewportHeight - actualHeight) < 2,+ 'Native insets must follow the current WebView after configuration changes'+ );+ results.configuration = {+ fontScalePreservedWebViewAndDraft: true,+ configured,+ actualHeight,+ };+ await adbRun(+ 'shell',+ 'settings',+ 'put',+ 'system',+ 'font_scale',+ fontScale === 'null' ? '1.0' : fontScale+ );+ await pause(500);+ await evaluate(+ `document.getElementById('android-smoke-input').style.top = 'calc(var(--dvh)*100 - 100px)'`+ );+ await adbRun(+ 'shell',+ 'wm',+ 'density',+ initialDensity === 240 ? '420' : '240'+ );+ await pause(1500);+ const resized = await evaluate(`(() => {+ const field = document.getElementById('android-smoke-input');+ return {height:innerHeight,bottom:field.getBoundingClientRect().bottom,draft:field.value,+ topInset:parseFloat(document.documentElement.style.getPropertyValue('--tauri-inset-top'))};+ })()`);+ assert.equal(resized.draft, 'Unsent Android draft');+ assert.ok(+ Math.abs(resized.height - resized.bottom - 20) < 2,+ 'Display density changes must keep bottom composers inside the CSS viewport'+ );+ const densityInsets = await invoke('getInsets');+ assert.ok(+ Math.abs(+ resized.topInset -+ (densityInsets.top * resized.height) / densityInsets.viewportHeight+ ) < 1,+ 'Safe areas must use the current CSS pixel scale after a density change'+ );+ results.configuration.displayDensityPreservedComposer = true;+ results.windowSizes = [];+ for (const size of ['1600x2560', '1350x1800']) {+ await adbRun('shell', 'wm', 'size', size);+ await pause(1000);+ const viewport = await evaluate(`(() => {+ const field = document.getElementById('android-smoke-input');+ return {width:innerWidth,height:innerHeight,bottom:field.getBoundingClientRect().bottom,draft:field.value};+ })()`);+ assert.equal(viewport.draft, 'Unsent Android draft');+ assert.ok(Math.abs(viewport.height - viewport.bottom - 20) < 2);+ results.windowSizes.push({ size, ...viewport });+ }+ await adbRun('shell', 'wm', 'size', sizeOverride ?? 'reset');+ await adbRun('shell', 'wm', 'density', densityOverride ?? 'reset');+ await pause(500);+ await evaluate(`document.getElementById('android-smoke-input').remove()`);++ const png =+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=';+ const { token } = await invoke('beginExport', {+ name: imageName,+ mimeType: 'image/png',+ size: 68,+ });+ exportToken = token;+ await invoke('appendExport', { token, data: png });+ await invoke('finishExport', { token, action: 'copy' });+ const clipboard = await invoke('stageClipboardImage');+ clipboardPath = clipboard.previewPath;+ assert.equal(clipboard.size, 68);+ assert.equal(clipboard.mimeType, 'image/png');+ const copied = await adbRun(+ 'shell',+ 'run-as',+ packageName,+ 'cat',+ clipboard.previewPath+ );+ assert.equal(Buffer.from(copied).toString('base64'), png);+ results.clipboard = { exactBytes: true, size: clipboard.size };+ console.log('Clipboard bytes passed');++ const uri = `content://${packageName}.fileprovider/exports/${token}/${imageName}`;+ sharesStarted = true;+ await adbRun(+ 'shell',+ 'am',+ 'start',+ '-n',+ `${packageName}/.MainActivity`,+ '-a',+ 'android.intent.action.SEND',+ '-t',+ 'image/png',+ '--eu',+ 'android.intent.extra.STREAM',+ uri+ );+ await pause(500);+ const first = await pendingShares();+ assert.equal(first.length, 1);+ assert.equal(first[0].name, imageName);+ assert.equal(first[0].size, 68);+ let uploaded;+ const receiver = Bun.serve({+ hostname: '127.0.0.1',+ port: 9237,+ async fetch(request) {+ uploaded = {+ bytes: Buffer.from(await request.arrayBuffer()).toString('base64'),+ checksum: request.headers.get('x-amz-checksum-sha256'),+ };+ return new Response(null, { status: 200 });+ },+ });+ try {+ const checksum = Buffer.from(first[0].sha256, 'hex').toString('base64');+ await evaluate(+ `window.__TAURI_INTERNALS__.invoke('upload_staged_file_to_presigned_url', ${JSON.stringify(+ {+ source: 'share',+ token: first[0].token,+ uploadUrl: 'http://10.0.2.2:9237/upload',+ mimeType: first[0].mimeType,+ checksumSha256: checksum,+ }+ )})`+ );+ assert.deepEqual(uploaded, { bytes: png, checksum });+ results.nativeUpload = { exactBytes: true, checksumHeader: true };+ console.log('Native streaming PUT and checksum passed');+ } finally {+ receiver.stop(true);+ }+ assert.equal((await pendingShares())[0].token, first[0].token);+ await adbRun(+ 'shell',+ 'am',+ 'start',+ '-n',+ `${packageName}/.MainActivity`,+ '-a',+ 'android.intent.action.SEND',+ '-t',+ 'text/plain',+ '--es',+ 'android.intent.extra.TEXT',+ sharedText+ );+ await pause(500);+ assert.equal(+ (await pendingShares())[0].token,+ first[0].token,+ 'Second share must not replace an open draft'+ );+ await adbRun('shell', 'am', 'force-stop', packageName);+ await adbRun('shell', 'am', 'start', '-n', `${packageName}/.MainActivity`);+ await connect();+ assert.equal(+ (await pendingShares())[0].token,+ first[0].token,+ 'Cold startup retains the share exactly once'+ );+ await invoke('clearShares', {+ tokens: testShareTokens(first, { imageName, sharedText }),+ });+ const second = await pendingShares();+ assert.equal(second.length, 1);+ assert.equal(second[0].sharedText, sharedText);+ await invoke('clearShares', {+ tokens: testShareTokens(second, { imageName, sharedText }),+ });+ assert.equal((await invoke('getPendingShares')).files.length, 0);+ results.shares = { queued: true, survivedColdStart: true, cleared: true };+ await writeFile(`${output}/results.json`, JSON.stringify(results, null, 2));+ console.log(JSON.stringify(results, null, 2));+} finally {+ // A failure in one cleanup must not skip the others or display restoration.+ const clean = async (action) => {+ try {+ await action();+ } catch (error) {+ console.error('Smoke cleanup failed:', error);+ process.exitCode = 1;+ }+ };+ if (sharesStarted) {+ await clean(discoverTestShares);+ }+ if (shareTokens.size > 0) {+ await clean(() => invoke('clearShares', { tokens: [...shareTokens] }));+ }+ if (clipboardPath) {+ await clean(() =>+ adbRun('shell', 'run-as', packageName, 'rm', '-f', clipboardPath)+ );+ }+ if (exportToken) {+ await clean(() => invoke('discardExport', { token: exportToken }));+ // Finished exports are no longer in the plugin's active map, and the map+ // is lost on restart. Remove just this run's export directory.+ await clean(() =>+ adbRun(+ 'shell',+ 'run-as',+ packageName,+ 'rm',+ '-rf',+ `cache/android-exports/${exportToken}`+ )+ );+ }+ try {+ await evaluate(`document.getElementById('android-smoke-input')?.remove()`);+ } catch {}+ await adbRun(+ 'shell',+ 'settings',+ 'put',+ 'secure',+ 'show_ime_with_hard_keyboard',+ keyboardSetting === 'null' ? '0' : keyboardSetting+ );+ await adbRun(+ 'shell',+ 'settings',+ 'put',+ 'secure',+ 'stylus_handwriting_enabled',+ handwritingSetting === 'null' ? '1' : handwritingSetting+ );+ await adbRun(+ 'shell',+ 'settings',+ 'put',+ 'system',+ 'font_scale',+ fontScale === 'null' ? '1.0' : fontScale+ );+ await adbRun('shell', 'wm', 'density', densityOverride ?? 'reset');+ await adbRun('shell', 'wm', 'size', sizeOverride ?? 'reset');+ socket?.close();+}diff --git a/bun.lock b/bun.lockindex a9be4212b5..d9b69c0501 100644--- a/bun.lock+++ b/bun.lock@@ -162,7 +162,6 @@"tabbable": "^6.2.0","tailwind-merge": "^3.4.0","tailwindcss": "^4.2.4",- "tauri-plugin-safe-area-insets": "^0.1.0","ts-pattern": "^5.9.0","unicode-emoji-json": "^0.8.0","uuid": "^10.0.0",@@ -3443,8 +3442,6 @@"tar-stream": ["[email protected]", "", { "dependencies": { "b4a": "^1.6.4", "bare-fs": "^4.5.5", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } }, "sha512-nqsEO8zLZJvrOMdEwkA0QdCLFbetHMn95Zqu4fKwX+hkaTWJPZZOrxx/PwtxoK0MMGQmBQNRW3CPs8IFYQz4cQ=="],- "tauri-plugin-safe-area-insets": ["[email protected]", "", { "dependencies": { "@tauri-apps/api": ">=2.0.0-beta.6" } }, "sha512-NhtxSQdU7+laTJiO4WZFlTB1CBzRlNE5EuHflGAGXS55fiwOkkaWztfNishFQO+eZtb9i5jLHX3Yho48lnqcRQ=="],-"teeny-request": ["[email protected]", "", { "dependencies": { "http-proxy-agent": "^5.0.0", "https-proxy-agent": "^5.0.0", "node-fetch": "^2.6.9", "stream-events": "^1.0.5", "uuid": "^9.0.0" } }, "sha512-resvxdc6Mgb7YEThw6G6bExlXKkv6+YbuzGg9xuXxSgxJF7Ozs+o8Y9+2R3sArdWdW8nOokoQb1yrpFB0pQK2g=="],"teex": ["[email protected]", "", { "dependencies": { "streamx": "^2.12.5" } }, "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg=="],diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex 90bf0b21c5..5eca98cc40 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -212,6 +212,8 @@ the shimmer.- Chat agents' empty input cycles tips about connectors, skills, mentions, andagents; coding agents show **Describe what you want to build**. Type `@` formentions and `/` for skills.+ Check `/` with the Android software keyboard too: the skills menu should open+ and filter while typing, without sending the draft.- Opening a conversation updates the URL based on that conversation's kind:`/app/agents/<id>` for Chat sessions, `/app/coders/<id>` for Code sessions,and `/app/agent-chats/<id>` for legacy chats. Reload and back/forward restorediff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex 767c640575..8d64d2d5ab 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -102,6 +102,14 @@ only the send control, with no format or discard button; Escape cancels the editThe iOS share sheet keeps its editor above the attachment and formatting controls.Check this arrangement at both phone and tablet widths.+On Android, tap `@` on the software keyboard in an empty channel composer or+after a space: the mentions menu should open above the keyboard. Type a name to+filter, then tap a result to insert one mention without sending the draft.+An `@` inside a word stays literal text. Check hardware-keyboard input too;+it should open only one menu.+The same software-keyboard check applies to `:` for emoji and `/` for formatting+commands: type a search and tap a result without sending the draft.+The shared `@` menu also offers `Recent agent sessions` after Channels andbefore Companies (the latest 500 accessible sessions, searchable by title orpersona). These inline chips show the shareddiff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex 10d79969e1..df341f86f5 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -337,6 +337,10 @@ nodes — use the snapshot itself to verify content. For formatting checks, runBody placeholder advertises: `/` for block commands, `@` to reference files, `;` for snippets.Markdown auto-format works while typing (`#` heading, `[]` checklist, `>` quote).+On Android, use the software keyboard to check `:` emoji, `/` commands, `;`+snippets, and `#` tags where enabled. Each should open once and filter as you+type. Tapping an emoji or command applies it; a second `#` closes the tags menu+and leaves literal `##` for Markdown headings.AI text-writing operations require a paragraph/list-item or text-run ID. Atable, row, cell, or list-container ID is rejected with guidance to choose a@@ -346,6 +350,9 @@ table cells is preserved in paragraphs when the editor opens the document.`@` opens the mention menu wherever the caret starts a word, including directlyin front of existing text — the menu opens empty there instead of searching forthe word ahead of the caret. Typed inside a word (`he@llo`) it stays literal text.+On Android, verify this with the software keyboard: tap `@`, type a name to+filter, and tap a result to insert a single mention. The menu should remain+visible above the keyboard while typing.`Ctrl+F` / `Cmd+F` opens the in-document find bar. Matches include paragraphtext and inline mention chips (tasks, docs, channels, skills, …) by the titlediff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex ac215c1f41..de160d2e14 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -11,6 +11,45 @@ queued mutations should resume promptly, without waiting for the old poll orlocal retry timer; durable leases and server-retry deadlines still apply.Switching tabs or navigating an in-app route is not a back/forward-cache restore.+## Android system navigation and sharing++In the Android app, Back first hides the keyboard, then dismisses the active+menu/drawer, then returns through mobile pane history. Root Back backgrounds the+app. Check that a canceled predictive Back gesture leaves the current screen and+draft untouched. After changing orientation or window size, focused inputs and+sheet actions should stay above the keyboard without an extra blank keyboard-sized+gap. Font-size and display-size changes should retain the active draft and update+safe areas. Also change display size with the keyboard hidden: bottom composers+must remain visible before the keyboard is opened again. Editors expose labeled+multiline textboxes for TalkBack.++With the keyboard closed, the Android dock sits above the measured system+navigation inset with the usual 12px gutter. Check both gesture and three-button+navigation, including after rotation and display-size changes. Opening the+keyboard leaves only the usual gutter above it. iOS retains its existing 28px+bottom padding with the keyboard closed and 12px with it open.++Sharing text, links, images, or documents from another Android app opens Share to+Macro after login. A second incoming share waits behind the current one. Back or+outside dismissal asks **Discard this share?**; **Keep editing** preserves the+message and attachments. Failed uploads show **Retry** and block Send until they+succeed. Send stays disabled while posting and after success, including when+native queue cleanup fails; retrying cleanup must not post the message again.+Test rapid repeated taps with delayed cleanup and retry after a failed send.+On Android and iOS, if a send finishes after its sheet is canceled, cleanup must+leave any newer share pending with its attachments intact.+**Cancel** explicitly discards the current share. Send+is a real channel/DM mutation: do not use it in verification without authorization.+Android attachment controls open the system picker. File downloads open Android's+Save dialog; image share actions open its share chooser. Canceling either should+return to the existing editor without changing its draft. Large exports show+preparation progress and **Cancel**; a canceled save must not report success.++The native share sheet is shared with iOS. When testing iOS email attachments,+paste an image and select one from Photos: plugins without a native checksum+must hash the staged image bytes, retain the real attachment size, and upload+successfully rather than hashing the empty JavaScript placeholder.+## Direct URLs (all under the frontend origin)| Route | Surface |diff --git a/docs/ANDROID_DEVELOPMENT.md b/docs/ANDROID_DEVELOPMENT.mdindex c81e56b701..40a9719ae3 100644--- a/docs/ANDROID_DEVELOPMENT.md+++ b/docs/ANDROID_DEVELOPMENT.md@@ -161,6 +161,95 @@ replacing the Macro session. After process death mid-flow, restart authenticatioorphaned callbacks must not silently log in the replacement process. Macro logoutdoes not sign out of Google/GitHub in the system browser.+iOS retains its existing auth/keyboard plugins. Android uses `android_mobile_plugin`+for live window/IME insets, committed system Back, content-URI sharing, clipboard+images, and file export; it does not build the old keyboard scaffold.++## Input, navigation, and files++The Android mobile plugin publishes window insets from the native WebView. The+WebView keeps its full edge-to-edge size under the keyboard, as on iOS: resizing it+made Chromium relayout the whole document on top of the CSS work. Instead the+plugin publishes the keyboard height and JS shrinks the layout root through+`--dvh` and lifts fixed sheets by `--virtual-keyboard-height`, so nothing subtracts+the keyboard twice. Native density can change before Chromium updates its CSS+viewport, so insets are scaled by the WebView width (which the keyboard never+changes) and re-applied on WebView resize as well as native inset events. Every+root custom-property write recalculates style for the whole document, so only+changed values are written.+System bars and cutouts remain separate safe-area values; floating keyboards with+no bottom inset do not consume viewport height. Insets refresh after layout,+rotation, and resume. Font scale, density, layout direction, and navigation-mode+changes are handled in the current Activity so Tauri retains a live WebView and+unsent drafts. See [Android's inset guidance](https://developer.android.com/develop/ui/views/layout/edge-to-edge).++Committed Back hides the IME first, then uses the existing overlay Escape handlers,+then mobile pane history. At the root it backgrounds the task. Canceled predictive+Back gestures do not dispatch navigation. The native share composer asks before+discarding on Back/outside dismissal; Keep editing retains its current contents.+Android editors use normal Lexical caret handling, without the iOS cursor plugin.++Incoming SEND/SEND_MULTIPLE text, URLs, and `content://` streams enter an atomic+private-cache queue. Providers are read while their URI grant is valid; names and+reported sizes are not trusted as paths or byte counts. Staging limits each intent+to 500 MiB total and 100 attachments. Files are checksummed while copying;+PDFs and other documents use the regular document-creation flow with native+streaming PUT and the S3 checksum header. Media uses the static-file uploader.+Failed uploads stay visible with a Retry action and block sending until resolved.+Missing or corrupt batches report an error and do not strand later shares.+The queue retains original bytes until send/cancel, survives process restarts and+login, and keeps a second share behind the active composer. Abandoned staging is+removed after 24 hours. Ordinary attachment selection continues to use the WebView+file input and Android's picker; no parallel photo-picker adapter is introduced.++Blob downloads use chunked native export and Android's Save dialog. Large transfers+show progress and can be canceled before the system chooser opens; canceled Save+dialogs do not report success. Email clipboard attachments use native bytes and+their actual size/checksum, including the email attachment-size limit. Image sharing+and copying use FileProvider content URIs with temporary read grants. Exported+files remain in a narrow private-cache provider directory for asynchronous+receivers and expire after 24 hours. The provider also exposes app-specific+Pictures for the WebView camera-capture fallback; it does not expose external+storage roots. The app removes device-info's unused legacy read/write-storage and+battery-stat permissions from the merged manifest. Downloads already authenticated/fetched by the app preserve those+bytes rather than reopening a URL in an unauthenticated external browser.++From `apps/web`, after installing the current debug APK and letting Macro load:++```sh+ANDROID_SERIAL=<dedicated-emulator-serial> bun tests/native/android/smoke.mjs+bunx vitest run src/lib/core/mobile/androidWindowInsets.test.ts src/lib/core/mobile/androidBack.test.tsx src/lib/core/mobile/androidFiles.test.ts src/lib/service-clients/service-storage/util/upload-native.test.ts src/features/channel/Input/tests/upload-attachments.test.ts+```++Use a dedicated emulator with no pending personal share. The smoke test injects a+temporary input, exercises native clipboard/export and incoming-share commands,+verifies font-scale and display-density changes retain the WebView/draft and+keep bottom controls inside the CSS viewport at tablet/foldable-sized windows, force-stops/relaunches+Macro, and writes results/screenshots under+`/tmp/macro-task03-smoke`. It never sends a message; a signed-in share composer can+upload the test attachment as it normally does. In Gboard's settings, Physical+keyboard → Show on-screen keyboard must be enabled to test the docked IME; the+system setting alone can leave Gboard showing only its physical-keyboard toolbar.++The plugin's tests use an isolated package (`com.macro.mobile.test`) and never+clear Macro's data. From the generated Gradle project, build/run them with:++```sh+./gradlew :tauri-plugin-android-mobile:testDebugUnitTest :tauri-plugin-android-mobile:assembleDebugAndroidTest+adb -s <serial> install -r ../../../android_mobile_plugin/android/build/outputs/apk/androidTest/debug/tauri-plugin-android-mobile-debug-androidTest.apk+adb -s <serial> shell am instrument -w com.macro.mobile.test/androidx.test.runner.AndroidJUnitRunner+```++These instrumented tests exercise Android content providers, duplicate URIs,+multiple streams with text, delayed consumption/recreation, missing files,+permission failures, MIME fallback, bounded large streams, and corrupt queues. Keep device qualification separate+from these checks: test real channel/email/AI/document editors, selection and+formatting, non-Latin IME composition, emoji/dictation, hardware keyboards,+TalkBack/large text, Samsung Keyboard, cloud providers/large files, rotation,+three-button/gesture navigation, canceled predictive Back, and tablet/foldable+windows before closing task 03. An API 36 emulator cannot establish the whole+physical-device matrix.+## App LinksApp Links require a domain association for `com.macro.app.prod` and the certificatediff --git a/docs/ANDROID_READINESS_AUDIT.md b/docs/ANDROID_READINESS_AUDIT.mdnew file mode 100644index 0000000000..16cba022a6--- /dev/null+++ b/docs/ANDROID_READINESS_AUDIT.md@@ -0,0 +1,157 @@+# Android readiness audit++Audited September 21, 2026, at commit `1c26a7c4fe`.++**Assessment: Android has a useful foundation, but it is not currently ready for a functional release.** The largest workstreams are native authentication, end-to-end push notifications, keyboard/input behavior, and calling. There are also source-level build blockers. A successful APK build alone would leave important product features unavailable.++Scope: parity with the current iPhone app, including sign-in/onboarding, messaging, email, documents, AI, attachments, notifications, calls, sharing, and updates. This is a source/configuration audit, including the exact cached dependency revisions and current Android/Play documentation. No Android build or device test was performed: `adb` was unavailable, the conventional local SDK directory was absent, and the repository's Android Nix shell is x86_64 Linux-only. Production Firebase, signing, Play Console, and deployed association files were not verified. Public association URLs could not be fetched through the web tool. Distinguish **confirmed gaps** below from **validation work**, which may not require new implementations.++## What can be reused++- The checked-in Android Gradle project already uses `com.macro.app.prod`, SDK/target 36, minimum SDK 24, Firebase Messaging, and custom-scheme/HTTP App Link intent filters. See [Android Gradle configuration](../apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts) and [manifest](../apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml).+- The shared Solid frontend recognizes Android, has mobile layouts, and already routes native HTTP/WebSocket traffic through Tauri. There is Android safe-area initialization.+- Native GraphQL caching and the bundle updater have cross-platform Rust implementations; the updater already reads Android's native build number.+- Device registration, Android device models, an SNS FCM transport, and dev/prod FCM infrastructure exist. **Delivery is incomplete**, as detailed below.+- Linux Android tooling and mobile browser spreadsheet tests exist. Neither constitutes an Android native release test suite.++Priorities: **P0** blocks a usable initial release; **P1** is required for full iPhone feature parity or a reliable production release. Size indicates relative scope, not a delivery estimate.++## Required work++### 1. Repair the Android build and plugin dependency graph — P0, medium++**Confirmed:** [app Cargo.toml](../apps/web/tauri/src-tauri/Cargo.toml) declares only `rlib` and `staticlib`; Android needs the shared library output (`cdylib`). The shared [mobile capability](../apps/web/tauri/src-tauri/capabilities/mobile.json) applies to Android but references edit-menu, pasteboard, photo-library, network-status, and call-kit permissions whose dependencies are restricted to iOS. The pinned Tauri build code validates these permissions against available plugin manifests.++More seriously, the pinned auth dependency (`macro-inc/tauri-plugins`, revision `6ddd6600e20436388f169e936b610fe93944b7b0`) has no Android implementation. Its [src/mobile.rs](https://github.com/macro-inc/tauri-plugins/blob/6ddd6600e20436388f169e936b610fe93944b7b0/packages/tauri-plugin-auth/src/mobile.rs) declares `handle` only under `cfg(target_os = "ios")`, then unconditionally constructs `Auth(handle)`. Its build script also references a nonexistent Android directory. This is a source-level Android build blocker, not just an unused feature.++The pinned virtual-keyboard dependency (`70e8e8325b5ff7d681ef5f3b996ac083d4fc5a01`) has an [Android example implementation](https://github.com/voxelbee/tauri-plugin-virtual-keyboard/blob/70e8e8325b5ff7d681ef5f3b996ac083d4fc5a01/android/src/main/java/ExamplePlugin.kt) whose Kotlin package is literally `com.plugin.virtual-keyboard`, with an invalid unescaped hyphen. It must be fixed/replaced; see item 5 for the missing behavior.++**Do:** add the required library output; separate shared and platform-specific capabilities; implement or replace incompatible plugins; build the actual pinned Tauri/Tao/HTTP/WebSocket/cache dependency graph. Provide repeatable Android prepare/dev/release commands, environment configuration, Firebase config injection, and a supported developer setup. Preserve iOS behavior while doing this.++**Done when:** a clean checkout produces an installable debug APK and a signed, minified release AAB; a Play-installed release launches without plugin initialization failures.++### 2. Implement Android authentication and connected-account handoff — P0, large++**Confirmed:** [useSsoLogin.ts](../apps/web/src/features/auth/useSsoLogin.ts) uses the native callback/session redemption flow only for iOS. Android falls through to browser navigation and sets `original_url` to the WebView's local origin. [The navigation plugin](../apps/web/tauri/navigation_plugin/src/lib.rs) opens external destinations in the system browser, where that local origin does not return the user to the app. The same iOS-only split appears in [Gmail linking](../apps/web/src/lib/core/email-link/index.ts) and [GitHub onboarding](../apps/web/src/features/auth/mobile-onboarding/OnboardingConnectAccounts.tsx).++**Do:** implement an Android browser/Custom Tabs authentication bridge with app callback delivery, cancellation, request correlation, and the existing one-time session-code exchange. Apply it consistently to every supported login provider, Gmail/calendar consent, account linking, and reauthentication. Reuse the backend session model; do not assume browser cookies automatically become native HTTP cookies. Keep intended destination/referral/onboarding state through the round trip and process recreation.++**Done when:** new and existing users can sign in, connect another inbox/GitHub account, grant calendar scopes, cancel/retry, relaunch while authenticated, log out, and switch accounts. Check email-code login as well as SSO and verify account-specific caches and push tokens are cleared/rebound.++### 3. Complete backend Android push delivery — P0, large++**Confirmed:** [notification ingress](../crates/notification/src/domain/service/ingress.rs), around lines 365 and 561, explicitly filters out `DeviceEndpoint::Android` for push delivery and push clearing. [NotificationChannel](../crates/notification/src/domain/models/queue_message.rs) has only iOS, email, and connection-gateway variants. [The Android payload model](../crates/notification/src/domain/models/android.rs) still has `new_temporary_empty` and `"Temporary placeholder"`; it is not a production message builder. Existing registration and [FCM infrastructure](../infra/stacks/notification-service/index.ts) do not connect this missing delivery path.++**Do:** add Android message construction, queue/worker handling, and dispatch. Preserve notification IDs, permissions, user preferences, grouping, read/dismiss synchronization, retry semantics, and invalid-token cleanup. Use a correct SNS/FCM payload contract, not the placeholder model. SNS supports an explicit [FCM HTTP v1 envelope](https://docs.aws.amazon.com/sns/latest/dg/sns-fcm-v1-payloads.html).++**Done when:** representative channel, mention, email, and other enabled notification types reach Android from real backend events; reading/dismissing on another client reconciles correctly. Include serialization and worker tests, not just device-registration tests.++### 4. Complete the Android push receiver and frontend contract — P0, large++**Confirmed:** the pinned notifications plugin's [Android implementation](https://github.com/macro-inc/tauri-plugins/blob/6ddd6600e20436388f169e936b610fe93944b7b0/packages/tauri-plugin-notifications/android/src/main/java/NotificationsPlugin.kt) initializes Firebase, requests permission, and fetches a token. It lacks the `watchNotifications` method called by [PushNotification.tsx](../apps/web/src/lib/tauri/PushNotification.tsx), and the audited app/plugin sources contain no custom `FirebaseMessagingService`, token refresh handler, or notification-tap intent bridge. Inherited Tauri `checkPermissions` returns a permission alias map (`postNotification`), while the Rust/JS contract expects a `status` field.++**Do:** normalize permission responses, handle pre/post Android 13 permission behavior, implement receive/tap/token-refresh handling, notification channels and icons, foreground behavior, and cold-start event buffering. Configure matching Firebase Android apps and supply ignored `google-services.json` files per environment. Validate SNS credentials/project alignment; their configuration references already exist.++The frontend currently suppresses local notifications once remote push reports granted. Until remote display works, that can leave users with neither path. Deliberately choose foreground display/deduplication behavior rather than copying iOS assumptions.++**Done when:** delivery and tap routing work in foreground, background, and normal process-dead states; permission denial/revocation, token rotation, account switch, and notification removal work. Test Doze and OEM battery management separately; user force-stop is a distinct OS state and should not be promised normal push delivery.++### 5. Implement Android keyboard, insets, and text-input behavior — P0, medium/large++**Confirmed:** [useAppSquishHandlers.ts](../apps/web/src/components/app/useAppSquishHandlers.ts) expects native `keyboardWillShow` / `keyboardWillHide` events on *both* mobile platforms. The pinned Android keyboard plugin implements only an example `ping` command. [TauriProvider.tsx](../apps/web/src/lib/tauri/TauriProvider.tsx) reads Android safe-area insets once on mount. The activity already enables edge-to-edge.++**Do:** provide Android IME/window-inset events, reconcile viewport resizing with keyboard height to avoid double subtraction, and update insets after rotation, navigation-mode changes, and window resizing. Test editor focus, caret visibility, bottom toolbars, sheets, scrolling, selection, clipboard menus, and keyboard dismissal. Review the iOS cursor-scroll plugin, currently enabled for all native mobile platforms in multiple editors, for Android behavior.++Test Gboard and Samsung Keyboard, composition/non-Latin input, dictation, emoji, multiline messages, and hardware keyboards. Edge-to-edge handling is a requirement for this target SDK, not optional cosmetic work; see [Android guidance](https://developer.android.com/develop/ui/views/layout/edge-to-edge).++**Done when:** channel, email, AI, comments, and document composers remain visible and retain correct text/selection through IME show/hide and rotation.++### 6. Fix App Links and unify the WebView origin — P0, medium++**Confirmed:** [assetlinks.json](../apps/web/tauri/src-tauri/.well-known/assetlinks.json) names `com.tauri.dev`; the application ID is `com.macro.app.prod`. Intent filters already exist for macro.com, dev.macro.com, and staging.macro.com, but the deployed association files were not verified. The native-app service's dynamic verification model currently supplies iOS association data only.++There is also a concrete configuration mismatch to resolve: [lib.rs](../apps/web/tauri/src-tauri/src/lib.rs) passes `https://tauri.localhost` to the custom protocol on Android, while its navigation allowlist includes only the HTTP form. [tauri.conf.json](../apps/web/tauri/src-tauri/tauri.conf.json) does not enable `useHttpsScheme` (false by default in the pinned Tauri code), and [backend CORS](../crates/macro_cors/src/lib.rs) includes HTTP, not HTTPS. This needs an actual device test to identify each failing request, but the inconsistent definitions are visible in source.++**Do:** choose the origin before launch and align protocol rewriting, navigation, browser API requirements, cookies, CORS where applicable, workers, and asset URLs. Changing the origin later changes browser-storage identity. Publish correct association files for the selected hosts and **Play App Signing** certificate, with separate debug/dev associations as needed. [Android's verification guidance](https://developer.android.com/training/app-links/verify-applinks) also covers the stricter multi-host behavior on older versions.++**Done when:** signed-release links open the correct entity on cold/warm launch, including logged-out users who must authenticate first; callback links and links from notifications are not dropped or duplicated.++### 7. Build native Android calling parity — P1, large++**Confirmed:** [CallKit setup](../apps/web/src/features/channel/Call/use-callkit.ts) is iOS-only; the native media session, audio routing, incoming-call coordination, and picture-in-picture implementation live in Swift under [callkit_plugin](../apps/web/tauri/callkit_plugin). [Backend VoIP dispatch](../crates/notification/src/domain/service/voip.rs) selects only `IosVoip` endpoints. Existing browser LiveKit calls are a reusable foreground path, not evidence of background or lock-screen calling support.++**Do:** implement the Android call lifecycle using an appropriate Telecom/Core-Telecom integration, incoming-call FCM delivery, ongoing-call foreground support, answer/decline/end actions, and an Android media session. Cover microphone/camera runtime permissions, audio focus, Bluetooth/speaker/headset routing, interruptions, reconnection, camera switching, background audio, and video/PiP parity. Handle stale/cancelled rings and calls answered on another device. [Core-Telecom](https://developer.android.com/develop/connectivity/telecom/voip-app/telecom) provides system call and foreground integration.++**Done when:** incoming and outgoing calls work with the app open, backgrounded, and the phone locked; calls survive navigation and network transitions without duplicate sessions. Treat this as a separate substantial project when planning capacity.++### 8. Add receiving shares from other Android apps — P1, medium++**Confirmed:** [share_target.rs](../apps/web/tauri/src-tauri/src/share_target.rs) selects the no-op implementation outside iOS. [ShareTargetProvider](../apps/web/src/lib/tauri/ShareTargetProvider.tsx) and [NativeShareSheet](../apps/web/src/features/sharing/native-share-sheet/NativeShareSheet.tsx) explicitly exclude Android. The manifest has no SEND/SEND_MULTIPLE filters.++**Do:** support Android share intents for text, URLs, images, and files; stage `content://` resources while permission grants remain valid; handle multiple files, MIME types, size limits, cancellation, cleanup, cold start, and an authentication detour. Reuse the destination picker/upload logic after removing iOS-specific assumptions. Scope FileProvider paths to the data actually shared.++**Done when:** sharing from Photos, Files, a browser, and another messaging app opens Macro and successfully sends to the selected destination without replaying old shares.++### 9. Verify and complete attachments, clipboard, downloads, and outgoing sharing — P1, medium++**Confirmed:** photo-library and pasteboard native implementations are iOS-only. [nativePhotoLibrary.ts](../apps/web/src/lib/core/mobile/nativePhotoLibrary.ts) invokes its plugin on every Tauri platform, catches failure, and permits a file-input fallback; ordinary Android attachments are therefore **unverified, not proven absent**. [Clipboard image recovery](../apps/web/src/lib/core/mobile/mobileClipboardImageRecovery.ts) similarly attempts an unavailable native command. [downloadFile](../apps/web/src/lib/filesystem/download.ts) uses a browser Blob/anchor, and [imageActions](../apps/web/src/lib/core/util/imageActions.ts) relies on Web Share/browser behavior.++**Do:** exercise actual Android WebView file picking and cloud content providers. Implement native Photo Picker/Storage Access Framework and staging only where the existing path cannot meet requirements. Add reliable save/export/open/share adapters for Blob and authenticated downloads as necessary; do not assume desktop anchor downloads work. Validate camera capture if exposed, large files/video, progress, failures, cancellation, clipboard images, and image saving. Restrict permissions to the chosen flows; inspect the merged manifest rather than assuming the app manifest is the complete permission list.++**Done when:** attachments and exports work across chat, email, documents, and AI, including files originating from Downloads and cloud providers.++### 10. Integrate system Back, haptics, and Android UI behavior — P1, small/medium++**Confirmed:** the pinned Tauri Android activity has default WebView-history Back behavior. No app listener for its `back-button` API was found; application drawers, overlays, and split navigation need an explicit behavior review. [Haptic calls](../apps/web/src/lib/core/mobile/haptics.ts) run for Tauri, but [native plugin registration](../apps/web/tauri/src-tauri/src/lib.rs) places haptics inside the iOS-only block.++**Do:** define/test Back priority (IME, overlay/sheet, nested screen, top-level exit), gesture/predictive Back, and unsent-draft preservation; use the existing Tauri mechanism where sufficient. Register haptics on Android and handle unsupported/error cases. Verify notification prompts/settings wording, TalkBack, large text, contrast, touch targets, rotation, tablets/foldables, split-screen, and external keyboards. Decide supported form factors explicitly; the scaffold also advertises a TV launcher category that should be removed unless intentionally supported.++**Done when:** normal Android navigation never unexpectedly exits a compose flow or strands an overlay, and supported layouts remain usable at changed window/font sizes.++### 11. Prove offline, resume, and process-death reliability — P1, medium validation++**Existing foundation:** native cache, queued mutations, native HTTP/WebSockets, and resume handling. **Confirmed gap:** [native-network-status.ts](../apps/web/src/lib/core/mobile/native-network-status.ts) and [query online-state integration](../apps/web/src/lib/queries/client.ts) use native reachability only on iOS. Android falls back to browser connectivity behavior; this is not proof that Android offline mode is broken.++**Do:** test Android's default connectivity behavior first; add ConnectivityManager monitoring if needed. Validate session refresh, WebSocket resubscription, missed-event replay, optimistic writes, unsent drafts, pending uploads, cached reads, and cross-account isolation after background suspension and process death. Audit Android backup/restore exclusions for credentials and account-specific caches. Measure cold launch, cache hydration, long lists, large documents, memory pressure, and battery use on a lower-end device.++**Done when:** airplane mode, Wi-Fi/cellular transitions, screen lock, backgrounding, and OS process reclamation do not lose acknowledged work or leak the prior account's data.++### 12. Make OTA updates safe across two mobile platforms — P1, medium++**Existing foundation:** Android native version retrieval, bundle checksums, compatibility/revocation policies, and update state UI. **Confirmed design constraint:** [native_app_service](../crates/native_app_service/src/domain/service.rs) fetches one bundle manifest with one `min_native_build`; target-specific policy rules exist, but the minimum is shared. Android and iOS native build numbering/capabilities must not be assumed equivalent.++**Do:** use aligned compatibility numbering or platform-specific minimum/capability metadata; prevent a shared JS update from invoking unavailable Android plugins. Test native build-number detection, interrupted download/extraction, cache eviction, incompatible updates, revocation, embedded-bundle fallback, and resume/apply behavior. Give Android users a working Play Store update destination. Check release update controls, not only development mode.++**Done when:** an old installed Android release remains functional when a new iOS/JS release ships, and rejected/interrupted updates recover cleanly.++### 13. Establish Play distribution, billing behavior, and release operations — P1, medium; billing may be large++**Confirmed:** no Android signing/release workflow was found in the audited GitHub workflows, and no release signing configuration appears in the checked-in Gradle app. External signing/Play setup may exist. [Billing](../apps/web/src/features/settings/Billing.tsx) and [paywalls](../apps/web/src/features/paywall/PaywallComponent.tsx) launch Stripe checkout without an Android-specific branch. [MobileApp settings](../apps/web/src/features/settings/MobileApp.tsx) advertise only the Apple App Store. Account deletion already exists in [Account settings](../apps/web/src/features/settings/Account.tsx).++**Do:** establish application ownership, Play App Signing/upload-key handling, monotonic version codes, reproducible CI AAB builds, release R8 testing, native symbols/source maps, crash/ANR monitoring, internal testing, staged rollout, and rollback procedures. Verify final launcher/adaptive/monochrome icons, splash screen, store listing/screenshots, support links, environment separation, and reviewer account access.++Current [Play target API requirements](https://support.google.com/googleplay/android-developer/answer/11926878?hl=en) call for API 36 for new phone apps/updates; the project already targets 36. Verify **16 KB page-size compatibility for every shipped native library**, including Rust/cache/media dependencies. The [Android tooling shell](../nix/tauri-dev-shells.nix) pins NDK 26.3; upgrade or explicitly configure and verify alignment rather than assuming compliance. See [Android's page-size guidance](https://developer.android.com/guide/practices/page-sizes).++Choose a billing strategy for the intended countries: Play Billing, an applicable enrolled alternative program, or a consumption-only Android app with appropriate purchase UI. Existing Stripe links are not automatically acceptable everywhere; [Google's policy](https://support.google.com/googleplay/android-developer/answer/10281818?hl=en) distinguishes these cases. Play Billing would add entitlement synchronization, restoration, cancellation/refund handling, and backend purchase verification work.++Complete privacy/Data safety declarations against actual SDK/data behavior and verify the existing deletion flow plus an external deletion-request path. See [Data safety](https://support.google.com/googleplay/android-developer/answer/10787469?hl=en) and [account deletion requirements](https://support.google.com/googleplay/android-developer/answer/13327111?hl=en). Recheck applicable policies at submission.++## Execution order and release gate++1. **Prove the shell:** fix build/plugin blockers; settle origin, signing/package identity, and developer tooling; install debug and release builds.+2. **Prove the daily-use loop:** sign in, connect inboxes, compose with the keyboard, upload files, navigate Back, receive/tap push, and relaunch without losing state.+3. **Complete parity:** native calls, inbound/outbound sharing, exports, clipboard, offline/process recovery, and OTA compatibility.+4. **Qualify the release:** billing decision, store setup, automated smoke coverage, real-device testing, observability, and staged Play rollout.++Build Android-native smoke coverage rather than treating mobile browser emulation as acceptance. Existing [native tests](../apps/web/tests/native/README.md) focus on Linux cache behavior, while the dedicated mobile smoke runner is [iOS-only](../apps/web/tests/native/ios/README.md).++| Test dimension | Minimum coverage |+| --- | --- |+| Devices | Pixel and Samsung physical phones; lower-memory device; supported minimum OS; Android 13 notification permissions; API 35/36; 16 KB emulator/device; tablet/foldable if supported |+| Build | Debug, signed minified release, and Play-installed AAB; clean install and upgrade |+| Core product | Search/inbox, channels/threads, email compose/reply, tasks, calendar, document/PDF/spreadsheet surfaces offered on mobile, AI streaming/tools, attachments, settings |+| Lifecycle | Foreground, background, locked, cold launch, OS process death, rotation/window resize, offline/reconnect |+| Native integrations | Authentication and OAuth return, push receipt/tap/clear, incoming/outgoing calls, file pick/save/share, clipboard, Back, keyboard/insets |+| Isolation/recovery | Logout/account switch, expired session, revoked permissions, token rotation, interrupted uploads, incompatible/interrupted OTA |++No application code was changed for this audit. Build failures are inferred from inspected source/configuration, not reproduced compiler output. No unit/integration suites or `just check` were run because this change is documentation-only; Android device validation remains the main missing evidence.diff --git a/docs/ANDROID_TASKS.md b/docs/ANDROID_TASKS.mdnew file mode 100644index 0000000000..3c3d1457e0--- /dev/null+++ b/docs/ANDROID_TASKS.md@@ -0,0 +1,107 @@+# Android release tasks++Created in Macro from `docs/ANDROID_READINESS_AUDIT.md` on September 21, 2026 (source snapshot `1c26a7c4fe`).++All six tasks verified: **Priority: High · Assignee: Peter ([email protected]) · Personal tag: android · Status: Not Started**. No due dates set.++1. [Make the Android app build, authenticate, and open app links](https://macro.com/app/task/01a0c5bb-52fd-7c0d-b6c1-488945ec7dba)+2. [Deliver Android push notifications end to end](https://macro.com/app/task/01a0c5bb-b55b-701e-b160-0e9fe90374d5)+3. [Complete Android input, navigation, attachments, and sharing](https://macro.com/app/task/01a0c5bb-b65f-7115-b6c6-5ae1685cb749)+4. [Implement native Android voice and video calling](https://macro.com/app/task/01a0c5bb-b746-75f4-840f-32aea38f59ed)+5. [Make Android offline recovery and OTA updates reliable](https://macro.com/app/task/01a0c5bb-b846-7235-af24-2002ddaa6e85)+6. [Qualify and release the Android app on Google Play](https://macro.com/app/task/01a0c5bb-ba45-7ac5-96c0-f6298a298d47)++## 1. Make the Android app build, authenticate, and open app links++Deliver a reproducible Android app that launches, signs users in, connects their accounts, and opens Macro links correctly.++Scope:+- Add Android shared-library output and separate shared/iOS/Android plugin capabilities. Repair or replace the pinned auth plugin's missing Android implementation and the keyboard plugin's invalid Android scaffold.+- Provide repeatable Android development/release commands, environment setup, and Firebase configuration injection. Preserve iOS behavior.+- Implement Android browser/Custom Tabs authentication, callback correlation/cancellation, and one-time session-code redemption for supported SSO providers, Gmail/calendar consent, GitHub linking, and reauthentication.+- Preserve intended destination, onboarding state, and account isolation through callback, relaunch, logout, and account switching. Verify email-code login too.+- Reconcile HTTP/HTTPS WebView origins across navigation, protocol handling, cookies, browser storage, assets/workers, and relevant CORS rules.+- Replace the `com.tauri.dev` association entry with the correct package and signing certificates; verify cold/warm App Links on intended production/dev hosts.++Acceptance: a clean checkout produces an installable debug APK and release AAB; users can sign in, cancel/retry, connect accounts, relaunch authenticated, switch accounts, and follow entity links through an authentication detour. A signed release launches without missing-plugin errors. Coordinate final signing/distribution with task 6.++Starting points: `apps/web/tauri/src-tauri/{Cargo.toml,capabilities/mobile.json,tauri.conf.json,src/lib.rs,.well-known/assetlinks.json}`, `apps/web/src/features/auth/useSsoLogin.ts`, `apps/web/src/lib/core/email-link/index.ts`, and audit items 1, 2, 6.++## 2. Deliver Android push notifications end to end++Make real backend notifications reach Android, display once, open the correct entity, and stay consistent across devices/accounts.++Scope:+- Add Android payload construction, queue/worker delivery, and read/dismiss clearing. Notification ingress currently drops Android endpoints; the Android payload model is a placeholder.+- Implement the Android receive/tap/token-refresh bridge, including cold-start buffering and a real notification watcher. Normalize the plugin's permission response to the frontend contract.+- Configure notification channels/icons, pre/post Android 13 permission handling, foreground behavior, and deduplication with websocket/local notifications.+- Verify dev/prod Firebase/SNS alignment, token rotation, invalid-token cleanup, logout/unregistration, and account rebinding.+- Preserve notification IDs, user preferences, grouping, retry behavior, and permissions. Include correct SNS/FCM payload serialization and worker coverage.++Acceptance: channel/mention/email and other enabled notification types arrive from real backend events in foreground, background, and normal process-dead states; taps route correctly; denial/revocation, rotation, read/dismiss synchronization, and account switching work. Test Doze/OEM battery behavior separately from user force-stop.++Starting points: `crates/notification/src/domain/{service/ingress.rs,models/queue_message.rs,models/android.rs}`, `infra/stacks/notification-service/index.ts`, `apps/web/src/lib/tauri/PushNotification.tsx`, the pinned notifications plugin, and audit items 3–4. Depends on task 1's working app/authentication.++## 3. Complete Android input, navigation, attachments, and sharing++Make everyday composing and file workflows behave correctly on Android across messaging, email, documents, comments, and AI.++Scope:+- Implement native IME/window-inset events; prevent double keyboard-height subtraction; update safe areas on rotation, window resizing, and navigation-mode changes.+- Validate focus, caret visibility, selection, clipboard menus, toolbar/sheet positioning, and iOS-specific cursor-scroll behavior currently applied to all native mobile platforms.+- Integrate system/predictive Back with keyboard, overlays, nested navigation, and unsent drafts; register Android haptics and handle unsupported cases.+- Implement inbound SEND/SEND_MULTIPLE sharing for text, URLs, images, and files, with safe `content://` staging, multiple attachments, cleanup, cold starts, and authentication detours.+- Verify existing WebView file-input fallbacks before adding Photo Picker/Storage Access Framework adapters. Complete clipboard-image handling, authenticated/Blob downloads, save/export/open, and outgoing sharing where needed.+- Test Gboard/Samsung Keyboard, composition/non-Latin input, emoji/dictation, large files/cloud providers, TalkBack, large text, and supported tablet/foldable layouts. Remove TV advertising unless intentionally supported.++Acceptance: every supported composer remains usable through keyboard and orientation changes; Back preserves drafts; users can attach, paste, export, and share files in both directions without duplicate shares, missing files, or stale staging data.++Starting points: `apps/web/src/components/app/useAppSquishHandlers.ts`, `apps/web/src/lib/tauri/{TauriProvider.tsx,ShareTargetProvider.tsx}`, `apps/web/src/lib/core/mobile/`, `apps/web/src/lib/filesystem/download.ts`, `apps/web/tauri/src-tauri/src/share_target.rs`, and audit items 5, 8–10. Depends on task 1's app shell.++## 4. Implement native Android voice and video calling++Bring Android calls to iPhone parity, including incoming calls while backgrounded or locked and a reliable native media lifecycle.++Scope:+- Implement Android Telecom/Core-Telecom integration, call-state coordination, incoming-call FCM delivery, and ongoing-call foreground support.+- Support answer/decline/end actions and an Android media session integrated with the existing shared call state and backend.+- Cover microphone/camera permissions, audio focus, speaker/Bluetooth/headset routing, interruptions, camera switching, background audio, video, and picture-in-picture.+- Handle stale/cancelled rings, calls answered on another device, network reconnects, navigation, and resume without duplicate sessions.+- Extend backend call notification targeting beyond iOS VoIP endpoints. Reuse browser LiveKit code where appropriate without assuming it provides background-call behavior.++Acceptance: incoming/outgoing calls work with the app open, backgrounded, and the phone locked; audio routing, remote cancellation, reconnects, and supported video/PiP flows work on Pixel and Samsung hardware.++Starting points: `apps/web/src/features/channel/Call/`, `apps/web/tauri/callkit_plugin/` as the iOS parity reference, `crates/notification/src/domain/service/voip.rs`, and audit item 7. Coordinate with task 2 for FCM and task 1 for the app shell.++## 5. Make Android offline recovery and OTA updates reliable++Preserve work and account isolation through Android lifecycle events and safely deliver shared frontend updates to both mobile platforms.++Scope:+- Validate native cache persistence, queued/optimistic mutations, cached reads, drafts, pending uploads, session refresh, websocket resubscription, and missed-event replay after backgrounding and OS process death.+- Exercise airplane mode and Wi-Fi/cellular transitions; add native ConnectivityManager reachability if browser signals are insufficient.+- Review backup/restore exclusions for credentials and account-specific data; verify logout/account-switch cleanup.+- Define compatible native build numbering or platform-specific minimum/capability metadata for OTA. Prevent new shared JS bundles from invoking unavailable Android native features.+- Test native build detection, interrupted download/extraction, cache eviction, incompatible/revoked updates, embedded fallback, and update application on resume. Provide a working Play Store update destination.+- Measure launch/cache hydration, large documents/lists, memory pressure, and battery behavior on lower-end hardware.++Acceptance: acknowledged work survives lifecycle/network changes without duplication or cross-account leakage; an older installed Android release remains functional when a newer iOS/shared-JS release ships; failed or rejected updates recover cleanly.++Starting points: `apps/web/src/lib/core/mobile/native-network-status.ts`, `apps/web/src/lib/queries/client.ts`, `apps/web/tauri/{graphql_cache_plugin,macro_bundle_updater_plugin}`, `crates/native_app_service/src/domain/service.rs`, and audit items 11–12. Depends on task 1 and coordinates with tasks 2–4 for lifecycle testing.++## 6. Qualify and release the Android app on Google Play++Establish repeatable Play distribution and demonstrate full Android release readiness on actual devices.++Scope:+- Set up/verify Play application ownership, App Signing/upload-key handling, monotonic version codes, CI release AAB builds, minification/R8 behavior, symbols/source maps, and crash/ANR monitoring.+- Verify target API requirements and 16 KB page-size compatibility for all native libraries; update/configure the NDK/toolchain as needed.+- Choose and implement the Android billing approach: Play Billing, an applicable enrolled alternative program, or appropriate consumption-only purchase UI. Include backend entitlement/restore/refund handling if Play Billing is chosen.+- Finalize launcher/adaptive/monochrome icons, splash screen, listing/screenshots, support/store links, reviewer access, privacy/Data safety declarations, and both in-app and external account-deletion paths.+- Add Android-native smoke automation for launch, authentication, core product navigation, push/link routing, composition, attachments, and lifecycle recovery.+- Run the audit's device/build/lifecycle matrix: Pixel and Samsung, lower-memory device, minimum supported OS, Android 13/35/36, 16 KB devices/emulators, and tablet/foldable layouts if supported. Exercise debug, minified release, and Play-installed builds through clean install and upgrade.+- Record results and remaining defects; use internal testing, staged rollout, monitoring, and rollback procedures for launch.++Acceptance: the signed Play-installed app passes the agreed feature/device matrix; billing/privacy requirements are satisfied for intended markets; release builds are reproducible; monitoring and rollback are ready. Complete tasks 1–5 before declaring feature parity.++Starting points: `apps/web/tauri/src-tauri/gen/android/`, `nix/tauri-dev-shells.nix`, `.github/workflows/`, `apps/web/src/features/{settings,paywall}/`, `apps/web/tests/native/`, and audit item 13 plus its release test matrix.diff --git a/nix-support/node_modules-hashes.json b/nix-support/node_modules-hashes.jsonindex 05b48db686..c7da1859a7 100644--- a/nix-support/node_modules-hashes.json+++ b/nix-support/node_modules-hashes.json@@ -1,6 +1,6 @@{"nodeModules": {- "aarch64-darwin": "sha256-OpA1y4RIW8R7IpH2AQiBQgf/fcUWs6vph6LlyuMncYI=",- "x86_64-linux": "sha256-dCG1cpkc1Bj0yY1BpY4kWRaohQskv1JFkDsGx3A2UuA="+ "aarch64-darwin": "sha256-utdtUbRN838L17aZfy1uwdsjrhInmL+H24Sjubxu/dg=",+ "x86_64-linux": "sha256-i/evewsktJimXtSzeuIr1dztUshec7TTpwXvZyrh+wA="}}