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
perf(mobile): stream saves through a binary channel
Elian Doranf6c7d866faa2
diff --git a/.claude/skills/developing-capacitor-mobile/SKILL.md b/.claude/skills/developing-capacitor-mobile/SKILL.mdindex a33c6a1491..79a24e1653 100644--- a/.claude/skills/developing-capacitor-mobile/SKILL.md+++ b/.claude/skills/developing-capacitor-mobile/SKILL.md@@ -12,8 +12,9 @@ Key files:```apps/mobile/capacitor.config.json # appId org.triliumnotes.trilium, androidScheme https, hostname localhost, pluginsapps/mobile/android/app/src/main/java/org/triliumnotes/trilium/- MainActivity.java # installs TriliumWebViewClient, edge-to-edge + insets, system bar appearance+ MainActivity.java # installs TriliumWebViewClient + TriliumFileSink, edge-to-edge + insets, system barsTriliumWebViewClient.java # streaming same-origin HTTP proxy for the sync worker (Android only)+ TriliumFileSink.java # binary file-write channel (WebMessageListener + ArrayBuffer, Android only)apps/mobile/ios/App/App/ViewController.swift # keyboard handling: pins outer scroll, drives --tn-keyboard-gapapps/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 only@@ -69,8 +70,17 @@ So the page does the saving: `open.download()` (`apps/client/src/services/open.tand the interceptors on iOS — writes it into `Directory.Cache` and hands the file to the system sharesheet.-- **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.+- **On Android the bytes ride `TriliumFileSink`, not the plugin bridge.** Every plugin call crosses+ as base64 inside a JSON string that `MessageHandler` re-parses whole with `org.json` — ~13 MB/s no+ matter the chunk size. The sink is a `WebViewCompat.addWebMessageListener` object+ (`window.triliumFileSink`) carrying raw `ArrayBuffer`s: the page resolves the absolute path via the+ Filesystem plugin's own mapping (`writeFile("")` + `getUri`), then streams `open`/chunks/`close`,+ each step acknowledged. The base64 plugin path stays as the fallback — iOS (`messageHandlers`+ cannot carry ArrayBuffers), WebViews without `WEB_MESSAGE_ARRAY_BUFFER`, and the sink-busy case.+- **Fallback 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.+ `rechunk()` in `capacitor_download.ts` owns that alignment (and bounds sink messages); the encode+ uses native `Uint8Array.prototype.toBase64` when the runtime has it.- **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.@@ -83,6 +93,11 @@ sheet.`capacitor.config.json` (iOS only builds what is listed), and `cap update android` to regenerate thetracked `capacitor.settings.gradle` / `app/capacitor.build.gradle`. iOS's `CapApp-SPM/Package.swift`is gitignored and regenerated by CI.+- **Throughput is measured, not guessed.** Every save logs one `[Save]` line (total, MB/s, encode vs+ transport-wait split, transport used) and the worker logs a `[Backup]` line for backups (reads vs+ waiting-on-consumer vs hashing/crypto). Read those before optimizing: the remaining backup-side+ cost on a phone is the container's incremental SHA-256, which is `@noble/hashes` pure JS+ (`packages/trilium-backup-container/src/backend-web.ts`) because WebCrypto has no streaming digest.- **The database backup takes the same last step, from a different source.** `saveDatabase()` in`local-bridge.ts` consumes the worker's `BACKUP_STREAM` channel in the page rather than relaying theport to the service worker, so no SW is involved (which is also why it works on iOS), anddiff --git a/apps/mobile/android/app/build.gradle b/apps/mobile/android/app/build.gradleindex cfbc31d4e7..c15695c09f 100644--- a/apps/mobile/android/app/build.gradle+++ b/apps/mobile/android/app/build.gradle@@ -67,6 +67,8 @@ dependencies {implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"+ // TriliumFileSink's WebMessageListener; Capacitor's own copy is implementation-scoped.+ implementation "androidx.webkit:webkit:$androidxWebkitVersion"implementation project(':capacitor-android')testImplementation "junit:junit:$junitVersion"androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"diff --git a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/MainActivity.java b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/MainActivity.javaindex 3d1635c9d1..a267f6633b 100644--- a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/MainActivity.java+++ b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/MainActivity.java@@ -22,6 +22,8 @@ public class MainActivity extends BridgeActivity {super.onCreate(savedInstanceState);// Streaming HTTP proxy for the sync worker (see TriliumWebViewClient).getBridge().setWebViewClient(new TriliumWebViewClient(getBridge()));+ // Binary write channel for downloads and backups (see TriliumFileSink).+ TriliumFileSink.install(getBridge());enableEdgeToEdge();forwardInsetsToWebView();applySystemBarsAppearance();diff --git a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumFileSink.java b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumFileSink.javanew file mode 100644index 0000000000..2d1242a296--- /dev/null+++ b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumFileSink.java@@ -0,0 +1,150 @@+package org.triliumnotes.trilium;++import android.os.Handler;+import android.os.Looper;+import android.util.Log;+import androidx.webkit.JavaScriptReplyProxy;+import androidx.webkit.WebMessageCompat;+import androidx.webkit.WebViewCompat;+import androidx.webkit.WebViewFeature;+import com.getcapacitor.Bridge;+import java.io.BufferedOutputStream;+import java.io.File;+import java.io.FileOutputStream;+import java.io.IOException;+import java.io.OutputStream;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import org.json.JSONObject;++/**+ * Binary file-write channel for the page's downloads and backups.+ *+ * <p>The Capacitor plugin bridge carries binary as base64 inside a JSON string, and the native+ * side re-parses that whole string per call ({@code MessageHandler} → {@code org.json}), which+ * caps file writes at roughly 13 MB/s. This listener receives raw {@code ArrayBuffer} messages+ * instead — no base64, no JSON around the payload — and appends them to a file on an IO thread.+ *+ * <p>Protocol, driven by {@code capacitor_download.ts}: a JSON string {@code {"type":"open",+ * "path":…}} (answered {@code opened}), then any number of ArrayBuffer chunks (each answered+ * {@code written}), then {@code {"type":"close"}} (answered {@code closed}). Any failure answers+ * {@code error:<detail>} and closes the file. The page sends nothing further until each answer+ * arrives, so one open file is all the state there is.+ *+ * <p>The path arrives absolute, resolved by the page through the Filesystem plugin's own+ * directory mapping. That grants the page no authority it does not already have: the Filesystem+ * plugin writes wherever the page asks, too.+ */+public final class TriliumFileSink {++ private static final String TAG = "TriliumFileSink";+ private static final String JS_OBJECT_NAME = "triliumFileSink";++ /** One thread, so writes land in the order the page sent them. */+ private final ExecutorService io = Executors.newSingleThreadExecutor();++ /** Replies must be posted from the UI thread, which the IO thread is not. */+ private final Handler mainHandler = new Handler(Looper.getMainLooper());++ private OutputStream out;++ private TriliumFileSink() {}++ /**+ * Registers the listener on the bridge's WebView, injecting {@code window.triliumFileSink}+ * into pages of the app origin. When the WebView cannot carry ArrayBuffer messages the object+ * is never injected, and the page falls back to the plugin bridge on its own.+ */+ public static void install(Bridge bridge) {+ if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)+ || !WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_ARRAY_BUFFER)) {+ Log.i(TAG, "WebMessage ArrayBuffers are unavailable; file writes stay on the plugin bridge");+ return;+ }++ TriliumFileSink sink = new TriliumFileSink();+ WebViewCompat.addWebMessageListener(+ bridge.getWebView(),+ JS_OBJECT_NAME,+ bridge.getAllowedOriginRules(),+ (view, message, sourceOrigin, isMainFrame, replyProxy) -> {+ if (isMainFrame) {+ sink.onMessage(message, replyProxy);+ }+ }+ );+ }++ private void onMessage(WebMessageCompat message, JavaScriptReplyProxy reply) {+ if (message.getType() == WebMessageCompat.TYPE_ARRAY_BUFFER) {+ byte[] chunk = message.getArrayBuffer();+ io.execute(() -> writeChunk(chunk, reply));+ } else {+ String command = message.getData();+ io.execute(() -> runCommand(command, reply));+ }+ }++ private void writeChunk(byte[] chunk, JavaScriptReplyProxy reply) {+ try {+ if (out == null) {+ throw new IOException("No file is open");+ }+ out.write(chunk);+ answer(reply, "written");+ } catch (Exception e) {+ fail(reply, e);+ }+ }++ private void runCommand(String command, JavaScriptReplyProxy reply) {+ try {+ JSONObject parsed = new JSONObject(command);+ String type = parsed.getString("type");++ if ("open".equals(type)) {+ // A leftover stream means the previous transfer died without a close; its file is+ // already accounted a failure on the page, so the new transfer simply wins.+ closeQuietly();+ File file = new File(parsed.getString("path"));+ File parent = file.getParentFile();+ if (parent != null && !parent.isDirectory() && !parent.mkdirs()) {+ throw new IOException("Cannot create " + parent);+ }+ out = new BufferedOutputStream(new FileOutputStream(file));+ answer(reply, "opened");+ } else if ("close".equals(type)) {+ if (out != null) {+ out.close();+ out = null;+ }+ answer(reply, "closed");+ } else {+ throw new IOException("Unknown command: " + type);+ }+ } catch (Exception e) {+ fail(reply, e);+ }+ }++ private void fail(JavaScriptReplyProxy reply, Exception e) {+ Log.w(TAG, "File sink failed", e);+ closeQuietly();+ answer(reply, "error:" + e.getMessage());+ }++ private void closeQuietly() {+ if (out != null) {+ try {+ out.close();+ } catch (IOException ignored) {+ // The caller is already on an error path, or replacing the stream.+ }+ out = null;+ }+ }++ private void answer(JavaScriptReplyProxy reply, String message) {+ mainHandler.post(() -> reply.postMessage(message));+ }+}diff --git a/apps/standalone/src/services/capacitor_download.spec.ts b/apps/standalone/src/services/capacitor_download.spec.tsindex b14a948a11..d3cc119188 100644--- a/apps/standalone/src/services/capacitor_download.spec.ts+++ b/apps/standalone/src/services/capacitor_download.spec.ts@@ -1,6 +1,15 @@-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { BACKUP_TARGET, fileNameOf, saveChunksToDevice, saveUrlToDevice } from "./capacitor_download.js";+import {+ BACKUP_TARGET, fileNameOf, saveChunksToDevice, saveUrlToDevice, setChunkBytesForTests+} from "./capacitor_download.js";++/**+ * The write size these specs run at. Small, so crossing a chunk boundary costs a few hundred+ * kilobytes of base64 rather than the production size, and fixed here so tuning that size does not+ * quietly stop the boundary being crossed at all.+ */+const CHUNK_BYTES = 96 * 1024;interface CapacitorWindow {Capacitor?: unknown;@@ -41,6 +50,40 @@ function installCapacitor({ share }: { share?: ReturnType<typeof vi.fn> } = {})return { filesystem, sharePlugin, registerPlugin, written, removed };}+/**+ * Models `window.triliumFileSink`, the binary channel `TriliumFileSink.java` injects: acknowledges+ * every message the way the native side does, or answers a chunk with an error when asked to.+ */+function installFileSink({ failOnChunk = false } = {}) {+ const posted: (string | ArrayBuffer)[] = [];+ const listeners = new Set<(event: { data: string }) => void>();+ const reply = (data: string) => queueMicrotask(() => {+ for (const listener of [ ...listeners ]) {+ listener({ data });+ }+ });++ const sink = {+ postMessage: (message: string | ArrayBuffer) => {+ posted.push(message);+ if (typeof message !== "string") {+ reply(failOnChunk ? "error:disk full" : "written");+ } else {+ reply((JSON.parse(message) as { type: string }).type === "open" ? "opened" : "closed");+ }+ },+ addEventListener: (_type: string, listener: (event: { data: string }) => void) => {+ listeners.add(listener);+ },+ removeEventListener: (_type: string, listener: (event: { data: string }) => void) => {+ listeners.delete(listener);+ }+ };+ (window as { triliumFileSink?: unknown }).triliumFileSink = sink;++ return { posted, listeners };+}+/** 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("");@@ -89,8 +132,14 @@ function fakeResponse({}describe("capacitor download", () => {+ beforeEach(() => {+ setChunkBytesForTests(CHUNK_BYTES);+ });+afterEach(() => {+ setChunkBytesForTests();delete (window as unknown as CapacitorWindow).Capacitor;+ delete (window as { triliumFileSink?: unknown }).triliumFileSink;vi.unstubAllGlobals();vi.restoreAllMocks();});@@ -133,14 +182,14 @@ describe("capacitor download", () => {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);+ // Over one 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: CHUNK_BYTES + 4001 }, (_, i) => i % 251);vi.stubGlobal("fetch", vi.fn(async () => streamingResponse(bytes,{ "content-disposition": `attachment; filename*=UTF-8''Export.zip` },- 64 * 1024+ 8 * 1024)));const result = await saveUrlToDevice("api/branches/b1/export/subtree/html/t1");@@ -230,13 +279,25 @@ describe("capacitor download", () => {}}+ /** The sink's messages joined back into the bytes they carried. */+ function concatBuffers(buffers: ArrayBuffer[]): Uint8Array {+ const total = buffers.reduce((sum, buffer) => sum + buffer.byteLength, 0);+ const out = new Uint8Array(total);+ let offset = 0;+ for (const buffer of buffers) {+ out.set(new Uint8Array(buffer), offset);+ offset += buffer.byteLength;+ }+ return out;+ }+it("realigns a source whose chunks are not a multiple of 3 bytes", async () => {const { written } = installCapacitor();// 4001 is coprime with 3, so every incoming piece straddles a base64 group. Writing// these through unaligned would pad mid-file and corrupt everything after the first// piece, which is exactly what the database backup's page-sized chunks would do. The- // total clears one 768 KiB write, so there is a boundary to get wrong.- const bytes = Uint8Array.from({ length: 800 * 1024 }, (_, i) => (i * 7) % 251);+ // total clears one write, so there is a boundary to get wrong.+ const bytes = Uint8Array.from({ length: CHUNK_BYTES * 2 + 7 }, (_, i) => (i * 7) % 251);const result = await saveChunksToDevice("db.tnbackup", inPieces(bytes, 4001), BACKUP_TARGET);@@ -266,6 +327,80 @@ describe("capacitor download", () => {});});+ it("streams raw bytes through the native sink when the shell provides one", async () => {+ const { filesystem, written, sharePlugin } = installCapacitor();+ const { posted, listeners } = installFileSink();+ const bytes = Uint8Array.from({ length: CHUNK_BYTES + 4001 }, (_, i) => (i * 13) % 251);++ const result = await saveChunksToDevice("db.tnbackup", inPieces(bytes, 4001), BACKUP_TARGET);++ expect(result).toMatchObject({ status: "saved", location: "/cache/Trilium/db.tnbackup" });+ // The plugin only creates the empty file, so its own directory mapping resolves the+ // absolute path; the bytes themselves never ride the plugin bridge.+ expect(written).toEqual([ expect.objectContaining({ data: "", append: false }) ]);+ expect(filesystem.appendFile).not.toHaveBeenCalled();++ expect(posted[0]).toBe(JSON.stringify({ type: "open", path: "/cache/Trilium/db.tnbackup" }));+ expect(posted.at(-1)).toBe(JSON.stringify({ type: "close" }));+ const streamed = posted.filter((message): message is ArrayBuffer => typeof message !== "string");+ expect(streamed.length).toBe(2);+ expect(concatBuffers(streamed)).toEqual(bytes);++ expect(sharePlugin.share).toHaveBeenCalled();+ // The transfer's listener is gone, so the next save starts with a clean channel.+ expect(listeners.size).toBe(0);+ });++ it("fails the save when the sink answers a chunk with an error, without sharing", async () => {+ const { sharePlugin } = installCapacitor();+ const { listeners } = installFileSink({ failOnChunk: true });++ const result = await saveChunksToDevice(+ "db.tnbackup", inPieces(Uint8Array.from([ 1, 2, 3 ]), 3), BACKUP_TARGET+ );++ expect(result).toEqual({+ status: "failed",+ fileName: "db.tnbackup",+ message: "disk full"+ });+ expect(sharePlugin.share).not.toHaveBeenCalled();+ expect(listeners.size).toBe(0);+ });++ it("encodes through the runtime's own toBase64 when it has one, to the same bytes", async () => {+ // Node has no Uint8Array.prototype.toBase64 yet, so the suite otherwise only ever runs+ // the fallback — while every current WebView takes this path.+ const proto = Uint8Array.prototype as unknown as { toBase64?: (this: Uint8Array) => string };+ const original = proto.toBase64;+ let calls = 0;+ proto.toBase64 = function (this: Uint8Array) {+ calls++;+ let binary = "";+ for (const byte of this) {+ binary += String.fromCharCode(byte);+ }+ return btoa(binary);+ };++ try {+ const { written } = installCapacitor();+ const bytes = Uint8Array.from({ length: CHUNK_BYTES + 17 }, (_, i) => (i * 11) % 251);++ const result = await saveChunksToDevice("n.bin", inPieces(bytes, 5000), BACKUP_TARGET);++ expect(result.status).toBe("saved");+ expect(calls).toBeGreaterThan(0);+ expect(writtenBytes(written)).toEqual(bytes);+ } finally {+ if (original) {+ proto.toBase64 = original;+ } else {+ delete proto.toBase64;+ }+ }+ });+it("fails without sharing when the source throws part-way through", async () => {const { sharePlugin } = installCapacitor();async function* breaks() {diff --git a/apps/standalone/src/services/capacitor_download.ts b/apps/standalone/src/services/capacitor_download.tsindex 666e341d9a..7803831094 100644--- a/apps/standalone/src/services/capacitor_download.ts+++ b/apps/standalone/src/services/capacitor_download.ts@@ -51,11 +51,28 @@ export const BACKUP_TARGET: SaveTarget = {};/**- * 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.+ * 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. Every `3n` KiB+ * satisfies that.+ *+ * The size is a trade against the bridge, which is what a write costs: the chunk crosses as base64+ * inside a JSON string, so the bytes are walked about five times between here and the file, and+ * the chunk, its base64 copy and both sides of the marshalled string are live at once — budget+ * roughly four times the chunk. Fewer, larger writes buy fewer round trips at that price.+ */+const DEFAULT_CHUNK_BYTES = 3 * 1024 * 1024;++let chunkBytes = DEFAULT_CHUNK_BYTES;++/**+ * Test-only: shrinks the write size, so a spec can cross a chunk boundary without pushing the+ * production size through base64 and back on every run.*/-const CHUNK_BYTES = 768 * 1024;+export function setChunkBytesForTests(bytes = DEFAULT_CHUNK_BYTES) {+ chunkBytes = bytes;+}/** Both platforms' Share plugin rejects with exactly this when the user dismisses the sheet. */const SHARE_CANCELLED = "Share canceled";@@ -92,7 +109,11 @@ export async function saveChunksToDevice(target: SaveTarget): Promise<StandaloneSaveResult> {try {- const uri = await writeChunks(fileName, chunks, target);+ const started = performance.now();+ const outcome = await writeChunks(fileName, chunks, target);+ reportThroughput(fileName, outcome, performance.now() - started);+ const { uri } = outcome;+return { ...await shareFile(uri, fileName), location: displayPath(uri) };} catch (e) {return {@@ -140,12 +161,20 @@ function getPlugin<T>(name: string): T {return plugin as T;}+interface WriteOutcome {+ uri: string;+ bytes: number;+ encodeMs: number;+ waitMs: number;+ transport: "sink" | "plugin";+}+/** Writes the chunks into `target` one at a time and returns the finished file's URI. */async function writeChunks(fileName: string,chunks: AsyncIterable<Uint8Array>,{ directory, folder, sweep }: SaveTarget-): Promise<string> {+): Promise<WriteOutcome> {const filesystem = getPlugin<FilesystemPlugin>("Filesystem");const path = `${folder}/${fileName}`;@@ -155,23 +184,205 @@ async function writeChunks(.catch(() => undefined);}+ const sink = takeFileSink();+ if (sink) {+ try {+ // The plugin creates the file first, so its own directory mapping — not a guess at+ // it — is what turns `path` into the absolute path the sink writes to.+ await filesystem.writeFile({ path, data: "", directory, recursive: true });+ const { uri } = await filesystem.getUri({ path, directory });++ return { uri, transport: "sink", ...await writeThroughSink(sink, displayPath(uri), chunks) };+ } finally {+ releaseFileSink();+ }+ }++ let bytes = 0;+ let encodeMs = 0;+ let waitMs = 0;let started = false;- for await (const chunk of rechunk(chunks, CHUNK_BYTES)) {- const data = toBase64(chunk);- if (started) {- await filesystem.appendFile({ path, data, directory });- } else {- await filesystem.writeFile({ path, data, directory, recursive: true });+ // One call is kept in flight while the next chunk encodes, so the encode's cost hides behind+ // the bridge's. Never two: appends are ordered only because each is issued after the previous+ // one resolves.+ let pending: Promise<unknown> | null = null;++ const awaitPending = async () => {+ if (pending) {+ const waitStart = performance.now();+ await pending;+ waitMs += performance.now() - waitStart;+ pending = null;+ }+ };++ await withoutCallLogging(async () => {+ for await (const chunk of rechunk(chunks, chunkBytes)) {+ const encodeStart = performance.now();+ const data = toBase64(chunk);+ encodeMs += performance.now() - encodeStart;++ await awaitPending();+ pending = started+ ? filesystem.appendFile({ path, data, directory })+ : filesystem.writeFile({ path, data, directory, recursive: true });started = true;+ bytes += chunk.length;}- }+ await awaitPending();+ });if (!started) {await filesystem.writeFile({ path, data: "", directory, recursive: true });}const { uri } = await filesystem.getUri({ path, directory });- return uri;+ return { uri, bytes, encodeMs, waitMs, transport: "plugin" };+}++/**+ * `window.triliumFileSink`: the binary write channel `TriliumFileSink.java` injects on Android.+ *+ * A `WebMessageListener` object, so it carries raw `ArrayBuffer`s — where the plugin bridge wraps+ * every chunk in base64 inside a JSON string that the native side re-parses whole, capping writes+ * around 13 MB/s. Absent on iOS, on WebViews too old for ArrayBuffer messages, and on the web.+ */+interface NativeFileSink {+ postMessage(message: string | ArrayBuffer): void;+ addEventListener(type: "message", listener: (event: { data: unknown }) => void): void;+ removeEventListener(type: "message", listener: (event: { data: unknown }) => void): void;+}++/** Whether a transfer already owns the sink, which holds one open file and no more. */+let sinkBusy = false;++function takeFileSink(): NativeFileSink | null {+ const sink = (window as { triliumFileSink?: NativeFileSink }).triliumFileSink;+ if (!sink || typeof sink.postMessage !== "function" || sinkBusy) {+ return null;+ }+ sinkBusy = true;+ return sink;+}++function releaseFileSink(): void {+ sinkBusy = false;+}++/** How long one acknowledged step may take before the transfer is declared dead. */+const SINK_ACK_TIMEOUT_MS = 30_000;++/**+ * Streams the chunks down the sink: `open`, one ArrayBuffer per chunk, `close`, each step+ * acknowledged before the next is sent — which is all the flow control there is, and enough,+ * because the native side answers only after its write lands.+ */+async function writeThroughSink(+ sink: NativeFileSink,+ filePath: string,+ chunks: AsyncIterable<Uint8Array>+): Promise<{ bytes: number; encodeMs: number; waitMs: number }> {+ let bytes = 0;+ let waitMs = 0;++ // Replies arrive in send order, so the head of this queue is always the awaited step.+ const waiting: ((reply: string) => void)[] = [];+ const listener = (event: { data: unknown }) => waiting.shift()?.(String(event.data));+ sink.addEventListener("message", listener);++ const send = (message: string | ArrayBuffer, expected: string) =>+ new Promise<void>((resolve, reject) => {+ const timer = setTimeout(+ () => reject(new Error("The file sink stopped answering.")),+ SINK_ACK_TIMEOUT_MS+ );+ waiting.push((reply) => {+ clearTimeout(timer);+ if (reply === expected) {+ resolve();+ } else {+ reject(new Error(reply.startsWith("error:")+ ? reply.slice("error:".length)+ : `Unexpected sink reply: ${reply}`));+ }+ });+ sink.postMessage(message);+ });++ try {+ await send(JSON.stringify({ type: "open", path: filePath }), "opened");+ for await (const chunk of rechunk(chunks, chunkBytes)) {+ const waitStart = performance.now();+ await send(exactBuffer(chunk), "written");+ waitMs += performance.now() - waitStart;+ bytes += chunk.length;+ }+ await send(JSON.stringify({ type: "close" }), "closed");+ } finally {+ sink.removeEventListener("message", listener);+ }++ return { bytes, encodeMs: 0, waitMs };+}++/** The chunk's bytes as exactly one ArrayBuffer, which is what the message channel carries. */+function exactBuffer(chunk: Uint8Array): ArrayBuffer {+ const { buffer, byteOffset, byteLength } = chunk;+ if (byteOffset === 0 && byteLength === buffer.byteLength && buffer instanceof ArrayBuffer) {+ return buffer;+ }+ return buffer.slice(byteOffset, byteOffset + byteLength) as ArrayBuffer;+}++/**+ * Runs `write` with Capacitor's per-call console logging turned off.+ *+ * A debuggable build logs every plugin call by handing the call object to `console.dir`, and a+ * write's call object holds the whole base64 chunk — megabytes through the console pipeline per+ * chunk, next to the write itself. The flag is read at call time, so this suppresses only those+ * call traces; the application's own console output reaches logcat by a different route.+ */+async function withoutCallLogging<T>(write: () => Promise<T>): Promise<T> {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const cap = (window as any).Capacitor;+ const wasEnabled = cap?.isLoggingEnabled;++ if (cap) {+ cap.isLoggingEnabled = false;+ }+ try {+ return await write();+ } finally {+ if (cap) {+ cap.isLoggingEnabled = wasEnabled;+ }+ }+}++/**+ * What the write achieved, which is the only place the transport's cost per byte is visible.+ *+ * The split names the suspect: `base64` is time in {@link toBase64}, the wait is time blocked on+ * the transport. What is left of the total is producing the bytes (the worker, for a backup) plus+ * everything the pipelining managed to hide.+ */+function reportThroughput(+ fileName: string,+ { bytes, encodeMs, waitMs, transport }: WriteOutcome,+ elapsedMs: number+): void {+ const seconds = elapsedMs / 1000;+ const megabytes = bytes / 1_000_000;+ const rate = seconds > 0 ? (megabytes / seconds).toFixed(1) : "—";+ const split = transport === "sink"+ ? `via the binary sink — write wait ${(waitMs / 1000).toFixed(1)}s`+ : `via the plugin bridge — base64 ${(encodeMs / 1000).toFixed(1)}s, `+ + `bridge wait ${(waitMs / 1000).toFixed(1)}s`;++ console.log(+ `[Save] ${fileName}: ${megabytes.toFixed(1)} MB in ${seconds.toFixed(1)}s (${rate} MB/s) `+ + `${split}, ${Math.ceil(bytes / chunkBytes)} writes of ${chunkBytes / 1024} KiB`+ );}/**@@ -230,10 +441,11 @@ async function* bodyChunks(response: Response): AsyncGenerator<Uint8Array> {/*** Regroups a stream into pieces of `size` bytes, with whatever is left over emitted last.*- * This is what keeps every write but the last a multiple of 3 bytes, so each encodes to base64- * independently. It belongs here rather than in the callers because a source picks its chunk sizes- * for its own reasons — a response body by packet, the backup stream by database page — and none- * of them is obliged to know what the writer needs.+ * This is what keeps every plugin-bridge write but the last a multiple of 3 bytes, so each encodes+ * to base64 independently, and what bounds a sink message to one chunk. It belongs here rather+ * than in the callers because a source picks its chunk sizes for its own reasons — a response body+ * by packet, the backup stream by database page — and none of them is obliged to know what the+ * writer needs.*/async function* rechunk(chunks: AsyncIterable<Uint8Array>, size: number): AsyncGenerator<Uint8Array> {// Held as they arrive and joined only when a whole chunk is due. Merging each arrival into one@@ -286,12 +498,20 @@ function take(parts: Uint8Array[], size: number): Uint8Array {}/**- * 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.+ * Base64 for the bridge, which carries binary as a string.+ *+ * `Uint8Array.prototype.toBase64` (Chrome 140+, so every current WebView) encodes in native code+ * with the same standard alphabet and padding `btoa` produces. The fallback is 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 native = (bytes as Uint8Array & { toBase64?: () => string }).toBase64;+ if (typeof native === "function") {+ return native.call(bytes);+ }+const STEP = 8192;let binary = "";for (let offset = 0; offset < bytes.length; offset += STEP) {