Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(mobile): save downloads through the share sheet
Elian Doran24c92de7ff04
diff --git a/.claude/skills/developing-capacitor-mobile/SKILL.md b/.claude/skills/developing-capacitor-mobile/SKILL.mdindex 1233cfc4b6..26419975c2 100644--- a/.claude/skills/developing-capacitor-mobile/SKILL.md+++ b/.claude/skills/developing-capacitor-mobile/SKILL.md@@ -1,6 +1,6 @@---name: developing-capacitor-mobile-description: Use when working on the Trilium mobile app (`apps/mobile`, Capacitor for Android/iOS) or on the standalone code paths that only run inside it — request routing on `capacitor://` vs `https://localhost`, the iOS fetch/XHR/image/stylesheet interceptors, the Android native streaming HTTP proxy (`TriliumWebViewClient`), the `NativeHttpHandler` sync transport, `MainActivity`/`ViewController` WebView tweaks (edge-to-edge, keyboard), `isMobileApp()` gating in the client, or the mobile CI/nightly builds. Also load it when reviewing a diff that touches these files, so working iOS-only code is not flagged as dead.+description: Use when working on the Trilium mobile app (`apps/mobile`, Capacitor for Android/iOS) or on the standalone code paths that only run inside it — request routing on `capacitor://` vs `https://localhost`, the iOS fetch/XHR/image/stylesheet interceptors, the Android native streaming HTTP proxy (`TriliumWebViewClient`), the `NativeHttpHandler` sync transport, downloads and exports (the WebView saves none itself — `capacitor_download.ts` writes them and opens the share sheet), `MainActivity`/`ViewController` WebView tweaks (edge-to-edge, keyboard), `isMobileApp()` gating in the client, adding a Capacitor plugin, or the mobile CI/nightly builds. Also load it when reviewing a diff that touches these files, so working iOS-only code is not flagged as dead.---# Developing the Capacitor mobile app@@ -18,6 +18,7 @@ apps/mobile/ios/App/App/ViewController.swift # keyboard handling: pins outer sapps/standalone/src/main.ts # boot: registers native HTTP handler if `Capacitor` in window; iOS interceptorsapps/standalone/src/ios-interceptors.ts # fetch / XHR / <img> / stylesheet interceptors, iOS onlyapps/standalone/src/services/capacitor_http_handler.ts # NativeHttpHandler: Android proxy probe + CapacitorHttp fallback+apps/standalone/src/services/capacitor_download.ts # saveUrlToDevice(): fetch → Filesystem cache → share sheetapps/standalone/src/local-bridge.ts # LOCAL_API_PREFIXES, localFetch(), registerNativeHttpHandler()apps/standalone/src/sw.ts # service worker routing (Android + web); guards for capacitor:// and the native proxyapps/client/src/services/utils.ts # isMobileApp() — running inside the native wrapper@@ -48,6 +49,43 @@ A fetch from the app origin to a sync server is cross-origin, so CORS and cookie- Responses hand **parsed JSON through `data`** and only non-JSON through `body`; the handler must not `JSON.stringify` — the extra string copy OOM-ed the iOS worker on large blobs. Preserve that contract when touching either side.- iOS has no `shouldInterceptRequest` equivalent for https, so it stays on the plugin transport; the geo map's tile referer workaround (`apps/client/src/widgets/collections/geomap/map.tsx`) has the same limitation.+## Downloads: the WebView has no download manager++A navigation whose response carries `Content-Disposition: attachment` is handed to+`WebView.setDownloadListener` on Android, and **nothing registers one** — not Capacitor, not+`MainActivity`. The response is dropped with no console output and no error, so an export "succeeds"+(the task's websocket `taskSucceeded` still fires the toast) while no file ever appears. On iOS the+same `window.location.href` is worse: the interceptors patch `fetch`/XHR/`<img>`/stylesheets, never a+top-level navigation, so the URL reaches Capacitor's scheme handler and navigates the app out of the+SPA.++Registering a native `DownloadListener` does not fix it. The listener receives only a URL, and a+native re-request of `https://localhost/api/…` goes to the real network stack, which the service+worker never sees and where no server exists.++So the page does the saving: `open.download()` (`apps/client/src/services/open.ts`) routes through+`window.standaloneApi.save.saveUrl()` when that exists, which `main.ts` defines only inside the shell.+`capacitor_download.ts` fetches the URL — still routed to the worker by the service worker on Android+and the interceptors on iOS — writes it into `Directory.Cache` and hands the file to the system share+sheet.++- **Chunks must be a multiple of 3 bytes.** The Filesystem plugin takes base64, and base64 pads any+ group narrower than three bytes; a padded group mid-file decodes to the wrong bytes.+- **Plugins come from `Capacitor.registerPlugin(name)`, not a `@capacitor/*` import.** `Capacitor.Plugins`+ holds only what the injected runtime registered (`CapacitorHttp` and the rest of core); the `@capacitor/*`+ packages exist so `cap sync` wires the **native** code in.+- **A shared file cannot be deleted after `share()` resolves** — the receiving app reads the URI on its+ own schedule. The cache directory is cleared before the *next* save instead.+- **Android needs no manifest change**: `file_paths.xml` already exposes `<cache-path path="."/>` to the+ `${applicationId}.fileprovider` the Share plugin looks up, and the cache directory is not external+ storage, so no permission prompt.+- **Adding a plugin means three edits**: `apps/mobile/package.json`, `includePlugins` in+ `capacitor.config.json` (iOS only builds what is listed), and `cap update android` to regenerate the+ tracked `capacitor.settings.gradle` / `app/capacitor.build.gradle`. iOS's `CapApp-SPM/Package.swift`+ is gitignored and regenerated by CI.+- **Still unfixed: the database backup download** (`downloadDatabase` in `local-bridge.ts`) navigates a+ hidden iframe to `/local-backup-download` and hits the same wall.+## Native shells- **Android `MainActivity`**: sets `TriliumWebViewClient`, draws edge-to-edge with transparent system bars, forwards window insets to the WebView (so the client can pad for the status/navigation bars) and re-applies system bar appearance on configuration change. Nightly and debug builds get a distinct `applicationId` suffix (`.nightly`, `.debug`) and launcher icon so they install side by side (`android/app/build.gradle`).@@ -116,6 +154,7 @@ Everything JS-side is under the standalone Vitest suite (happy-dom + real sqlite```bashpnpm --filter standalone test ios-interceptors # iOS interceptorspnpm --filter standalone test capacitor_http_handler # Android proxy probe / plugin fallback+pnpm --filter standalone test capacitor_download # chunked base64 write, filename parsing, share sheetpnpm --filter standalone test sw # service-worker routing incl. capacitor:// guardpnpm --filter standalone test main # boot wiring (native handler registered, interceptors installed on capacitor:)```diff --git a/apps/client/src/services/open.spec.ts b/apps/client/src/services/open.spec.tsindex 99c5404c66..ba856d9eb2 100644--- a/apps/client/src/services/open.spec.ts+++ b/apps/client/src/services/open.spec.ts@@ -24,10 +24,15 @@ function removeElectronApi() {delete realWindow.electronApi;}+function removeStandaloneApi() {+ delete realWindow.standaloneApi;+}+describe("open service", () => {beforeEach(() => {vi.restoreAllMocks();removeElectronApi();+ removeStandaloneApi();// Default: behave like a plain web browser.vi.spyOn(utils, "isElectron").mockReturnValue(false);vi.spyOn(utils, "isMac").mockReturnValue(false);@@ -37,6 +42,7 @@ describe("open service", () => {afterEach(() => {removeElectronApi();+ removeStandaloneApi();});describe("getUrlForDownload", () => {@@ -63,6 +69,36 @@ describe("open service", () => {open.download("http://example/y");expect(window.location.href).toContain("http://example/y");});++ it("saves through the share sheet when the standalone build offers one", async () => {+ // The Capacitor WebView has no download manager, so navigating would silently do+ // nothing; standalone exposes `save` only there.+ const saveUrl = vi.fn(async () => ({ status: "saved" as const, fileName: "Export.zip" }));+ realWindow.standaloneApi = { save: { saveUrl } };+ const toastSpy = vi.spyOn(toast, "showError").mockImplementation(() => {});++ open.download("api/branches/b1/export/subtree/html/t1");++ await vi.waitFor(() => expect(saveUrl).toHaveBeenCalledWith("api/branches/b1/export/subtree/html/t1"));+ expect(window.location.href).not.toContain("api/branches/b1");+ expect(toastSpy).not.toHaveBeenCalled();+ });++ it("reports a failed save, but stays quiet when the user dismisses the share sheet", async () => {+ const saveUrl = vi.fn(async () => ({ status: "failed" as const, message: "No space left" }));+ realWindow.standaloneApi = { save: { saveUrl } };+ const toastSpy = vi.spyOn(toast, "showError").mockImplementation(() => {});+ vi.spyOn(console, "error").mockImplementation(() => {});++ open.download("api/notes/n1/download");+ await vi.waitFor(() => expect(toastSpy).toHaveBeenCalled());++ toastSpy.mockClear();+ saveUrl.mockResolvedValue({ status: "cancelled" } as never);+ open.download("api/notes/n1/download");+ await vi.waitFor(() => expect(saveUrl).toHaveBeenCalledTimes(2));+ expect(toastSpy).not.toHaveBeenCalled();+ });});describe("downloadFileNote", () => {diff --git a/apps/client/src/services/open.ts b/apps/client/src/services/open.tsindex 22b6fb542a..3506a70b1a 100644--- a/apps/client/src/services/open.ts+++ b/apps/client/src/services/open.ts@@ -32,6 +32,8 @@ function getOpenFileUrl(type: string, noteId: string) {function download(url: string) {if (window.electronApi) {window.electronApi.shell.downloadURL(url);+ } else if (window.standaloneApi?.save) {+ void saveToDevice(url);} else {window.location.href = url;}@@ -178,6 +180,23 @@ function reportDirectoryFailure(directory: string, reason: string) {toast.showError(t("open.directory_failed", { directory, reason }));}+/**+ * Saves a download through the mobile app's share sheet, which is how a file leaves the Capacitor+ * WebView: it has no download manager, so `window.location.href` would resolve to an `attachment`+ * response that nothing ever writes.+ *+ * The sheet is the confirmation, so only a failure is worth a message; dismissing it is a choice,+ * not an error.+ */+async function saveToDevice(url: string) {+ const result = await window.standaloneApi?.save?.saveUrl(url);++ if (result?.status === "failed") {+ console.error("Failed to save the download:", url, result.message);+ toast.showError(t("open.download_failed", { reason: result.message ?? "" }));+ }+}+export default {download,downloadFileNote,diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 00a2e7ec22..07e4099479 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2190,7 +2190,8 @@"mismatch": "The passwords do not match."},"open": {- "directory_failed": "Could not open {{- directory}}: {{- reason}}"+ "directory_failed": "Could not open {{- directory}}: {{- reason}}",+ "download_failed": "Could not save the download: {{- reason}}"},"etapi": {"description": "ETAPI is a REST API used to access Trilium instance programmatically, without UI.",diff --git a/apps/mobile/android/app/capacitor.build.gradle b/apps/mobile/android/app/capacitor.build.gradleindex d9733c6f6d..861def3db1 100644--- a/apps/mobile/android/app/capacitor.build.gradle+++ b/apps/mobile/android/app/capacitor.build.gradle@@ -9,7 +9,9 @@ android {apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"dependencies {+ implementation project(':capacitor-filesystem')implementation project(':capacitor-keyboard')+ implementation project(':capacitor-share')implementation project(':capacitor-splash-screen')}diff --git a/apps/mobile/android/capacitor.settings.gradle b/apps/mobile/android/capacitor.settings.gradleindex 2210763cf4..c98ec53a26 100644--- a/apps/mobile/android/capacitor.settings.gradle+++ b/apps/mobile/android/capacitor.settings.gradle@@ -2,8 +2,14 @@include ':capacitor-android'project(':capacitor-android').projectDir = new File('../../../node_modules/@capacitor/android/capacitor')+include ':capacitor-filesystem'+project(':capacitor-filesystem').projectDir = new File('../../../node_modules/@capacitor/filesystem/android')+include ':capacitor-keyboard'project(':capacitor-keyboard').projectDir = new File('../../../node_modules/@capacitor/keyboard/android')+include ':capacitor-share'+project(':capacitor-share').projectDir = new File('../../../node_modules/@capacitor/share/android')+include ':capacitor-splash-screen'project(':capacitor-splash-screen').projectDir = new File('../../../node_modules/@capacitor/splash-screen/android')diff --git a/apps/mobile/capacitor.config.json b/apps/mobile/capacitor.config.jsonindex 6b86ac9aff..93840453eb 100644--- a/apps/mobile/capacitor.config.json+++ b/apps/mobile/capacitor.config.json@@ -8,7 +8,7 @@},"ios": {"limitsNavigationsToAppBoundDomains": true,- "includePlugins": ["@capacitor/keyboard"]+ "includePlugins": ["@capacitor/keyboard", "@capacitor/filesystem", "@capacitor/share"]},"plugins": {"Keyboard": {diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex f8888e1b9b..6a2d19fe6e 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -16,8 +16,10 @@"dependencies": {"@capacitor/android": "8.5.1","@capacitor/core": "8.5.1",+ "@capacitor/filesystem": "^8.1.3","@capacitor/ios": "8.5.1","@capacitor/keyboard": "8.0.5",+ "@capacitor/share": "^8.0.1","@capacitor/splash-screen": "8.0.2"},"devDependencies": {diff --git a/apps/standalone/src/main.spec.ts b/apps/standalone/src/main.spec.tsindex a49ebbaa43..1e3031142a 100644--- a/apps/standalone/src/main.spec.ts+++ b/apps/standalone/src/main.spec.ts@@ -7,7 +7,8 @@ const mocks = vi.hoisted(() => ({restoreBackup: vi.fn(),downloadDatabase: vi.fn(),announceLeadership: vi.fn(),- capacitorHttpHandler: vi.fn()+ capacitorHttpHandler: vi.fn(),+ saveUrlToDevice: vi.fn()}));// Whether this tab wins the database lock. Only the leader may start a worker;@@ -30,6 +31,7 @@ vi.mock("./leader_election.js", () => ({}}));vi.mock("./services/capacitor_http_handler.js", () => ({ capacitorHttpHandler: mocks.capacitorHttpHandler }));+vi.mock("./services/capacitor_download.js", () => ({ saveUrlToDevice: mocks.saveUrlToDevice }));// Avoid pulling the entire client bundle when loadScripts() runs.vi.mock("../../client/src/index.js", () => ({}));@@ -39,7 +41,10 @@ interface ServiceWorkerLike {ready: Promise<unknown>;}-interface WindowWithCapacitor { Capacitor?: unknown }+interface WindowWithCapacitor {+ Capacitor?: unknown;+ standaloneApi?: { save?: { saveUrl: unknown } };+}function setServiceWorker(sw: ServiceWorkerLike | undefined) {Object.defineProperty(navigator, "serviceWorker", { value: sw, configurable: true });@@ -99,11 +104,18 @@ describe("bootstrap", () => {expect(mocks.announceLeadership).not.toHaveBeenCalled();});- it("registers the native HTTP handler under Capacitor", async () => {- (window as unknown as WindowWithCapacitor).Capacitor = {};+ it("registers the native HTTP handler and the share-sheet save under Capacitor only", async () => {setServiceWorker({ controller: {}, register: vi.fn(), ready: Promise.resolve() });await runBootstrap();+ await vi.waitFor(() => expect(mocks.startLocalServerWorker).toHaveBeenCalled());+ // A browser saves its own downloads, so the client keeps navigating to them there.+ const win = window as unknown as WindowWithCapacitor;+ expect(win.standaloneApi?.save).toBeUndefined();++ win.Capacitor = {};+ await runBootstrap();await vi.waitFor(() => expect(mocks.registerNativeHttpHandler).toHaveBeenCalledWith(mocks.capacitorHttpHandler));+ await vi.waitFor(() => expect(win.standaloneApi?.save?.saveUrl).toBe(mocks.saveUrlToDevice));});it("registers and waits for the SW, then loads scripts once it controls", async () => {diff --git a/apps/standalone/src/main.ts b/apps/standalone/src/main.tsindex 43d2aa3165..dec7feb4f8 100644--- a/apps/standalone/src/main.ts+++ b/apps/standalone/src/main.ts@@ -1,3 +1,5 @@+import type { StandaloneApi } from "@triliumnext/commons";+import {initSplashProgress, reportSplashPhase, type SplashPhase} from "../../client/src/services/splash.js";@@ -83,10 +85,11 @@ async function bootstrap() {// The client's way to the worker for the few things that carry a file, which the request path// would serialise whole and time out on. The desktop's `window.electronApi` is the same idea.- window.standaloneApi = {+ const standaloneApi: StandaloneApi = {restore: { importBackup: restoreBackup },backup: { downloadDatabase }};+ window.standaloneApi = standaloneApi;try {// When running inside a Capacitor WebView, register the native HTTP@@ -94,6 +97,11 @@ async function bootstrap() {if ("Capacitor" in window) {const { capacitorHttpHandler } = await import("./services/capacitor_http_handler.js");registerNativeHttpHandler(capacitorHttpHandler);++ // The shell's WebView drops a download the moment the response says `attachment`,+ // so the client routes downloads through the share sheet instead.+ const { saveUrlToDevice } = await import("./services/capacitor_download.js");+ standaloneApi.save = { saveUrl: saveUrlToDevice };}// 1) Start the local worker ASAP (so /bootstrap is fast) — but only indiff --git a/apps/standalone/src/services/capacitor_download.spec.ts b/apps/standalone/src/services/capacitor_download.spec.tsnew file mode 100644index 0000000000..579ca0abb1--- /dev/null+++ b/apps/standalone/src/services/capacitor_download.spec.ts@@ -0,0 +1,209 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { fileNameOf, saveUrlToDevice } from "./capacitor_download.js";++interface CapacitorWindow {+ Capacitor?: unknown;+}++/**+ * Models the bridge the module reaches through: neither Filesystem nor Share is registered by the+ * injected runtime, so both arrive via `registerPlugin()` rather than from `Plugins`.+ */+function installCapacitor({ share }: { share?: ReturnType<typeof vi.fn> } = {}) {+ const written: { path: string; data: string; directory: string; append: boolean }[] = [];+ const removed: string[] = [];++ const filesystem = {+ writeFile: vi.fn(async (opts: { path: string; data: string; directory: string }) => {+ written.push({ ...opts, append: false });+ return { uri: `file:///cache/${opts.path}` };+ }),+ appendFile: vi.fn(async (opts: { path: string; data: string; directory: string }) => {+ written.push({ ...opts, append: true });+ }),+ getUri: vi.fn(async (opts: { path: string }) => ({ uri: `file:///cache/${opts.path}` })),+ rmdir: vi.fn(async (opts: { path: string }) => {+ removed.push(opts.path);+ })+ };++ const sharePlugin = { share: share ?? vi.fn(async () => ({ activityType: "com.example" })) };++ const registerPlugin = vi.fn((name: string) => {+ if (name === "Filesystem") return filesystem;+ if (name === "Share") return sharePlugin;+ return undefined;+ });++ (window as unknown as CapacitorWindow).Capacitor = { Plugins: {}, registerPlugin };++ return { filesystem, sharePlugin, registerPlugin, written, removed };+}++/** The bytes handed to the plugin, decoded back out of the base64 each write carried. */+function writtenBytes(written: { data: string }[]): Uint8Array {+ const binary = written.map((write) => atob(write.data)).join("");+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));+}++/** A response whose body streams in `chunkSize` pieces, as a real network body would. */+function streamingResponse(bytes: Uint8Array, headers: Record<string, string>, chunkSize: number): Response {+ let offset = 0;+ const body = new ReadableStream<Uint8Array>({+ pull(controller) {+ if (offset >= bytes.length) {+ controller.close();+ return;+ }+ controller.enqueue(bytes.slice(offset, offset + chunkSize));+ offset += chunkSize;+ }+ });+ return fakeResponse({ headers, body });+}++function fakeResponse({+ status = 200,+ headers = {},+ body = null,+ buffer+}: {+ status?: number;+ headers?: Record<string, string>;+ body?: ReadableStream<Uint8Array> | null;+ buffer?: Uint8Array;+}): Response {+ const map = new Map(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));+ return {+ ok: status >= 200 && status < 300,+ status,+ headers: { get: (key: string) => map.get(key.toLowerCase()) ?? null },+ body,+ arrayBuffer: async () => (buffer ?? new Uint8Array(0)).buffer+ } as unknown as Response;+}++describe("capacitor download", () => {+ afterEach(() => {+ delete (window as unknown as CapacitorWindow).Capacitor;+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ describe("fileNameOf", () => {+ it("prefers filename* over filename, decodes both, and falls back to the URL then a default", () => {+ const disposition = (value: string) =>+ fakeResponse({ headers: { "content-disposition": value } });++ expect(fileNameOf(+ disposition(`attachment; filename="Plain.zip"; filename*=UTF-8''N%C3%B6tes.zip`),+ "https://localhost/api/x"+ )).toBe("Nötes.zip");++ expect(fileNameOf(+ disposition(`attachment; filename="My%20Notes.zip"`),+ "https://localhost/api/x"+ )).toBe("My Notes.zip");++ expect(fileNameOf(+ fakeResponse({}),+ "https://localhost/api/notes/abc/download?123"+ )).toBe("download");++ expect(fileNameOf(fakeResponse({}), "https://localhost/api/")).toBe("download");+ });++ it("keeps the name to a single, harmless path segment", () => {+ const named = (value: string) =>+ fileNameOf(+ fakeResponse({ headers: { "content-disposition": `attachment; filename="${value}"` } }),+ "https://localhost/api/x"+ );++ expect(named("..%2F..%2Fetc%2Fpasswd")).toBe("-..-etc-passwd");+ expect(named("a%3Ab%3Fc.zip")).toBe("a-b-c.zip");+ });+ });++ describe("saveUrlToDevice", () => {+ it("writes the body in chunks that decode back to the original bytes, then shares the file", async () => {+ const { filesystem, sharePlugin, written, removed } = installCapacitor();+ // Over one 768 KiB chunk, so the write is split and the append path runs. The pattern+ // repeats at 251 (a prime, coprime with the chunk size) so a chunk boundary landing on+ // the wrong byte shows up as a mismatch rather than an accidental match.+ const bytes = Uint8Array.from({ length: 900 * 1024 }, (_, i) => i % 251);+ vi.stubGlobal("fetch", vi.fn(async () => streamingResponse(+ bytes,+ { "content-disposition": `attachment; filename*=UTF-8''Export.zip` },+ 64 * 1024+ )));++ const result = await saveUrlToDevice("api/branches/b1/export/subtree/html/t1");++ expect(result).toEqual({ status: "saved", fileName: "Export.zip" });+ expect(removed).toEqual(["trilium-downloads"]);+ expect(written.map((write) => write.append)).toEqual([false, true]);+ expect(written.every((write) => write.path === "trilium-downloads/Export.zip")).toBe(true);+ expect(writtenBytes(written)).toEqual(bytes);+ expect(filesystem.writeFile).toHaveBeenCalledWith(+ expect.objectContaining({ directory: "CACHE", recursive: true })+ );+ expect(sharePlugin.share).toHaveBeenCalledWith({+ title: "Export.zip",+ files: ["file:///cache/trilium-downloads/Export.zip"]+ });+ });++ it("reads a response with no streaming body whole, and writes an empty one as an empty file", async () => {+ const { written } = installCapacitor();+ const bytes = Uint8Array.from([1, 2, 3, 4, 5]);+ vi.stubGlobal("fetch", vi.fn(async () => fakeResponse({+ headers: { "content-disposition": `attachment; filename="a.bin"` },+ buffer: bytes+ })));+ expect(await saveUrlToDevice("api/x")).toEqual({ status: "saved", fileName: "a.bin" });+ expect(writtenBytes(written)).toEqual(bytes);++ written.length = 0;+ vi.stubGlobal("fetch", vi.fn(async () => fakeResponse({})));+ expect(await saveUrlToDevice("api/empty.bin")).toEqual({ status: "saved", fileName: "empty.bin" });+ expect(written).toEqual([+ expect.objectContaining({ data: "", append: false })+ ]);+ });++ it("reports a cancelled share sheet as cancelled, and any other share error as a failure", async () => {+ installCapacitor({ share: vi.fn(async () => { throw new Error("Share canceled"); }) });+ vi.stubGlobal("fetch", vi.fn(async () => fakeResponse({ buffer: Uint8Array.from([1]) })));+ expect(await saveUrlToDevice("api/a.bin")).toEqual({ status: "cancelled", fileName: "a.bin" });++ installCapacitor({ share: vi.fn(async () => { throw new Error("No app can open this"); }) });+ expect(await saveUrlToDevice("api/a.bin")).toEqual({+ status: "failed",+ fileName: "a.bin",+ message: "No app can open this"+ });+ });++ it("fails on an error status, and on a bridge that has no Filesystem plugin", async () => {+ installCapacitor();+ vi.stubGlobal("fetch", vi.fn(async () => fakeResponse({ status: 500 })));+ expect(await saveUrlToDevice("api/x")).toEqual({+ status: "failed",+ message: "The download answered 500."+ });++ (window as unknown as CapacitorWindow).Capacitor = { Plugins: {} };+ vi.stubGlobal("fetch", vi.fn(async () => fakeResponse({+ headers: { "content-disposition": `attachment; filename="a.bin"` },+ buffer: Uint8Array.from([1])+ })));+ expect(await saveUrlToDevice("api/x")).toEqual({+ status: "failed",+ fileName: "a.bin",+ message: "The Filesystem plugin is not available"+ });+ });+ });+});diff --git a/apps/standalone/src/services/capacitor_download.ts b/apps/standalone/src/services/capacitor_download.tsnew file mode 100644index 0000000000..34f1be3e08--- /dev/null+++ b/apps/standalone/src/services/capacitor_download.ts@@ -0,0 +1,217 @@+import type { StandaloneSaveResult } from "@triliumnext/commons";++/**+ * Saving a download inside the Capacitor shell, which has no download manager of its own.+ *+ * A WebView answers a navigation that resolves to `Content-Disposition: attachment` by calling+ * `WebView.setDownloadListener`, and neither Capacitor nor `MainActivity` registers one — the+ * response is dropped without a trace. Re-requesting the URL natively would not help either: the+ * bytes come from the SQLite worker inside the page, so nothing outside the WebView can fetch+ * them. The page therefore does the whole job: fetch (still routed to the worker by the service+ * worker on Android and by the iOS interceptors on `capacitor://`), write to the app's cache+ * directory, hand the file to the system share sheet.+ */++/** Where a saved file waits between being written and being handed to the share sheet. */+const DOWNLOAD_DIR = "trilium-downloads";++/** `Directory.Cache` — the Filesystem plugin takes the enum's string value over the bridge. */+const CACHE = "CACHE";++/**+ * Bytes per write. A multiple of 3, so each chunk encodes independently: base64 pads any group+ * narrower than three bytes, and a padded group in the middle of a file decodes to the wrong+ * bytes. 768 KiB keeps the base64 copy of a chunk around a megabyte.+ */+const CHUNK_BYTES = 768 * 1024;++/** Both platforms' Share plugin rejects with exactly this when the user dismisses the sheet. */+const SHARE_CANCELLED = "Share canceled";++export async function saveUrlToDevice(url: string): Promise<StandaloneSaveResult> {+ let fileName = "download";+ try {+ const response = await fetch(url, { cache: "no-store" });+ if (!response.ok) {+ return { status: "failed", message: `The download answered ${response.status}.` };+ }++ fileName = fileNameOf(response, url);+ const uri = await writeToCache(fileName, response);+ return await shareFile(uri, fileName);+ } catch (e) {+ return {+ status: "failed",+ fileName,+ message: e instanceof Error ? e.message : String(e)+ };+ }+}++interface WriteOptions {+ path: string;+ data: string;+ directory: string;+ recursive?: boolean;+}++interface FilesystemPlugin {+ writeFile(opts: WriteOptions): Promise<{ uri: string }>;+ appendFile(opts: WriteOptions): Promise<void>;+ getUri(opts: { path: string; directory: string }): Promise<{ uri: string }>;+ rmdir(opts: { path: string; directory: string; recursive: boolean }): Promise<void>;+}++interface SharePlugin {+ share(opts: { title?: string; files: string[] }): Promise<{ activityType?: string }>;+}++/**+ * A native plugin, reached through the global Capacitor bridge rather than a `@capacitor/*`+ * import — bare module specifiers do not resolve in the browser's native ES module loader.+ * `Capacitor.Plugins` holds only what the injected runtime registered (`CapacitorHttp` and the+ * rest of core), so everything else is registered here, on the same bridge, from the+ * `PluginHeaders` the native side published.+ */+function getPlugin<T>(name: string): T {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const cap = (window as any).Capacitor;+ const plugin = cap?.Plugins?.[name] ?? cap?.registerPlugin?.(name);++ if (!plugin) {+ throw new Error(`The ${name} plugin is not available`);+ }++ return plugin as T;+}++/** Writes the response into the cache directory a chunk at a time and returns the file's URI. */+async function writeToCache(fileName: string, response: Response): Promise<string> {+ const filesystem = getPlugin<FilesystemPlugin>("Filesystem");+ const path = `${DOWNLOAD_DIR}/${fileName}`;++ // What the previous save left behind. The share sheet hands the receiving app a URI it reads+ // on its own schedule, so a shared file can only be removed before the next save, never after+ // `share()` resolves.+ await filesystem+ .rmdir({ path: DOWNLOAD_DIR, directory: CACHE, recursive: true })+ .catch(() => undefined);++ let started = false;+ for await (const chunk of chunksOf(response, CHUNK_BYTES)) {+ const data = toBase64(chunk);+ if (started) {+ await filesystem.appendFile({ path, data, directory: CACHE });+ } else {+ await filesystem.writeFile({ path, data, directory: CACHE, recursive: true });+ started = true;+ }+ }++ if (!started) {+ await filesystem.writeFile({ path, data: "", directory: CACHE, recursive: true });+ }++ const { uri } = await filesystem.getUri({ path, directory: CACHE });+ return uri;+}++async function shareFile(uri: string, fileName: string): Promise<StandaloneSaveResult> {+ try {+ await getPlugin<SharePlugin>("Share").share({ title: fileName, files: [uri] });+ return { status: "saved", fileName };+ } catch (e) {+ const message = e instanceof Error ? e.message : String(e);+ if (message.includes(SHARE_CANCELLED)) {+ return { status: "cancelled", fileName };+ }+ return { status: "failed", fileName, message };+ }+}++/**+ * Reads the body in pieces of `size` bytes, with whatever is left over emitted last.+ *+ * A response with no `body` — happy-dom under the specs, and a WebView old enough to lack+ * streaming — is read whole instead.+ */+async function* chunksOf(response: Response, size: number): AsyncGenerator<Uint8Array> {+ const reader = response.body?.getReader();+ if (!reader) {+ const whole = new Uint8Array(await response.arrayBuffer());+ if (whole.length) {+ yield whole;+ }+ return;+ }++ let pending = new Uint8Array(0);+ for (;;) {+ const { done, value } = await reader.read();+ if (value?.length) {+ const merged = new Uint8Array(pending.length + value.length);+ merged.set(pending, 0);+ merged.set(value, pending.length);+ pending = merged;++ while (pending.length >= size) {+ const chunk = pending.slice(0, size);+ pending = pending.slice(size);+ yield chunk;+ }+ }+ if (done) {+ break;+ }+ }++ if (pending.length) {+ yield pending;+ }+}++/**+ * Base64 for the bridge, which carries binary as a string. Built in steps because+ * `String.fromCharCode` takes its bytes as arguments, and a chunk's worth at once overflows the+ * call stack. The crypto provider's `encodeBase64` is not reachable from here: it lives in the+ * worker, and this runs on the page.+ */+function toBase64(bytes: Uint8Array): string {+ const STEP = 8192;+ let binary = "";+ for (let offset = 0; offset < bytes.length; offset += STEP) {+ binary += String.fromCharCode(...bytes.subarray(offset, offset + STEP));+ }+ return btoa(binary);+}++/**+ * The name the response asks for, preferring RFC 5987's `filename*` over the plain parameter.+ * Trilium URI-encodes both (see `getContentDisposition`), so both are decoded the same way.+ */+export function fileNameOf(response: Response, url: string): string {+ const disposition = response.headers.get("content-disposition") ?? "";+ const extended = /filename\*=UTF-8''([^;]+)/i.exec(disposition);+ const plain = /filename="([^"]*)"/i.exec(disposition);++ return sanitize(decode(extended?.[1] ?? plain?.[1]))+ || sanitize(decode(new URL(url, location.href).pathname.split("/").pop()))+ || "download";+}++function decode(value: string | undefined): string {+ if (!value) {+ return "";+ }+ try {+ return decodeURIComponent(value);+ } catch {+ return value;+ }+}++/** Keeps the name a name: one path segment, no leading dot, nothing a filesystem chokes on. */+function sanitize(name: string): string {+ // eslint-disable-next-line no-control-regex+ return name.replace(/[/\\:*?"<>|\x00-\x1f]/g, "-").replace(/^\.+/, "").trim();+}diff --git a/packages/commons/src/lib/standalone_api_interface.ts b/packages/commons/src/lib/standalone_api_interface.tsindex 5582ff3f0c..ffb38b8be3 100644--- a/packages/commons/src/lib/standalone_api_interface.ts+++ b/packages/commons/src/lib/standalone_api_interface.ts@@ -72,8 +72,35 @@ export interface StandaloneBackupApi {): Promise<StandaloneDownloadResult>;}+/** How saving a download onto the device ended. */+export interface StandaloneSaveResult {+ status: "saved" | "cancelled" | "failed";+ /** The name the file was written under, which the message to the user names. */+ fileName?: string;+ /** What stopped it, when `status` is `failed`. */+ message?: string;+}++export interface StandaloneSaveApi {+ /**+ * Fetches a download URL and puts the file on the device through the system share sheet.+ *+ * The Capacitor WebView has no download manager: a navigation that resolves to an+ * `attachment` response is dropped, silently. So the bytes are fetched by the page instead —+ * where the service worker (Android) or the iOS interceptors still route them to the local+ * worker — written to the app's cache directory, and handed to the share sheet, which is+ * where the user picks what the file becomes: a file in Downloads, a Drive upload, a mail+ * attachment.+ *+ * `cancelled` means the user dismissed that sheet, which is not a failure to report as one.+ */+ saveUrl(url: string): Promise<StandaloneSaveResult>;+}+/** The complete surface the standalone build exposes to the client. */export interface StandaloneApi {restore: StandaloneRestoreApi;backup: StandaloneBackupApi;+ /** Present only inside the Capacitor shell, where the browser saves no downloads itself. */+ save?: StandaloneSaveApi;}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8394ef8e60..2aa951911b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -584,12 +584,18 @@ importers:'@capacitor/core':specifier: 8.5.1version: 8.5.1+ '@capacitor/filesystem':+ specifier: ^8.1.3+ version: 8.1.3(@capacitor/[email protected])'@capacitor/ios':specifier: 8.5.1version: 8.5.1(@capacitor/[email protected])'@capacitor/keyboard':specifier: 8.0.5version: 8.0.5(@capacitor/[email protected])+ '@capacitor/share':+ specifier: ^8.0.1+ version: 8.0.1(@capacitor/[email protected])'@capacitor/splash-screen':specifier: 8.0.2version: 8.0.2(@capacitor/[email protected])@@ -1751,6 +1757,11 @@ packages:'@capacitor/[email protected]':resolution: {integrity: sha512-IOQ7ynG1qgrJ/RLuCO3WgyRGmkmmG/cdStRR4ftU2dWEN1FdtLrnI/XpZmZuUsOEHEnzBRJY/PmRH8eTLiXfhA==}+ '@capacitor/[email protected]':+ resolution: {integrity: sha512-GNBlRkaXEEb+6WP/YsDXr2zygyOHoieuye6viyd2ZkEdBwfseG41jxfarVxLWH0r0owhyNUbwJ/Qi8fubqr6wA==}+ peerDependencies:+ '@capacitor/core': '>=8.0.0'+'@capacitor/[email protected]':resolution: {integrity: sha512-0EVqwCYf3RUp2JAjUGZ04xmG6dSpIsPmPacI9zKxn6mu9RSiHhmFF230ghe00HrkyB6ig6SfNdoADvVODxYhlQ==}peerDependencies:@@ -1761,11 +1772,19 @@ packages:peerDependencies:'@capacitor/core': '>=8.0.0'+ '@capacitor/[email protected]':+ resolution: {integrity: sha512-3cSBKBCJVon54rKDROP2rqGyeGks4pBh9TbaEk9S375Kbek/ZHe72N50zIa0Vn9Eac/SuhwgehO/mmA4CsUOiw==}+ peerDependencies:+ '@capacitor/core': '>=8.0.0'+'@capacitor/[email protected]':resolution: {integrity: sha512-0C6rYScr13WfAE9nPl4ScOQynmjFv9NT3Th+RZkD4ezYHmER6mcl1/lDYsv7jg3Rj3FOvLrlTlmNkUrr83kZzQ==}peerDependencies:'@capacitor/core': '>=8.0.0'+ '@capacitor/[email protected]':+ resolution: {integrity: sha512-/C1FUo8/OkKuAT4nCIu/34ny9siNHr9qtFezu4kxm6GY1wNFxrCFWjfYx5C1tUhVGz3fxBABegupkpjXvjCHrw==}+'@catppuccin/[email protected]':resolution: {integrity: sha512-P1ZCj4DZVLqr/TNz28m3aaF2Elrikpb8OOnzN0Vyf95Un4pTWTkCSvhbskbnJbnNJ87Rfvt3fXoaUj4o55X30Q==}@@ -12025,6 +12044,11 @@ snapshots:dependencies:tslib: 2.8.1+ '@capacitor/[email protected](@capacitor/[email protected])':+ dependencies:+ '@capacitor/core': 8.5.1+ '@capacitor/synapse': 1.0.4+'@capacitor/[email protected](@capacitor/[email protected])':dependencies:'@capacitor/core': 8.5.1@@ -12033,10 +12057,16 @@ snapshots:dependencies:'@capacitor/core': 8.5.1+ '@capacitor/[email protected](@capacitor/[email protected])':+ dependencies:+ '@capacitor/core': 8.5.1+'@capacitor/[email protected](@capacitor/[email protected])':dependencies:'@capacitor/core': 8.5.1+ '@capacitor/[email protected]': {}+'@catppuccin/[email protected]':dependencies:'@catppuccin/palette': 1.8.0