diff --git a/app/src-tauri/.env.local.example b/app/src-tauri/.env.local.example new file mode 100644 index 0000000..96b3452 --- /dev/null +++ b/app/src-tauri/.env.local.example @@ -0,0 +1,7 @@ +# Copy to .env.local (git-ignored) to build MnemoScript with Google Drive sync enabled. +# Create an OAuth client of type "Desktop app" in your own Google Cloud project with the +# Drive API enabled and the https://www.googleapis.com/auth/drive.appdata scope on the +# consent screen. Google documents a desktop client secret as not confidential, but keep +# this file out of git anyway. Rebuild after changing it. +MNEMO_GOOGLE_CLIENT_ID= +MNEMO_GOOGLE_CLIENT_SECRET= diff --git a/app/src-tauri/.gitignore b/app/src-tauri/.gitignore index 502406b..48e499f 100644 --- a/app/src-tauri/.gitignore +++ b/app/src-tauri/.gitignore @@ -2,3 +2,6 @@ # will have compiled files and executables /target/ /gen/schemas + +# Google OAuth client for Drive sync (never commit; see .env.local.example) +/.env.local diff --git a/app/src-tauri/Cargo.lock b/app/src-tauri/Cargo.lock index de5e70f..d154a2c 100644 --- a/app/src-tauri/Cargo.lock +++ b/app/src-tauri/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "adler2" @@ -29,6 +29,18 @@ dependencies = [ "version_check", ] +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + [[package]] name = "aho-corasick" version = "1.1.4" @@ -53,6 +65,12 @@ dependencies = [ "alloc-no-stdlib", ] +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + [[package]] name = "android_log-sys" version = "0.3.2" @@ -93,22 +111,31 @@ dependencies = [ "chacha20poly1305", "chrono", "dirs 5.0.1", + "flate2", "futures-util", + "html-escape", "keyring", "log", + "lol_html", + "open", "reqwest 0.12.28", "rfd 0.15.4", + "rusqlite", "serde", "serde_json", + "sha2", "spake2", "tauri", "tauri-build", "tauri-plugin-dialog", "tauri-plugin-fs", "tauri-plugin-log", + "tempfile", "tiny_http", "tokio", + "url", "uuid", + "zip", ] [[package]] @@ -465,9 +492,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.20.2" +version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" [[package]] name = "byte-unit" @@ -725,6 +752,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + [[package]] name = "convert_case" version = "0.4.0" @@ -791,6 +827,12 @@ dependencies = [ "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -811,9 +853,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.0" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" dependencies = [ "cfg-if", ] @@ -1215,6 +1257,20 @@ version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "endi" version = "1.1.1" @@ -1300,6 +1356,18 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "fastrand" version = "2.4.1" @@ -1354,6 +1422,7 @@ checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" dependencies = [ "crc32fast", "miniz_oxide", + "zlib-rs", ] [[package]] @@ -1433,6 +1502,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" dependencies = [ "futures-core", + "futures-sink", ] [[package]] @@ -1834,7 +1904,16 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" dependencies = [ - "ahash", + "ahash 0.7.8", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash 0.8.12", ] [[package]] @@ -1851,6 +1930,20 @@ name = "hashbrown" version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + +[[package]] +name = "hashlink" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +dependencies = [ + "hashbrown 0.14.5", +] [[package]] name = "heck" @@ -1894,6 +1987,12 @@ dependencies = [ "digest", ] +[[package]] +name = "html-escape" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9356095b4b41197bba32173600e1582792cda618f65d12f68e2e77d273413c5" + [[package]] name = "html5ever" version = "0.29.1" @@ -2232,6 +2331,25 @@ dependencies = [ "serde", ] +[[package]] +name = "is-docker" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" +dependencies = [ + "once_cell", +] + +[[package]] +name = "is-wsl" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +dependencies = [ + "is-docker", + "once_cell", +] + [[package]] name = "itoa" version = "1.0.18" @@ -2408,9 +2526,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.185" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libdbus-sys" @@ -2440,6 +2558,17 @@ dependencies = [ "libc", ] +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -2463,13 +2592,32 @@ dependencies = [ [[package]] name = "log" -version = "0.4.29" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" dependencies = [ "value-bag", ] +[[package]] +name = "lol_html" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "691b898297b684292c8808d0285769fc05fb721a36ee5b62c75c8da83e60d350" +dependencies = [ + "bitflags 2.11.1", + "cfg-if", + "cssparser 0.36.0", + "encoding_rs", + "foldhash 0.2.0", + "hashbrown 0.17.0", + "memchr", + "mime", + "precomputed-hash", + "selectors 0.37.0", + "thiserror 2.0.18", +] + [[package]] name = "lru-slab" version = "0.1.3" @@ -2587,6 +2735,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "ndk" version = "0.9.0" @@ -2617,6 +2771,18 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.11.1", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nodrop" version = "0.1.14" @@ -2877,6 +3043,16 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" +[[package]] +name = "open" +version = "5.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95" +dependencies = [ + "is-wsl", + "libc", +] + [[package]] name = "option-ext" version = "0.2.0" @@ -3687,6 +3863,7 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ "base64 0.22.1", "bytes", + "futures-channel", "futures-core", "futures-util", "http", @@ -3845,6 +4022,20 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "rusqlite" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" +dependencies = [ + "bitflags 2.11.1", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + [[package]] name = "rust_decimal" version = "1.41.0" @@ -4088,6 +4279,25 @@ dependencies = [ "smallvec", ] +[[package]] +name = "selectors" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cfaaa6035167f0e604e42723c7650d59ee269ef220d7bbe0565602c8a0173b9" +dependencies = [ + "bitflags 2.11.1", + "cssparser 0.36.0", + "derive_more 2.1.1", + "log", + "new_debug_unreachable", + "phf 0.13.1", + "phf_codegen 0.13.1", + "precomputed-hash", + "rustc-hash", + "servo_arc 0.4.3", + "smallvec", +] + [[package]] name = "semver" version = "1.0.28" @@ -4306,9 +4516,9 @@ dependencies = [ [[package]] name = "simd-adler32" -version = "0.3.9" +version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" [[package]] name = "simdutf8" @@ -5332,6 +5542,12 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + [[package]] name = "typeid" version = "1.0.3" @@ -5497,6 +5713,12 @@ version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0" +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version-compare" version = "0.2.1" @@ -6712,6 +6934,20 @@ name = "zeroize" version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] [[package]] name = "zerotrie" @@ -6746,12 +6982,50 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "zip" +version = "9.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302" +dependencies = [ + "constant_time_eq", + "crc32fast", + "flate2", + "getrandom 0.4.2", + "indexmap 2.14.0", + "libc", + "memchr", + "nix", + "typed-path", + "windows-sys 0.61.2", + "zeroize", + "zopfli", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + [[package]] name = "zvariant" version = "5.11.0" diff --git a/app/src-tauri/Cargo.toml b/app/src-tauri/Cargo.toml index 5e3d15a..0a58033 100644 --- a/app/src-tauri/Cargo.toml +++ b/app/src-tauri/Cargo.toml @@ -6,7 +6,7 @@ authors = ["ehitimum"] license = "" repository = "https://github.com/ehitimum/MnemoScript" edition = "2021" -rust-version = "1.77.2" +rust-version = "1.88" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -38,13 +38,26 @@ dirs = "5" # AI assistant: async runtime pieces (process spawn, channels), HTTPS streaming to the # provider APIs (rustls/ring — no OpenSSL or CMake needed on Windows/Android). tokio = { version = "1", features = ["process", "io-util", "sync", "time", "macros", "rt"] } -reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "stream", "json"] } +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "stream", "json", "blocking"] } futures-util = "0.3" # Phone ↔ PC pairing: SPAKE2 turns the short pairing code into a strong shared key (no offline # guessing), XChaCha20-Poly1305 encrypts and authenticates every message, base64 for the wire. spake2 = "0.4" chacha20poly1305 = "0.10" base64 = "0.22" +# Versioned, checksummed local recovery archives; only pure-Rust ZIP deflate. +zip = { version = "9.5", default-features = false, features = ["deflate"] } +sha2 = "0.10" +lol_html = "3" +html-escape = "0.2" +# MnemoSync state (revisions, outbox, conflicts, Drive cursors). Bundled SQLite: no system +# library on Windows/Android. Project JSON files stay the source of truth. +rusqlite = { version = "0.32", features = ["bundled"] } +flate2 = "1" +url = "2" + +[dev-dependencies] +tempfile = "3" # Native folder picker — desktop only (rfd has no Android/iOS backend). Mobile # uses the dialog/fs plugins instead. @@ -54,4 +67,6 @@ rfd = "0.15" keyring = { version = "3", features = ["windows-native", "apple-native"] } # Tiny local HTTP server for the in-app MCP endpoint the Claude Code CLI connects to. tiny_http = "0.12" +# Opens Google sign-in in the writer's own browser (desktop OAuth loopback flow). +open = "5" diff --git a/app/src-tauri/build.rs b/app/src-tauri/build.rs index 795b9b7..328c662 100644 --- a/app/src-tauri/build.rs +++ b/app/src-tauri/build.rs @@ -1,3 +1,31 @@ +/// Google Drive sync is enabled only in builds that know an OAuth client. The values come from +/// the environment or from a git-ignored `.env.local`, so no client is ever committed. +fn google_oauth_env() { + const KEYS: [&str; 2] = ["MNEMO_GOOGLE_CLIENT_ID", "MNEMO_GOOGLE_CLIENT_SECRET"]; + println!("cargo:rerun-if-changed=.env.local"); + let file = std::fs::read_to_string(".env.local").unwrap_or_default(); + for key in KEYS { + println!("cargo:rerun-if-env-changed={key}"); + let from_file = file.lines().find_map(|line| { + let (k, v) = line.trim().split_once('=')?; + (k.trim() == key).then(|| v.trim().trim_matches('"').to_string()) + }); + let value = std::env::var(key).ok().or(from_file).unwrap_or_default(); + if !value.is_empty() { + println!("cargo:rustc-env={key}={value}"); + } + } +} + fn main() { - tauri_build::build() + google_oauth_env(); + // `google-auth` is the app's own Android plugin (Google's native Drive authorization in + // `gen/android/.../GoogleAuthPlugin.kt`). Declaring it here gives it an ACL permission. + let attributes = tauri_build::Attributes::new().plugin( + "google-auth", + tauri_build::InlinedPlugin::new() + .commands(&["authorize"]) + .default_permission(tauri_build::DefaultPermissionRule::AllowAllCommands), + ); + tauri_build::try_build(attributes).expect("failed to run tauri-build"); } diff --git a/app/src-tauri/capabilities/default.json b/app/src-tauri/capabilities/default.json index 582cbd8..c8f8e83 100644 --- a/app/src-tauri/capabilities/default.json +++ b/app/src-tauri/capabilities/default.json @@ -10,6 +10,7 @@ "dialog:default", "fs:default", "fs:allow-read-file", + "google-auth:default", "core:window:allow-close", "core:window:allow-destroy", "dialog:allow-save", diff --git a/app/src-tauri/gen/android/app/build.gradle.kts b/app/src-tauri/gen/android/app/build.gradle.kts index 199d3bc..cc40aa6 100644 --- a/app/src-tauri/gen/android/app/build.gradle.kts +++ b/app/src-tauri/gen/android/app/build.gradle.kts @@ -84,6 +84,8 @@ dependencies { implementation("androidx.appcompat:appcompat:1.7.1") implementation("androidx.activity:activity-ktx:1.10.1") implementation("com.google.android.material:material:1.12.0") + // Google Drive sync: native authorization (AuthorizationClient) for the drive.appdata scope. + implementation("com.google.android.gms:play-services-auth:21.3.0") testImplementation("junit:junit:4.13.2") androidTestImplementation("androidx.test.ext:junit:1.1.4") androidTestImplementation("androidx.test.espresso:espresso-core:3.5.0") diff --git a/app/src-tauri/gen/android/app/src/main/java/com/mnemoscript/app/GoogleAuthPlugin.kt b/app/src-tauri/gen/android/app/src/main/java/com/mnemoscript/app/GoogleAuthPlugin.kt new file mode 100644 index 0000000..9c4ef94 --- /dev/null +++ b/app/src-tauri/gen/android/app/src/main/java/com/mnemoscript/app/GoogleAuthPlugin.kt @@ -0,0 +1,79 @@ +package com.mnemoscript.app + +import android.app.Activity +import androidx.activity.result.ActivityResult +import androidx.activity.result.IntentSenderRequest +import app.tauri.annotation.ActivityCallback +import app.tauri.annotation.Command +import app.tauri.annotation.InvokeArg +import app.tauri.annotation.TauriPlugin +import app.tauri.plugin.Invoke +import app.tauri.plugin.JSObject +import app.tauri.plugin.Plugin +import com.google.android.gms.auth.api.identity.AuthorizationRequest +import com.google.android.gms.auth.api.identity.AuthorizationResult +import com.google.android.gms.auth.api.identity.Identity +import com.google.android.gms.common.api.Scope + +/** Only MnemoScript's own hidden Drive folder; never the writer's other files. */ +private const val DRIVE_APPDATA = "https://www.googleapis.com/auth/drive.appdata" + +@InvokeArg +class AuthorizeArgs { + /** false = never show UI (silent refresh); true = Google may show its account/consent sheet. */ + var interactive: Boolean = true +} + +/** + * Google Drive authorization on Android through Google Play services' AuthorizationClient. + * Google identifies the app by its package name and signing certificate (an "Android" OAuth + * client in the writer's Google Cloud project), shows its own account and consent sheet, and + * returns a short-lived access token. No password or refresh token is ever handled here. + */ +@TauriPlugin +class GoogleAuthPlugin(private val activity: Activity) : Plugin(activity) { + private fun request(): AuthorizationRequest = + AuthorizationRequest.builder().setRequestedScopes(listOf(Scope(DRIVE_APPDATA))).build() + + @Command + fun authorize(invoke: Invoke) { + val args = invoke.parseArgs(AuthorizeArgs::class.java) + Identity.getAuthorizationClient(activity) + .authorize(request()) + .addOnSuccessListener { result -> + if (result.hasResolution()) { + val pending = result.pendingIntent + if (!args.interactive || pending == null) { + invoke.reject("Google needs you to confirm Drive access") + return@addOnSuccessListener + } + startIntentSenderForResult(invoke, IntentSenderRequest.Builder(pending.intentSender).build(), "onAuthorized") + } else { + resolve(invoke, result) + } + } + .addOnFailureListener { e -> invoke.reject(e.message ?: "Google authorization failed") } + } + + @ActivityCallback + private fun onAuthorized(invoke: Invoke, result: ActivityResult) { + try { + resolve(invoke, Identity.getAuthorizationClient(activity).getAuthorizationResultFromIntent(result.data)) + } catch (e: Exception) { + invoke.reject("Google sign-in was cancelled") + } + } + + private fun resolve(invoke: Invoke, result: AuthorizationResult) { + val token = result.accessToken + if (token.isNullOrEmpty()) { + invoke.reject("Google did not grant Drive access") + return + } + val out = JSObject() + out.put("accessToken", token) + // Google access tokens last about an hour; the backend refreshes a little early. + out.put("expiresIn", 3300) + invoke.resolve(out) + } +} diff --git a/app/src-tauri/src/ai/pair_crypto.rs b/app/src-tauri/src/ai/pair_crypto.rs index 85559c1..35e78cb 100644 --- a/app/src-tauri/src/ai/pair_crypto.rs +++ b/app/src-tauri/src/ai/pair_crypto.rs @@ -20,6 +20,7 @@ pub const PROTOCOL: &str = "mnemoscript-pair-v1"; pub const DEFAULT_PORT: u16 = 47815; pub const DISCOVER_PROBE: &[u8] = b"MNEMOSCRIPT-DISCOVER v1"; /// Accept requests whose clock is within this window (phones and PCs sync time, loosely). +#[cfg_attr(not(desktop), allow(dead_code))] // used by the PC-side server only pub const MAX_SKEW_MS: i64 = 10 * 60 * 1000; pub fn b64(bytes: &[u8]) -> String { @@ -30,6 +31,7 @@ pub fn unb64(s: &str) -> Result, String> { B64.decode(s.trim()).map_err(|_| "Malformed message".to_string()) } +#[cfg_attr(not(desktop), allow(dead_code))] pub fn random_key() -> [u8; 32] { let k = XChaCha20Poly1305::generate_key(&mut OsRng); let mut out = [0u8; 32]; @@ -44,6 +46,7 @@ pub fn random_id() -> String { } /// "4821 7730": 8 random digits, shown with a space for readability. +#[cfg_attr(not(desktop), allow(dead_code))] pub fn pairing_code() -> String { let n = OsRng.next_u64() % 100_000_000; let s = format!("{n:08}"); diff --git a/app/src-tauri/src/backup.rs b/app/src-tauri/src/backup.rs new file mode 100644 index 0000000..e96ff79 --- /dev/null +++ b/app/src-tauri/src/backup.rs @@ -0,0 +1,756 @@ +//! Local recovery only. Archives are not sync batches and confer no device trust. +use crate::project::{Document, Project}; +use lol_html::{element, rewrite_str, RewriteStrSettings}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::fs::{self, File}; +use std::io::{Read, Seek, Write}; +use std::path::{Path, PathBuf}; +use uuid::Uuid; +use zip::{write::SimpleFileOptions, ZipArchive, ZipWriter}; + +const MANIFEST: &str = "mnemoscript-backup.json"; +const MAX_FILES: usize = 10_000; +const MAX_FILE: u64 = 128 * 1024 * 1024; +const MAX_TOTAL: u64 = 512 * 1024 * 1024; +pub const MAX_ARCHIVE: u64 = 600 * 1024 * 1024; +const MAX_MANIFEST: u64 = 4 * 1024 * 1024; +const SCHEMA: u32 = 2; +/// Portable image reference inside archives: `mnemo-asset:` (as MnemoSync uses). +const ASSET_SCHEME: &str = "mnemo-asset:"; + +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Manifest { + format: String, + schema_version: u32, + project_id: String, + /// Schema 1 only: the source folder, used to relocate absolute image paths. Schema 2 archives + /// carry portable `mnemo-asset:` references and never record where the project lived. + #[serde(default, skip_serializing_if = "Option::is_none")] + source_root: Option, + /// Schema 2: chapter files that could not be read when the backup was made, copied as-is. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + damaged: Vec, + files: BTreeMap, +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct FileDigest { + size: u64, + sha256: String, +} + +fn err(e: impl std::fmt::Display) -> String { + e.to_string() +} +fn hash(bytes: &[u8]) -> String { + format!("{:x}", Sha256::digest(bytes)) +} + +// Deliberately stricter than the host OS: backups must also be safe on Windows. +fn safe_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 1024 + && name.split('/').all(|part| { + let stem = part.split('.').next().unwrap_or("").to_ascii_uppercase(); + !part.is_empty() + && part != "." + && part != ".." + && !part.ends_with(['.', ' ']) + && !part + .chars() + .any(|c| c.is_control() || "\\:<>\"|?*".contains(c)) + && !matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") + && !(stem.len() == 4 + && (stem.starts_with("COM") || stem.starts_with("LPT")) + && matches!(stem.as_bytes()[3], b'1'..=b'9')) + }) +} + +fn allowed(name: &str) -> bool { + if !safe_name(name) { + return false; + } + let parts: Vec<_> = name.split('/').collect(); + match parts.as_slice() { + ["project.json"] => true, + ["documents", file] | ["ai", "sessions", file] => file.ends_with(".json"), + ["assets", ..] | ["exports", ..] => parts.len() > 1, + _ => false, + } +} + +fn bounded_read(reader: impl Read, limit: u64) -> Result, String> { + let mut bytes = Vec::new(); + reader + .take(limit + 1) + .read_to_end(&mut bytes) + .map_err(err)?; + if bytes.len() as u64 > limit { + return Err("Backup size limit exceeded".into()); + } + Ok(bytes) +} + +fn collect(root: &Path, dir: &Path, out: &mut BTreeMap) -> Result<(), String> { + for entry in fs::read_dir(dir).map_err(err)? { + let entry = entry.map_err(err)?; + let path = entry.path(); + let relative = path + .strip_prefix(root) + .map_err(err)? + .to_str() + .ok_or("Backup requires UTF-8 file names")? + .replace('\\', "/"); + let kind = fs::symlink_metadata(&path).map_err(err)?; + // Never follow links, junctions or other reparse points into private data. + #[cfg(windows)] + let reparse = { + use std::os::windows::fs::MetadataExt; + kind.file_attributes() & 0x400 != 0 + }; + #[cfg(not(windows))] + let reparse = kind.file_type().is_symlink(); + if reparse { + return Err(format!("Backup cannot include linked files: {relative}")); + } + if kind.is_dir() { + if matches!( + relative.as_str(), + "documents" | "assets" | "exports" | "ai" | "ai/sessions" + ) || relative.starts_with("assets/") + || relative.starts_with("exports/") + { + if !safe_name(&relative) { + return Err("Unsafe backup folder name".into()); + } + collect(root, &path, out)?; + } + } else if allowed(&relative) { + if !kind.is_file() { + return Err("Backup contains a special file".into()); + } + if out.len() >= MAX_FILES { + return Err("Too many backup files".into()); + } + let bytes = bounded_read(File::open(&path).map_err(err)?, MAX_FILE)?; + out.insert( + relative, + FileDigest { + size: bytes.len() as u64, + sha256: hash(&bytes), + }, + ); + if out.values().map(|d| d.size).sum::() > MAX_TOTAL { + return Err("Project exceeds the 512 MiB backup limit".into()); + } + } + } + Ok(()) +} + +fn inventory(root: &Path) -> Result, String> { + let mut files = BTreeMap::new(); + collect(root, root, &mut files)?; + if !files.contains_key("project.json") { + return Err("Not a project folder".into()); + } + let mut unique = HashSet::new(); + if files.keys().any(|p| !unique.insert(p.to_lowercase())) { + return Err("Backup contains case-colliding paths".into()); + } + Ok(files) +} + +/// How a document refers to an image or map file. +enum Reference { + /// Inside this project's `assets/` folder: the path relative to the project, e.g. `assets/a.png`. + Project(String), + /// A local file elsewhere on this device (or an app-internal URL to one). + External, + /// Anything else (web images, data URLs, prose): left alone. + Other, +} + +fn classify(value: &str, root: &str) -> Reference { + let normalized = value.replace('\\', "/"); + let root = root.replace('\\', "/"); + let root = root.trim_start_matches("//?/").trim_end_matches('/'); + let path = normalized.trim_start_matches("//?/"); + let prefix = format!("{root}/"); + let windows = root.as_bytes().get(1) == Some(&b':'); + let relative = path + .strip_prefix(&prefix) + .or_else(|| { + (windows && path.get(..prefix.len()).is_some_and(|s| s.eq_ignore_ascii_case(&prefix))) + .then(|| &path[prefix.len()..]) + }) + .or_else(|| path.starts_with("assets/").then_some(path)); + if let Some(relative) = relative { + return if relative.to_ascii_lowercase().starts_with("assets/") && safe_name(relative) { + Reference::Project(relative.to_string()) + } else { + Reference::External + }; + } + let local = path.starts_with('/') + || path.as_bytes().get(1) == Some(&b':') + || path.starts_with("asset:") + || path.starts_with("file:") + || path.starts_with("blob:") + || path.starts_with("http://asset.localhost/") + || path.starts_with("https://asset.localhost/"); + if local { + Reference::External + } else { + Reference::Other + } +} + +/// Schema 1 restore: relocate an absolute path from the source machine. Strict, as before. +fn asset_reference( + value: &str, + old_root: &str, + new_root: &Path, + files: &BTreeMap, +) -> Result, String> { + let windows_source = old_root.replace('\\', "/").trim_start_matches("//?/").as_bytes().get(1) == Some(&b':'); + match classify(value, old_root) { + Reference::Project(relative) => { + let actual = files + .keys() + .find(|name| **name == relative || (windows_source && name.eq_ignore_ascii_case(&relative))) + .ok_or("A document references a missing project asset")?; + Ok(Some(new_root.join(actual).to_string_lossy().into_owned())) + } + Reference::External => { + Err("A document references an external local asset; import it into this project before backup".into()) + } + Reference::Other => Ok(None), + } +} + +/// Apply `map` to every image reference of a document (`` in chapters, the path keys +/// of map JSON). Unknown fields, marks, graph ids and prose stay untouched. +fn rewrite_references( + document: &mut Value, + map: &dyn Fn(&str) -> Result, String>, +) -> Result<(), String> { + let content = document["content"].as_str().ok_or("Missing document content")?; + let mapped = match document.get("docType").and_then(Value::as_str).unwrap_or("text") { + "text" => rewrite_str( + content, + RewriteStrSettings::new().append_element_content_handler(element!("img[src]", |el| { + let raw_src = el.get_attribute("src").unwrap_or_default(); + let src = html_escape::decode_html_entities(&raw_src); + if let Some(mapped) = map(&src)? { + el.set_attribute("src", &html_escape::encode_double_quoted_attribute(&mapped))?; + } + Ok(()) + })), + ) + .map_err(err)?, + _ => { + let mut graph: Value = serde_json::from_str(content).map_err(|_| "Damaged map document")?; + remap_json(&mut graph, map)?; + serde_json::to_string(&graph).map_err(err)? + } + }; + document["content"] = Value::String(mapped); + Ok(()) +} + +fn remap_json(value: &mut Value, map: &dyn Fn(&str) -> Result, String>) -> Result<(), String> { + match value { + Value::Object(fields) => { + for (key, value) in fields { + if matches!(key.as_str(), "assetPath" | "imagePath" | "bakedAssetPath") { + if let Some(path) = value.as_str() { + if let Some(mapped) = map(path)? { + *value = Value::String(mapped); + } + } + } else if key == "imports" { + // Fantasy-map "My Imports" library entries keep their disk path in `path`. + // Only that field of each entry is relocated, never an arbitrary `path` key. + for item in value.as_array_mut().into_iter().flatten() { + if let Some(Value::String(path)) = item.get_mut("path") { + if let Some(mapped) = map(path)? { + *path = mapped; + } + } + } + } else { + remap_json(value, map)?; + } + } + } + Value::Array(items) => { + for item in items { + remap_json(item, map)?; + } + } + _ => {} + } + Ok(()) +} + +/// Folder tree and project identity: a backup of a project with these broken is refused. +fn validate_structure(project: &Project) -> Result, String> { + if Uuid::parse_str(&project.id).is_err() { + return Err("Invalid project identity".into()); + } + let folder_ids: HashSet = project.folders.iter().map(|f| f.id.clone()).collect(); + if folder_ids.len() != project.folders.len() { + return Err("Duplicate folder identity".into()); + } + for folder in &project.folders { + let mut visited = HashSet::from([folder.id.as_str()]); + let mut parent = folder.parent_id.as_deref(); + while let Some(id) = parent { + if !visited.insert(id) { + return Err("Folder cycle in backup".into()); + } + parent = project + .folders + .iter() + .find(|f| f.id == id) + .ok_or("Missing parent folder in backup")? + .parent_id + .as_deref(); + } + } + Ok(folder_ids) +} + +/// A valid chapter/map file, or why it is not one. +fn check_document(bytes: &[u8], name: &str, folder_ids: &HashSet) -> Result { + let document: Document = serde_json::from_slice(bytes).map_err(|_| "unreadable")?; + if *name != format!("documents/{}.json", document.id) { + return Err("its id does not match its file name"); + } + if !matches!(document.doc_type.as_str(), "text" | "mindmap" | "fantasymap") { + return Err("unknown document type"); + } + if document.folder_id.as_ref().is_some_and(|id| !folder_ids.contains(id)) { + return Err("its folder is missing"); + } + Ok(document) +} + +fn plural(n: usize, one: &str, many: &str) -> String { + format!("{n} {}", if n == 1 { one } else { many }) +} + +/// File-backed, bounded ZIP writer. Source files are never modified. Image references become +/// portable (`mnemo-asset:`), so the archive never records where the project lived. +/// +/// Everything valid is backed up; problems are returned as warnings instead of blocking the +/// backup (a project with a damaged chapter is the one that most needs one): damaged chapter +/// files are copied as they are, and images outside the project or missing are named. +pub fn export_in(root: &Path, destination: &Path) -> Result, String> { + let root = root.canonicalize().map_err(err)?; + let root_text = root.to_string_lossy().into_owned(); + let disk = inventory(&root)?; + let project: Project = serde_json::from_slice(&fs::read(root.join("project.json")).map_err(err)?) + .map_err(|_| "The project file (project.json) is damaged")?; + let folder_ids = validate_structure(&project)?; + + let mut warnings = Vec::new(); + let mut damaged = Vec::new(); + let mut rewritten: BTreeMap> = BTreeMap::new(); + let outside = std::cell::RefCell::new(BTreeSet::new()); + let missing = std::cell::RefCell::new(BTreeSet::new()); + let windows = root_text.replace('\\', "/").trim_start_matches("//?/").as_bytes().get(1) == Some(&b':'); + let to_portable = |value: &str| -> Result, String> { + match classify(value, &root_text) { + Reference::Project(relative) => { + let actual = disk + .keys() + .find(|name| **name == relative || (windows && name.eq_ignore_ascii_case(&relative))) + .cloned(); + if actual.is_none() { + missing.borrow_mut().insert(relative.to_lowercase()); + } + let file = actual.unwrap_or(relative); + Ok(Some(format!("{ASSET_SCHEME}{}", &file["assets/".len()..]))) + } + Reference::External => { + outside.borrow_mut().insert(value.to_string()); + Ok(None) + } + Reference::Other => Ok(None), + } + }; + let mut on_disk = HashSet::new(); + for name in disk.keys().filter(|p| p.starts_with("documents/")) { + let bytes = bounded_read(File::open(root.join(name)).map_err(err)?, MAX_FILE)?; + match check_document(&bytes, name, &folder_ids) { + Ok(document) => { + on_disk.insert(document.id); + let mut value: Value = serde_json::from_slice(&bytes).map_err(err)?; + if rewrite_references(&mut value, &to_portable).is_err() { + damaged.push(name.clone()); + warnings.push(format!("\"{}\" has damaged content and was copied as it is.", value["title"].as_str().unwrap_or(name))); + continue; + } + rewritten.insert(name.clone(), serde_json::to_vec_pretty(&value).map_err(err)?); + } + Err(why) => { + damaged.push(name.clone()); + let reason = if why == "unreadable" { String::new() } else { format!(" ({why})") }; + warnings.push(format!("{} could not be read{reason} and was copied as it is.", &name["documents/".len()..])); + } + } + } + let unlisted = project.documents.iter().filter(|d| !on_disk.contains(&d.id)).count(); + if unlisted > damaged.len() { + warnings.push(format!("{} listed in the project file {} not found on disk.", plural(unlisted - damaged.len(), "chapter", "chapters"), if unlisted - damaged.len() == 1 { "was" } else { "were" })); + } + let (outside, missing) = (outside.into_inner().len(), missing.into_inner().len()); + if outside > 0 { + warnings.push(format!("{} outside this project {} not included. Import {} into the project to back {} up.", plural(outside, "image", "images"), if outside == 1 { "was" } else { "were" }, if outside == 1 { "it" } else { "them" }, if outside == 1 { "it" } else { "them" })); + } + if missing > 0 { + warnings.push(format!("{} missing from the project's assets folder.", plural(missing, "image is", "images are"))); + } + + let files: BTreeMap = disk + .iter() + .map(|(name, digest)| { + let digest = match rewritten.get(name) { + Some(bytes) => FileDigest { size: bytes.len() as u64, sha256: hash(bytes) }, + None => FileDigest { size: digest.size, sha256: digest.sha256.clone() }, + }; + (name.clone(), digest) + }) + .collect(); + let manifest = Manifest { + format: "mnemoscript-project-backup".into(), + schema_version: SCHEMA, + project_id: project.id, + source_root: None, + damaged, + files, + }; + // create_new prevents overwriting an archive or an existing manuscript file. + let file = File::options().write(true).read(true).create_new(true).open(destination).map_err(err)?; + let result = (|| { + let mut zip = ZipWriter::new(file); + let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + for name in manifest.files.keys() { + let bytes = match rewritten.get(name) { + Some(bytes) => bytes.clone(), + None => { + let bytes = bounded_read(File::open(root.join(name)).map_err(err)?, MAX_FILE)?; + if hash(&bytes) != disk[name].sha256 { + return Err("Project changed during backup; try again".to_string()); + } + bytes + } + }; + zip.start_file(name, options).map_err(err)?; + zip.write_all(&bytes).map_err(err)?; + } + let bytes = serde_json::to_vec_pretty(&manifest).map_err(err)?; + if bytes.len() as u64 > MAX_MANIFEST { + return Err("Backup manifest too large".into()); + } + zip.start_file(MANIFEST, options).map_err(err)?; + zip.write_all(&bytes).map_err(err)?; + zip.finish().map_err(err)?.sync_all().map_err(err)?; + // Catch concurrent saves, deletions and additions rather than silently mixing snapshots. + let after = inventory(&root)?; + if after.len() != disk.len() || after.iter().any(|(name, digest)| disk.get(name).is_none_or(|old| old.sha256 != digest.sha256)) { + return Err("Project changed during backup; try again".into()); + } + Ok(()) + })(); + if result.is_err() { + let _ = fs::remove_file(destination); + } + result.map(|()| warnings) +} + +/// Verify every entry before activation. Only a private, newly created stage is written. +fn extract(source: R, stage: &Path) -> Result { + let mut zip = ZipArchive::new(source).map_err(err)?; + if zip.len() > MAX_FILES + 1 { + return Err("Too many backup files".into()); + } + let manifest = read_manifest(&mut zip)?; + if manifest.format != "mnemoscript-project-backup" || !matches!(manifest.schema_version, 1 | SCHEMA) { + return Err("Unsupported backup format; update MnemoScript".into()); + } + // Schema 1 relocates absolute paths from its source folder; schema 2 never records one. + if (manifest.schema_version == 1) != manifest.source_root.is_some() + || (manifest.schema_version == 1 && !manifest.damaged.is_empty()) + { + return Err("Invalid backup manifest".into()); + } + if manifest.files.len() > MAX_FILES + || zip.len() != manifest.files.len() + 1 + || !manifest.files.contains_key("project.json") + || manifest.damaged.iter().any(|d| !d.starts_with("documents/") || !manifest.files.contains_key(d)) + { + return Err("Backup file list does not match its manifest".into()); + } + let mut total = 0_u64; + for (name, digest) in &manifest.files { + if !allowed(name) || digest.size > MAX_FILE || digest.sha256.len() != 64 { + return Err("Invalid backup manifest entry".into()); + } + total = total.checked_add(digest.size).ok_or("Backup size overflow")?; + if total > MAX_TOTAL { + return Err("Backup exceeds the 512 MiB limit".into()); + } + } + let mut seen = HashSet::new(); + for index in 0..zip.len() { + let file = zip.by_index(index).map_err(err)?; + let name = file.name().map_err(err)?.into_owned(); + if !safe_name(&name) + || !seen.insert(name.to_lowercase()) + || file.is_dir() + || file.unix_mode().is_some_and(|mode| mode & 0o170000 != 0 && mode & 0o170000 != 0o100000) + { + return Err("Unsafe or duplicate backup path".into()); + } + if name == MANIFEST { + continue; + } + let digest = manifest.files.get(&name).ok_or("Unexpected file in backup")?; + if file.size() != digest.size { + return Err("Backup size mismatch".into()); + } + let bytes = bounded_read(file, digest.size)?; + if bytes.len() as u64 != digest.size || hash(&bytes) != digest.sha256 { + return Err(format!("Backup checksum mismatch: {name}")); + } + let path = stage.join(&name); + fs::create_dir_all(path.parent().ok_or("Missing parent")?).map_err(err)?; + let mut output = File::options().write(true).create_new(true).open(path).map_err(err)?; + output.write_all(&bytes).map_err(err)?; + output.sync_all().map_err(err)?; + } + Ok(manifest) +} + +fn read_manifest(zip: &mut ZipArchive) -> Result { + let file = zip.by_name(MANIFEST).map_err(|_| "Not a MnemoScript recovery archive")?; + serde_json::from_slice(&bounded_read(file, MAX_MANIFEST)?).map_err(err) +} + +/// Restore as an independent copy; never overwrite or unregister a source project. +/// +/// Strict where it protects the writer: every file's size and checksum, safe paths, the folder +/// tree, and every chapter that was valid when backed up. Chapter files the backup itself +/// recorded as damaged are restored as they are, so the backup stays restorable. +pub fn restore_in(source: R, projects_dir: &Path) -> Result { + fs::create_dir_all(projects_dir).map_err(err)?; + let id = Uuid::new_v4().to_string(); + let stage = projects_dir.join(format!(".restore-{id}")); + let destination = projects_dir.join(&id); + fs::create_dir(&stage).map_err(err)?; + let result = (|| { + let manifest = extract(source, &stage)?; + let path = stage.join("project.json"); + let mut value: Value = serde_json::from_slice(&fs::read(&path).map_err(err)?).map_err(err)?; + let project: Project = serde_json::from_value(value.clone()).map_err(err)?; + if project.id != manifest.project_id { + return Err("Backup project identity mismatch".into()); + } + let folder_ids = validate_structure(&project)?; + let damaged: HashSet<&String> = manifest.damaged.iter().collect(); + let to_local = |value: &str| -> Result, String> { + match &manifest.source_root { + Some(old) => asset_reference(value, old, &destination, &manifest.files), + None => Ok(value.strip_prefix(ASSET_SCHEME).and_then(|file| { + let relative = format!("assets/{file}"); + manifest.files.contains_key(&relative).then(|| destination.join(&relative).to_string_lossy().into_owned()) + })), + } + }; + let mut documents = Vec::new(); + for name in manifest.files.keys().filter(|p| p.starts_with("documents/")) { + let file = stage.join(name); + let bytes = fs::read(&file).map_err(err)?; + if damaged.contains(name) { + // Kept byte for byte; the app skips it on load as it did on the source device. + if let Ok(document) = serde_json::from_slice::(&bytes) { + documents.push(document); + } + continue; + } + check_document(&bytes, name, &folder_ids).map_err(|why| format!("Invalid document in backup: {name} ({why})"))?; + let mut value: Value = serde_json::from_slice(&bytes).map_err(err)?; + rewrite_references(&mut value, &to_local)?; + crate::project::write_atomic(&file, &serde_json::to_string_pretty(&value).map_err(err)?)?; + documents.push(serde_json::from_value(value).map_err(err)?); + } + value["id"] = Value::String(id); + value["name"] = Value::String(format!("{} (restored)", project.name)); + value["path"] = Value::String(destination.to_string_lossy().into_owned()); + // A recovered copy is local-only and does not inherit a device/provider connection. + value.as_object_mut().ok_or("Invalid project metadata")?.remove("ai"); + crate::project::write_atomic(&path, &serde_json::to_string_pretty(&value).map_err(err)?)?; + let mut restored: Project = serde_json::from_value(value).map_err(err)?; + documents.sort_by(|a, b| a.order.cmp(&b.order).then(a.updated_at.cmp(&b.updated_at))); + restored.documents = documents; + fs::rename(&stage, &destination).map_err(err)?; + Ok(restored) + })(); + // Only this invocation's private staging folder can be removed. Activated data is retained. + if stage.exists() { + let _ = fs::remove_dir_all(&stage); + } + result +} + +// ---- the backups folder ------------------------------------------------------------------------ + +/// Backups kept per project; older ones are removed when a new one is made. +pub const KEEP: usize = 5; + +fn backups_dir() -> PathBuf { + crate::project::data_dir().join("backups") +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Created { + pub path: String, + pub file_name: String, + /// Problems that did not stop the backup (damaged chapters, images outside the project). + pub warnings: Vec, +} + +#[derive(Serialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct BackupInfo { + pub path: String, + pub file_name: String, + pub project_id: String, + pub project_name: String, + pub size: u64, + pub created_at: String, +} + +/// The project and name recorded inside an archive (read without extracting it). +fn header(path: &Path) -> Option<(String, String)> { + let mut zip = ZipArchive::new(File::open(path).ok()?).ok()?; + let manifest = read_manifest(&mut zip).ok()?; + let name = zip + .by_name("project.json") + .ok() + .and_then(|f| bounded_read(f, MAX_MANIFEST).ok()) + .and_then(|b| serde_json::from_slice::(&b).ok()) + .and_then(|v| v["name"].as_str().map(String::from)) + .unwrap_or_default(); + Some((manifest.project_id, name)) +} + +fn list_in(folder: &Path) -> Vec { + let Ok(entries) = fs::read_dir(folder) else { return Vec::new() }; + let mut out: Vec = entries + .flatten() + .filter(|e| e.path().extension().and_then(|x| x.to_str()) == Some("zip") && e.path().is_file()) + .filter_map(|e| { + let path = e.path(); + let (project_id, project_name) = header(&path)?; + let meta = e.metadata().ok()?; + let created_at = meta.modified().ok().map(|t| chrono::DateTime::::from(t).to_rfc3339()).unwrap_or_default(); + Some(BackupInfo { + file_name: e.file_name().to_string_lossy().into_owned(), + path: path.to_string_lossy().into_owned(), + project_id, + project_name, + size: meta.len(), + created_at, + }) + }) + .collect(); + out.sort_by(|a, b| b.created_at.cmp(&a.created_at).then(b.file_name.cmp(&a.file_name))); + out +} + +/// Every backup in the backups folder, newest first. +pub fn list() -> Vec { + list_in(&backups_dir()) +} + +/// Keep the newest `keep` backups of one project; never the file just written. +fn prune_in(folder: &Path, project_id: &str, keep: usize, newest: &Path) { + for old in list_in(folder).into_iter().filter(|b| b.project_id == project_id).skip(keep) { + if Path::new(&old.path) != newest { + let _ = fs::remove_file(&old.path); + } + } +} + +/// `-.zip`, unique in `folder`. +fn backup_name(folder: &Path, project_name: &str) -> PathBuf { + let base: String = crate::project::safe_dir_name(project_name).chars().take(60).collect::().trim().to_string(); + let base = if base.is_empty() || !safe_name(&base) { "project".to_string() } else { base }; + let stamp = chrono::Local::now().format("%Y-%m-%d-%H%M"); + let mut candidate = folder.join(format!("{base}-{stamp}.zip")); + let mut n = 2; + while candidate.exists() { + candidate = folder.join(format!("{base}-{stamp}-{n}.zip")); + n += 1; + } + candidate +} + +pub fn create(project_id: &str) -> Result { + create_in(project_id, &Project::resolve_dir(project_id), &backups_dir()) +} + +fn create_in(project_id: &str, project_dir: &Path, folder: &Path) -> Result { + if Uuid::parse_str(project_id).is_err() { + return Err("Invalid project identity".into()); + } + fs::create_dir_all(folder).map_err(err)?; + let name = fs::read(project_dir.join("project.json")) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .and_then(|v| v["name"].as_str().map(String::from)) + .unwrap_or_default(); + let destination = backup_name(folder, &name); + let warnings = export_in(project_dir, &destination)?; + prune_in(folder, project_id, KEEP, &destination); + Ok(Created { + file_name: destination.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), + path: destination.to_string_lossy().into_owned(), + warnings, + }) +} + +/// A path the frontend names must be one of the backups in the backups folder. +fn in_folder(folder: &Path, path: &str) -> Result { + let folder = folder.canonicalize().map_err(err)?; + let file = Path::new(path).canonicalize().map_err(|_| "That backup no longer exists")?; + if file.parent() != Some(folder.as_path()) || file.extension().and_then(|e| e.to_str()) != Some("zip") { + return Err("Not a MnemoScript backup".into()); + } + Ok(file) +} + +pub fn delete(path: &str) -> Result<(), String> { + fs::remove_file(in_folder(&backups_dir(), path)?).map_err(err) +} + +/// Copy a backup to a writer (a file the writer chose, possibly an Android document). +pub fn copy_to(path: &str, destination: &mut impl Write) -> Result { + let mut source = File::open(in_folder(&backups_dir(), path)?).map_err(err)?; + let copied = std::io::copy(&mut source, destination).map_err(err)?; + destination.flush().map_err(err)?; + Ok(copied) +} + +#[cfg(test)] +mod tests; diff --git a/app/src-tauri/src/backup/tests.rs b/app/src-tauri/src/backup/tests.rs new file mode 100644 index 0000000..d4fdf00 --- /dev/null +++ b/app/src-tauri/src/backup/tests.rs @@ -0,0 +1,552 @@ +use super::*; +use std::io::Cursor; +use tempfile::{tempdir, TempDir}; + +fn put(root: &Path, name: &str, bytes: impl AsRef<[u8]>) { + let path = root.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, bytes).unwrap(); +} + +fn fixture() -> TempDir { + let dir = tempfile::Builder::new() + .prefix("mnemo & test ") + .tempdir() + .unwrap(); + let project = serde_json::json!({ + "id": Uuid::new_v4().to_string(), "name": "Novel", "created_at": "2026-11-12", + "path": dir.path(), "author": "Writer", "customField": { "kept": true }, + "folders": [{"id": "volume-1", "name": "Volume 1", "order": 0}], + "documents": [{"id": "chapter-1", "title": "Chapter 1", "content": "", "updated_at": "now"}], + "ai": { "provider": "paired-pc", "model": "local" } + }); + put(dir.path(), "project.json", project.to_string()); + put(dir.path(), "assets/image.png", [0, 255, 12, 34]); + let content = format!( + "

Chapter 1

বাংলা — {}

\"Map\"", + dir.path().display(), + html_escape::encode_double_quoted_attribute( + &dir.path().join("assets/image.png").to_string_lossy() + ) + ); + put( + dir.path(), + "documents/chapter-1.json", + serde_json::json!({ + "id": "chapter-1", "title": "Chapter 1", "content": content, "updated_at": "now", + "folderId": "volume-1", "docType": "text", "order": 2, "unknown": 42 + }) + .to_string(), + ); + for (id, kind) in [("map-1", "fantasymap"), ("mind-1", "mindmap")] { + let content = serde_json::json!({ + "nodes": [{ "id": "n1", "data": { "label": dir.path().display().to_string() }}], "edges": [], + "items": [{ "assetPath": dir.path().join("assets/image.png") }], + "canvas": { "background": { "imagePath": dir.path().join("assets/image.png") } }, + "terrain": { "bakedAssetPath": dir.path().join("assets/image.png") } + }).to_string(); + put(dir.path(), &format!("documents/{id}.json"), serde_json::json!({ + "id": id, "title": id, "content": content, "updated_at": "now", "docType": kind, "order": 0 + }).to_string()); + } + put( + dir.path(), + "ai/sessions/session.json", + "{\"id\":\"session\",\"messages\":[\"private conversation\"]}", + ); + put(dir.path(), "exports/book.pdf", b"test exported bytes"); + put(dir.path(), "credentials.json", "never back this up"); + put(dir.path(), "ai/keys.json", "never back this up either"); + dir +} + +fn archive(root: &Path) -> Vec { + let dir = tempdir().unwrap(); + let path = dir.path().join("backup.zip"); + export_in(root, &path).unwrap(); + fs::read(path).unwrap() +} + +fn unpack(bytes: &[u8]) -> BTreeMap> { + let mut zip = ZipArchive::new(Cursor::new(bytes)).unwrap(); + (0..zip.len()) + .map(|i| { + let mut file = zip.by_index(i).unwrap(); + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes).unwrap(); + (file.name().unwrap().into_owned(), bytes) + }) + .collect() +} + +fn repack(files: BTreeMap>) -> Vec { + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + for (name, bytes) in files { + zip.start_file(name, SimpleFileOptions::default()).unwrap(); + zip.write_all(&bytes).unwrap(); + } + zip.finish().unwrap().into_inner() +} + +fn rejected(bytes: Vec) -> String { + let destination = tempdir().unwrap(); + let error = restore_in(Cursor::new(bytes), destination.path()) + .err() + .expect("must reject"); + assert_eq!( + fs::read_dir(destination.path()).unwrap().count(), + 0, + "no activated or staged partial project" + ); + error +} + +#[test] +fn round_trip_preserves_text_hierarchy_graphs_assets_sessions_exports_and_originals() { + let source = fixture(); + let before = inventory(source.path()).unwrap(); + let bytes = archive(source.path()); + let entries = unpack(&bytes); + assert!(!entries.contains_key("credentials.json")); + assert!(!entries.contains_key("ai/keys.json")); + let destination = tempdir().unwrap(); + let restored = restore_in(Cursor::new(bytes), destination.path()).unwrap(); + assert_eq!(restored.documents.len(), 3); + assert_eq!(restored.folders[0].name, "Volume 1"); + assert_eq!(restored.author.as_deref(), Some("Writer")); + assert!(restored.ai.is_none()); + let original: Project = + serde_json::from_slice(&fs::read(source.path().join("project.json")).unwrap()).unwrap(); + assert_ne!(restored.id, original.id); + let target = restored.get_dir(); + for name in [ + "assets/image.png", + "ai/sessions/session.json", + "exports/book.pdf", + ] { + assert_eq!(fs::read(target.join(name)).unwrap(), entries[name]); + } + let chapter = restored + .documents + .iter() + .find(|d| d.id == "chapter-1") + .unwrap(); + assert_eq!(chapter.folder_id.as_deref(), Some("volume-1")); + assert!(chapter.content.contains("বাংলা")); + assert!(chapter.content.contains(&format!( + "

বাংলা — {}

", + source.path().display() + ))); + assert!(chapter.content.contains( + &target + .join("assets/image.png") + .to_string_lossy() + .to_string() + )); + let doc: Value = + serde_json::from_slice(&fs::read(target.join("documents/chapter-1.json")).unwrap()) + .unwrap(); + assert_eq!(doc["unknown"], 42); + let metadata: Value = + serde_json::from_slice(&fs::read(target.join("project.json")).unwrap()).unwrap(); + assert_eq!(metadata["customField"]["kept"], true); + let map = restored.documents.iter().find(|d| d.id == "map-1").unwrap(); + let graph: Value = serde_json::from_str(&map.content).unwrap(); + for path in [ + "/items/0/assetPath", + "/canvas/background/imagePath", + "/terrain/bakedAssetPath", + ] { + assert_eq!( + graph.pointer(path).unwrap(), + &target + .join("assets/image.png") + .to_string_lossy() + .to_string() + ); + } + assert_eq!( + graph["nodes"][0]["data"]["label"], + source.path().display().to_string() + ); + assert_eq!( + before.keys().collect::>(), + inventory(source.path()).unwrap().keys().collect::>() + ); + for (name, digest) in before { + assert_eq!( + digest.sha256, + hash(&fs::read(source.path().join(name)).unwrap()) + ); + } + // Repeated restore never replaces an existing recovered copy. + let second = restore_in(Cursor::new(archive(source.path())), destination.path()).unwrap(); + assert_ne!(second.id, restored.id); + assert!(target.exists()); +} + +#[test] +fn refuses_overwrite_and_preserves_the_existing_destination() { + let source = fixture(); + let target = source.path().join("project.json"); + let original = fs::read(&target).unwrap(); + assert!(export_in(source.path(), &target).is_err()); + assert_eq!(fs::read(target).unwrap(), original); +} + +#[test] +fn detects_tampered_missing_extra_and_truncated_files() { + let source = fixture(); + let bytes = archive(source.path()); + for change in ["tamper", "missing", "extra"] { + let mut files = unpack(&bytes); + match change { + "tamper" => { + files.insert("assets/image.png".into(), vec![1, 2, 3, 4]); + } + "missing" => { + files.remove("assets/image.png"); + } + _ => { + files.insert("assets/extra.png".into(), vec![1]); + } + } + rejected(repack(files)); + } + rejected(bytes[..bytes.len() / 2].to_vec()); +} + +#[test] +fn rejects_newer_schema_and_oversized_entries_before_extraction() { + let source = fixture(); + let bytes = archive(source.path()); + for mode in ["schema", "size", "identity"] { + let mut files = unpack(&bytes); + let mut manifest: Value = serde_json::from_slice(&files[MANIFEST]).unwrap(); + match mode { + "schema" => manifest["schemaVersion"] = 999.into(), + "size" => manifest["files"]["assets/image.png"]["size"] = (MAX_FILE + 1).into(), + _ => manifest["projectId"] = Uuid::new_v4().to_string().into(), + } + files.insert(MANIFEST.into(), serde_json::to_vec(&manifest).unwrap()); + rejected(repack(files)); + } +} + +#[test] +fn rejects_paths_unsafe_on_either_platform_and_case_collisions() { + for name in [ + "../escape", + "/root", + "C:/file", + "assets/../file", + "assets\\evil", + "assets/x:stream", + "assets/CON.txt", + "assets/LPT1", + "assets/trailing.", + "assets/a//b", + ] { + assert!(!safe_name(name), "{name}"); + } + let source = fixture(); + let bytes = archive(source.path()); + for name in ["../escape", "assets/IMAGE.PNG", "ai/keys.json"] { + let mut files = unpack(&bytes); + let digest = serde_json::json!({"size": 1, "sha256": hash(&[1])}); + let mut manifest: Value = serde_json::from_slice(&files[MANIFEST]).unwrap(); + manifest["files"][name] = digest; + files.insert(name.into(), vec![1]); + files.insert(MANIFEST.into(), serde_json::to_vec(&manifest).unwrap()); + rejected(repack(files)); + } +} + +/// Regression (PR #3 review, item 1): one damaged chapter blocked every backup of the project, +/// though the app itself opens the project. It is now copied as it is, named in a warning, and +/// the backup restores; every other chapter is still checked strictly on restore. +#[test] +fn a_damaged_chapter_is_backed_up_as_is_with_a_warning() { + let source = fixture(); + put(source.path(), "documents/chapter-1.json", "damaged json"); + let dir = tempdir().unwrap(); + let path = dir.path().join("backup.zip"); + let warnings = export_in(source.path(), &path).unwrap(); + assert_eq!(warnings, vec!["chapter-1.json could not be read and was copied as it is.".to_string()]); + let bytes = fs::read(&path).unwrap(); + let entries = unpack(&bytes); + assert_eq!(entries["documents/chapter-1.json"], b"damaged json"); + let manifest: Value = serde_json::from_slice(&entries[MANIFEST]).unwrap(); + assert_eq!(manifest["damaged"], serde_json::json!(["documents/chapter-1.json"])); + let destination = tempdir().unwrap(); + let restored = restore_in(Cursor::new(bytes.clone()), destination.path()).unwrap(); + assert_eq!(restored.documents.len(), 2, "the readable chapters come back"); + assert_eq!(fs::read(restored.get_dir().join("documents/chapter-1.json")).unwrap(), b"damaged json"); + + // Only files the backup itself marked as damaged may be invalid on restore. + let mut files = unpack(&bytes); + let mut manifest: Value = serde_json::from_slice(&files[MANIFEST]).unwrap(); + manifest.as_object_mut().unwrap().remove("damaged"); + files.insert(MANIFEST.into(), serde_json::to_vec(&manifest).unwrap()); + assert!(rejected(repack(files)).contains("Invalid document")); + + // A chapter missing from disk but listed in the project file is a warning, not a refusal. + fs::remove_file(source.path().join("documents/chapter-1.json")).unwrap(); + let warnings = export_in(source.path(), &dir.path().join("second.zip")).unwrap(); + assert!(warnings.iter().any(|w| w.contains("1 chapter listed in the project file was not found")), "{warnings:?}"); +} + +/// Regression (PR #3 review, item 1): an image outside the project or a missing one refused the +/// whole backup. Both are now warnings, counted per image. +#[test] +fn missing_and_outside_images_are_warnings_not_refusals() { + let source = fixture(); + fs::remove_file(source.path().join("assets/image.png")).unwrap(); + let outside = tempdir().unwrap(); + let external = outside.path().join("photo.png"); + fs::write(&external, [1, 2]).unwrap(); + let mut doc: Value = serde_json::from_slice(&fs::read(source.path().join("documents/chapter-1.json")).unwrap()).unwrap(); + let content = format!( + "{}", + doc["content"].as_str().unwrap(), + html_escape::encode_double_quoted_attribute(&external.to_string_lossy()) + ); + doc["content"] = Value::String(content); + put(source.path(), "documents/chapter-1.json", doc.to_string()); + let dir = tempdir().unwrap(); + let path = dir.path().join("backup.zip"); + let warnings = export_in(source.path(), &path).unwrap(); + assert!(warnings.contains(&"1 image outside this project was not included. Import it into the project to back it up.".to_string()), "{warnings:?}"); + assert!(warnings.contains(&"1 image is missing from the project's assets folder.".to_string()), "{warnings:?}"); + let target = tempdir().unwrap(); + let restored = restore_in(Cursor::new(fs::read(&path).unwrap()), target.path()).unwrap(); + let chapter = restored.documents.iter().find(|d| d.id == "chapter-1").unwrap(); + assert!(chapter.content.contains("mnemo-asset:image.png"), "a missing image stays a portable, harmless reference"); +} + +/// Regression (PR #3 review, item 2): the archive recorded the project's absolute folder (with +/// the OS user name), and chapters kept absolute image paths. +#[test] +fn archives_are_portable_and_never_record_the_source_folder() { + let source = fixture(); + let bytes = archive(source.path()); + let entries = unpack(&bytes); + let manifest: Value = serde_json::from_slice(&entries[MANIFEST]).unwrap(); + assert_eq!(manifest["schemaVersion"], 2); + assert!(manifest.get("sourceRoot").is_none()); + let root = source.path().canonicalize().unwrap().to_string_lossy().replace('\\', "/"); + let root = root.trim_start_matches("//?/").to_string(); + for name in ["documents/chapter-1.json", "documents/map-1.json", "documents/mind-1.json"] { + let doc: Value = serde_json::from_slice(&entries[name]).unwrap(); + let content = doc["content"].as_str().unwrap().replace("\\\\", "/").replace('\\', "/"); + assert!(content.contains("mnemo-asset:image.png"), "{name}"); + assert!(!content.contains(&format!("{root}/assets")), "{name} keeps no absolute image path"); + } + let raw = String::from_utf8_lossy(&entries[MANIFEST]).replace("\\\\", "/"); + assert!(!raw.contains(&root)); +} + +/// Archives made before schema 2 (with `sourceRoot` and absolute paths) still restore. +#[test] +fn schema_one_archives_still_restore() { + let mut files = BTreeMap::new(); + let pid = Uuid::new_v4().to_string(); + let old = r"C:\Users\Writer\Novel"; + files.insert( + "project.json".to_string(), + serde_json::json!({"id": pid, "name": "Old", "created_at": "2026", "folders": [], "documents": []}).to_string().into_bytes(), + ); + files.insert("assets/a.png".to_string(), vec![9, 9]); + let content = format!(""); + files.insert( + "documents/c1.json".to_string(), + serde_json::json!({"id": "c1", "title": "C1", "content": content, "updated_at": "now"}).to_string().into_bytes(), + ); + let digests: serde_json::Map = + files.iter().map(|(n, b)| (n.clone(), serde_json::json!({"size": b.len(), "sha256": hash(b)}))).collect(); + let manifest = serde_json::json!({"format": "mnemoscript-project-backup", "schemaVersion": 1, "projectId": pid, "sourceRoot": old, "files": digests}); + files.insert(MANIFEST.to_string(), serde_json::to_vec(&manifest).unwrap()); + let destination = tempdir().unwrap(); + let restored = restore_in(Cursor::new(repack(files)), destination.path()).unwrap(); + let expected = restored.get_dir().join("assets/a.png").to_string_lossy().into_owned(); + assert!(restored.documents[0].content.contains(&*html_escape::encode_double_quoted_attribute(&expected))); +} + +/// Regression (PR #3 review, item 3): every backup was `-.zip` and they piled up +/// unseen. Names now carry the project and time, the newest `KEEP` per project are kept, and the +/// list reads the project from inside each archive. +#[test] +fn backups_are_named_listed_and_pruned_per_project() { + let source = fixture(); + let other = fixture(); + let folder = tempdir().unwrap(); + let pid = |dir: &TempDir| { + serde_json::from_slice::(&fs::read(dir.path().join("project.json")).unwrap()).unwrap()["id"].as_str().unwrap().to_string() + }; + let theirs = create_in(&pid(&other), other.path(), folder.path()).unwrap(); + let mut made = Vec::new(); + for _ in 0..KEEP + 2 { + made.push(create_in(&pid(&source), source.path(), folder.path()).unwrap()); + } + let name = &made.last().unwrap().file_name; + assert!(name.starts_with("Novel-20") && name.ends_with(".zip"), "{name}"); + let list = list_in(folder.path()); + let mine: Vec<_> = list.iter().filter(|b| b.project_id == pid(&source)).collect(); + assert_eq!(mine.len(), KEEP); + assert!(mine.iter().all(|b| b.project_name == "Novel" && b.size > 0)); + assert!(Path::new(&made.last().unwrap().path).exists(), "the newest is never pruned"); + assert!(Path::new(&theirs.path).exists(), "other projects' backups are untouched"); +} + +/// Only files directly in the backups folder can be copied or deleted by name. +#[test] +fn only_backups_in_the_backups_folder_can_be_named() { + let folder = tempdir().unwrap(); + let inside = folder.path().join("Novel-2026-11-15-1200.zip"); + fs::write(&inside, b"zip").unwrap(); + assert!(in_folder(folder.path(), &inside.to_string_lossy()).is_ok()); + let source = fixture(); + let nested = folder.path().join("sub"); + fs::create_dir_all(&nested).unwrap(); + let parent = folder.path().parent().unwrap().join(format!("x-{}.zip", Uuid::new_v4())); + for outside in [source.path().join("project.json"), nested.join("x.zip"), parent.clone()] { + fs::write(&outside, b"x").unwrap(); + assert!(in_folder(folder.path(), &outside.to_string_lossy()).is_err(), "{}", outside.display()); + } + let _ = fs::remove_file(parent); +} + +#[test] +fn asset_remapping_is_structural_and_cross_platform() { + let mut files = BTreeMap::new(); + files.insert( + "assets/Image.png".into(), + FileDigest { + size: 0, + sha256: hash(&[]), + }, + ); + let target = Path::new("/restored/novel"); + assert_eq!( + asset_reference( + "C:\\Novel\\assets\\image.png", + "\\\\?\\C:\\Novel", + target, + &files + ) + .unwrap(), + Some( + target + .join("assets/Image.png") + .to_string_lossy() + .into_owned() + ) + ); + assert!(asset_reference( + "C:\\NovelOther\\assets\\Image.png", + "C:\\Novel", + target, + &files + ) + .is_err()); + assert!(asset_reference( + "C:\\Novel\\assets\\missing.png", + "C:\\Novel", + target, + &files + ) + .is_err()); + assert_eq!( + asset_reference("https://example.org/image.png", "C:\\Novel", target, &files).unwrap(), + None + ); + assert!(asset_reference("file:///private/image.png", "C:\\Novel", target, &files).is_err()); +} + +#[test] +fn rejects_symlink_archive_entries() { + let source = fixture(); + let bytes = archive(source.path()); + let files = unpack(&bytes); + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + for (name, bytes) in files { + if name == "assets/image.png" { + zip.add_symlink(name, "/private/secret", SimpleFileOptions::default()) + .unwrap(); + } else { + zip.start_file(name, SimpleFileOptions::default()).unwrap(); + zip.write_all(&bytes).unwrap(); + } + } + assert!(rejected(zip.finish().unwrap().into_inner()).contains("Unsafe")); +} + +#[test] +fn rejects_folder_cycles() { + let source = fixture(); + let path = source.path().join("project.json"); + let mut metadata: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap(); + metadata["folders"][0]["parentId"] = "volume-1".into(); + put(source.path(), "project.json", metadata.to_string()); + assert!(export_in(source.path(), &source.path().join("bad.zip")) + .unwrap_err() + .contains("cycle")); +} + +#[test] +fn image_attributes_decode_source_entities_and_escape_restored_paths() { + let source = fixture(); + let parent = tempdir().unwrap(); + let target = parent.path().join("Restore " & notes"); + let restored = restore_in(Cursor::new(archive(source.path())), &target).unwrap(); + let chapter = restored + .documents + .iter() + .find(|d| d.id == "chapter-1") + .unwrap(); + assert!(chapter.content.contains("Restore &quot; & notes")); + assert!(restored.get_dir().join("assets/image.png").is_file()); +} + +/// Regression (2026-11-13): restore relocated item/background/terrain paths but left the map's +/// "My Imports" library pointing at the original project, so those images broke once the +/// original was gone or the backup was restored on another device. +#[test] +fn restore_relocates_fantasy_map_import_library_paths() { + let source = fixture(); + let path = source.path().join("documents/map-1.json"); + let mut doc: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap(); + let mut graph: Value = serde_json::from_str(doc["content"].as_str().unwrap()).unwrap(); + graph["imports"] = serde_json::json!([ + { "id": "imp-1", "name": "Tower", "path": source.path().join("assets/image.png") }, + { "id": "imp-2", "name": "Unrelated", "note": { "path": "kept as written" } } + ]); + doc["content"] = Value::String(graph.to_string()); + fs::write(&path, doc.to_string()).unwrap(); + + let destination = tempdir().unwrap(); + let restored = restore_in(Cursor::new(archive(source.path())), destination.path()).unwrap(); + let map = restored.documents.iter().find(|d| d.id == "map-1").unwrap(); + let graph: Value = serde_json::from_str(&map.content).unwrap(); + assert_eq!( + graph["imports"][0]["path"], + restored.get_dir().join("assets/image.png").to_string_lossy().to_string() + ); + assert_eq!(graph["imports"][1]["note"]["path"], "kept as written"); +} + +/// A map import outside the project is not included, and the writer is told (PR #3 review: +/// it used to refuse the whole backup). +#[test] +fn a_map_import_outside_the_project_is_a_warning() { + let source = fixture(); + let path = source.path().join("documents/map-1.json"); + let mut doc: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap(); + let mut graph: Value = serde_json::from_str(doc["content"].as_str().unwrap()).unwrap(); + graph["imports"] = serde_json::json!([{ "id": "imp-1", "name": "Elsewhere", "path": "C:/Other/assets/x.png" }]); + doc["content"] = Value::String(graph.to_string()); + fs::write(&path, doc.to_string()).unwrap(); + let dir = tempdir().unwrap(); + let warnings = export_in(source.path(), &dir.path().join("b.zip")).unwrap(); + assert!(warnings.iter().any(|w| w.contains("1 image outside this project")), "{warnings:?}"); +} diff --git a/app/src-tauri/src/lib.rs b/app/src-tauri/src/lib.rs index cbec2a8..5cdab09 100644 --- a/app/src-tauri/src/lib.rs +++ b/app/src-tauri/src/lib.rs @@ -1,4 +1,6 @@ mod ai; +mod backup; +mod sync; mod project; use project::{Document, Project, Registry}; @@ -84,7 +86,10 @@ fn create_project( #[tauri::command] fn save_project(project: Project) -> ApiResponse<()> { match project.save() { - Ok(()) => ApiResponse::success(()), + Ok(()) => { + sync::service::nudge(&project.id); + ApiResponse::success(()) + } Err(e) => ApiResponse::error(e), } } @@ -101,7 +106,10 @@ fn rename_project(project_id: String, name: String) -> ApiResponse { Ok(mut project) => { project.name = name; match project.save() { - Ok(()) => ApiResponse::success(project), + Ok(()) => { + sync::service::nudge(&project.id); + ApiResponse::success(project) + } Err(e) => ApiResponse::error(e), } } @@ -120,7 +128,11 @@ fn delete_project(project_id: String, delete_files: Option) -> ApiResponse } } match Registry::remove(&project_id) { - Ok(()) => ApiResponse::success(()), + Ok(()) => { + // A forgotten or deleted project stops syncing on this device (Drive keeps its copy). + sync::service::forget(&project_id); + ApiResponse::success(()) + } Err(e) => ApiResponse::error(e), } } @@ -156,7 +168,10 @@ fn create_document( order.unwrap_or(0), ); match doc.save(&project_id) { - Ok(()) => ApiResponse::success(doc), + Ok(()) => { + sync::service::nudge(&project_id); + ApiResponse::success(doc) + } Err(e) => ApiResponse::error(e), } } @@ -226,12 +241,27 @@ fn save_asset(request: Request<'_>) -> ApiResponse { } let dest = assets_dir.join(format!("{}.{}", Uuid::new_v4(), safe_ext)); - match fs::write(&dest, &bytes) { - Ok(_) => ApiResponse::success(dest.to_string_lossy().to_string()), - Err(e) => ApiResponse::error(e.to_string()), + match write_bytes_atomic(&dest, &bytes) { + Ok(()) => { + sync::service::nudge(&project_id); + ApiResponse::success(dest.to_string_lossy().to_string()) + } + Err(e) => ApiResponse::error(e), } } +/// Write bytes via a temp file + rename so a crash, or a sync scan, never sees a half-written +/// image. Asset files are treated as immutable once they have their final name. +fn write_bytes_atomic(dest: &std::path::Path, bytes: &[u8]) -> Result<(), String> { + let name = dest.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let tmp = dest.with_file_name(format!(".{name}.{}.tmp", Uuid::new_v4())); + fs::write(&tmp, bytes).map_err(|e| e.to_string())?; + fs::rename(&tmp, dest).map_err(|e| { + let _ = fs::remove_file(&tmp); + e.to_string() + }) +} + /// Write an exported file (e.g. a rendered map PNG) into `/exports/` /// and return its path. Raw body; headers `x-project-id` / `x-name`. #[tauri::command] @@ -259,7 +289,10 @@ fn export_file(request: Request<'_>) -> ApiResponse { #[tauri::command] fn save_document(project_id: String, document: Document) -> ApiResponse<()> { match document.save(&project_id) { - Ok(()) => ApiResponse::success(()), + Ok(()) => { + sync::service::nudge(&project_id); + ApiResponse::success(()) + } Err(e) => ApiResponse::error(e), } } @@ -267,7 +300,10 @@ fn save_document(project_id: String, document: Document) -> ApiResponse<()> { #[tauri::command] fn delete_document(project_id: String, document_id: String) -> ApiResponse<()> { match Document::delete(&project_id, &document_id) { - Ok(()) => ApiResponse::success(()), + Ok(()) => { + sync::service::nudge(&project_id); + ApiResponse::success(()) + } Err(e) => ApiResponse::error(e), } } @@ -280,9 +316,87 @@ fn load_document(project_id: String, document_id: String) -> ApiResponse ApiResponse { + blocking(move || backup::create(&project_id)).await +} + +#[tauri::command] +async fn list_backups() -> ApiResponse> { + blocking(|| Ok(backup::list())).await +} + +#[tauri::command] +async fn delete_backup(path: String) -> ApiResponse<()> { + blocking(move || backup::delete(&path)).await +} + +async fn blocking(f: impl FnOnce() -> Result + Send + 'static) -> ApiResponse { + match tauri::async_runtime::spawn_blocking(f).await { + Ok(Ok(v)) => ApiResponse::success(v), + Ok(Err(e)) => ApiResponse::error(e), + Err(e) => ApiResponse::error(e.to_string()), + } +} + +/// Open a file the writer picked in a dialog: a path on desktop (which the dialog added to the +/// fs scope, so nothing else on disk can be named here), or an Android document URI. +fn open_picked(app: &tauri::AppHandle, picked: &str, write: bool) -> Result { + use tauri_plugin_fs::{FilePath, FsExt, OpenOptions}; + let path: FilePath = picked.parse().map_err(|_| "Invalid file location".to_string())?; + if let FilePath::Path(p) = &path { + if !app.fs_scope().is_allowed(p) { + return Err("Choose the file again".into()); + } + } + let mut options = OpenOptions::new(); + options.read(!write).write(write).create(write).truncate(write); + app.fs().open(path, options).map_err(|e| e.to_string()) +} + +/// Restore reads the archive straight from the chosen file: the bytes never pass through the +/// web view or sit in memory whole, so large projects restore on phones too. +#[tauri::command] +async fn restore_project_backup(app: tauri::AppHandle, path: String) -> ApiResponse { + blocking(move || { + let file = open_picked(&app, &path, false)?; + if file.metadata().map(|m| m.len()).unwrap_or(0) > backup::MAX_ARCHIVE { + return Err("Backup exceeds the 600 MiB archive limit".into()); + } + let project = backup::restore_in(file, &Project::projects_dir())?; + Registry::add(&project).map_err(|e| format!("Restored files at {}; registration failed: {e}", project.get_dir().display()))?; + Ok(project) + }) + .await +} + +/// "Save a copy": file to file in the backend (works with Android's document picker). +#[tauri::command] +async fn save_backup_copy(app: tauri::AppHandle, source: String, destination: String) -> ApiResponse { + blocking(move || { + let mut out = open_picked(&app, &destination, true)?; + backup::copy_to(&source, &mut out) + }) + .await +} + +/// Google's native Drive authorization on Android (Kotlin: `GoogleAuthPlugin`). Desktop signs +/// in through the loopback flow in `sync::drive::auth` instead, so nothing registers there. +fn google_auth_plugin() -> tauri::plugin::TauriPlugin { + tauri::plugin::Builder::new("google-auth") + .setup(|_app, _api| { + #[cfg(target_os = "android")] + _api.register_android_plugin("com.mnemoscript.app", "GoogleAuthPlugin")?; + Ok(()) + }) + .build() +} + #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() + .plugin(google_auth_plugin()) .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_fs::init()) .setup(|app| { @@ -306,6 +420,8 @@ pub fn run() { }; fs::create_dir_all(&base).ok(); project::init_data_dir(base); + // MnemoSync worker: idle until the writer connects Google Drive and picks projects. + sync::service::start(app.handle().clone()); // Phone pairing listens again at launch if the writer turned it on (desktop only). #[cfg(desktop)] ai::pair_server::autostart(); @@ -334,6 +450,27 @@ pub fn run() { export_file, select_directory, open_project_by_path, + backup_project, + restore_project_backup, + list_backups, + delete_backup, + save_backup_copy, + sync::service::sync_status, + sync::service::drive_sign_in, + sync::service::drive_cancel_sign_in, + sync::service::drive_set_access_token, + sync::service::drive_sign_out, + sync::service::sync_enable_project, + sync::service::sync_disable_project, + sync::service::drive_remote_projects, + sync::service::drive_usage, + sync::service::sync_download_project, + sync::service::sync_now, + sync::service::sync_set_active, + sync::service::sync_apply_staged, + sync::service::sync_conflict, + sync::service::sync_resolve_conflict, + sync::service::sync_dismiss_notice, ai::commands::list_ai_sessions, ai::commands::load_ai_session, ai::commands::save_ai_session, diff --git a/app/src-tauri/src/project.rs b/app/src-tauri/src/project.rs index 65d9167..78995af 100644 --- a/app/src-tauri/src/project.rs +++ b/app/src-tauri/src/project.rs @@ -38,6 +38,15 @@ pub fn write_atomic(path: &Path, contents: &str) -> Result<(), String> { Ok(()) } +/// Serialises read-modify-write of project files between the app's own saves and the sync +/// engine, so the engine's "is the file still what I scanned?" check and its write are one +/// step and a save can never land in between. Writes are short; one lock for all projects. +static FILES_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +pub fn files_lock() -> std::sync::MutexGuard<'static, ()> { + FILES_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +} + /// A filesystem-safe folder name derived from a project name. pub fn safe_dir_name(name: &str) -> String { let cleaned: String = name @@ -241,7 +250,10 @@ impl Project { }; let metadata_path = project_dir.join("project.json"); let metadata_json = serde_json::to_string_pretty(&snapshot).map_err(|e| e.to_string())?; - write_atomic(&metadata_path, &metadata_json)?; + { + let _files = files_lock(); + write_atomic(&metadata_path, &metadata_json)?; + } // Add to global project registry Registry::add(self)?; @@ -360,6 +372,7 @@ impl Document { fs::create_dir_all(&doc_dir).map_err(|e| e.to_string())?; let doc_path = doc_dir.join(format!("{}.json", self.id)); let doc_json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?; + let _files = files_lock(); write_atomic(&doc_path, &doc_json) } @@ -381,6 +394,7 @@ impl Document { let doc_path = project_dir .join("documents") .join(format!("{}.json", document_id)); + let _files = files_lock(); if doc_path.exists() { fs::remove_file(doc_path).map_err(|e| e.to_string())?; } diff --git a/app/src-tauri/src/sync/drive/api.rs b/app/src-tauri/src/sync/drive/api.rs new file mode 100644 index 0000000..1132b83 --- /dev/null +++ b/app/src-tauri/src/sync/drive/api.rs @@ -0,0 +1,695 @@ +//! Google Drive transport over the hidden `appDataFolder`. +//! +//! Nothing on Drive is ever edited in place except a device's own small catalogue entry. +//! Files (flat names; `appProperties` carry the query keys): +//! `mnemo-b--` gzip blob: chapter text or image bytes +//! `mnemo-o---` gzip JSON batch of revisions (the commit marker) +//! `mnemo-i--` JSON catalogue entry (project name, device name) +//! Blobs are uploaded before the batch that references them. New batches are found through the +//! Drive changes feed (one cursor per account), with a full listing as the fallback. +use super::super::engine::{Transport, TransportError}; +use super::super::model::{self, Batch}; +use super::super::store::Store; +use super::auth; +use flate2::read::GzDecoder; +use flate2::write::GzEncoder; +use reqwest::blocking::{Client, RequestBuilder, Response}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::io::{Read, Write}; +use std::time::Duration; + +const FILES: &str = "https://www.googleapis.com/drive/v3/files"; +const UPLOAD: &str = "https://www.googleapis.com/upload/drive/v3/files"; +const CHANGES: &str = "https://www.googleapis.com/drive/v3/changes"; +const ABOUT: &str = "https://www.googleapis.com/drive/v3/about"; +/// Above this, use a resumable upload session (Drive's multipart limit is 5 MB). +const SIMPLE_LIMIT: usize = 4 * 1024 * 1024; +/// Hard ceiling on any decompressed download (defends against decompression bombs). +const MAX_DOWNLOAD: u64 = 256 * 1024 * 1024; + +#[derive(Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct DriveFile { + pub id: String, + #[serde(default)] + pub app_properties: std::collections::BTreeMap, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct FileList { + #[serde(default)] + files: Vec, + next_page_token: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Change { + #[serde(default)] + removed: bool, + file: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct ChangeList { + #[serde(default)] + changes: Vec, + next_page_token: Option, + new_start_page_token: Option, +} + +#[derive(Serialize, Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Account { + pub id: String, + pub email: String, + pub name: String, +} + +#[derive(Serialize, Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct RemoteProject { + pub project_id: String, + pub name: String, + pub device_name: String, + pub updated_at: String, +} + +/// Map an HTTP failure to the engine's error classes. Pure, so it is unit tested. +pub fn classify(status: u16, body: &str) -> TransportError { + // Google uses two error shapes: the classic `error.errors[].reason` and the newer + // `error.details[].reason` (google.rpc.ErrorInfo, e.g. SERVICE_DISABLED). Read both. + let parsed = serde_json::from_str::(body).ok(); + let reason = parsed + .as_ref() + .and_then(|v| { + v.pointer("/error/errors/0/reason").and_then(Value::as_str).or_else(|| { + v.pointer("/error/details") + .and_then(Value::as_array) + .and_then(|d| d.iter().find_map(|e| e.get("reason").and_then(Value::as_str))) + }) + }) + .map(String::from) + .unwrap_or_default(); + match (status, reason.as_str()) { + (401, _) => TransportError::Auth("Google Drive sign-in expired".into()), + // Seen on first setup: the OAuth client works but its Cloud project lacks the Drive API. + // Only whoever built the app can fix it, so a release build says less. + (403, "accessNotConfigured" | "SERVICE_DISABLED") => TransportError::Other(if cfg!(debug_assertions) { + "The Google Drive API isn't enabled in this app's Google Cloud project. Enable it in the Cloud console, wait a minute, then connect again.".into() + } else { + "Drive sync isn't set up correctly in this build of MnemoScript. Your projects are safe on this device.".into() + }), + (403, "storageQuotaExceeded") => TransportError::Quota("Your Google Drive storage is full".into()), + (403, "rateLimitExceeded" | "userRateLimitExceeded" | "backendError") | (429, _) => TransportError::Busy("Google Drive asked MnemoScript to slow down".into()), + (403, "insufficientPermissions" | "insufficientScopes" | "appNotAuthorizedToFile") => { + TransportError::Auth("MnemoScript no longer has access to its Drive folder".into()) + } + (500..=599, _) => TransportError::Busy(format!("Google Drive is temporarily unavailable ({status})")), + _ => TransportError::Other(format!("Google Drive request failed ({status}{})", if reason.is_empty() { String::new() } else { format!(": {reason}") })), + } +} + +/// The change feed answers an old or unknown cursor with 400/404/410; the caller then falls +/// back to a full listing. Decided by status, never by message wording. +pub fn cursor_expired(status: u16) -> bool { + matches!(status, 400 | 404 | 410) +} + +fn net(e: reqwest::Error) -> TransportError { + if e.is_connect() || e.is_timeout() || e.is_request() { + TransportError::Offline("Can't reach Google Drive".into()) + } else { + TransportError::Other(e.to_string()) + } +} + +fn auth_err(e: auth::AuthError) -> TransportError { + match e { + auth::AuthError::Revoked(m) => TransportError::Auth(m), + auth::AuthError::Network(_) => TransportError::Offline("Can't reach Google".into()), + auth::AuthError::Other(m) => TransportError::Auth(m), + } +} + +pub fn gzip(bytes: &[u8]) -> Vec { + let mut e = GzEncoder::new(Vec::new(), flate2::Compression::default()); + e.write_all(bytes).expect("in-memory gzip"); + e.finish().expect("in-memory gzip") +} + +pub fn gunzip(bytes: &[u8]) -> Result, TransportError> { + let mut out = Vec::new(); + GzDecoder::new(bytes) + .take(MAX_DOWNLOAD + 1) + .read_to_end(&mut out) + .map_err(|_| TransportError::Other("A Drive file is damaged".into()))?; + if out.len() as u64 > MAX_DOWNLOAD { + return Err(TransportError::Other("A Drive file is too large".into())); + } + Ok(out) +} + +/// Drive query for files with all of the given app properties. Values are validated ids. +pub fn query(props: &[(&str, &str)]) -> String { + props + .iter() + .map(|(k, v)| format!("appProperties has {{ key='{k}' and value='{}' }}", v.replace(['\\', '\''], ""))) + .collect::>() + .join(" and ") +} + +pub struct Drive { + http: Client, +} + +impl Default for Drive { + fn default() -> Self { + Self::new() + } +} + +impl Drive { + pub fn new() -> Self { + Drive { + http: Client::builder() + .timeout(Duration::from_secs(120)) + .connect_timeout(Duration::from_secs(15)) + .user_agent("MnemoScript") + .build() + .expect("HTTP client"), + } + } + + /// Send with a bearer token; on 401 refresh once and retry. Any other status is returned. + fn send_raw(&self, build: &dyn Fn(&Client) -> RequestBuilder) -> Result { + for attempt in 0..2 { + let token = auth::access_token(attempt > 0).map_err(auth_err)?; + let response = build(&self.http).bearer_auth(token).send().map_err(net)?; + if response.status().as_u16() == 401 && attempt == 0 { + auth::forget_access(); + continue; + } + return Ok(response); + } + Err(TransportError::Auth("Google Drive sign-in expired".into())) + } + + /// `send_raw`, with failures (other than 404) classified. + fn send(&self, build: &dyn Fn(&Client) -> RequestBuilder) -> Result { + let response = self.send_raw(build)?; + let status = response.status().as_u16(); + if response.status().is_success() || status == 404 { + return Ok(response); + } + let body = response.text().unwrap_or_default(); + Err(classify(status, &body)) + } + + fn json Deserialize<'de>>(&self, build: &dyn Fn(&Client) -> RequestBuilder) -> Result, TransportError> { + let r = self.send(build)?; + if r.status().as_u16() == 404 { + return Ok(None); + } + r.json().map(Some).map_err(|e| TransportError::Other(e.to_string())) + } + + pub fn about(&self) -> Result { + let v: Value = self + .json(&|c| c.get(ABOUT).query(&[("fields", "user(displayName,emailAddress,permissionId)")]))? + .ok_or_else(|| TransportError::Other("Drive account not found".into()))?; + let user = &v["user"]; + let id = user["permissionId"].as_str().ok_or_else(|| TransportError::Other("Drive did not identify the account".into()))?; + Ok(Account { + id: id.into(), + email: user["emailAddress"].as_str().unwrap_or_default().into(), + name: user["displayName"].as_str().unwrap_or_default().into(), + }) + } + + pub fn list(&self, q: &str) -> Result, TransportError> { + let mut out = Vec::new(); + let mut page: Option = None; + loop { + let token = page.clone(); + let list: FileList = self + .json(&|c| { + let mut r = c.get(FILES).query(&[ + ("spaces", "appDataFolder"), + ("q", q), + ("pageSize", "1000"), + ("fields", "nextPageToken,files(id,appProperties)"), + ]); + if let Some(t) = &token { + r = r.query(&[("pageToken", t.as_str())]); + } + r + })? + .ok_or_else(|| TransportError::Other("Drive listing failed".into()))?; + out.extend(list.files); + match list.next_page_token { + Some(t) => page = Some(t), + None => return Ok(out), + } + } + } + + pub fn download(&self, id: &str) -> Result>, TransportError> { + let url = format!("{FILES}/{id}"); + let r = self.send(&|c| c.get(&url).query(&[("alt", "media")]))?; + if r.status().as_u16() == 404 { + return Ok(None); + } + let mut bytes = Vec::new(); + r.take(MAX_DOWNLOAD + 1).read_to_end(&mut bytes).map_err(|e| TransportError::Offline(e.to_string()))?; + Ok(Some(bytes)) + } + + pub fn create(&self, name: &str, props: Value, bytes: &[u8], mime: &str) -> Result { + let meta = json!({"name": name, "parents": ["appDataFolder"], "appProperties": props}); + let v: Value = if bytes.len() <= SIMPLE_LIMIT { + let boundary = format!("mnemo{}", uuid::Uuid::new_v4().simple()); + let mut body = Vec::with_capacity(bytes.len() + 512); + body.extend_from_slice(format!("--{boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n{meta}\r\n--{boundary}\r\nContent-Type: {mime}\r\n\r\n").as_bytes()); + body.extend_from_slice(bytes); + body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes()); + self.json(&|c| { + c.post(UPLOAD) + .query(&[("uploadType", "multipart"), ("fields", "id")]) + .header("Content-Type", format!("multipart/related; boundary={boundary}")) + .body(body.clone()) + })? + } else { + let session = self.send(&|c| { + c.post(UPLOAD) + .query(&[("uploadType", "resumable"), ("fields", "id")]) + .header("X-Upload-Content-Type", mime) + .json(&meta) + })?; + let location = session + .headers() + .get("location") + .and_then(|l| l.to_str().ok()) + .ok_or_else(|| TransportError::Other("Drive did not start the upload".into()))? + .to_string(); + self.json(&|c| c.put(&location).header("Content-Type", mime).body(bytes.to_vec()))? + } + .ok_or_else(|| TransportError::Other("Drive upload failed".into()))?; + v["id"].as_str().map(String::from).ok_or_else(|| TransportError::Other("Drive upload returned no id".into())) + } + + pub fn update(&self, id: &str, bytes: &[u8], mime: &str) -> Result { + let url = format!("{UPLOAD}/{id}"); + let r = self.send(&|c| c.patch(&url).query(&[("uploadType", "media")]).header("Content-Type", mime).body(bytes.to_vec()))?; + Ok(r.status().as_u16() != 404) + } + + /// Remove one of MnemoScript's own app-folder files (used by the live test to clean up). + #[cfg(test)] + pub fn delete(&self, id: &str) -> Result<(), TransportError> { + let url = format!("{FILES}/{id}"); + self.send(&|c| c.delete(&url)).map(|_| ()) + } + + pub fn start_page_token(&self) -> Result { + let v: Value = self + .json(&|c| c.get(format!("{CHANGES}/startPageToken")))? + .ok_or_else(|| TransportError::Other("Drive changes are unavailable".into()))?; + v["startPageToken"].as_str().map(String::from).ok_or_else(|| TransportError::Other("Drive returned no change cursor".into())) + } + + /// New/changed files since `token`, and the cursor to continue from. `Ok(None)` when the + /// cursor is no longer valid (the caller falls back to a full listing). + pub fn changes(&self, token: &str) -> Result, String)>, TransportError> { + let mut files = Vec::new(); + let mut page = token.to_string(); + loop { + let current = page.clone(); + let r = self.send_raw(&|c| { + c.get(CHANGES).query(&[ + ("pageToken", current.as_str()), + ("spaces", "appDataFolder"), + ("pageSize", "1000"), + ("fields", "nextPageToken,newStartPageToken,changes(removed,file(id,appProperties))"), + ]) + })?; + let status = r.status().as_u16(); + if cursor_expired(status) { + return Ok(None); + } + if !r.status().is_success() { + return Err(classify(status, &r.text().unwrap_or_default())); + } + let list: ChangeList = r.json().map_err(|e| TransportError::Other(e.to_string()))?; + files.extend(list.changes.into_iter().filter(|c| !c.removed).filter_map(|c| c.file)); + if let Some(next) = list.next_page_token { + page = next; + continue; + } + return Ok(Some((files, list.new_start_page_token.unwrap_or(page)))); + } + } + + // ---- catalogue ------------------------------------------------------------------------- + + pub fn remote_projects(&self) -> Result, TransportError> { + let mut by_project: std::collections::BTreeMap = Default::default(); + for f in self.list(&query(&[("m", "1"), ("k", "i")]))? { + let Some(bytes) = self.download(&f.id)? else { continue }; + let Ok(entry) = serde_json::from_slice::(&bytes) else { continue }; + if !model::safe_id(&entry.project_id) || f.app_properties.get("p") != Some(&entry.project_id) { + continue; + } + let newer = by_project.get(&entry.project_id).is_none_or(|e| e.updated_at < entry.updated_at); + if newer { + by_project.insert(entry.project_id.clone(), entry); + } + } + Ok(by_project.into_values().collect()) + } + + /// Create or refresh this device's catalogue entry for a project. `published` = this round + /// sent changes; the entry's date then moves forward (at most hourly, to spare requests), so + /// "last synced from" in the download list is current, not the first sync. + pub fn publish_info(&self, store: &Store, project_id: &str, name: &str, device_id: &str, device_name: &str, published: bool) -> Result<(), TransportError> { + let now = chrono::Utc::now(); + let entry = RemoteProject { + project_id: project_id.into(), + name: name.into(), + device_name: device_name.into(), + updated_at: now.to_rfc3339(), + }; + let bytes = serde_json::to_vec(&entry).map_err(|e| TransportError::Other(e.to_string()))?; + let key = format!("drive.info.{project_id}"); + let recent = store + .get_meta(&format!("{key}.at"))? + .and_then(|at| chrono::DateTime::parse_from_rfc3339(&at).ok()) + .is_some_and(|at| now.signed_duration_since(at) < chrono::Duration::hours(1)); + if store.get_meta(&format!("{key}.name"))?.as_deref() == Some(name) && (!published || recent) { + return Ok(()); + } + let done = |id: Option<&str>| -> Result<(), TransportError> { + if let Some(id) = id { + store.set_meta(&key, id)?; + } + store.set_meta(&format!("{key}.name"), name)?; + store.set_meta(&format!("{key}.at"), &now.to_rfc3339())?; + Ok(()) + }; + if let Some(id) = store.get_meta(&key)? { + if self.update(&id, &bytes, "application/json")? { + return done(None); + } + } + let id = self.create( + &format!("mnemo-i-{project_id}-{device_id}"), + json!({"m": "1", "k": "i", "p": project_id, "d": device_id}), + &bytes, + "application/json", + )?; + done(Some(&id)) + } + + /// Bytes MnemoScript keeps in the writer's Drive (its hidden app folder, every device and + /// project together). Old revisions are not pruned yet, so this only grows; the settings + /// card shows it so a full Drive is never a surprise. + pub fn usage(&self) -> Result { + let mut total = 0u64; + let mut page: Option = None; + loop { + let token = page.clone(); + let v: Value = self + .json(&|c| { + let mut r = c.get(FILES).query(&[("spaces", "appDataFolder"), ("pageSize", "1000"), ("fields", "nextPageToken,files(size)")]); + if let Some(t) = &token { + r = r.query(&[("pageToken", t.as_str())]); + } + r + })? + .ok_or_else(|| TransportError::Other("Drive listing failed".into()))?; + total += v["files"] + .as_array() + .into_iter() + .flatten() + .filter_map(|f| f["size"].as_str().and_then(|s| s.parse::().ok())) + .sum::(); + match v["nextPageToken"].as_str() { + Some(t) => page = Some(t.to_string()), + None => return Ok(total), + } + } + } +} + +/// Remember batch files found on Drive (from the change feed or a listing). +fn record_batches(store: &Store, files: &[DriveFile]) -> Result<(), String> { + for f in files { + let p = &f.app_properties; + if p.get("m").map(String::as_str) != Some("1") || p.get("k").map(String::as_str) != Some("o") { + continue; + } + let (Some(project), Some(device), Some(seq)) = (p.get("p"), p.get("d"), p.get("s").and_then(|s| s.parse::().ok())) else { continue }; + if !model::safe_id(project) || !model::safe_id(device) { + continue; + } + // The first file wins for a (device, seq): a retried upload's duplicate is ignored. + store + .conn + .execute( + "INSERT OR IGNORE INTO drive_files (project_id, device, seq, file_id) VALUES (?1, ?2, ?3, ?4)", + rusqlite::params![project, device, seq as i64, f.id], + ) + .map_err(|e| e.to_string())?; + } + Ok(()) +} + +pub fn ensure_tables(store: &Store) -> Result<(), String> { + store + .conn + .execute_batch( + "CREATE TABLE IF NOT EXISTS drive_files (project_id TEXT NOT NULL, device TEXT NOT NULL, seq INTEGER NOT NULL, file_id TEXT NOT NULL, PRIMARY KEY (project_id, device, seq)); + CREATE TABLE IF NOT EXISTS drive_blob_ids (project_id TEXT NOT NULL, sha TEXT NOT NULL, file_id TEXT NOT NULL, PRIMARY KEY (project_id, sha));", + ) + .map_err(|e| e.to_string()) +} + +/// Read the change feed once per round for every project (one cheap request when idle). +pub fn refresh_changes(drive: &Drive, store: &Store, account: &str) -> Result<(), TransportError> { + ensure_tables(store)?; + let key = format!("drive.cursor.{account}"); + match store.get_meta(&key)? { + None => { + // Take the cursor *before* any listing so nothing published meanwhile is missed. + let token = drive.start_page_token()?; + store.set_meta(&key, &token)?; + } + Some(token) => match drive.changes(&token)? { + Some((files, next)) => { + record_batches(store, &files)?; + store.set_meta(&key, &next)?; + } + None => { + // The cursor expired: start again and re-list every synced project. + store.delete_meta(&key)?; + store.conn.execute("DELETE FROM meta WHERE key LIKE 'drive.listed.%'", []).map_err(|e| e.to_string())?; + let token = drive.start_page_token()?; + store.set_meta(&key, &token)?; + } + }, + } + Ok(()) +} + +pub struct DriveTransport<'a> { + pub drive: &'a Drive, + pub store: &'a Store, + pub device_id: String, +} + +impl DriveTransport<'_> { + fn blob_file(&mut self, project_id: &str, sha: &str) -> Result, TransportError> { + let cached: Option = self + .store + .conn + .query_row("SELECT file_id FROM drive_blob_ids WHERE project_id = ?1 AND sha = ?2", [project_id, sha], |r| r.get(0)) + .ok(); + if cached.is_some() { + return Ok(cached); + } + let found = self.drive.list(&query(&[("k", "b"), ("p", project_id), ("h", sha)]))?.into_iter().next().map(|f| f.id); + if let Some(id) = &found { + self.store + .conn + .execute("INSERT OR IGNORE INTO drive_blob_ids (project_id, sha, file_id) VALUES (?1, ?2, ?3)", [project_id, sha, id]) + .map_err(|e| TransportError::Other(e.to_string()))?; + } + Ok(found) + } +} + +impl Transport for DriveTransport<'_> { + fn id(&self) -> &'static str { + "drive" + } + + fn has_blob(&mut self, project_id: &str, sha: &str) -> Result { + Ok(self.blob_file(project_id, sha)?.is_some()) + } + + fn put_blob(&mut self, project_id: &str, sha: &str, bytes: &[u8]) -> Result<(), TransportError> { + let id = self.drive.create( + &format!("mnemo-b-{project_id}-{sha}"), + json!({"m": "1", "k": "b", "p": project_id, "h": sha}), + &gzip(bytes), + "application/gzip", + )?; + self.store + .conn + .execute("INSERT OR IGNORE INTO drive_blob_ids (project_id, sha, file_id) VALUES (?1, ?2, ?3)", [project_id, sha, &id]) + .map_err(|e| TransportError::Other(e.to_string()))?; + Ok(()) + } + + fn get_blob(&mut self, project_id: &str, sha: &str) -> Result>, TransportError> { + let Some(id) = self.blob_file(project_id, sha)? else { return Ok(None) }; + match self.drive.download(&id)? { + Some(bytes) => gunzip(&bytes).map(Some), + None => { + self.store.conn.execute("DELETE FROM drive_blob_ids WHERE file_id = ?1", [&id]).map_err(|e| TransportError::Other(e.to_string()))?; + Ok(None) + } + } + } + + fn put_batch(&mut self, batch: &Batch) -> Result<(), TransportError> { + let seq = batch.seq.to_string(); + let props = [("k", "o"), ("p", batch.project_id.as_str()), ("d", batch.device_id.as_str()), ("s", seq.as_str())]; + // A retry after a lost reply must not publish a second copy. + if !self.drive.list(&query(&props))?.is_empty() { + return Ok(()); + } + let body = serde_json::to_vec(batch).map_err(|e| TransportError::Other(e.to_string()))?; + self.drive.create( + &format!("mnemo-o-{}-{}-{:08}", batch.project_id, batch.device_id, batch.seq), + json!({"m": "1", "k": "o", "p": batch.project_id, "d": batch.device_id, "s": seq}), + &gzip(&body), + "application/gzip", + )?; + Ok(()) + } + + fn pull(&mut self, project_id: &str, seen: &dyn Fn(&str, u64) -> bool) -> Result, TransportError> { + ensure_tables(self.store)?; + let listed = format!("drive.listed.{project_id}"); + if self.store.get_meta(&listed)?.is_none() { + let files = self.drive.list(&query(&[("m", "1"), ("k", "o"), ("p", project_id)]))?; + record_batches(self.store, &files)?; + self.store.set_meta(&listed, "1")?; + } + let rows: Vec<(String, i64, String)> = { + let mut stmt = self + .store + .conn + .prepare("SELECT device, seq, file_id FROM drive_files WHERE project_id = ?1 ORDER BY device, seq") + .map_err(|e| TransportError::Other(e.to_string()))?; + let rows = stmt + .query_map([project_id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))) + .map_err(|e| TransportError::Other(e.to_string()))?; + rows.collect::>().map_err(|e| TransportError::Other(e.to_string()))? + }; + let mut out = Vec::new(); + for (device, seq, file) in rows { + if device == self.device_id || seen(&device, seq as u64) { + continue; + } + let Some(bytes) = self.drive.download(&file)? else { + self.store.conn.execute("DELETE FROM drive_files WHERE file_id = ?1", [&file]).map_err(|e| TransportError::Other(e.to_string()))?; + continue; + }; + match serde_json::from_slice::(&gunzip(&bytes)?) { + Ok(b) if b.device_id == device && b.seq == seq as u64 && b.project_id == project_id => out.push(b), + // A file whose content contradicts its labels is ignored, never applied. + _ => log::warn!("ignoring malformed sync batch {file}"), + } + } + Ok(out) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn errors_map_to_actionable_states() { + let quota = r#"{"error":{"errors":[{"reason":"storageQuotaExceeded"}],"code":403}}"#; + let rate = r#"{"error":{"errors":[{"reason":"userRateLimitExceeded"}],"code":403}}"#; + assert!(matches!(classify(403, quota), TransportError::Quota(_))); + assert!(matches!(classify(403, rate), TransportError::Busy(_))); + assert!(matches!(classify(429, ""), TransportError::Busy(_))); + assert!(matches!(classify(503, ""), TransportError::Busy(_))); + assert!(matches!(classify(401, ""), TransportError::Auth(_))); + assert!(matches!(classify(400, "{}"), TransportError::Other(_))); + // Regression (2026-11-13, first live setup): a disabled Drive API showed a raw reason code. + let disabled = r#"{"error":{"errors":[{"reason":"accessNotConfigured"}],"code":403}}"#; + assert!(classify(403, disabled).to_string().contains("Google Drive API isn't enabled")); + // Regression (PR #4 review): the newer error shape carries the reason in `details`. + let newer = r#"{"error":{"code":403,"status":"PERMISSION_DENIED","message":"Drive API has not been used", + "details":[{"@type":"type.googleapis.com/google.rpc.Help"},{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"SERVICE_DISABLED","domain":"googleapis.com"}]}}"#; + assert!(classify(403, newer).to_string().contains("Google Drive API isn't enabled")); + let full = r#"{"error":{"code":403,"details":[{"reason":"storageQuotaExceeded"}]}}"#; + assert!(matches!(classify(403, full), TransportError::Quota(_))); + } + + /// Regression (PR #4 review): an expired change cursor was recognised by matching "(400" in + /// an error message, so a wording change would have disabled the listing fallback. + #[test] + fn an_expired_change_cursor_is_recognised_by_status() { + for status in [400, 404, 410] { + assert!(cursor_expired(status)); + } + for status in [200, 401, 403, 429, 500] { + assert!(!cursor_expired(status)); + } + } + + #[test] + fn queries_escape_values_and_target_app_properties() { + assert_eq!(query(&[("k", "o"), ("p", "a'b")]), "appProperties has { key='k' and value='o' } and appProperties has { key='p' and value='ab' }"); + } + + #[test] + fn gzip_round_trips_and_rejects_garbage() { + let data = b"

The bells rang at dawn.

".repeat(100); + let packed = gzip(&data); + assert!(packed.len() < data.len()); + assert_eq!(gunzip(&packed).unwrap(), data); + assert!(gunzip(b"not gzip").is_err()); + } + + #[test] + fn duplicate_batch_files_keep_the_first_and_ignore_foreign_labels() { + let store = Store::memory(); + ensure_tables(&store).unwrap(); + let file = |id: &str, props: &[(&str, &str)]| DriveFile { + id: id.into(), + app_properties: props.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(), + }; + record_batches( + &store, + &[ + file("f1", &[("m", "1"), ("k", "o"), ("p", "proj"), ("d", "dev"), ("s", "1")]), + file("f2", &[("m", "1"), ("k", "o"), ("p", "proj"), ("d", "dev"), ("s", "1")]), + file("f3", &[("m", "1"), ("k", "o"), ("p", "../x"), ("d", "dev"), ("s", "2")]), + file("f4", &[("m", "1"), ("k", "b"), ("p", "proj"), ("h", "abc")]), + ], + ) + .unwrap(); + let ids: Vec = store.conn.prepare("SELECT file_id FROM drive_files").unwrap().query_map([], |r| r.get(0)).unwrap().map(Result::unwrap).collect(); + assert_eq!(ids, vec!["f1".to_string()]); + } +} diff --git a/app/src-tauri/src/sync/drive/auth.rs b/app/src-tauri/src/sync/drive/auth.rs new file mode 100644 index 0000000..d30805a --- /dev/null +++ b/app/src-tauri/src/sync/drive/auth.rs @@ -0,0 +1,405 @@ +//! Google sign-in for Drive sync. +//! +//! * Desktop: OAuth 2.0 authorization code + PKCE (S256) with a loopback redirect on +//! `127.0.0.1:`, in the writer's own browser. MnemoScript never sees the Google +//! password. The refresh token goes to the OS secret store (as AI keys do); access tokens +//! live only in memory. +//! * Android: Google's native authorization API supplies short-lived access tokens through the +//! app (`set_access_token`); no refresh token is stored on the phone. +//! +//! Only the `drive.appdata` scope is requested: MnemoScript's own hidden Drive folder, never +//! the writer's other files. +// The loopback flow (PKCE, redirect parsing, the browser page) is desktop-only. +#![cfg_attr(not(desktop), allow(dead_code))] +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine as _; +use serde::Deserialize; +use sha2::{Digest, Sha256}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +pub const SCOPE: &str = "https://www.googleapis.com/auth/drive.appdata"; +const AUTH_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth"; +const TOKEN_URL: &str = "https://oauth2.googleapis.com/token"; +const REVOKE_URL: &str = "https://oauth2.googleapis.com/revoke"; + +/// The OAuth client this build was configured with (see `build.rs` / `.env.local.example`). +pub fn client_id() -> Option<&'static str> { + option_env!("MNEMO_GOOGLE_CLIENT_ID").filter(|v| !v.is_empty()) +} + +fn client_secret() -> Option<&'static str> { + option_env!("MNEMO_GOOGLE_CLIENT_SECRET").filter(|v| !v.is_empty()) +} + +/// Why Drive sync cannot be offered on this platform at all, whatever the build's client id. +/// Linux: `keyring` is built without a Linux backend, so the refresh token would not persist +/// and the writer would have to sign in again every hour. Off until a secret store is wired up. +pub fn unavailable_reason() -> Option<&'static str> { + if cfg!(target_os = "linux") { + Some("Google Drive sync isn't available on Linux yet: MnemoScript can't keep your Google sign-in securely there.") + } else { + None + } +} + +/// Whether this build can sign in to Google at all. +pub fn configured() -> bool { + if unavailable_reason().is_some() { + return false; + } + if cfg!(any(target_os = "android", target_os = "ios")) { + // Android authorizes by package name + signing certificate; no client id is compiled in. + cfg!(target_os = "android") + } else { + client_id().is_some() + } +} + +#[derive(Debug)] +pub enum AuthError { + /// The grant is gone (revoked, expired, password changed): the writer must sign in again. + Revoked(String), + Network(String), + Other(String), +} + +impl std::fmt::Display for AuthError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + AuthError::Revoked(m) | AuthError::Network(m) | AuthError::Other(m) => f.write_str(m), + } + } +} + +struct Access { + token: String, + expires: Instant, +} + +static ACCESS: Mutex> = Mutex::new(None); +static CANCEL: AtomicBool = AtomicBool::new(false); + +fn lock() -> std::sync::MutexGuard<'static, Option> { + ACCESS.lock().unwrap_or_else(|p| p.into_inner()) +} + +pub fn forget_access() { + *lock() = None; +} + +/// Android: the app obtained a fresh access token from Google's authorization API. +pub fn set_access_token(token: &str, expires_in: u64) { + *lock() = Some(Access { token: token.into(), expires: Instant::now() + Duration::from_secs(expires_in.saturating_sub(60)) }); +} + +/// A valid access token, refreshing it from the stored grant when needed. +pub fn access_token(force_refresh: bool) -> Result { + if !force_refresh { + if let Some(a) = lock().as_ref() { + if a.expires > Instant::now() { + return Ok(a.token.clone()); + } + } + } + let Some(refresh) = secret::get()? else { + return Err(AuthError::Revoked("Sign in to Google Drive to sync".into())); + }; + let (token, expires_in) = refresh_access(&refresh)?; + set_access_token(&token, expires_in); + Ok(token) +} + +#[derive(Deserialize)] +struct TokenResponse { + access_token: String, + #[serde(default)] + expires_in: u64, + refresh_token: Option, +} + +#[derive(Deserialize)] +struct TokenError { + error: String, + #[serde(default)] + error_description: String, +} + +fn http() -> reqwest::blocking::Client { + reqwest::blocking::Client::builder() + .timeout(Duration::from_secs(30)) + .user_agent("MnemoScript") + .build() + .expect("HTTP client") +} + +fn token_request(form: &[(&str, &str)]) -> Result { + let response = http().post(TOKEN_URL).form(form).send().map_err(|e| AuthError::Network(e.to_string()))?; + let status = response.status(); + let body = response.text().map_err(|e| AuthError::Network(e.to_string()))?; + if status.is_success() { + return serde_json::from_str(&body).map_err(|e| AuthError::Other(e.to_string())); + } + let detail: Option = serde_json::from_str(&body).ok(); + match detail { + Some(e) if e.error == "invalid_grant" => Err(AuthError::Revoked("Google sign-in expired; sign in again".into())), + Some(e) => Err(AuthError::Other(format!("Google sign-in failed: {} {}", e.error, e.error_description).trim().to_string())), + None if status.is_server_error() => Err(AuthError::Network(format!("Google sign-in is unavailable ({status})"))), + None => Err(AuthError::Other(format!("Google sign-in failed ({status})"))), + } +} + +fn refresh_access(refresh: &str) -> Result<(String, u64), AuthError> { + let id = client_id().ok_or_else(|| AuthError::Other("Drive sync is not configured in this build".into()))?; + let mut form = vec![("client_id", id), ("refresh_token", refresh), ("grant_type", "refresh_token")]; + if let Some(secret) = client_secret() { + form.push(("client_secret", secret)); + } + let t = token_request(&form)?; + Ok((t.access_token, t.expires_in.max(60))) +} + +/// PKCE verifier/challenge pair (RFC 7636): 64 random URL-safe characters, S256 challenge. +pub fn pkce() -> (String, String) { + let mut bytes = Vec::with_capacity(48); + for _ in 0..3 { + bytes.extend_from_slice(uuid::Uuid::new_v4().as_bytes()); + } + let verifier = URL_SAFE_NO_PAD.encode(&bytes); + let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())); + (verifier, challenge) +} + +pub fn authorize_url(client_id: &str, redirect: &str, challenge: &str, state: &str) -> String { + let mut url = url::Url::parse(AUTH_URL).expect("static URL"); + url.query_pairs_mut() + .append_pair("client_id", client_id) + .append_pair("redirect_uri", redirect) + .append_pair("response_type", "code") + .append_pair("scope", SCOPE) + .append_pair("code_challenge", challenge) + .append_pair("code_challenge_method", "S256") + .append_pair("state", state) + .append_pair("access_type", "offline") + .append_pair("prompt", "consent"); + url.into() +} + +/// What one request to the loopback port means for the sign-in in progress. +#[derive(Debug, PartialEq)] +pub enum Redirect { + /// Not the redirect path (a favicon, a probe): answer 404 and keep waiting. + Ignore, + /// The redirect path without this sign-in's `state` (a browser preconnect, an old tab, + /// another program): refuse it, but keep waiting for the real one. + Foreign, + /// Google's answer to this sign-in: the code, or why there is none. + Finished(Result), +} + +/// Parse a loopback request. A code is accepted only with this sign-in's `state`. +pub fn parse_redirect(path: &str, state: &str) -> Redirect { + let Ok(url) = url::Url::parse(&format!("http://127.0.0.1{path}")) else { return Redirect::Ignore }; + if url.path() != "/" { + return Redirect::Ignore; + } + let get = |k: &str| url.query_pairs().find(|(key, _)| key == k).map(|(_, v)| v.into_owned()); + if get("state").as_deref() != Some(state) { + return Redirect::Foreign; + } + if let Some(e) = get("error") { + return Redirect::Finished(Err(if e == "access_denied" { "Google sign-in was cancelled".into() } else { format!("Google sign-in failed: {e}") })); + } + Redirect::Finished(get("code").ok_or_else(|| "Google did not return an authorization code".into())) +} + +const DONE_PAGE: &str = r#"MnemoScript + +
✓

{{TITLE}}

{{BODY}}

"#; + +fn page(title: &str, body: &str) -> String { + DONE_PAGE.replace("{{TITLE}}", title).replace("{{BODY}}", body) +} + +pub fn cancel_sign_in() { + CANCEL.store(true, Ordering::SeqCst); +} + +/// Desktop sign-in. Blocks until the browser returns, the writer cancels, or 5 minutes pass. +#[cfg(desktop)] +pub fn sign_in() -> Result<(), AuthError> { + let id = client_id().ok_or_else(|| AuthError::Other("Drive sync is not configured in this build".into()))?; + CANCEL.store(false, Ordering::SeqCst); + let server = tiny_http::Server::http("127.0.0.1:0").map_err(|e| AuthError::Other(e.to_string()))?; + let port = server.server_addr().to_ip().map(|a| a.port()).ok_or_else(|| AuthError::Other("No loopback port".into()))?; + let redirect = format!("http://127.0.0.1:{port}"); + let (verifier, challenge) = pkce(); + let state = uuid::Uuid::new_v4().simple().to_string(); + open::that_detached(authorize_url(id, &redirect, &challenge, &state)).map_err(|e| AuthError::Other(format!("Could not open your browser: {e}")))?; + let deadline = Instant::now() + Duration::from_secs(300); + let code = loop { + if CANCEL.load(Ordering::SeqCst) { + return Err(AuthError::Other("Google sign-in was cancelled".into())); + } + if Instant::now() > deadline { + return Err(AuthError::Other("Google sign-in timed out; please try again".into())); + } + let Ok(Some(request)) = server.recv_timeout(Duration::from_millis(400)) else { continue }; + let html = tiny_http::Header::from_bytes(&b"Content-Type"[..], &b"text/html; charset=utf-8"[..]).expect("static header"); + match parse_redirect(request.url(), &state) { + Redirect::Ignore => { + let _ = request.respond(tiny_http::Response::empty(404)); + } + Redirect::Foreign => { + let body = page("This isn't the current sign-in", "Use the Google page MnemoScript just opened, or press Connect again in MnemoScript."); + let _ = request.respond(tiny_http::Response::from_string(body).with_status_code(400).with_header(html)); + } + Redirect::Finished(Ok(code)) => { + let _ = request.respond(tiny_http::Response::from_string(page("You're connected", "Google Drive sync is ready. You can close this tab and return to MnemoScript.")).with_header(html)); + break code; + } + Redirect::Finished(Err(e)) => { + let _ = request.respond(tiny_http::Response::from_string(page("Sign-in didn't finish", &html_escape::encode_text(&e))).with_header(html)); + return Err(AuthError::Other(e)); + } + } + }; + let mut form = vec![ + ("client_id", id), + ("code", code.as_str()), + ("code_verifier", verifier.as_str()), + ("grant_type", "authorization_code"), + ("redirect_uri", redirect.as_str()), + ]; + if let Some(secret) = client_secret() { + form.push(("client_secret", secret)); + } + let tokens = token_request(&form)?; + let refresh = tokens.refresh_token.ok_or_else(|| AuthError::Other("Google did not grant offline access; please sign in again".into()))?; + secret::set(&refresh)?; + set_access_token(&tokens.access_token, tokens.expires_in.max(60)); + Ok(()) +} + +#[cfg(not(desktop))] +pub fn sign_in() -> Result<(), AuthError> { + Err(AuthError::Other("On this device, sign in through the Google prompt".into())) +} + +/// Revoke the grant at Google (best effort) and forget it locally. +pub fn sign_out() -> Result<(), String> { + let token = secret::get().ok().flatten().or_else(|| lock().as_ref().map(|a| a.token.clone())); + if let Some(token) = token { + let _ = http().post(REVOKE_URL).form(&[("token", token.as_str())]).send(); + } + forget_access(); + secret::clear().map_err(|e| e.to_string()) +} + +pub fn has_grant() -> bool { + matches!(secret::get(), Ok(Some(_))) || lock().as_ref().is_some_and(|a| a.expires > Instant::now()) +} + +/// Refresh-token storage: the OS secret store on desktop (debug builds use their own service +/// name so development never touches the installed app). Phones keep no refresh token. +#[cfg(desktop)] +mod secret { + use super::AuthError; + const SERVICE: &str = if cfg!(debug_assertions) { "MnemoScript-dev" } else { "MnemoScript" }; + const ACCOUNT: &str = "google-drive-refresh"; + + fn entry() -> Result { + keyring::Entry::new(SERVICE, ACCOUNT).map_err(|e| AuthError::Other(e.to_string())) + } + pub fn get() -> Result, AuthError> { + match entry()?.get_password() { + Ok(v) => Ok(Some(v)), + Err(keyring::Error::NoEntry) => Ok(None), + Err(e) => Err(AuthError::Other(e.to_string())), + } + } + pub fn set(value: &str) -> Result<(), AuthError> { + entry()?.set_password(value).map_err(|e| AuthError::Other(format!("Could not store the Google sign-in securely: {e}"))) + } + pub fn clear() -> Result<(), AuthError> { + match entry()?.delete_credential() { + Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), + Err(e) => Err(AuthError::Other(e.to_string())), + } + } +} + +#[cfg(not(desktop))] +mod secret { + use super::AuthError; + pub fn get() -> Result, AuthError> { + Ok(None) + } + pub fn clear() -> Result<(), AuthError> { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pkce_challenge_matches_rfc7636_s256() { + let (verifier, challenge) = pkce(); + assert!(verifier.len() >= 43 && verifier.len() <= 128); + assert!(verifier.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')); + assert_eq!(challenge, URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))); + assert_ne!(pkce().0, verifier, "fresh randomness per sign-in"); + // RFC 7636 appendix B test vector. + assert_eq!( + URL_SAFE_NO_PAD.encode(Sha256::digest(b"dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")), + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + ); + } + + #[test] + fn authorize_url_requests_only_app_data_with_pkce() { + let url = url::Url::parse(&authorize_url("cid.apps.googleusercontent.com", "http://127.0.0.1:5123", "chal", "st8")).unwrap(); + let q: std::collections::HashMap<_, _> = url.query_pairs().into_owned().collect(); + assert_eq!(q["scope"], SCOPE); + assert_eq!(q["code_challenge_method"], "S256"); + assert_eq!(q["redirect_uri"], "http://127.0.0.1:5123"); + assert_eq!(q["access_type"], "offline"); + assert!(!url.as_str().contains("auth/drive "), "never the full-Drive scope"); + } + + #[test] + fn redirect_requires_matching_state() { + assert_eq!(parse_redirect("/?state=abc&code=4%2F0xyz", "abc"), Redirect::Finished(Ok("4/0xyz".into()))); + assert!(matches!(parse_redirect("/?state=abc&error=access_denied", "abc"), Redirect::Finished(Err(e)) if e.contains("cancelled"))); + assert_eq!(parse_redirect("/favicon.ico", "abc"), Redirect::Ignore); + } + + /// Regression (PR #4 review): any request to `/` without the right `state` (a preconnect, + /// a port scanner, an old tab) ended the whole sign-in, and the real redirect then found the + /// server closed. Such requests are refused without accepting their code, and waiting goes on. + #[test] + fn a_stray_request_never_ends_the_sign_in() { + assert_eq!(parse_redirect("/?state=evil&code=x", "abc"), Redirect::Foreign); + assert_eq!(parse_redirect("/", "abc"), Redirect::Foreign); + assert_eq!(parse_redirect("/?code=stolen", "abc"), Redirect::Foreign); + // The real redirect afterwards still completes. + assert_eq!(parse_redirect("/?code=real&state=abc", "abc"), Redirect::Finished(Ok("real".into()))); + } + + /// Regression (PR #4 review): on Linux the keyring crate has no backend in this build, so a + /// stored grant vanished and sync asked to sign in again every hour. + #[test] + fn drive_sync_is_offered_only_where_the_sign_in_can_be_kept() { + if cfg!(target_os = "linux") { + assert!(!configured()); + assert!(unavailable_reason().is_some()); + } else { + assert!(unavailable_reason().is_none()); + } + } +} diff --git a/app/src-tauri/src/sync/drive/live_tests.rs b/app/src-tauri/src/sync/drive/live_tests.rs new file mode 100644 index 0000000..9d86e24 --- /dev/null +++ b/app/src-tauri/src/sync/drive/live_tests.rs @@ -0,0 +1,133 @@ +//! Live Google Drive round trip (ignored by default; needs a signed-in dev build). +//! +//! `cargo test live_drive -- --ignored --nocapture` +//! +//! Plays two devices against the real Drive of the account signed in to the *debug* app +//! (keychain service `MnemoScript-dev`), under a throwaway project id, and deletes every file it +//! created afterwards. Synthetic text only; no real project is touched. Windows and macOS only: +//! the grant lives in the OS keychain, and Drive sync is off on Linux (no keyring backend). +//! +//! The throwaway project is named `zz-live-test-…` and its id is printed first, so a leftover +//! is easy to recognise. A cleanup that fails makes the test fail. +use super::api::{self as drive_api, query, Drive, DriveTransport}; +use super::auth; +use crate::sync::engine::Engine; +use crate::sync::store::Store; +use serde_json::{json, Value}; +use std::fs; +use std::path::Path; + +fn write(path: &Path, value: &Value) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, value.to_string()).unwrap(); +} + +fn read(path: &Path) -> Value { + serde_json::from_slice(&fs::read(path).unwrap()).unwrap() +} + +/// One sync round as the service runs it: change feed first, then the engine. +fn round(drive: &Drive, store: &Store, engine: &Engine, pid: &str, dir: &Path) -> crate::sync::engine::SyncReport { + drive_api::refresh_changes(drive, store, "live-test").expect("change feed"); + let mut t = DriveTransport { drive, store, device_id: engine.device_id.clone() }; + engine.sync(pid, dir, &mut t, None).expect("sync round") +} + +#[test] +#[ignore] +fn live_drive_round_trip() { + if auth::client_id().is_none() || auth::access_token(false).is_err() { + panic!("Sign in to Google Drive in the dev app first (Settings -> Sync with Google Drive)"); + } + let drive = Drive::new(); + let account = drive.about().expect("Drive account"); + println!("Drive account reachable (id length {})", account.id.len()); + + let pid = uuid::Uuid::new_v4().to_string(); + println!("throwaway project id: {pid}"); + let (a_dir, b_dir) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); + let (a_store, b_store) = (Store::memory(), Store::memory()); + for s in [&a_store, &b_store] { + drive_api::ensure_tables(s).unwrap(); + } + let a = Engine::new(&a_store, "Live test desktop").unwrap(); + let b = Engine::new(&b_store, "Live test phone").unwrap(); + + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + // Device A: a small project with a folder, two chapters and an image. + write(&a_dir.path().join("project.json"), &json!({"id": pid, "name": "zz-live-test-sync", "description": null, + "created_at": "2026-11-15T00:00:00Z", "folders": [{"id": "vol1", "name": "Volume 1", "order": 0, "parentId": null}]})); + fs::create_dir_all(a_dir.path().join("assets")).unwrap(); + fs::write(a_dir.path().join("assets").join("map.png"), b"\x89PNG live test bytes").unwrap(); + let img = a_dir.path().join("assets").join("map.png").to_string_lossy().into_owned(); + write(&a_dir.path().join("documents").join("ch1.json"), &json!({"id": "ch1", "title": "Chapter 1", + "content": format!("

The bells rang at dawn.

"), "updated_at": "now", "docType": "text", "order": 1, "folderId": "vol1"})); + write(&a_dir.path().join("documents").join("ch2.json"), &json!({"id": "ch2", "title": "Chapter 2", + "content": "

Ash fell like snow.

", "updated_at": "now", "docType": "text", "order": 2, "folderId": "vol1"})); + a_store.enable_project(&pid, "live-test", false).unwrap(); + let published = round(&drive, &a_store, &a, &pid, a_dir.path()).published; + println!("device A published {published} revisions"); + assert!(published >= 6); + + // Device B downloads it (Drive listings can lag a few seconds). + write(&b_dir.path().join("project.json"), &json!({"id": pid, "name": "Downloading", "description": null, + "created_at": "2026-11-15T00:00:00Z", "folders": []})); + b_store.enable_project(&pid, "live-test", true).unwrap(); + for attempt in 0..6 { + round(&drive, &b_store, &b, &pid, b_dir.path()); + if b_dir.path().join("documents").join("ch2.json").exists() { + break; + } + println!("device B: waiting for Drive (attempt {attempt})"); + std::thread::sleep(std::time::Duration::from_secs(3)); + } + assert_eq!(read(&b_dir.path().join("project.json"))["name"], "zz-live-test-sync"); + assert_eq!(read(&b_dir.path().join("documents").join("ch2.json"))["content"], "

Ash fell like snow.

"); + assert_eq!(fs::read(b_dir.path().join("assets").join("map.png")).unwrap(), b"\x89PNG live test bytes"); + let ch1 = read(&b_dir.path().join("documents").join("ch1.json")); + assert!(ch1["content"].as_str().unwrap().contains(&*b_dir.path().join("assets").join("map.png").to_string_lossy())); + println!("device B downloaded the project, image and portable image reference"); + + // B edits, A picks it up through the change feed. + let mut doc = read(&b_dir.path().join("documents").join("ch2.json")); + doc["content"] = json!("

Ash fell like snow, then like rain.

"); + write(&b_dir.path().join("documents").join("ch2.json"), &doc); + round(&drive, &b_store, &b, &pid, b_dir.path()); + let mut got = false; + for attempt in 0..6 { + round(&drive, &a_store, &a, &pid, a_dir.path()); + if read(&a_dir.path().join("documents").join("ch2.json"))["content"] == "

Ash fell like snow, then like rain.

" { + got = true; + break; + } + println!("device A: waiting for the change feed (attempt {attempt})"); + std::thread::sleep(std::time::Duration::from_secs(3)); + } + assert!(got, "device A never saw device B's edit"); + println!("device A received device B's edit through the change feed"); + })); + + // Clean up every file this run created in the app folder, pass or fail. Leftovers would + // be invisible in the Drive UI, so any failure here fails the test (after the original one). + let cleanup = (|| -> Result { + let files = drive.list(&query(&[("m", "1"), ("p", &pid)])).map_err(|e| format!("listing test files failed: {e}"))?; + for f in &files { + drive.delete(&f.id).map_err(|e| format!("deleting a test file failed: {e}"))?; + } + let left = drive.list(&query(&[("m", "1"), ("p", &pid)])).map_err(|e| format!("re-listing failed: {e}"))?; + if !left.is_empty() { + return Err(format!("{} test files are still in the app folder", left.len())); + } + Ok(files.len()) + })(); + match (&cleanup, result) { + (_, Err(e)) => { + if let Err(c) = &cleanup { + eprintln!("cleanup also failed for project {pid}: {c}"); + } + std::panic::resume_unwind(e); + } + (Ok(n), Ok(())) => println!("cleaned up {n} test files from the app folder"), + (Err(c), Ok(())) => panic!("cleanup failed for project {pid}: {c}"), + } +} diff --git a/app/src-tauri/src/sync/drive/mod.rs b/app/src-tauri/src/sync/drive/mod.rs new file mode 100644 index 0000000..3b1264b --- /dev/null +++ b/app/src-tauri/src/sync/drive/mod.rs @@ -0,0 +1,6 @@ +//! MnemoDrive: the writer's own Google Drive (`appDataFolder`) as a sync transport. +pub mod api; +pub mod auth; + +#[cfg(test)] +mod live_tests; diff --git a/app/src-tauri/src/sync/engine.rs b/app/src-tauri/src/sync/engine.rs new file mode 100644 index 0000000..b1b5c29 --- /dev/null +++ b/app/src-tauri/src/sync/engine.rs @@ -0,0 +1,1108 @@ +//! The transport-neutral sync engine. +//! +//! * `scan` compares the project files on disk with the last state the engine knows and +//! records every difference as a new immutable revision (queued for each transport). Saves +//! therefore never depend on React or on a hook firing: whatever is on disk is captured. +//! * `apply_batch` stores verified remote revisions and reconciles each touched entity: +//! fast-forward when causally newer, deterministic field merge for metadata, preserved +//! conflict heads for chapter/map text, edit-beats-delete, and a staged update instead of a +//! disk write for the chapter currently open in the editor. +//! * `resolve` turns a writer's conflict choice into a merge revision. +use super::model::{self, merge_fields, parse_entity, state_hash, Batch, Kind, Revision, SCHEMA_VERSION}; +use super::portable; +use super::store::Store; +use serde::Serialize; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::Path; + +fn err(e: impl std::fmt::Display) -> String { + e.to_string() +} + +const MAX_BATCH: usize = 400; + +/// Errors a transport reports. The engine never discards local data on any of them. +#[derive(Debug, Clone, PartialEq)] +pub enum TransportError { + /// Sign-in expired or revoked: pause this transport and ask the writer to reconnect. + Auth(String), + /// No network. Changes stay queued. + Offline(String), + /// Rate limited / temporarily unavailable; retry later with backoff. + Busy(String), + /// The writer's storage is full. + Quota(String), + Other(String), +} + +impl std::fmt::Display for TransportError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + TransportError::Auth(m) => write!(f, "Sign-in needed: {m}"), + TransportError::Offline(m) => write!(f, "Offline: {m}"), + TransportError::Busy(m) => write!(f, "Service busy: {m}"), + TransportError::Quota(m) => write!(f, "Storage full: {m}"), + TransportError::Other(m) => write!(f, "{m}"), + } + } +} + +impl From for TransportError { + fn from(e: String) -> Self { + TransportError::Other(e) + } +} + +/// What a sync destination must provide. LAN (later) and Google Drive implement the same +/// contract, and identical revision ids deduplicate across them. +pub trait Transport { + fn id(&self) -> &'static str; + fn has_blob(&mut self, project_id: &str, sha: &str) -> Result; + fn put_blob(&mut self, project_id: &str, sha: &str, bytes: &[u8]) -> Result<(), TransportError>; + /// `Ok(None)` when the blob is not (yet) visible at the destination. + fn get_blob(&mut self, project_id: &str, sha: &str) -> Result>, TransportError>; + /// Publishing the same `(device, seq)` twice must not create a second logical batch. + fn put_batch(&mut self, batch: &Batch) -> Result<(), TransportError>; + /// Batches of a project not yet applied here (`seen(device, seq)` filters known ones). + fn pull(&mut self, project_id: &str, seen: &dyn Fn(&str, u64) -> bool) -> Result, TransportError>; +} + +/// Entities found on disk, plus the portable text bodies keyed by hash. +struct Disk { + entities: BTreeMap, + texts: BTreeMap>, + /// Chapter files that exist but cannot be read (damaged, locked, wrong id). Their last + /// known state is kept: "unreadable here" must never become "deleted everywhere". + unreadable: BTreeSet, + /// The documents folder itself is there. Without it no chapter absence means a delete. + docs_present: bool, +} + +/// Chapters removed by another device (or damaged copies replaced from another device) are +/// moved here instead of deleted, and kept this long. +const TRASH_DIR: &str = "sync-trash"; +const TRASH_DAYS: u64 = 30; + +/// The sync entities of one chapter file: `(id, doc metadata, text payload, portable body)`. +/// `None` when the file is not a valid chapter (bad JSON, no or unsafe id, id ≠ file name). +fn doc_entities(path: &Path, roots: &[String]) -> Option<(String, Value, Value, Vec)> { + let doc = read_json(path).ok()?; + let id = doc.get("id").and_then(Value::as_str).filter(|id| model::safe_id(id))?.to_string(); + if path.file_stem().and_then(|s| s.to_str()) != Some(id.as_str()) { + return None; + } + let doc_type = doc.get("docType").and_then(Value::as_str).unwrap_or("text"); + let meta = json!({"title": opt_str(&doc, "title"), "docType": doc_type, "order": int(&doc, "order"), "folderId": opt_str(&doc, "folderId")}); + let content = doc.get("content").and_then(Value::as_str).unwrap_or(""); + let body = portable::to_portable(content, doc_type, roots).into_bytes(); + let text = json!({"sha256": model::sha256_hex(&body)}); + Some((id, meta, text, body)) +} + +/// Drop trash files older than `TRASH_DAYS`. Best effort: a failure only keeps them longer. +fn prune_trash(trash: &Path) { + let Ok(entries) = fs::read_dir(trash) else { return }; + let limit = std::time::Duration::from_secs(TRASH_DAYS * 24 * 3600); + for entry in entries.flatten() { + let old = entry.metadata().ok().and_then(|m| m.modified().ok()).and_then(|t| t.elapsed().ok()).is_some_and(|age| age > limit); + if old && entry.path().extension().and_then(|e| e.to_str()) == Some("json") { + let _ = fs::remove_file(entry.path()); + } + } +} + +/// Project-level entities in project.json: the project itself and its folders. +fn project_entities(meta: &Value) -> BTreeMap { + let mut out = BTreeMap::new(); + out.insert( + "project".to_string(), + json!({"name": opt_str(meta, "name"), "description": opt_str(meta, "description"), "author": opt_str(meta, "author")}), + ); + for folder in meta.get("folders").and_then(Value::as_array).into_iter().flatten() { + let Some(id) = folder.get("id").and_then(Value::as_str).filter(|id| model::safe_id(id)) else { continue }; + out.insert( + format!("folder:{id}"), + json!({"name": opt_str(folder, "name"), "order": int(folder, "order"), "parentId": opt_str(folder, "parentId")}), + ); + } + out +} + +#[derive(Default, Debug, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct SyncReport { + /// Entities written to disk from remote changes (the UI reloads these). + pub changed: Vec, + /// Chapters whose remote update waits until the writer leaves them. + pub staged: Vec, + pub published: usize, + pub held: usize, +} + +pub struct Engine<'a> { + pub store: &'a Store, + pub device_id: String, + pub device_name: String, +} + +fn read_json(path: &Path) -> Result { + serde_json::from_slice(&fs::read(path).map_err(err)?).map_err(err) +} + +fn opt_str(v: &Value, key: &str) -> Value { + match v.get(key) { + Some(Value::String(s)) => Value::String(s.clone()), + _ => Value::Null, + } +} + +fn int(v: &Value, key: &str) -> Value { + json!(v.get(key).and_then(Value::as_i64).unwrap_or(0)) +} + +impl<'a> Engine<'a> { + pub fn new(store: &'a Store, device_name: &str) -> Result { + Ok(Engine { store, device_id: store.device_id()?, device_name: device_name.to_string() }) + } + + fn read_disk(&self, project_id: &str, dir: &Path) -> Result { + let meta = read_json(&dir.join("project.json"))?; + if meta.get("id").and_then(Value::as_str) != Some(project_id) { + return Err("Project folder does not match the synced project".into()); + } + let mut entities = project_entities(&meta); + let mut texts = BTreeMap::new(); + let mut unreadable = BTreeSet::new(); + let roots = portable::roots_for(dir); + let docs = dir.join("documents"); + let docs_present = docs.is_dir(); + if docs_present { + for entry in fs::read_dir(&docs).map_err(err)? { + let path = entry.map_err(err)?.path(); + if path.extension().and_then(|e| e.to_str()) != Some("json") || !path.is_file() { + continue; + } + // Same tolerance as Project::load: one damaged chapter never blocks sync. It is + // remembered, so scan keeps its last good state instead of recording a delete. + let Some((id, meta, text, body)) = doc_entities(&path, &roots) else { + if let Some(stem) = path.file_stem().and_then(|s| s.to_str()).filter(|s| model::safe_id(s)) { + unreadable.insert(stem.to_string()); + } + continue; + }; + let sha = text["sha256"].as_str().unwrap_or_default().to_string(); + entities.insert(format!("doc:{id}"), meta); + entities.insert(format!("text:{id}"), text); + texts.insert(sha, body); + } + } + let assets = dir.join("assets"); + if assets.is_dir() { + for entry in fs::read_dir(&assets).map_err(err)? { + let entry = entry.map_err(err)?; + let name = entry.file_name().to_string_lossy().into_owned(); + let kind = fs::symlink_metadata(entry.path()).map_err(err)?; + if !kind.is_file() || !model::safe_asset_name(&name) || name.ends_with(".tmp") { + continue; + } + let key = format!("asset:{name}"); + // Asset files are immutable (fresh uuid names), so a known one is not re-hashed. + if let Some((rev, _)) = self.store.disk_state(project_id, &key)? { + if let Some(r) = self.store.revision(project_id, &rev)? { + if let Some(p) = r.payload { + entities.insert(key, p); + continue; + } + } + } + let bytes = fs::read(entry.path()).map_err(err)?; + entities.insert(key, json!({"sha256": model::sha256_hex(&bytes), "size": bytes.len()})); + } + } + Ok(Disk { entities, texts, unreadable, docs_present }) + } + + /// What is on disk for one entity right now. `Err` when its file exists but is unreadable. + fn current(&self, dir: &Path, entity: &str) -> Result, String> { + let (kind, id) = parse_entity(entity).ok_or("bad entity")?; + match kind { + Kind::Project | Kind::Folder => Ok(project_entities(&read_json(&dir.join("project.json"))?).remove(entity)), + Kind::Doc | Kind::Text => { + let path = dir.join("documents").join(format!("{id}.json")); + if !path.exists() { + return Ok(None); + } + let (_, meta, text, _) = doc_entities(&path, &portable::roots_for(dir)).ok_or("Damaged chapter file")?; + Ok(Some(if kind == Kind::Doc { meta } else { text })) + } + Kind::Asset => Ok(None), + } + } + + fn known_hash(&self, project_id: &str, entity: &str) -> Result { + Ok(self.store.disk_state(project_id, entity)?.map(|(_, h)| h).unwrap_or_else(|| state_hash(None))) + } + + /// Write `rev` only if the files still hold what the engine last scanned. Holds the files + /// lock (shared with the app's saves) from the check to the end of the write. `Ok(false)`: + /// something was saved since the scan, so the caller captures it first and decides again. + fn write_checked(&self, project_id: &str, dir: &Path, entity: &str, rev: &str) -> Result { + let (kind, id) = parse_entity(entity).ok_or("bad entity")?; + if kind == Kind::Asset { + return Ok(true); + } + let _files = crate::project::files_lock(); + let mut check = vec![entity.to_string()]; + if kind == Kind::Doc && self.payload(project_id, rev)?.is_none() { + // Removing the file also removes its text: unsaved-to-sync typing must be captured. + check.push(format!("text:{id}")); + } + for e in &check { + match self.current(dir, e) { + Ok(now) => { + if state_hash(now.as_ref()) != self.known_hash(project_id, e)? && !self.engine_made(project_id, e, now.as_ref())? { + return Ok(false); + } + } + Err(_) if matches!(kind, Kind::Doc | Kind::Text) => { + // A damaged local copy is replaced by the good version, but never destroyed. + self.set_aside(project_id, dir, id, "damaged")?; + break; + } + Err(e) => return Err(e), + } + } + self.write(project_id, dir, entity, rev)?; + Ok(true) + } + + /// A difference from the last scan that sync itself made, not the writer: the downloaded + /// project's placeholder `project.json` (never scanned), a chapter file built from its + /// metadata before its text arrived (empty), or a chapter file sync just removed. + fn engine_made(&self, project_id: &str, entity: &str, now: Option<&Value>) -> Result { + if entity == "project" { + return Ok(self.store.disk_state(project_id, entity)?.is_none()); + } + let Some(id) = entity.strip_prefix("text:") else { return Ok(false) }; + Ok(match now { + Some(v) => self.known_text(project_id, id)?.is_none() && v["sha256"].as_str() == Some(model::sha256_hex(b"").as_str()), + None => match self.store.disk_state(project_id, &format!("doc:{id}"))? { + Some((doc_rev, _)) => self.payload(project_id, &doc_rev)?.is_none(), + None => false, + }, + }) + } + + /// Move a chapter file into the project's sync trash (kept `TRASH_DAYS`), with a notice. + fn set_aside(&self, project_id: &str, dir: &Path, id: &str, why: &str) -> Result<(), String> { + let path = dir.join("documents").join(format!("{id}.json")); + if !path.exists() { + return Ok(()); + } + let title = read_json(&path).ok().and_then(|d| d.get("title").and_then(Value::as_str).map(String::from)).unwrap_or_else(|| { + self.store + .disk_state(project_id, &format!("doc:{id}")) + .ok() + .flatten() + .and_then(|(r, _)| self.payload(project_id, &r).ok().flatten()) + .and_then(|p| p["title"].as_str().map(String::from)) + .unwrap_or_else(|| "Untitled".into()) + }); + let trash = dir.join(TRASH_DIR); + fs::create_dir_all(&trash).map_err(err)?; + prune_trash(&trash); + let stamp = chrono::Utc::now().format("%Y%m%d-%H%M%S"); + fs::rename(&path, trash.join(format!("{id}-{stamp}.json"))).map_err(err)?; + let detail = match why { + "damaged" => format!("\"{title}\" could not be read on this device and was replaced by the version from another device. The damaged copy is in the project's {TRASH_DIR} folder for {TRASH_DAYS} days."), + _ => format!("\"{title}\" was deleted on another device. A copy is in the project's {TRASH_DIR} folder for {TRASH_DAYS} days."), + }; + self.store.add_notice(project_id, &format!("doc:{id}"), if why == "damaged" { "replaced" } else { "deleted" }, &detail) + } + + /// The last synced text of a chapter, for rebuilding a chapter file that went missing. + fn known_text(&self, project_id: &str, id: &str) -> Result, String> { + let Some((rev, _)) = self.store.disk_state(project_id, &format!("text:{id}"))? else { return Ok(None) }; + let Some(sha) = self.payload(project_id, &rev)?.and_then(|p| p["sha256"].as_str().map(String::from)) else { return Ok(None) }; + Ok(self.store.blob(&sha)?.and_then(|b| String::from_utf8(b).ok())) + } + + /// Record local edits as revisions. Returns the new revisions (already queued). + pub fn scan(&self, project_id: &str, dir: &Path, transports: &[&str]) -> Result, String> { + let disk = self.read_disk(project_id, dir)?; + let known: BTreeMap = + self.store.entities(project_id)?.into_iter().map(|(e, r, h)| (e, (r, h))).collect(); + let mut keys: BTreeSet<&String> = disk.entities.keys().collect(); + keys.extend(known.keys()); + let mut created = Vec::new(); + let tx = self.store.conn.unchecked_transaction().map_err(err)?; + for entity in keys { + let current = disk.entities.get(entity); + // A missing asset file is not a delete: it may simply not be downloaded yet. + if current.is_none() && entity.starts_with("asset:") { + continue; + } + // A chapter that is there but unreadable, or a missing documents folder, is not a + // delete either: keep the last good state (and say so once) until it reads again. + if current.is_none() { + if let Some((Kind::Doc | Kind::Text, id)) = parse_entity(entity) { + if !disk.docs_present { + self.store.add_notice_once(project_id, "project", "unreadable", "The project's documents folder is missing on this device. Sync will not remove any chapter until it is back.")?; + continue; + } + if disk.unreadable.contains(id) { + if entity.starts_with("doc:") { + let title = known.get(entity).and_then(|(r, _)| self.payload(project_id, r).ok().flatten()).and_then(|p| p["title"].as_str().map(String::from)).unwrap_or_else(|| "A chapter".into()); + self.store.add_notice_once(project_id, entity, "unreadable", &format!("\"{title}\" could not be read on this device. Its last synced version is kept on your other devices."))?; + } + continue; + } + } + } + let hash = state_hash(current); + let parents = match known.get(entity) { + Some((_, h)) if *h == hash => continue, + Some((rev, _)) => vec![rev.clone()], + None if current.is_none() => continue, + None => Vec::new(), + }; + if let Some(sha) = current.and_then(|c| c.get("sha256")).and_then(Value::as_str) { + if let Some(body) = disk.texts.get(sha) { + self.store.put_blob(sha, body)?; + } + } + let rev = Revision::new(entity, parents, current.cloned(), &self.device_id); + self.store.insert_revision(project_id, &rev)?; + self.store.set_disk_state(project_id, entity, &rev.rev, &hash)?; + for t in transports { + self.store.enqueue(project_id, t, &rev.rev)?; + } + created.push(rev); + } + tx.commit().map_err(err)?; + Ok(created) + } + + // ---- applying remote revisions ---------------------------------------------------------- + + /// Fetch, verify and store a blob the revision needs. `Ok(false)` = not available yet. + fn ensure_blob( + &self, + project_id: &str, + dir: &Path, + rev: &Revision, + transport: &mut dyn Transport, + ) -> Result { + let Some(sha) = rev.blob() else { return Ok(true) }; + let (kind, name) = parse_entity(&rev.entity).ok_or_else(|| TransportError::Other("bad entity".into()))?; + if kind == Kind::Asset { + let path = dir.join("assets").join(name); + if path.exists() { + return Ok(true); + } + let Some(bytes) = transport.get_blob(project_id, &sha)? else { return Ok(false) }; + if model::sha256_hex(&bytes) != sha { + return Err(TransportError::Other("Downloaded image failed its checksum".into())); + } + fs::create_dir_all(dir.join("assets")).map_err(err)?; + let tmp = dir.join("assets").join(format!(".{name}.{}.tmp", uuid::Uuid::new_v4())); + fs::write(&tmp, &bytes).map_err(err)?; + fs::rename(&tmp, &path).map_err(|e| { + let _ = fs::remove_file(&tmp); + TransportError::Other(e.to_string()) + })?; + return Ok(true); + } + if self.store.blob(&sha)?.is_some() { + return Ok(true); + } + let Some(bytes) = transport.get_blob(project_id, &sha)? else { return Ok(false) }; + if model::sha256_hex(&bytes) != sha || std::str::from_utf8(&bytes).is_err() { + return Err(TransportError::Other("Downloaded chapter failed its checksum".into())); + } + self.store.put_blob(&sha, &bytes)?; + Ok(true) + } + + /// Apply one remote batch. `Ok(false)` means it must wait (missing parents or blobs). + pub fn apply_batch( + &self, + project_id: &str, + dir: &Path, + batch: &Batch, + transport: &mut dyn Transport, + active_doc: Option<&str>, + report: &mut SyncReport, + ) -> Result { + let tid = transport.id(); + if self.store.batch_applied(project_id, tid, &batch.device_id, batch.seq)? { + return Ok(true); + } + if batch.schema_version != SCHEMA_VERSION { + return Err(TransportError::Other("Another device uses a newer sync format; update MnemoScript".into())); + } + if batch.project_id != project_id || batch.revisions.iter().any(|r| !r.verify()) { + // Damaged or forged data never reaches disk; record it and move on. + self.store.add_notice(project_id, "project", "rejected", &format!("Ignored damaged changes from {}", batch.device_name))?; + self.store.mark_applied(project_id, tid, &batch.device_id, batch.seq)?; + return Ok(true); + } + let mut in_batch = BTreeSet::new(); + for rev in &batch.revisions { + for parent in &rev.parents { + if !in_batch.contains(parent) && !self.store.has_revision(project_id, parent)? { + return Ok(false); + } + } + in_batch.insert(rev.rev.clone()); + } + for rev in &batch.revisions { + if !self.ensure_blob(project_id, dir, rev, transport)? { + return Ok(false); + } + } + if batch.device_id != self.device_id { + self.store.remember_device(&batch.device_id, &batch.device_name)?; + } + let mut touched = BTreeSet::new(); + for rev in &batch.revisions { + if self.store.insert_revision(project_id, rev)? { + touched.insert(rev.entity.clone()); + } + } + let mut incoming: BTreeMap> = BTreeMap::new(); + for rev in &batch.revisions { + incoming.entry(rev.entity.clone()).or_default().push(rev.rev.clone()); + } + // Folders and documents first so text always lands in an existing chapter file. + let order = |e: &String| match parse_entity(e).map(|k| k.0) { + Some(Kind::Project) => 0, + Some(Kind::Folder) => 1, + Some(Kind::Asset) => 2, + Some(Kind::Doc) => 3, + _ => 4, + }; + let mut entities: Vec = touched.into_iter().collect(); + entities.sort_by_key(order); + for entity in &entities { + self.reconcile(project_id, dir, entity, &incoming[entity], active_doc, report)?; + } + self.repair(project_id, dir, report)?; + self.store.mark_applied(project_id, tid, &batch.device_id, batch.seq)?; + Ok(true) + } + + fn payload(&self, project_id: &str, rev: &str) -> Result, String> { + Ok(self.store.revision(project_id, rev)?.and_then(|r| r.payload)) + } + + /// The maximal revisions among `candidates` (none is an ancestor of another). + fn heads(&self, project_id: &str, candidates: &BTreeSet) -> Result, String> { + let mut heads = Vec::new(); + for c in candidates { + let mut dominated = false; + for other in candidates { + if other != c && self.store.is_ancestor(project_id, c, other)? { + dominated = true; + break; + } + } + if !dominated { + heads.push(c.clone()); + } + } + Ok(heads) + } + + fn record_local(&self, project_id: &str, rev: &Revision) -> Result<(), String> { + if self.store.insert_revision(project_id, rev)? { + for t in self.store.project_transports(project_id)? { + self.store.enqueue(project_id, t, &rev.rev)?; + } + } + Ok(()) + } + + fn reconcile( + &self, + project_id: &str, + dir: &Path, + entity: &str, + incoming: &[String], + active_doc: Option<&str>, + report: &mut SyncReport, + ) -> Result<(), String> { + let (kind, id) = parse_entity(entity).ok_or("bad entity")?; + let mut target = String::new(); + for _ in 0..3 { + let disk = self.store.disk_state(project_id, entity)?.map(|(r, _)| r); + let staged = self.store.staged(project_id, entity)?; + target = self.decide(project_id, entity, kind, disk.as_deref(), staged.as_deref(), incoming)?; + if disk.as_deref() == Some(target.as_str()) { + if staged.is_some() { + self.store.set_staged(project_id, entity, None)?; + } + return Ok(()); + } + // Never write under the editor: the open chapter's text (or its removal) waits for the + // writer. Title, folder and order changes still apply; the app merges them in place. + let removes = kind == Kind::Doc && self.payload(project_id, &target)?.is_none(); + if (kind == Kind::Text || removes) && active_doc == Some(id) { + self.store.set_staged(project_id, entity, Some(&target))?; + report.staged.push(entity.to_string()); + return Ok(()); + } + if self.write_checked(project_id, dir, entity, &target)? { + self.store.set_staged(project_id, entity, None)?; + report.changed.push(entity.to_string()); + return Ok(()); + } + // Saved since this round's scan (an autosave, the assistant, a late map flush): + // capture it as a local revision first, so it merges or conflicts instead of being + // overwritten, then decide again. + let transports = self.store.project_transports(project_id)?; + self.scan(project_id, dir, &transports)?; + } + // Still changing under us: keep the remote version waiting; a later round applies it. + self.store.set_staged(project_id, entity, Some(&target))?; + report.staged.push(entity.to_string()); + Ok(()) + } + + /// The revision this device should hold for `entity`, recording any merge it needs. + fn decide(&self, project_id: &str, entity: &str, kind: Kind, disk: Option<&str>, staged: Option<&str>, incoming: &[String]) -> Result { + let mut candidates: BTreeSet = self.store.conflicts(project_id, entity)?.into_iter().collect(); + candidates.extend(disk.map(String::from)); + candidates.extend(staged.map(String::from)); + candidates.extend(incoming.iter().cloned()); + let mut heads = self.heads(project_id, &candidates)?; + + let target = if heads.len() == 1 { + self.store.set_conflicts(project_id, entity, &[])?; + heads[0].clone() + } else if kind == Kind::Text { + let mut live = Vec::new(); + let mut dead = Vec::new(); + let mut payloads = BTreeSet::new(); + for h in &heads { + match self.payload(project_id, h)? { + Some(p) => { + payloads.insert(state_hash(Some(&p))); + live.push(h.clone()); + } + None => dead.push(h.clone()), + } + } + if payloads.len() <= 1 { + // Identical results merge silently; edit beats delete. + let keep = self.first_live(project_id, &heads)?; + let merged = Revision::new(entity, heads.clone(), self.payload(project_id, &keep)?, &self.device_id); + if !dead.is_empty() && !live.is_empty() { + self.store.add_notice(project_id, entity, "kept", "Kept a chapter that was deleted on another device but edited elsewhere")?; + } + self.record_local(project_id, &merged)?; + self.store.set_conflicts(project_id, entity, &[])?; + merged.rev + } else { + if !dead.is_empty() { + // Deleted on one device and edited differently on others: the edits beat the + // delete, and stay a normal conflict between them. Every device absorbs the + // deletes into the same (lowest) live head, so they agree on the result. + let first = live[0].clone(); + let mut parents = dead.clone(); + parents.push(first.clone()); + let absorbed = Revision::new(entity, parents, self.payload(project_id, &first)?, &self.device_id); + self.store.add_notice(project_id, entity, "kept", "Kept a chapter that was deleted on another device but edited elsewhere")?; + self.record_local(project_id, &absorbed)?; + heads = std::iter::once(absorbed.rev).chain(live.into_iter().skip(1)).collect(); + } + // Keep what the writer has on this device; preserve every other version. + let local = match disk { + Some(d) => heads + .iter() + .find(|h| self.store.is_ancestor(project_id, d, h).unwrap_or(false)) + .cloned() + .unwrap_or_else(|| heads[0].clone()), + None => heads[0].clone(), + }; + let others: Vec = heads.iter().filter(|h| **h != local).cloned().collect(); + self.store.set_conflicts(project_id, entity, &others)?; + local + } + } else { + // Metadata: deterministic field merge folded over every head. + let mut acc = heads[0].clone(); + for other in &heads[1..] { + let base = self.store.merge_base(project_id, &acc, other)?; + let base_payload = match base { + Some(b) => self.payload(project_id, &b)?, + None => None, + }; + let (ours, theirs) = (self.payload(project_id, &acc)?, self.payload(project_id, other)?); + let (merged, collided) = merge_fields(base_payload.as_ref(), (&acc, ours.as_ref()), (other, theirs.as_ref())); + let rev = Revision::new(entity, vec![acc.clone(), other.clone()], merged, &self.device_id); + if !collided.is_empty() { + let label = theirs.or(ours).and_then(|p| p.get("title").or(p.get("name")).and_then(Value::as_str).map(String::from)).unwrap_or_default(); + self.store.add_notice(project_id, entity, "merged", &format!("\"{label}\" changed on two devices ({}); one version was kept", collided.join(", ")))?; + } + self.record_local(project_id, &rev)?; + acc = rev.rev; + } + self.store.set_conflicts(project_id, entity, &[])?; + acc + }; + Ok(target) + } + + fn first_live(&self, project_id: &str, heads: &[String]) -> Result { + for h in heads { + if self.payload(project_id, h)?.is_some() { + return Ok(h.clone()); + } + } + Ok(heads[0].clone()) + } + + /// Write one entity's revision to the project files and remember it as the disk state. + fn write(&self, project_id: &str, dir: &Path, entity: &str, rev: &str) -> Result<(), String> { + let (kind, id) = parse_entity(entity).ok_or("bad entity")?; + let payload = self.payload(project_id, rev)?; + match kind { + Kind::Project => { + let path = dir.join("project.json"); + let mut meta = read_json(&path)?; + if let Some(p) = &payload { + for key in ["name", "description", "author"] { + meta[key] = p.get(key).cloned().unwrap_or(Value::Null); + } + } + crate::project::write_atomic(&path, &serde_json::to_string_pretty(&meta).map_err(err)?)?; + } + Kind::Folder => { + let path = dir.join("project.json"); + let mut meta = read_json(&path)?; + let folders = meta.as_object_mut().ok_or("bad project.json")?.entry("folders").or_insert(json!([])); + let list = folders.as_array_mut().ok_or("bad folders")?; + list.retain(|f| f.get("id").and_then(Value::as_str) != Some(id)); + if let Some(p) = &payload { + list.push(json!({"id": id, "name": p["name"], "order": p["order"], "parentId": p["parentId"]})); + } + crate::project::write_atomic(&path, &serde_json::to_string_pretty(&meta).map_err(err)?)?; + } + Kind::Doc => { + let path = dir.join("documents").join(format!("{id}.json")); + match &payload { + // Recoverable: the file goes to the project's sync trash, not away. + None => self.set_aside(project_id, dir, id, "deleted")?, + Some(p) => { + let mut doc = match read_json(&path) { + Ok(doc) => doc, + Err(_) => { + // Rebuilt chapter file: keep its last synced text, so the next scan + // does not mistake the rebuild for the writer emptying it. + let doc_type = p["docType"].as_str().unwrap_or("text"); + let content = self.known_text(project_id, id)?.map(|t| portable::to_local(&t, doc_type, dir)).unwrap_or_default(); + json!({"id": id, "content": content}) + } + }; + for key in ["title", "docType", "order", "folderId"] { + doc[key] = p.get(key).cloned().unwrap_or(Value::Null); + } + if doc["title"].is_null() { + doc["title"] = json!("Untitled"); + } + doc["updated_at"] = json!(chrono::Utc::now().to_rfc3339()); + crate::project::write_atomic(&path, &serde_json::to_string_pretty(&doc).map_err(err)?)?; + } + } + } + Kind::Text => { + let path = dir.join("documents").join(format!("{id}.json")); + if let Some(p) = &payload { + let sha = p.get("sha256").and_then(Value::as_str).ok_or("bad text payload")?; + let body = self.store.blob(sha)?.ok_or("Missing chapter text")?; + let body = String::from_utf8(body).map_err(err)?; + let mut doc = match read_json(&path) { + Ok(doc) => doc, + Err(_) => self.restore_doc_meta(project_id, id)?, + }; + let doc_type = doc.get("docType").and_then(Value::as_str).unwrap_or("text").to_string(); + doc["content"] = json!(portable::to_local(&body, &doc_type, dir)); + doc["updated_at"] = json!(chrono::Utc::now().to_rfc3339()); + crate::project::write_atomic(&path, &serde_json::to_string_pretty(&doc).map_err(err)?)?; + } + } + Kind::Asset => {} + } + self.store.set_disk_state(project_id, entity, rev, &state_hash(payload.as_ref())) + } + + /// Keep the tree valid after merging concurrent changes from several devices: no chapter in + /// a deleted folder, no folder cycles, and no chapter text without its chapter. + fn repair(&self, project_id: &str, dir: &Path, report: &mut SyncReport) -> Result<(), String> { + let disk = self.read_disk(project_id, dir)?; + let folders: BTreeMap> = disk + .entities + .iter() + .filter_map(|(k, v)| k.strip_prefix("folder:").map(|id| (id.to_string(), v["parentId"].as_str().map(String::from)))) + .collect(); + let mut fixes: Vec<(String, Value)> = Vec::new(); + for (id, parent) in &folders { + let mut cycle = vec![id.clone()]; + let mut cursor = parent.clone(); + let mut broken = false; + while let Some(p) = cursor { + if !folders.contains_key(&p) { + broken = true; + break; + } + if cycle.contains(&p) { + // Detach the smallest id in the loop: every device picks the same one. + broken = cycle.iter().min() == Some(id); + break; + } + cycle.push(p.clone()); + cursor = folders[&p].clone(); + } + if broken && parent.is_some() { + let mut v = disk.entities[&format!("folder:{id}")].clone(); + v["parentId"] = Value::Null; + fixes.push((format!("folder:{id}"), v)); + } + } + for (key, v) in &disk.entities { + if key.starts_with("doc:") { + if let Some(f) = v["folderId"].as_str() { + if !folders.contains_key(f) { + let mut v = v.clone(); + v["folderId"] = Value::Null; + fixes.push((key.clone(), v)); + } + } + } + } + for (entity, value) in fixes { + let Some((parent, _)) = self.store.disk_state(project_id, &entity)? else { continue }; + let r = Revision::new(&entity, vec![parent], Some(value), &self.device_id); + self.record_local(project_id, &r)?; + // Saved meanwhile: leave it; the next round scans the save and repairs again. + if self.write_checked(project_id, dir, &entity, &r.rev)? { + report.changed.push(entity); + } + } + Ok(()) + } + + /// The chapter file is missing but its text is live (edit beat a delete, or text arrived + /// first): rebuild the chapter from its last known metadata, recorded as a revision so every + /// device reaches the same result. + fn restore_doc_meta(&self, project_id: &str, id: &str) -> Result { + let doc_key = format!("doc:{id}"); + let mut meta = json!({"title": "Untitled", "docType": "text", "order": 0, "folderId": null}); + if let Some((doc_rev, _)) = self.store.disk_state(project_id, &doc_key)? { + match self.payload(project_id, &doc_rev)? { + Some(live) => meta = live, + None => { + if let Some(last) = self.last_live(project_id, &doc_rev)? { + let r = Revision::new(&doc_key, vec![doc_rev], Some(last.clone()), &self.device_id); + self.record_local(project_id, &r)?; + self.store.set_disk_state(project_id, &doc_key, &r.rev, &state_hash(Some(&last)))?; + self.store.add_notice(project_id, &doc_key, "kept", &format!( + "Kept \"{}\": it was deleted on one device but edited on another", + last["title"].as_str().unwrap_or("Untitled") + ))?; + meta = last; + } + } + } + } + let mut doc = meta; + doc["id"] = json!(id); + doc["content"] = json!(""); + Ok(doc) + } + + fn last_live(&self, project_id: &str, rev: &str) -> Result, String> { + let mut queue = std::collections::VecDeque::from([rev.to_string()]); + let mut seen = BTreeSet::new(); + while let Some(r) = queue.pop_front() { + if !seen.insert(r.clone()) { + continue; + } + if let Some(found) = self.store.revision(project_id, &r)? { + if found.payload.is_some() { + return Ok(found.payload); + } + queue.extend(found.parents); + } + } + Ok(None) + } + + /// Apply a staged remote update for a chapter once the writer allows it (or leaves it). + /// Local edits made in the meantime are captured first and become a conflict, never lost. + pub fn apply_staged(&self, project_id: &str, dir: &Path, doc_id: &str, report: &mut SyncReport) -> Result<(), String> { + let mut staged = Vec::new(); + for entity in [format!("doc:{doc_id}"), format!("text:{doc_id}")] { + if let Some(rev) = self.store.staged(project_id, &entity)? { + staged.push((entity, rev)); + } + } + if staged.is_empty() { + return Ok(()); + } + let transports = self.store.project_transports(project_id)?; + self.scan(project_id, dir, &transports)?; + for (entity, rev) in staged { + self.reconcile(project_id, dir, &entity, &[rev], None, report)?; + self.store.set_staged(project_id, &entity, None)?; + } + self.repair(project_id, dir, report) + } + + // ---- publishing ---------------------------------------------------------------------------- + + /// The next batch to publish for a transport (a frozen, previously started one first). + pub fn next_batch(&self, project_id: &str, transport: &str) -> Result, String> { + if let Some(b) = self.store.pending_batch(project_id, transport)? { + return Ok(Some(b)); + } + let revs = self.store.outbox(project_id, transport, MAX_BATCH)?; + if revs.is_empty() { + return Ok(None); + } + let mut revisions = Vec::new(); + for r in &revs { + if let Some(rev) = self.store.revision(project_id, r)? { + revisions.push(rev); + } + } + let batch = Batch { + schema_version: SCHEMA_VERSION, + project_id: project_id.into(), + device_id: self.device_id.clone(), + device_name: self.device_name.clone(), + seq: self.store.next_seq(project_id)?, + created_at: chrono::Utc::now().to_rfc3339(), + revisions, + }; + self.store.freeze_batch(&batch, transport)?; + Ok(Some(batch)) + } + + /// Upload content first, then the batch: a published batch never points at missing bytes. + pub fn publish(&self, project_id: &str, dir: &Path, transport: &mut dyn Transport) -> Result { + let tid = transport.id(); + let mut published = 0; + while let Some(mut batch) = self.next_batch(project_id, tid)? { + let before = batch.revisions.len(); + let mut kept = Vec::new(); + for rev in std::mem::take(&mut batch.revisions) { + let Some(sha) = rev.blob() else { + kept.push(rev); + continue; + }; + if !self.store.remote_has_blob(project_id, tid, &sha)? { + let bytes = match parse_entity(&rev.entity) { + Some((Kind::Asset, name)) => fs::read(dir.join("assets").join(name)).ok().filter(|b| model::sha256_hex(b) == sha), + _ => self.store.blob(&sha)?, + }; + let Some(bytes) = bytes else { + // The bytes are gone locally; a reference to them would stall other devices. + self.store.dequeue(project_id, tid, &rev.rev)?; + continue; + }; + if !transport.has_blob(project_id, &sha)? { + transport.put_blob(project_id, &sha, &bytes)?; + } + self.store.mark_remote_blob(project_id, tid, &sha)?; + } + kept.push(rev); + } + batch.revisions = kept; + if batch.revisions.len() != before { + // Not uploaded yet, so the frozen batch can still shrink under the same number. + self.store.refreeze_batch(&batch, tid)?; + } + if !batch.revisions.is_empty() { + transport.put_batch(&batch)?; + } + self.store.publish_done(&batch, tid)?; + published += batch.revisions.len(); + } + Ok(published) + } + + /// One full round: capture local edits, apply what others published, publish ours. + pub fn sync(&self, project_id: &str, dir: &Path, transport: &mut dyn Transport, active_doc: Option<&str>) -> Result { + let tid = transport.id(); + let mut report = SyncReport::default(); + // A freshly downloaded project is an empty skeleton: pull first so its placeholder + // metadata never competes with the real project. + if self.store.is_fresh(project_id)? { + self.pull(project_id, dir, transport, active_doc, &mut report)?; + self.store.set_fresh(project_id, false)?; + } + self.scan(project_id, dir, &[tid])?; + self.pull(project_id, dir, transport, active_doc, &mut report)?; + self.retry_waiting(project_id, dir, active_doc, &mut report)?; + report.published = self.publish(project_id, dir, transport)?; + report.changed.sort(); + report.changed.dedup(); + report.staged.sort(); + report.staged.dedup(); + Ok(report) + } + + /// Updates waiting for a chapter that is not open (left while the app was closed, or held + /// because the file kept changing during a round): apply them now, still checked. + fn retry_waiting(&self, project_id: &str, dir: &Path, active_doc: Option<&str>, report: &mut SyncReport) -> Result<(), String> { + for entity in self.store.staged_entities(project_id)? { + let Some((_, id)) = parse_entity(&entity) else { continue }; + if active_doc == Some(id) { + continue; + } + if let Some(rev) = self.store.staged(project_id, &entity)? { + self.reconcile(project_id, dir, &entity, &[rev], active_doc, report)?; + } + } + Ok(()) + } + + fn pull(&self, project_id: &str, dir: &Path, transport: &mut dyn Transport, active_doc: Option<&str>, report: &mut SyncReport) -> Result<(), TransportError> { + let tid = transport.id(); + let store = self.store; + let seen = |device: &str, seq: u64| store.batch_applied(project_id, tid, device, seq).unwrap_or(false); + let mut pending = self.store.held(project_id, tid)?; + for b in transport.pull(project_id, &seen)? { + if b.project_id == project_id && !pending.iter().any(|p| p.device_id == b.device_id && p.seq == b.seq) { + pending.push(b); + } + } + pending.sort_by(|a, b| (a.device_id.as_str(), a.seq).cmp(&(b.device_id.as_str(), b.seq))); + loop { + let mut progressed = false; + let mut waiting = Vec::new(); + for batch in pending { + if batch.device_id == self.device_id { + // Our own batch seen through the remote: nothing to apply. + self.store.mark_applied(project_id, tid, &batch.device_id, batch.seq)?; + continue; + } + if self.apply_batch(project_id, dir, &batch, transport, active_doc, report)? { + progressed = true; + } else { + waiting.push(batch); + } + } + pending = waiting; + if !progressed || pending.is_empty() { + break; + } + } + for b in &pending { + self.store.hold(b, tid)?; + } + report.held = pending.len(); + Ok(()) + } + + // ---- conflicts ----------------------------------------------------------------------------- + + /// The versions in a chapter's conflict. Captures the latest save first, so "this device" + /// is what the writer last typed, not what the previous round saw. + pub fn conflict_versions(&self, project_id: &str, dir: &Path, doc_id: &str) -> Result, String> { + let transports = self.store.project_transports(project_id)?; + self.scan(project_id, dir, &transports)?; + let entity = format!("text:{doc_id}"); + let mut out = Vec::new(); + let doc_type = read_json(&dir.join("documents").join(format!("{doc_id}.json"))) + .ok() + .and_then(|d| d.get("docType").and_then(Value::as_str).map(String::from)) + .unwrap_or_else(|| "text".into()); + let mut revs: Vec<(String, bool)> = Vec::new(); + if let Some((disk, _)) = self.store.disk_state(project_id, &entity)? { + revs.push((disk, true)); + } + revs.extend(self.store.conflicts(project_id, &entity)?.into_iter().map(|r| (r, false))); + for (rev, local) in revs { + let Some(r) = self.store.revision(project_id, &rev)? else { continue }; + let content = match r.payload.as_ref().and_then(|p| p.get("sha256")).and_then(Value::as_str) { + Some(sha) => String::from_utf8(self.store.blob(sha)?.unwrap_or_default()).map_err(err)?, + None => String::new(), + }; + let device = if r.origin == self.device_id { + self.device_name.clone() + } else { + self.store.device_name(&r.origin)?.unwrap_or_else(|| "Another device".into()) + }; + out.push(ConflictVersion { rev, local, device, content: portable::to_local(&content, &doc_type, dir) }); + } + Ok(out) + } + + /// Settle a text conflict: `keep` names the version to keep in place; with `keep_copies` + /// every other version becomes its own chapter next to it, so nothing is lost either way. + pub fn resolve(&self, project_id: &str, dir: &Path, doc_id: &str, keep: &str, keep_copies: bool) -> Result, String> { + let entity = format!("text:{doc_id}"); + // Capture typing saved since the last round, so it is one of the versions (and kept). + let versions = self.conflict_versions(project_id, dir, doc_id)?; + let (disk, _) = self.store.disk_state(project_id, &entity)?.ok_or("Nothing to resolve")?; + let others = self.store.conflicts(project_id, &entity)?; + if others.is_empty() { + return Ok(Vec::new()); + } + // "Keep this device's version", chosen before the latest save was captured, means the + // latest local text. + let keep = if keep != disk && self.store.is_ancestor(project_id, keep, &disk)? { disk.as_str() } else { keep }; + let mut all = vec![disk.clone()]; + all.extend(others.iter().cloned()); + if !all.iter().any(|r| r == keep) { + return Err("That version is no longer part of the conflict".into()); + } + let mut created = Vec::new(); + if keep_copies { + let doc_path = dir.join("documents").join(format!("{doc_id}.json")); + let doc = read_json(&doc_path)?; + for v in versions.iter().filter(|v| v.rev != keep) { + let mut copy = doc.clone(); + let id = uuid::Uuid::new_v4().to_string(); + copy["id"] = json!(id); + copy["title"] = json!(format!("{} ({})", doc["title"].as_str().unwrap_or("Untitled"), v.device)); + copy["content"] = json!(v.content); + copy["order"] = json!(doc["order"].as_i64().unwrap_or(0) + 1); + copy["updated_at"] = json!(chrono::Utc::now().to_rfc3339()); + crate::project::write_atomic(&dir.join("documents").join(format!("{id}.json")), &serde_json::to_string_pretty(©).map_err(err)?)?; + created.push(id); + } + } + let merged = Revision::new(&entity, all, self.payload(project_id, keep)?, &self.device_id); + self.record_local(project_id, &merged)?; + self.store.set_conflicts(project_id, &entity, &[])?; + self.store.set_staged(project_id, &entity, None)?; + if !self.write_checked(project_id, dir, &entity, &merged.rev)? { + // Saved again while the writer was choosing: that text stays, as a new conflict + // against the chosen version. + let transports = self.store.project_transports(project_id)?; + self.scan(project_id, dir, &transports)?; + self.store.set_conflicts(project_id, &entity, &[merged.rev])?; + return Err("The chapter changed while you were choosing. Review it again.".into()); + } + Ok(created) + } +} + +#[derive(Serialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct ConflictVersion { + pub rev: String, + pub local: bool, + pub device: String, + pub content: String, +} + +#[cfg(test)] +#[path = "engine_tests.rs"] +mod tests; diff --git a/app/src-tauri/src/sync/engine_tests.rs b/app/src-tauri/src/sync/engine_tests.rs new file mode 100644 index 0000000..3f45358 --- /dev/null +++ b/app/src-tauri/src/sync/engine_tests.rs @@ -0,0 +1,545 @@ +//! Multi-device simulations over the in-memory transport. Synthetic writing only. +use super::*; +use crate::sync::memory::{MemoryTransport, Remote}; +use std::cell::RefCell; +use std::rc::Rc; +use tempfile::TempDir; + +const PID: &str = "6f0e3a52-1b7c-4f43-9d55-0a1b2c3d4e5f"; + +struct Device { + store: Store, + dir: TempDir, + name: &'static str, +} + +impl Device { + fn engine(&self) -> Engine<'_> { + Engine::new(&self.store, self.name).unwrap() + } + fn path(&self) -> &Path { + self.dir.path() + } + fn sync(&self, remote: &Rc>) -> SyncReport { + self.sync_with(remote, None) + } + fn sync_with(&self, remote: &Rc>, active: Option<&str>) -> SyncReport { + let mut t = MemoryTransport::new(remote); + self.engine().sync(PID, self.path(), &mut t, active).unwrap() + } + fn doc(&self, id: &str) -> Option { + read_json(&self.path().join("documents").join(format!("{id}.json"))).ok() + } + fn content(&self, id: &str) -> String { + self.doc(id).map(|d| d["content"].as_str().unwrap().to_string()).unwrap_or_default() + } + fn write_doc(&self, id: &str, title: &str, content: &str, folder: Option<&str>, order: i64) { + let doc = json!({"id": id, "title": title, "content": content, "updated_at": "2026-11-13T00:00:00Z", "docType": "text", "order": order, "folderId": folder}); + crate::project::write_atomic(&self.path().join("documents").join(format!("{id}.json")), &doc.to_string()).unwrap(); + } + fn edit(&self, id: &str, f: impl FnOnce(&mut Value)) { + let mut doc = self.doc(id).unwrap(); + f(&mut doc); + crate::project::write_atomic(&self.path().join("documents").join(format!("{id}.json")), &doc.to_string()).unwrap(); + } + fn meta(&self) -> Value { + read_json(&self.path().join("project.json")).unwrap() + } + fn set_meta(&self, f: impl FnOnce(&mut Value)) { + let mut m = self.meta(); + f(&mut m); + crate::project::write_atomic(&self.path().join("project.json"), &m.to_string()).unwrap(); + } + /// Comparable view of the project (portable text, so paths differ per device but not here). + fn snapshot(&self) -> BTreeMap { + let disk = self.engine().read_disk(PID, self.path()).unwrap(); + disk.entities + } +} + +fn origin(name: &'static str) -> Device { + let dir = TempDir::new().unwrap(); + let meta = json!({"id": PID, "name": "The Ashen Crown", "description": null, "created_at": "2026-11-01T00:00:00Z", + "folders": [{"id": "vol1", "name": "Volume 1", "order": 0, "parentId": null}], "ai": {"provider": "local-only"}}); + crate::project::write_atomic(&dir.path().join("project.json"), &meta.to_string()).unwrap(); + let d = Device { store: Store::memory(), dir, name }; + d.store.enable_project(PID, "acct-1", false).unwrap(); + d +} + +/// A second device that downloads the project into an empty skeleton. +fn joiner(name: &'static str) -> Device { + let dir = TempDir::new().unwrap(); + let meta = json!({"id": PID, "name": "Downloading…", "description": null, "created_at": "2026-11-13T00:00:00Z", "folders": []}); + crate::project::write_atomic(&dir.path().join("project.json"), &meta.to_string()).unwrap(); + let d = Device { store: Store::memory(), dir, name }; + d.store.enable_project(PID, "acct-1", true).unwrap(); + d +} + +fn remote() -> Rc> { + Rc::new(RefCell::new(Remote::default())) +} + +fn seeded() -> (Rc>, Device, Device) { + let r = remote(); + let a = origin("Desktop"); + a.write_doc("ch1", "Chapter 1", "

The bells rang at dawn.

", Some("vol1"), 1); + a.write_doc("ch2", "Chapter 2", "

Ash fell like snow.

", Some("vol1"), 2); + a.write_doc("ch3", "Chapter 3", "

The crown was cold.

", Some("vol1"), 3); + a.sync(&r); + let b = joiner("Pixel"); + b.sync(&r); + (r, a, b) +} + +#[test] +fn a_second_device_downloads_the_whole_project_with_portable_images() { + let r = remote(); + let a = origin("Desktop"); + fs::create_dir_all(a.path().join("assets")).unwrap(); + fs::write(a.path().join("assets").join("map1.png"), b"\x89PNG fake bytes").unwrap(); + let img = a.path().join("assets").join("map1.png").to_string_lossy().into_owned(); + a.write_doc("ch1", "Chapter 1", &format!(r#"

Look:

"#), Some("vol1"), 1); + let report = a.sync(&r); + assert!(report.published >= 4, "{report:?}"); + + let b = joiner("Pixel"); + let got = b.sync(&r); + assert!(got.changed.contains(&"text:ch1".to_string())); + assert_eq!(b.meta()["name"], "The Ashen Crown"); + assert_eq!(b.meta()["folders"][0]["name"], "Volume 1"); + assert!(b.meta().get("ai").is_none(), "per-device AI settings never sync"); + let doc = b.doc("ch1").unwrap(); + assert_eq!(doc["title"], "Chapter 1"); + assert_eq!(doc["folderId"], "vol1"); + let local_img = b.path().join("assets").join("map1.png"); + assert_eq!(fs::read(&local_img).unwrap(), b"\x89PNG fake bytes"); + assert!(doc["content"].as_str().unwrap().contains(&html_escape::encode_double_quoted_attribute(&local_img.to_string_lossy()).to_string())); + assert_eq!(a.snapshot(), b.snapshot()); + // Nothing more to send or apply. + let again = b.sync(&r); + assert_eq!(again.published, 0); + assert!(again.changed.is_empty()); +} + +#[test] +fn move_on_one_device_and_text_edit_on_the_other_both_apply() { + let (r, a, b) = seeded(); + a.edit("ch2", |d| d["folderId"] = Value::Null); + b.edit("ch2", |d| d["content"] = json!("

Ash fell like snow, then like rain.

")); + a.sync(&r); + b.sync(&r); + a.sync(&r); + for d in [&a, &b] { + let doc = d.doc("ch2").unwrap(); + assert_eq!(doc["folderId"], Value::Null); + assert_eq!(doc["content"], "

Ash fell like snow, then like rain.

"); + assert!(d.store.conflicted_entities(PID).unwrap().is_empty()); + } + assert_eq!(a.snapshot(), b.snapshot()); +} + +#[test] +fn concurrent_chapter_edits_keep_both_versions_until_the_writer_chooses() { + let (r, a, b) = seeded(); + a.edit("ch3", |d| d["content"] = json!("

Desktop draft.

")); + b.edit("ch3", |d| d["content"] = json!("

Phone draft.

")); + a.sync(&r); + b.sync(&r); + a.sync(&r); + // Each device keeps its own text in place; the other version is preserved, never dropped. + assert_eq!(a.content("ch3"), "

Desktop draft.

"); + assert_eq!(b.content("ch3"), "

Phone draft.

"); + for d in [&a, &b] { + assert_eq!(d.store.conflicted_entities(PID).unwrap(), vec!["text:ch3".to_string()]); + let versions = d.engine().conflict_versions(PID, d.path(), "ch3").unwrap(); + let texts: BTreeSet = versions.iter().map(|v| v.content.clone()).collect(); + assert_eq!(texts, BTreeSet::from(["

Desktop draft.

".to_string(), "

Phone draft.

".to_string()])); + } + // The phone keeps the desktop text and saves its own draft as a separate chapter. + let versions = b.engine().conflict_versions(PID, b.path(), "ch3").unwrap(); + let desktop = versions.iter().find(|v| !v.local).unwrap(); + assert_eq!(desktop.device, "Desktop"); + let copies = b.engine().resolve(PID, b.path(), "ch3", &desktop.rev, true).unwrap(); + assert_eq!(copies.len(), 1); + assert_eq!(b.content("ch3"), "

Desktop draft.

"); + assert_eq!(b.content(&copies[0]), "

Phone draft.

"); + assert_eq!(b.doc(&copies[0]).unwrap()["title"], "Chapter 3 (Pixel)"); + b.sync(&r); + a.sync(&r); + assert!(a.store.conflicted_entities(PID).unwrap().is_empty()); + assert_eq!(a.content(&copies[0]), "

Phone draft.

"); + assert_eq!(a.snapshot(), b.snapshot()); +} + +#[test] +fn delete_on_one_device_and_edit_on_the_other_keeps_the_chapter() { + let (r, a, b) = seeded(); + fs::remove_file(a.path().join("documents").join("ch1.json")).unwrap(); + b.edit("ch1", |d| d["content"] = json!("

Saved from deletion.

")); + a.sync(&r); + b.sync(&r); + a.sync(&r); + b.sync(&r); + for d in [&a, &b] { + assert_eq!(d.content("ch1"), "

Saved from deletion.

", "{}", d.name); + assert_eq!(d.doc("ch1").unwrap()["title"], "Chapter 1"); + } + // The device that merged the delete with the edit tells its writer why the chapter stayed. + assert!(b.store.notices(PID, 10).unwrap().iter().any(|n| n.2 == "kept")); + assert_eq!(a.snapshot(), b.snapshot()); +} + +#[test] +fn a_delete_reaches_an_offline_device_and_is_not_resurrected() { + let (r, a, b) = seeded(); + fs::remove_file(a.path().join("documents").join("ch2.json")).unwrap(); + a.set_meta(|m| m["name"] = json!("The Ashen Crown (draft 2)")); + r.borrow_mut().offline = true; + let mut t = MemoryTransport::new(&r); + assert!(matches!(a.engine().sync(PID, a.path(), &mut t, None), Err(TransportError::Offline(_)))); + r.borrow_mut().offline = false; + a.sync(&r); + b.sync(&r); + assert!(b.doc("ch2").is_none()); + assert_eq!(b.meta()["name"], "The Ashen Crown (draft 2)"); + assert!(b.store.notices(PID, 10).unwrap().iter().any(|n| n.2 == "deleted")); + // The phone syncing again later must not bring the chapter back. + b.sync(&r); + a.sync(&r); + assert!(a.doc("ch2").is_none()); + assert_eq!(a.snapshot(), b.snapshot()); +} + +#[test] +fn duplicate_and_reordered_deliveries_apply_once() { + let (r, a, b) = seeded(); + a.write_doc("ch4", "Chapter 4", "

New.

", Some("vol1"), 4); + a.sync(&r); + a.edit("ch4", |d| d["content"] = json!("

New, revised.

")); + a.sync(&r); + { + let mut remote = r.borrow_mut(); + let copies = remote.batches.clone(); + remote.batches.extend(copies); + remote.reverse = true; + } + b.sync(&r); + assert_eq!(b.content("ch4"), "

New, revised.

"); + let docs = fs::read_dir(b.path().join("documents")).unwrap().count(); + assert_eq!(docs, 4, "no duplicated chapters"); + assert_eq!(a.snapshot(), b.snapshot()); +} + +#[test] +fn the_open_chapter_is_never_overwritten_under_the_editor() { + let (r, a, b) = seeded(); + a.edit("ch1", |d| d["content"] = json!("

Desktop rewrite.

")); + a.sync(&r); + let report = b.sync_with(&r, Some("ch1")); + assert_eq!(report.staged, vec!["text:ch1".to_string()]); + assert_eq!(b.content("ch1"), "

The bells rang at dawn.

"); + // Writer accepts the update without having typed: plain fast-forward. + let mut rep = SyncReport::default(); + b.engine().apply_staged(PID, b.path(), "ch1", &mut rep).unwrap(); + assert_eq!(b.content("ch1"), "

Desktop rewrite.

"); + + // Next time the writer keeps typing before accepting: their words become a conflict. + a.edit("ch1", |d| d["content"] = json!("

Desktop again.

")); + a.sync(&r); + b.sync_with(&r, Some("ch1")); + b.edit("ch1", |d| d["content"] = json!("

Phone typing meanwhile.

")); + b.engine().apply_staged(PID, b.path(), "ch1", &mut rep).unwrap(); + assert_eq!(b.content("ch1"), "

Phone typing meanwhile.

"); + assert_eq!(b.store.conflicted_entities(PID).unwrap(), vec!["text:ch1".to_string()]); +} + +#[test] +fn a_remote_delete_of_the_open_chapter_waits_and_typing_keeps_it() { + let (r, a, b) = seeded(); + fs::remove_file(a.path().join("documents").join("ch2.json")).unwrap(); + a.sync(&r); + let report = b.sync_with(&r, Some("ch2")); + assert!(report.staged.contains(&"doc:ch2".to_string()), "{report:?}"); + assert!(b.doc("ch2").is_some(), "the open chapter's file is not removed under the editor"); + // The writer kept typing, then left the chapter: their words win over the delete. + b.edit("ch2", |d| d["content"] = json!("

Still writing.

")); + let mut rep = SyncReport::default(); + b.engine().apply_staged(PID, b.path(), "ch2", &mut rep).unwrap(); + assert_eq!(b.content("ch2"), "

Still writing.

"); + b.sync(&r); + a.sync(&r); + assert_eq!(a.content("ch2"), "

Still writing.

"); + assert_eq!(a.snapshot(), b.snapshot()); +} + +#[test] +fn a_batch_waits_for_content_that_is_not_visible_yet() { + let (r, a, b) = seeded(); + a.edit("ch1", |d| d["content"] = json!("

Slow upload.

")); + a.sync(&r); + let sha = model::sha256_hex(b"

Slow upload.

"); + r.borrow_mut().hidden.push(sha); + let held = b.sync(&r); + assert_eq!(held.held, 1); + assert_eq!(b.content("ch1"), "

The bells rang at dawn.

"); + r.borrow_mut().hidden.clear(); + b.sync(&r); + assert_eq!(b.content("ch1"), "

Slow upload.

"); +} + +#[test] +fn an_interrupted_publish_retries_the_same_frozen_batch() { + let r = remote(); + let a = origin("Desktop"); + a.write_doc("ch1", "Chapter 1", "

One.

", None, 1); + let e = a.engine(); + e.scan(PID, a.path(), &["drive"]).unwrap(); + let frozen = e.next_batch(PID, "drive").unwrap().unwrap(); + // More writing happens before the retry; it must go into a *later* batch. + a.write_doc("ch2", "Chapter 2", "

Two.

", None, 2); + e.scan(PID, a.path(), &["drive"]).unwrap(); + let mut t = MemoryTransport::new(&r); + e.publish(PID, a.path(), &mut t).unwrap(); + let remote = r.borrow(); + assert_eq!(remote.batches.len(), 2); + assert_eq!(remote.batches[0].seq, frozen.seq); + assert_eq!(remote.batches[0].revisions, frozen.revisions); + assert_eq!(remote.batches[1].seq, frozen.seq + 1); +} + +#[test] +fn concurrent_folder_moves_never_leave_a_cycle_or_orphan() { + let (r, a, b) = seeded(); + a.set_meta(|m| m["folders"] = json!([{"id": "vol1", "name": "Volume 1", "order": 0, "parentId": null}, {"id": "vol2", "name": "Volume 2", "order": 1, "parentId": null}])); + a.sync(&r); + b.sync(&r); + // Desktop nests Volume 1 in Volume 2; phone nests Volume 2 in Volume 1 and deletes nothing. + a.set_meta(|m| m["folders"][0]["parentId"] = json!("vol2")); + b.set_meta(|m| m["folders"][1]["parentId"] = json!("vol1")); + a.sync(&r); + b.sync(&r); + a.sync(&r); + b.sync(&r); + for d in [&a, &b] { + let folders = d.meta()["folders"].as_array().unwrap().clone(); + let roots = folders.iter().filter(|f| f["parentId"].is_null()).count(); + assert!(roots >= 1, "a cycle must be broken: {folders:?}"); + } + assert_eq!(a.snapshot(), b.snapshot()); +} + +#[test] +fn three_devices_converge_under_shuffled_sync_order() { + let (r, a, b) = seeded(); + let c = joiner("Tablet"); + c.sync(&r); + let devices = [&a, &b, &c]; + let mut seed: u64 = 0x5eed; + let mut next = || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as usize + }; + for round in 0..12 { + let d = devices[next() % 3]; + // Each device edits a different field, so everything should merge without conflicts. + match d.name { + "Desktop" => d.edit("ch1", |doc| doc["content"] = json!(format!("

Desktop {round}

"))), + "Pixel" => d.edit("ch2", |doc| doc["title"] = json!(format!("Chapter Two v{round}"))), + _ => d.set_meta(|m| m["description"] = json!(format!("Tablet note {round}"))), + } + devices[next() % 3].sync(&r); + d.sync(&r); + } + for _ in 0..2 { + for d in devices { + d.sync(&r); + } + } + assert_eq!(a.snapshot(), b.snapshot()); + assert_eq!(b.snapshot(), c.snapshot()); + for d in devices { + assert!(d.store.conflicted_entities(PID).unwrap().is_empty()); + } +} + +/// Regression (2026-11-13): turning sync off removed the project's row and with it the batch +/// counter, so after turning it back on new batches reused published numbers and were skipped. +#[test] +fn turning_sync_off_and_on_never_reuses_a_batch_number() { + let (r, a, b) = seeded(); + let before = a.store.next_seq(PID).unwrap(); + a.store.disable_project(PID).unwrap(); + a.write_doc("ch4", "Chapter 4", "

Written while sync was off.

", Some("vol1"), 4); + a.store.enable_project(PID, "acct-1", false).unwrap(); + assert_eq!(a.store.next_seq(PID).unwrap(), before); + a.sync(&r); + let seqs: Vec = r.borrow().batches.iter().filter(|x| x.device_id == a.engine().device_id).map(|x| x.seq).collect(); + let unique: BTreeSet = seqs.iter().copied().collect(); + assert_eq!(seqs.len(), unique.len(), "duplicate batch numbers: {seqs:?}"); + b.sync(&r); + assert_eq!(b.content("ch4"), "

Written while sync was off.

"); +} + +/// Regression (2026-11-13): re-enabling a project under another Google account published +/// nothing, because every revision already counted as sent to the first account. +#[test] +fn a_new_google_account_receives_the_whole_project_history() { + let (_r1, a, _b) = seeded(); + a.store.disable_project(PID).unwrap(); + a.store.enable_project(PID, "acct-2", false).unwrap(); + let r2 = remote(); + a.sync(&r2); + let c = joiner("Tablet"); + c.store.enable_project(PID, "acct-2", true).unwrap(); + c.sync(&r2); + assert_eq!(c.content("ch3"), "

The crown was cold.

"); + assert_eq!(a.snapshot(), c.snapshot()); +} + +#[test] +fn damaged_remote_data_is_rejected_without_touching_disk() { + let (r, a, b) = seeded(); + a.edit("ch1", |d| d["content"] = json!("

Real.

")); + a.sync(&r); + { + let mut remote = r.borrow_mut(); + let last = remote.batches.last_mut().unwrap(); + last.revisions[0].payload = Some(json!({"title": "Forged"})); + } + b.sync(&r); + assert_eq!(b.content("ch1"), "

The bells rang at dawn.

"); + assert!(b.store.notices(PID, 10).unwrap().iter().any(|n| n.2 == "rejected")); +} + +/// Regression (PR #4 review, finding 1): a chapter file that one device cannot read was +/// recorded as a delete and removed from every other device. +#[test] +fn a_chapter_damaged_on_one_device_is_never_deleted_elsewhere() { + let (r, a, b) = seeded(); + fs::write(a.path().join("documents").join("ch2.json"), "{ half a file").unwrap(); + a.sync(&r); + b.sync(&r); + assert_eq!(b.content("ch2"), "

Ash fell like snow.

", "the phone keeps its healthy copy"); + assert!(a.store.notices(PID, 10).unwrap().iter().any(|n| n.2 == "unreadable" && n.3.contains("Chapter 2"))); + // Reported once, not every round. + a.sync(&r); + assert_eq!(a.store.notices(PID, 10).unwrap().iter().filter(|n| n.2 == "unreadable").count(), 1); + + // A later edit elsewhere repairs the damaged copy; the damaged file is set aside, not lost. + b.edit("ch2", |d| d["content"] = json!("

Ash fell, and kept falling.

")); + b.sync(&r); + a.sync(&r); + assert_eq!(a.content("ch2"), "

Ash fell, and kept falling.

"); + let trash: Vec<_> = fs::read_dir(a.path().join(TRASH_DIR)).unwrap().flatten().collect(); + assert_eq!(trash.len(), 1); + assert_eq!(fs::read_to_string(trash[0].path()).unwrap(), "{ half a file"); + assert!(a.store.notices(PID, 10).unwrap().iter().any(|n| n.2 == "replaced")); + assert_eq!(a.snapshot(), b.snapshot()); +} + +/// Regression (PR #4 review, finding 1): with the documents folder briefly gone (moved by +/// hand, a sync client mid-copy) every chapter was deleted everywhere. +#[test] +fn a_missing_documents_folder_deletes_nothing() { + let (r, a, b) = seeded(); + fs::rename(a.path().join("documents"), a.path().join("documents-moved")).unwrap(); + a.sync(&r); + b.sync(&r); + for id in ["ch1", "ch2", "ch3"] { + assert!(b.doc(id).is_some(), "{id} must survive"); + } + assert!(a.store.notices(PID, 10).unwrap().iter().any(|n| n.2 == "unreadable")); + fs::rename(a.path().join("documents-moved"), a.path().join("documents")).unwrap(); + a.sync(&r); + assert_eq!(a.snapshot(), b.snapshot()); +} + +/// Regression (PR #4 review, finding 1): a remote delete removed the file outright. +#[test] +fn a_remote_delete_moves_the_chapter_to_the_sync_trash() { + let (r, a, b) = seeded(); + fs::remove_file(a.path().join("documents").join("ch3.json")).unwrap(); + a.sync(&r); + b.sync(&r); + assert!(b.doc("ch3").is_none()); + let trash: Vec<_> = fs::read_dir(b.path().join(TRASH_DIR)).unwrap().flatten().collect(); + assert_eq!(trash.len(), 1); + assert!(fs::read_to_string(trash[0].path()).unwrap().contains("The crown was cold.")); + assert!(b.store.notices(PID, 10).unwrap().iter().any(|n| n.2 == "deleted" && n.3.contains(TRASH_DIR))); + // The trash is not part of the project: syncing again changes nothing. + assert!(b.sync(&r).changed.is_empty()); + assert_eq!(a.snapshot(), b.snapshot()); +} + +/// Regression (PR #4 review, finding 2): a save that landed between a round's scan and its +/// write (the assistant editing a closed chapter, a late map flush) was overwritten. +#[test] +fn a_save_after_the_scan_is_never_overwritten_by_a_remote_update() { + let (r, a, b) = seeded(); + a.edit("ch1", |d| d["content"] = json!("

Desktop rewrite.

")); + a.edit("ch2", |d| d["title"] = json!("Chapter Two")); + a.sync(&r); + let e = b.engine(); + e.scan(PID, b.path(), &["drive"]).unwrap(); + // Saved on the phone after the scan, before the pull writes. + b.edit("ch1", |d| d["content"] = json!("

Phone save after the scan.

")); + b.edit("ch2", |d| d["content"] = json!("

Ash fell, unscanned.

")); + let mut t = MemoryTransport::new(&r); + let mut report = SyncReport::default(); + e.pull(PID, b.path(), &mut t, None, &mut report).unwrap(); + assert_eq!(b.content("ch1"), "

Phone save after the scan.

"); + assert_eq!(b.store.conflicted_entities(PID).unwrap(), vec!["text:ch1".to_string()]); + let versions: BTreeSet = e.conflict_versions(PID, b.path(), "ch1").unwrap().into_iter().map(|v| v.content).collect(); + assert!(versions.contains("

Desktop rewrite.

")); + // The remote rename still applied, and the unscanned text in the same file survived it. + assert_eq!(b.doc("ch2").unwrap()["title"], "Chapter Two"); + assert_eq!(b.content("ch2"), "

Ash fell, unscanned.

"); +} + +/// Regression (PR #4 review, finding 3): the conflict review offered, and resolving kept, the +/// text from the last round instead of what the writer had typed since. +#[test] +fn resolving_a_conflict_keeps_typing_saved_since_the_last_round() { + let (r, a, b) = seeded(); + a.edit("ch3", |d| d["content"] = json!("

Desktop draft.

")); + b.edit("ch3", |d| d["content"] = json!("

Phone draft.

")); + a.sync(&r); + b.sync(&r); + // The review was opened, then the writer typed more and the app saved it. + let before = b.engine().conflict_versions(PID, b.path(), "ch3").unwrap(); + let old_local = before.iter().find(|v| v.local).unwrap().rev.clone(); + b.edit("ch3", |d| d["content"] = json!("

Phone draft, with a new ending.

")); + let versions = b.engine().conflict_versions(PID, b.path(), "ch3").unwrap(); + assert!(versions.iter().any(|v| v.local && v.content == "

Phone draft, with a new ending.

")); + // Choosing "this device" from the earlier screen keeps the latest typing. + b.engine().resolve(PID, b.path(), "ch3", &old_local, false).unwrap(); + assert_eq!(b.content("ch3"), "

Phone draft, with a new ending.

"); + b.sync(&r); + a.sync(&r); + assert_eq!(a.content("ch3"), "

Phone draft, with a new ending.

"); + assert!(a.store.conflicted_entities(PID).unwrap().is_empty()); +} + +/// Regression (PR #4 review, finding 4): deleted on one device and edited differently on two +/// others, one of the two edits was dropped with only a "kept" notice. +#[test] +fn a_delete_and_two_different_edits_keep_both_edits() { + let (r, a, b) = seeded(); + let c = joiner("Tablet"); + c.sync(&r); + fs::remove_file(a.path().join("documents").join("ch1.json")).unwrap(); + b.edit("ch1", |d| d["content"] = json!("

Phone ending.

")); + c.edit("ch1", |d| d["content"] = json!("

Tablet ending.

")); + for d in [&a, &b, &c, &a, &b, &c] { + d.sync(&r); + } + let both = BTreeSet::from(["

Phone ending.

".to_string(), "

Tablet ending.

".to_string()]); + for d in [&a, &b, &c] { + assert!(d.doc("ch1").is_some(), "{}: the edits beat the delete", d.name); + assert_eq!(d.store.conflicted_entities(PID).unwrap(), vec!["text:ch1".to_string()], "{}", d.name); + let texts: BTreeSet = d.engine().conflict_versions(PID, d.path(), "ch1").unwrap().into_iter().map(|v| v.content).collect(); + assert_eq!(texts, both, "{}: neither edit is dropped", d.name); + } +} diff --git a/app/src-tauri/src/sync/memory.rs b/app/src-tauri/src/sync/memory.rs new file mode 100644 index 0000000..2249077 --- /dev/null +++ b/app/src-tauri/src/sync/memory.rs @@ -0,0 +1,79 @@ +//! In-memory transport for deterministic multi-device tests. It can drop, duplicate and reorder +//! deliveries and hide blobs, to exercise the engine's idempotence and hold/retry paths. +use super::engine::{Transport, TransportError}; +use super::model::Batch; +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::rc::Rc; + +#[derive(Default)] +pub struct Remote { + pub batches: Vec, + pub blobs: BTreeMap>, + /// Blobs uploaded but not yet "visible" (eventual consistency). + pub hidden: Vec, + pub offline: bool, + pub reverse: bool, +} + +#[derive(Clone)] +pub struct MemoryTransport { + pub remote: Rc>, +} + +impl MemoryTransport { + pub fn new(remote: &Rc>) -> Self { + MemoryTransport { remote: remote.clone() } + } + + fn check(&self) -> Result<(), TransportError> { + if self.remote.borrow().offline { + Err(TransportError::Offline("test network down".into())) + } else { + Ok(()) + } + } +} + +impl Transport for MemoryTransport { + fn id(&self) -> &'static str { + "drive" + } + fn has_blob(&mut self, _p: &str, sha: &str) -> Result { + self.check()?; + Ok(self.remote.borrow().blobs.contains_key(sha)) + } + fn put_blob(&mut self, _p: &str, sha: &str, bytes: &[u8]) -> Result<(), TransportError> { + self.check()?; + self.remote.borrow_mut().blobs.insert(sha.into(), bytes.to_vec()); + Ok(()) + } + fn get_blob(&mut self, _p: &str, sha: &str) -> Result>, TransportError> { + self.check()?; + let r = self.remote.borrow(); + if r.hidden.iter().any(|h| h == sha) { + return Ok(None); + } + Ok(r.blobs.get(sha).cloned()) + } + fn put_batch(&mut self, batch: &Batch) -> Result<(), TransportError> { + self.check()?; + // Duplicate uploads (a retry after a lost reply) are kept, like duplicate Drive files. + self.remote.borrow_mut().batches.push(batch.clone()); + Ok(()) + } + fn pull(&mut self, project_id: &str, seen: &dyn Fn(&str, u64) -> bool) -> Result, TransportError> { + self.check()?; + let r = self.remote.borrow(); + let mut out: Vec = r + .batches + .iter() + .filter(|b| b.project_id == project_id && !seen(&b.device_id, b.seq)) + .cloned() + .collect(); + if r.reverse { + out.reverse(); + } + Ok(out) + } +} diff --git a/app/src-tauri/src/sync/mod.rs b/app/src-tauri/src/sync/mod.rs new file mode 100644 index 0000000..aebcd1d --- /dev/null +++ b/app/src-tauri/src/sync/mod.rs @@ -0,0 +1,13 @@ +//! MnemoSync: optional, local-first project sync. See `docs/MNEMOSYNC_ARCHITECTURE.md`. +//! +//! The engine (`engine.rs`) is transport-neutral; Google Drive (`drive/`) is the first +//! transport. Local saves never wait for, or depend on, a transport. +pub mod drive; +pub mod engine; +pub mod model; +pub mod portable; +pub mod service; +pub mod store; + +#[cfg(test)] +pub mod memory; diff --git a/app/src-tauri/src/sync/model.rs b/app/src-tauri/src/sync/model.rs new file mode 100644 index 0000000..50c1536 --- /dev/null +++ b/app/src-tauri/src/sync/model.rs @@ -0,0 +1,279 @@ +//! Transport-neutral MnemoSync records: entity keys, canonical snapshots and revision ids. +//! +//! A project is split into small entities so independent edits never collide: +//! `project` (name/description/author), `folder:` (name/order/parent), +//! `doc:` (title/type/order/folder), `text:` (the chapter or map body, by hash) and +//! `asset:` (image bytes, by hash). Moving a chapter on one device and editing its text +//! on another therefore touches two different entities and both changes apply. +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use sha2::{Digest, Sha256}; + +pub const SCHEMA_VERSION: u32 = 1; + +pub fn sha256_hex(bytes: &[u8]) -> String { + format!("{:x}", Sha256::digest(bytes)) +} + +/// Serialise with object keys sorted at every level, independent of serde_json's map backend, +/// so the same logical snapshot always hashes to the same revision id on every device. +pub fn canonical(value: &Value) -> String { + fn write(value: &Value, out: &mut String) { + match value { + Value::Object(map) => { + let mut keys: Vec<&String> = map.keys().collect(); + keys.sort(); + out.push('{'); + for (i, key) in keys.iter().enumerate() { + if i > 0 { + out.push(','); + } + out.push_str(&Value::String((*key).clone()).to_string()); + out.push(':'); + write(&map[*key], out); + } + out.push('}'); + } + Value::Array(items) => { + out.push('['); + for (i, item) in items.iter().enumerate() { + if i > 0 { + out.push(','); + } + write(item, out); + } + out.push(']'); + } + other => out.push_str(&other.to_string()), + } + } + let mut out = String::new(); + write(value, &mut out); + out +} + +/// Hash of an entity state (`None` = deleted). Used to notice local edits cheaply. +pub fn state_hash(payload: Option<&Value>) -> String { + sha256_hex(payload.map(canonical).unwrap_or_else(|| "null".into()).as_bytes()) +} + +/// The id of a revision depends only on its entity, causal parents and content, never on the +/// device or clock. Two devices that reach the same merge independently produce the same id. +pub fn revision_id(entity: &str, parents: &[String], payload: Option<&Value>) -> String { + let mut sorted = parents.to_vec(); + sorted.sort(); + sorted.dedup(); + let body = format!( + "mnemo-rev-v1\n{entity}\n{}\n{}", + sorted.join(","), + payload.map(canonical).unwrap_or_else(|| "null".into()) + ); + sha256_hex(body.as_bytes()) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Project, + Folder, + Doc, + Text, + Asset, +} + +/// Parse and validate an entity key. Remote data is untrusted: ids become file names, so only +/// plain identifier characters are accepted. +pub fn parse_entity(entity: &str) -> Option<(Kind, &str)> { + if entity == "project" { + return Some((Kind::Project, "")); + } + let (kind, id) = entity.split_once(':')?; + let kind = match kind { + "folder" => Kind::Folder, + "doc" => Kind::Doc, + "text" => Kind::Text, + "asset" => Kind::Asset, + _ => return None, + }; + let ok = match kind { + Kind::Asset => safe_asset_name(id), + _ => safe_id(id), + }; + ok.then_some((kind, id)) +} + +pub fn safe_id(id: &str) -> bool { + !id.is_empty() && id.len() <= 80 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') +} + +pub fn safe_asset_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 128 + && !name.starts_with('.') + && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) + && !name.contains("..") +} + +/// One immutable revision as exchanged between devices. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Revision { + pub entity: String, + pub rev: String, + pub parents: Vec, + /// `null` is a tombstone (the entity was deleted). + pub payload: Option, + pub origin: String, +} + +impl Revision { + pub fn new(entity: &str, parents: Vec, payload: Option, origin: &str) -> Self { + let mut parents = parents; + parents.sort(); + parents.dedup(); + let rev = revision_id(entity, &parents, payload.as_ref()); + Revision { entity: entity.into(), rev, parents, payload, origin: origin.into() } + } + + /// Recompute the id: a received revision whose id does not match its content is rejected. + pub fn verify(&self) -> bool { + parse_entity(&self.entity).is_some() + && self.parents.len() <= 64 + && self.rev == revision_id(&self.entity, &self.parents, self.payload.as_ref()) + } + + /// Hash of a content blob this revision needs (`text` and `asset` entities only). + pub fn blob(&self) -> Option { + let (kind, _) = parse_entity(&self.entity)?; + if !matches!(kind, Kind::Text | Kind::Asset) { + return None; + } + let sha = self.payload.as_ref()?.get("sha256")?.as_str()?; + (sha.len() == 64 && sha.chars().all(|c| c.is_ascii_hexdigit())).then(|| sha.to_ascii_lowercase()) + } +} + +/// A device's numbered publication. Batches from one device are applied in sequence order. +#[derive(Serialize, Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Batch { + pub schema_version: u32, + pub project_id: String, + pub device_id: String, + pub device_name: String, + pub seq: u64, + pub created_at: String, + pub revisions: Vec, +} + +/// Field-level three-way merge for small metadata entities. Symmetric and deterministic: both +/// devices compute the same result. Returns the merged value and the keys that truly collided. +pub fn merge_fields( + base: Option<&Value>, + ours: (&str, Option<&Value>), + theirs: (&str, Option<&Value>), +) -> (Option, Vec) { + let (our_rev, ours) = ours; + let (their_rev, theirs) = theirs; + match (ours, theirs) { + (None, None) => return (None, Vec::new()), + // Edit beats delete: a chapter changed elsewhere is never silently lost. An unchanged + // side accepts the delete. + (None, Some(kept)) | (Some(kept), None) => { + return if base == Some(kept) { + (None, Vec::new()) + } else { + (Some(kept.clone()), vec!["deleted".into()]) + }; + } + _ => {} + } + let empty = Map::new(); + let o = ours.and_then(Value::as_object).unwrap_or(&empty); + let t = theirs.and_then(Value::as_object).unwrap_or(&empty); + let b = base.and_then(Value::as_object).unwrap_or(&empty); + let mut keys: Vec<&String> = o.keys().chain(t.keys()).collect(); + keys.sort(); + keys.dedup(); + let mut merged = Map::new(); + let mut collided = Vec::new(); + for key in keys { + let (ov, tv, bv) = (o.get(key), t.get(key), b.get(key)); + let pick = if ov == tv || tv == bv { + ov + } else if ov == bv { + tv + } else { + collided.push(key.clone()); + // Deterministic, clock-free tie-break so every replica converges. + if our_rev > their_rev { ov } else { tv } + }; + if let Some(v) = pick { + merged.insert(key.clone(), v.clone()); + } + } + (Some(Value::Object(merged)), collided) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn canonical_json_ignores_key_order() { + let a = json!({"b": 1, "a": {"y": [1, {"d": 2, "c": 3}], "x": null}}); + let b: Value = serde_json::from_str(r#"{"a":{"x":null,"y":[1,{"c":3,"d":2}]},"b":1}"#).unwrap(); + assert_eq!(canonical(&a), canonical(&b)); + assert_eq!(canonical(&a), r#"{"a":{"x":null,"y":[1,{"c":3,"d":2}]},"b":1}"#); + } + + #[test] + fn revision_ids_are_device_independent_and_verified() { + let one = Revision::new("doc:a", vec!["p2".into(), "p1".into()], Some(json!({"title": "One"})), "phone"); + let two = Revision::new("doc:a", vec!["p1".into(), "p2".into()], Some(json!({"title": "One"})), "desktop"); + assert_eq!(one.rev, two.rev); + assert!(one.verify()); + let mut forged = one.clone(); + forged.payload = Some(json!({"title": "Two"})); + assert!(!forged.verify()); + } + + #[test] + fn entity_keys_reject_paths() { + assert!(parse_entity("doc:3f2a-11").is_some()); + assert!(parse_entity("asset:9c1e.png").is_some()); + assert!(parse_entity("doc:../x").is_none()); + assert!(parse_entity("asset:..png").is_none()); + assert!(parse_entity("asset:a/b.png").is_none()); + assert!(parse_entity("asset:.hidden").is_none()); + assert!(parse_entity("other:x").is_none()); + } + + #[test] + fn metadata_merge_takes_both_sides_and_is_symmetric() { + let base = json!({"title": "Ch 2", "folderId": null, "order": 1}); + let moved = json!({"title": "Ch 2", "folderId": "vol1", "order": 1}); + let renamed = json!({"title": "Chapter Two", "folderId": null, "order": 1}); + let (m1, c1) = merge_fields(Some(&base), ("a", Some(&moved)), ("b", Some(&renamed))); + let (m2, c2) = merge_fields(Some(&base), ("b", Some(&renamed)), ("a", Some(&moved))); + assert_eq!(m1, Some(json!({"title": "Chapter Two", "folderId": "vol1", "order": 1}))); + assert_eq!(m1, m2); + assert!(c1.is_empty() && c2.is_empty()); + + let x = json!({"title": "X"}); + let y = json!({"title": "Y"}); + let (r1, k1) = merge_fields(Some(&base), ("a", Some(&x)), ("b", Some(&y))); + let (r2, _) = merge_fields(Some(&base), ("b", Some(&y)), ("a", Some(&x))); + assert_eq!(r1, r2); + assert_eq!(k1, vec!["title".to_string()]); + } + + #[test] + fn edit_wins_over_concurrent_delete() { + let base = json!({"title": "A"}); + let edited = json!({"title": "B"}); + let (merged, notes) = merge_fields(Some(&base), ("a", None), ("b", Some(&edited))); + assert_eq!(merged, Some(edited)); + assert_eq!(notes, vec!["deleted".to_string()]); + } +} diff --git a/app/src-tauri/src/sync/portable.rs b/app/src-tauri/src/sync/portable.rs new file mode 100644 index 0000000..914dbae --- /dev/null +++ b/app/src-tauri/src/sync/portable.rs @@ -0,0 +1,166 @@ +//! Portable asset references for synced content. +//! +//! Documents on disk keep absolute paths to `/assets/` (the editor and maps +//! resolve them at render time). Synced snapshots replace exactly those references with +//! `mnemo-asset:`, and the receiving device turns them back into its own absolute path. +//! Only `` in chapters and whole JSON string values in maps are touched; prose, +//! graph labels and ids are never rewritten. +use lol_html::{element, rewrite_str, RewriteStrSettings}; +use serde_json::Value; +use std::path::Path; + +pub const SCHEME: &str = "mnemo-asset:"; + +fn normalize(path: &str) -> String { + path.replace('\\', "/").trim_start_matches("//?/").trim_end_matches('/').to_string() +} + +/// The asset file name if `value` points into this project's `assets/` folder. +fn project_asset(value: &str, roots: &[String]) -> Option { + let path = normalize(value); + for root in roots { + let prefix = format!("{}/assets/", normalize(root)); + let windows = prefix.as_bytes().get(1) == Some(&b':'); + let matches = path.starts_with(&prefix) + || (windows && path.get(..prefix.len()).is_some_and(|p| p.eq_ignore_ascii_case(&prefix))); + if matches { + let name = &path[prefix.len()..]; + if super::model::safe_asset_name(name) { + return Some(name.to_string()); + } + } + } + None +} + +/// Every textual form of a project root that a stored path might start with. +pub fn roots_for(dir: &Path) -> Vec { + let mut roots = vec![dir.to_string_lossy().into_owned()]; + if let Ok(canonical) = dir.canonicalize() { + let c = canonical.to_string_lossy().into_owned(); + if !roots.contains(&c) { + roots.push(c); + } + } + roots +} + +fn rewrite_html(html: &str, map: &dyn Fn(&str) -> Option) -> String { + if !html.contains(" Option) -> bool { + match value { + Value::String(s) => match map(s) { + Some(mapped) => { + *s = mapped; + true + } + None => false, + }, + Value::Array(items) => items.iter_mut().fold(false, |changed, v| rewrite_json(v, map) | changed), + Value::Object(obj) => obj.values_mut().fold(false, |changed, v| rewrite_json(v, map) | changed), + _ => false, + } +} + +fn rewrite(content: &str, doc_type: &str, map: &dyn Fn(&str) -> Option) -> String { + if doc_type == "text" { + return rewrite_html(content, map); + } + // Untouched content keeps its exact bytes; only rewritten maps are re-serialised. + match serde_json::from_str::(content) { + Ok(mut graph) => { + if rewrite_json(&mut graph, map) { + serde_json::to_string(&graph).unwrap_or_else(|_| content.to_string()) + } else { + content.to_string() + } + } + Err(_) => content.to_string(), + } +} + +/// Disk content -> synced content. +pub fn to_portable(content: &str, doc_type: &str, roots: &[String]) -> String { + rewrite(content, doc_type, &|v| project_asset(v, roots).map(|name| format!("{SCHEME}{name}"))) +} + +/// Synced content -> disk content for this device's copy of the project. +pub fn to_local(content: &str, doc_type: &str, project_dir: &Path) -> String { + let assets = project_dir.join("assets"); + rewrite(content, doc_type, &|v| { + let name = v.strip_prefix(SCHEME)?; + super::model::safe_asset_name(name).then(|| assets.join(name).to_string_lossy().into_owned()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn chapter_images_round_trip_between_devices() { + let desktop = Path::new(r"C:\Users\Writer\Novels\Ashen"); + let roots = roots_for(desktop); + let html = r#"

Before map after & C:\Users\Writer\Novels\Ashen\assets\a1.png

"#; + let portable = to_portable(html, "text", &roots); + assert!(portable.contains(r#"src="mnemo-asset:a1.png""#), "{portable}"); + assert!(portable.contains(r"after & C:\Users\Writer\Novels\Ashen\assets\a1.png"), "prose is untouched"); + + let phone = Path::new("/data/user/0/app/projects/p1"); + let local = to_local(&portable, "text", phone); + assert!(local.contains("/data/user/0/app/projects/p1")); + assert_eq!(to_portable(&local, "text", &roots_for(phone)), portable, "stable round trip"); + } + + #[test] + fn windows_paths_match_case_insensitively_and_with_forward_slashes() { + let roots = vec![r"C:\Novels\Ashen".to_string()]; + let html = r#""#; + assert_eq!(to_portable(html, "text", &roots), r#""#); + } + + #[test] + fn map_documents_rewrite_whole_path_values_including_imports() { + let roots = vec!["/home/w/p".to_string()]; + let map = r#"{"items":[{"assetPath":"/home/w/p/assets/i.png","label":"/home/w/p/assets/i.png is here"}],"imports":[{"id":"x","name":"Tower","path":"/home/w/p/assets/t.png"}],"other":"/elsewhere/z.png"}"#; + let portable = to_portable(map, "fantasymap", &roots); + let v: Value = serde_json::from_str(&portable).unwrap(); + assert_eq!(v["items"][0]["assetPath"], "mnemo-asset:i.png"); + assert_eq!(v["items"][0]["label"], "/home/w/p/assets/i.png is here"); + assert_eq!(v["imports"][0]["path"], "mnemo-asset:t.png"); + assert_eq!(v["other"], "/elsewhere/z.png", "assets outside the project are left alone"); + let back = to_local(&portable, "fantasymap", Path::new("/phone/p")); + assert_eq!(to_portable(&back, "fantasymap", &["/phone/p".to_string()]), portable); + } + + #[test] + fn content_without_assets_keeps_its_exact_bytes() { + let map = "{ \"nodes\": [ ], \"edges\": [] }"; + assert_eq!(to_portable(map, "mindmap", &["/p".into()]), map); + assert_eq!(to_local(map, "mindmap", Path::new("/p")), map); + assert_eq!(to_portable("

Hi

", "text", &["/p".into()]), "

Hi

"); + } + + #[test] + fn hostile_portable_names_are_not_turned_into_paths() { + let html = r#""#; + assert_eq!(to_local(html, "text", Path::new("/p")), html); + } +} diff --git a/app/src-tauri/src/sync/service.rs b/app/src-tauri/src/sync/service.rs new file mode 100644 index 0000000..fb76515 --- /dev/null +++ b/app/src-tauri/src/sync/service.rs @@ -0,0 +1,814 @@ +//! The sync service: a background worker that runs sync rounds, and the Tauri commands the +//! frontend reaches through `lib/api.ts`. Saving never waits for it; a save only nudges it. +use super::drive::api::{self as drive_api, Account, Drive, DriveTransport, RemoteProject}; +use super::drive::auth; +use super::engine::{ConflictVersion, Engine, SyncReport, TransportError}; +use super::model; +use super::store::Store; +use crate::project::{Project, Registry}; +use crate::ApiResponse; +use serde::Serialize; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; +use std::sync::{Condvar, Mutex, OnceLock}; +use std::time::{Duration, Instant}; +use tauri::{AppHandle, Emitter}; + +const POLL: Duration = Duration::from_secs(90); +const SAVE_DELAY: Duration = Duration::from_secs(8); +const MAX_BACKOFF: Duration = Duration::from_secs(15 * 60); + +/// One sync round (or engine-changing command) at a time. +static ENGINE: Mutex<()> = Mutex::new(()); +static SERVICE: OnceLock = OnceLock::new(); + +struct Wake { + due: Option, + backoff: Duration, +} + +#[derive(Default, Clone)] +struct Global { + state: String, + message: Option, + last_round: Option, +} + +struct Service { + app: Option, + wake: Mutex, + cv: Condvar, + active: Mutex>, + global: Mutex, +} + +fn service() -> Option<&'static Service> { + SERVICE.get() +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|p| p.into_inner()) +} + +fn db_path() -> PathBuf { + crate::project::data_dir().join("sync").join("mnemosync.db") +} + +fn open_store() -> Result { + let store = Store::open(&db_path())?; + drive_api::ensure_tables(&store)?; + Ok(store) +} + +pub fn device_name() -> String { + if cfg!(target_os = "android") { + // The phone's model ("Pixel 8"), so conflict copies from two phones are told apart. + return android_model().unwrap_or_else(|| "Android device".into()); + } + std::env::var("COMPUTERNAME") + .or_else(|_| std::env::var("HOSTNAME")) + .ok() + .filter(|n| !n.trim().is_empty()) + .unwrap_or_else(|| "Desktop".into()) +} + +/// `ro.product.model` through Android's `getprop` (readable by apps, no permission needed). +fn android_model() -> Option { + if !cfg!(target_os = "android") { + return None; + } + static MODEL: OnceLock> = OnceLock::new(); + MODEL + .get_or_init(|| { + let out = std::process::Command::new("/system/bin/getprop").arg("ro.product.model").output().ok()?; + let name = String::from_utf8(out.stdout).ok()?.trim().chars().take(60).collect::(); + (!name.is_empty()).then_some(name) + }) + .clone() +} + +fn account(store: &Store) -> Result, String> { + store.get_meta("drive.account")?.map(|a| serde_json::from_str(&a).map_err(|e| e.to_string())).transpose() +} + +/// Start the worker (once, from the Tauri setup hook). +pub fn start(app: AppHandle) { + let svc = Service { + app: Some(app), + wake: Mutex::new(Wake { due: Some(Instant::now() + Duration::from_secs(3)), backoff: POLL }), + cv: Condvar::new(), + active: Mutex::new(None), + global: Mutex::new(Global { state: "idle".into(), ..Default::default() }), + }; + if SERVICE.set(svc).is_err() { + return; + } + std::thread::Builder::new() + .name("mnemosync".into()) + .spawn(worker) + .expect("sync worker thread"); +} + +/// A save happened: sync soon (debounced so a burst of saves makes one round). +pub fn nudge(project_id: &str) { + let Some(s) = service() else { return }; + if !model::safe_id(project_id) { + return; + } + let mut w = lock(&s.wake); + let soon = Instant::now() + SAVE_DELAY; + if w.due.is_none_or(|d| d > soon) { + w.due = Some(soon); + } + s.cv.notify_all(); +} + +/// The project left this device's library: stop syncing it here. Its history stays, so adding +/// it again later resumes instead of duplicating. +pub fn forget(project_id: &str) { + if service().is_none() { + return; + } + let _guard = lock(&ENGINE); + if let Ok(store) = open_store() { + let _ = store.disable_project(project_id); + } +} + +fn wake_now() { + if let Some(s) = service() { + lock(&s.wake).due = Some(Instant::now()); + s.cv.notify_all(); + } +} + +fn worker() { + let Some(s) = service() else { return }; + loop { + { + let mut w = lock(&s.wake); + loop { + let now = Instant::now(); + match w.due { + Some(due) if due <= now => break, + Some(due) => w = s.cv.wait_timeout(w, due - now).unwrap_or_else(|p| p.into_inner()).0, + None => w = s.cv.wait(w).unwrap_or_else(|p| p.into_inner()), + } + } + w.due = None; + } + let outcome = round(None); + let mut w = lock(&s.wake); + let next = match outcome { + Round::Idle => None, + Round::Ok => { + w.backoff = POLL; + Some(POLL) + } + Round::Retry => { + w.backoff = (w.backoff * 2).clamp(Duration::from_secs(30), MAX_BACKOFF); + Some(w.backoff) + } + }; + if let Some(delay) = next { + let at = Instant::now() + delay; + if w.due.is_none_or(|d| d > at) { + w.due = Some(at); + } + } + } +} + +enum Round { + /// Nothing to do (signed out / nothing enabled): sleep until nudged. + Idle, + Ok, + Retry, +} + +fn set_global(state: &str, message: Option) { + if let Some(s) = service() { + let mut g = lock(&s.global); + g.state = state.into(); + g.message = message; + if state == "idle" { + g.last_round = Some(chrono::Utc::now().to_rfc3339()); + } + } + emit("sync://status", status_value()); +} + +fn emit(event: &str, payload: Value) { + if let Some(app) = service().and_then(|s| s.app.as_ref()) { + let _ = app.emit(event, payload); + } +} + +fn active_doc(project_id: &str) -> Option { + let s = service()?; + lock(&s.active).as_ref().filter(|(p, _)| p == project_id).map(|(_, d)| d.clone()) +} + +/// Rebuild project.json's content-free document index after remote changes so the library and +/// `list_projects` see the same chapters as the documents folder. +fn refresh_index(dir: &Path) -> Result<(), String> { + let project = Project::load_from_path(dir)?; + project.save() +} + +fn after_changes(project_id: &str, dir: &Path, report: &SyncReport) { + if report.changed.is_empty() && report.staged.is_empty() { + return; + } + if !report.changed.is_empty() { + if let Err(e) = refresh_index(dir) { + log::warn!("sync: index refresh failed: {e}"); + } + } + emit("sync://applied", json!({"projectId": project_id, "changed": report.changed, "staged": report.staged})); +} + +/// Run a sync round for every enabled project (or just `only`). Holds the engine lock. +fn round(only: Option<&str>) -> Round { + let _guard = lock(&ENGINE); + let store = match open_store() { + Ok(s) => s, + Err(e) => { + set_global("error", Some(e)); + return Round::Retry; + } + }; + let projects = store.enabled_projects().unwrap_or_default(); + let Ok(Some(acct)) = account(&store) else { + set_global("signed-out", None); + return Round::Idle; + }; + if projects.is_empty() { + set_global("idle", None); + return Round::Idle; + } + if !auth::has_grant() && !cfg!(target_os = "android") { + set_global("needs-auth", Some("Sign in to Google Drive again to keep syncing".into())); + return Round::Idle; + } + set_global("syncing", None); + let drive = Drive::new(); + if let Err(e) = drive_api::refresh_changes(&drive, &store, &acct.id) { + return fail(e); + } + let name = device_name(); + let mut worst: Option = None; + for (project_id, project_account) in projects { + if only.is_some_and(|o| o != project_id) || project_account != acct.id { + continue; + } + let dir = Project::resolve_dir(&project_id); + if !dir.join("project.json").exists() { + let _ = store.set_project_result(&project_id, Some("The project folder is missing on this device")); + continue; + } + let Ok(engine) = Engine::new(&store, &name) else { continue }; + let mut transport = DriveTransport { drive: &drive, store: &store, device_id: engine.device_id.clone() }; + let active = active_doc(&project_id); + match engine.sync(&project_id, &dir, &mut transport, active.as_deref()) { + Ok(report) => { + let _ = store.set_project_result(&project_id, None); + after_changes(&project_id, &dir, &report); + if let Ok(project) = Project::load_from_path(&dir) { + if let Err(e) = drive.publish_info(&store, &project_id, &project.name, &engine.device_id, &name, report.published > 0) { + log::warn!("sync: catalogue update failed: {e}"); + } + } + } + Err(e) => { + let _ = store.set_project_result(&project_id, Some(&e.to_string())); + let severe = matches!(e, TransportError::Auth(_) | TransportError::Offline(_)); + if worst.is_none() || severe { + worst = Some(e); + } + } + } + } + match worst { + None => { + set_global("idle", None); + Round::Ok + } + Some(e) => fail(e), + } +} + +fn fail(e: TransportError) -> Round { + match e { + TransportError::Auth(m) => { + set_global("needs-auth", Some(m)); + Round::Idle + } + TransportError::Offline(m) => { + set_global("offline", Some(m)); + Round::Retry + } + TransportError::Busy(m) => { + set_global("busy", Some(m)); + Round::Retry + } + TransportError::Quota(m) => { + set_global("error", Some(m)); + Round::Retry + } + TransportError::Other(m) => { + set_global("error", Some(m)); + Round::Retry + } + } +} + +// ---- status --------------------------------------------------------------------------------- + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ConflictSummary { + pub doc_id: String, + pub title: String, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ProjectStatus { + pub project_id: String, + pub state: String, + pub pending: u64, + pub conflicts: Vec, + pub staged: Vec, + pub last_sync: Option, + pub error: Option, + pub notices: Vec, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Notice { + pub id: i64, + pub kind: String, + pub detail: String, + pub created_at: String, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SyncStatus { + pub configured: bool, + pub platform: &'static str, + pub account: Option, + pub state: String, + pub message: Option, + pub last_round: Option, + pub device_name: String, + pub projects: Vec, +} + +fn doc_title(dir: &Path, doc_id: &str) -> String { + std::fs::read(dir.join("documents").join(format!("{doc_id}.json"))) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .and_then(|d| d["title"].as_str().map(String::from)) + .unwrap_or_else(|| "Untitled".into()) +} + +fn project_status(store: &Store, project_id: &str, global: &str) -> Result { + let dir = Project::resolve_dir(project_id); + let pending = store.outbox_len(project_id, "drive")?; + let conflicts: Vec = store + .conflicted_entities(project_id)? + .into_iter() + .filter_map(|e| e.strip_prefix("text:").map(String::from)) + .map(|doc_id| ConflictSummary { title: doc_title(&dir, &doc_id), doc_id }) + .collect(); + let mut staged: Vec = store + .staged_entities(project_id)? + .into_iter() + .filter_map(|e| e.split_once(':').map(|(_, id)| id.to_string())) + .collect(); + staged.sort(); + staged.dedup(); + let (last_sync, error) = store.project_result(project_id)?; + let acct = account(store)?; + let state = if store.project_account(project_id)? != acct.as_ref().map(|a| a.id.clone()) { + "account-mismatch" + } else if !conflicts.is_empty() { + "conflict" + } else if error.is_some() && global != "syncing" { + match global { + "offline" => "offline", + "needs-auth" => "needs-auth", + _ => "error", + } + } else if global == "syncing" { + "syncing" + } else if pending > 0 || last_sync.is_none() { + "pending" + } else { + "synced" + }; + let notices = store + .notices(project_id, 20)? + .into_iter() + .map(|(id, _, kind, detail, created_at)| Notice { id, kind, detail, created_at }) + .collect(); + Ok(ProjectStatus { project_id: project_id.into(), state: state.into(), pending, conflicts, staged, last_sync, error, notices }) +} + +fn status_value() -> Value { + serde_json::to_value(status().unwrap_or_else(|e| SyncStatus { + configured: auth::configured(), + platform: platform(), + account: None, + state: "error".into(), + message: Some(e), + last_round: None, + device_name: device_name(), + projects: Vec::new(), + })) + .unwrap_or(Value::Null) +} + +fn platform() -> &'static str { + if cfg!(target_os = "android") { + "android" + } else if cfg!(any(target_os = "ios")) { + "ios" + } else { + "desktop" + } +} + +pub fn status() -> Result { + let store = open_store()?; + let g = service().map(|s| lock(&s.global).clone()).unwrap_or_default(); + let acct = account(&store)?; + let state = if !auth::configured() { + "unconfigured".to_string() + } else if acct.is_none() { + "signed-out".to_string() + } else if !cfg!(target_os = "android") && !auth::has_grant() { + // Signed out (or revoked) while projects stay bound to this account: offer Reconnect. + "needs-auth".to_string() + } else if g.state.is_empty() { + "idle".to_string() + } else { + g.state.clone() + }; + let projects = store + .enabled_projects()? + .into_iter() + .map(|(id, _)| project_status(&store, &id, &state)) + .collect::>()?; + Ok(SyncStatus { + configured: auth::configured(), + platform: platform(), + account: acct, + // Why sync is unavailable here (Linux), shown instead of build instructions. + message: if state == "unconfigured" { auth::unavailable_reason().map(String::from) } else { g.message }, + state, + last_round: g.last_round, + device_name: device_name(), + projects, + }) +} + +// ---- commands --------------------------------------------------------------------------------- + +fn respond(r: Result) -> ApiResponse { + match r { + Ok(v) => ApiResponse::success(v), + Err(e) => ApiResponse::error(e), + } +} + +async fn blocking(f: impl FnOnce() -> Result + Send + 'static) -> ApiResponse { + respond(tauri::async_runtime::spawn_blocking(f).await.map_err(|e| e.to_string()).and_then(|r| r)) +} + +fn valid_project(project_id: &str) -> Result<(), String> { + if uuid::Uuid::parse_str(project_id).is_ok() || model::safe_id(project_id) { + Ok(()) + } else { + Err("Invalid project".into()) + } +} + +/// Every command that turns ids into paths checks them first (`documents/.json`, the +/// project folder), whoever the caller is. +fn valid_ids(project_id: &str, document_id: Option<&str>) -> Result<(), String> { + valid_project(project_id)?; + match document_id { + Some(d) if !model::safe_id(d) => Err("Invalid document".into()), + _ => Ok(()), + } +} + +/// After a grant: identify the Google account and refuse to silently switch accounts. +fn adopt_account() -> Result { + adopt_account_typed().map_err(|e| e.to_string()) +} + +fn adopt_account_typed() -> Result { + let fresh = Drive::new().about()?; + let store = open_store()?; + if let Some(previous) = account(&store)? { + if previous.id != fresh.id && !store.enabled_projects()?.is_empty() { + // Keep the grant out of use: projects stay tied to the account they were synced with. + let _ = auth::sign_out(); + return Err(TransportError::Other(format!( + "Signed in as {}, but this device syncs with {}. Sign in with that account, or turn sync off for every project first.", + if fresh.email.is_empty() { "another account".to_string() } else { fresh.email.clone() }, + if previous.email.is_empty() { "another account".to_string() } else { previous.email.clone() }, + ))); + } + } + store.set_meta("drive.account", &serde_json::to_string(&fresh).map_err(|e| e.to_string())?)?; + Ok(fresh) +} + +#[tauri::command] +pub fn sync_status() -> ApiResponse { + respond(status()) +} + +#[tauri::command] +pub async fn drive_sign_in() -> ApiResponse { + blocking(|| { + // A grant from a sign-in whose account check failed (e.g. the Drive API was still off) + // is reused, so retrying doesn't send the writer through Google's pages again. Only a + // grant Google no longer accepts leads to a new sign-in; any other failure (API still + // off, offline, rate limited, wrong account) is reported and the grant is kept. + if auth::has_grant() { + match adopt_account_typed() { + Ok(_) => { + wake_now(); + return status(); + } + Err(TransportError::Auth(_)) => {} + Err(e) => return Err(e.to_string()), + } + } + auth::sign_in().map_err(|e| e.to_string())?; + adopt_account()?; + wake_now(); + status() + }) + .await +} + +#[tauri::command] +pub fn drive_cancel_sign_in() -> ApiResponse<()> { + auth::cancel_sign_in(); + ApiResponse::success(()) +} + +/// Android: an access token from Google's native authorization prompt. +#[tauri::command] +pub async fn drive_set_access_token(token: String, expires_in: u64) -> ApiResponse { + blocking(move || { + if token.trim().is_empty() || token.len() > 4096 { + return Err("Invalid Google authorization".into()); + } + auth::set_access_token(token.trim(), expires_in.clamp(60, 3600)); + adopt_account()?; + wake_now(); + status() + }) + .await +} + +/// Sign out of Google on this device. Synced projects stay on disk and keep their history, +/// so signing back in with the same account resumes without duplicating anything. +#[tauri::command] +pub async fn drive_sign_out() -> ApiResponse { + blocking(|| { + let _guard = lock(&ENGINE); + auth::sign_out()?; + let store = open_store()?; + if store.enabled_projects()?.is_empty() { + store.delete_meta("drive.account")?; + } + drop(store); + set_global("signed-out", None); + status() + }) + .await +} + +#[tauri::command] +pub async fn sync_enable_project(project_id: String) -> ApiResponse { + blocking(move || { + valid_project(&project_id)?; + { + let _guard = lock(&ENGINE); + let store = open_store()?; + let acct = account(&store)?.ok_or("Sign in to Google Drive first")?; + if !Project::resolve_dir(&project_id).join("project.json").exists() { + return Err("Project not found".into()); + } + store.enable_project(&project_id, &acct.id, false)?; + } + wake_now(); + status() + }) + .await +} + +#[tauri::command] +pub async fn sync_disable_project(project_id: String) -> ApiResponse { + blocking(move || { + valid_ids(&project_id, None)?; + let _guard = lock(&ENGINE); + open_store()?.disable_project(&project_id)?; + drop(_guard); + status() + }) + .await +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RemoteEntry { + #[serde(flatten)] + pub remote: RemoteProject, + /// Already on this device (same project identity). + pub local: bool, + pub syncing: bool, +} + +#[tauri::command] +pub async fn drive_remote_projects() -> ApiResponse> { + blocking(|| { + let store = open_store()?; + account(&store)?.ok_or("Sign in to Google Drive first")?; + let enabled: Vec = store.enabled_projects()?.into_iter().map(|(p, _)| p).collect(); + let remote = Drive::new().remote_projects().map_err(|e| e.to_string())?; + Ok(remote + .into_iter() + .map(|r| RemoteEntry { + local: Registry::get_path(&r.project_id).is_some(), + syncing: enabled.contains(&r.project_id), + remote: r, + }) + .collect()) + }) + .await +} + +/// Download a project from Drive into a new local folder (or link the same project already here). +#[tauri::command] +pub async fn sync_download_project(project_id: String, name: String) -> ApiResponse { + blocking(move || { + valid_project(&project_id)?; + { + let _guard = lock(&ENGINE); + let store = open_store()?; + let acct = account(&store)?.ok_or("Sign in to Google Drive first")?; + let existing = Registry::get_path(&project_id).map(PathBuf::from).filter(|d| d.join("project.json").exists()); + match existing { + Some(_) => store.enable_project(&project_id, &acct.id, false)?, + None => { + let dir = Project::projects_dir().join(&project_id); + if dir.join("project.json").exists() { + return Err("A project folder with this identity already exists".into()); + } + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let label = name.trim().chars().take(200).collect::(); + let skeleton = json!({ + "id": project_id, "name": if label.is_empty() { "Synced project".into() } else { label }, + "description": null, "created_at": chrono::Utc::now().to_rfc3339(), "folders": [], "documents": [] + }); + crate::project::write_atomic(&dir.join("project.json"), &skeleton.to_string())?; + Project::load_from_path(&dir)?; + store.enable_project(&project_id, &acct.id, true)?; + } + } + } + // Pull right away so the writer can open it; offline, it finishes in a later round. + round(Some(&project_id)); + Project::load(&project_id) + }) + .await +} + +#[tauri::command] +pub fn sync_now() -> ApiResponse<()> { + wake_now(); + ApiResponse::success(()) +} + +/// The editor tells the backend which chapter is open. Leaving a chapter applies any update +/// that was held back for it (the app has saved it first). +#[tauri::command] +pub async fn sync_set_active(project_id: Option, document_id: Option) -> ApiResponse<()> { + blocking(move || { + let next = project_id.zip(document_id); + if let Some((p, d)) = &next { + valid_ids(p, Some(d))?; + } + let previous = match service() { + Some(s) => std::mem::replace(&mut *lock(&s.active), next.clone()), + None => None, + }; + if let Some((p, d)) = previous.filter(|prev| Some(prev) != next.as_ref()) { + apply_staged_inner(&p, &d)?; + } + Ok(()) + }) + .await +} + +fn apply_staged_inner(project_id: &str, doc_id: &str) -> Result { + let _guard = lock(&ENGINE); + let store = open_store()?; + if store.project_account(project_id)?.is_none() { + return Ok(SyncReport::default()); + } + let dir = Project::resolve_dir(project_id); + let engine = Engine::new(&store, &device_name())?; + let mut report = SyncReport::default(); + engine.apply_staged(project_id, &dir, doc_id, &mut report)?; + after_changes(project_id, &dir, &report); + emit("sync://status", status_value()); + Ok(report) +} + +/// "Load the new version": the writer accepts a held-back update for the open chapter. +#[tauri::command] +pub async fn sync_apply_staged(project_id: String, document_id: String) -> ApiResponse { + blocking(move || { + valid_ids(&project_id, Some(&document_id))?; + let report = apply_staged_inner(&project_id, &document_id)?; + nudge(&project_id); + Ok(report) + }) + .await +} + +#[tauri::command] +pub async fn sync_conflict(project_id: String, document_id: String) -> ApiResponse> { + blocking(move || { + valid_ids(&project_id, Some(&document_id))?; + let _guard = lock(&ENGINE); + let store = open_store()?; + let dir = Project::resolve_dir(&project_id); + Engine::new(&store, &device_name())?.conflict_versions(&project_id, &dir, &document_id) + }) + .await +} + +/// Keep one version in place; with `keep_copies` the others become separate chapters. +#[tauri::command] +pub async fn sync_resolve_conflict(project_id: String, document_id: String, keep: String, keep_copies: bool) -> ApiResponse> { + blocking(move || { + valid_ids(&project_id, Some(&document_id))?; + let created = { + let _guard = lock(&ENGINE); + let store = open_store()?; + let dir = Project::resolve_dir(&project_id); + let created = Engine::new(&store, &device_name())?.resolve(&project_id, &dir, &document_id, &keep, keep_copies)?; + refresh_index(&dir)?; + created + }; + emit("sync://applied", json!({"projectId": project_id, "changed": [format!("text:{document_id}")], "staged": []})); + nudge(&project_id); + emit("sync://status", status_value()); + Ok(created) + }) + .await +} + +/// Bytes MnemoScript keeps in the writer's Drive (asked for when the settings card opens). +#[tauri::command] +pub async fn drive_usage() -> ApiResponse { + blocking(|| { + account(&open_store()?)?.ok_or("Sign in to Google Drive first")?; + Drive::new().usage().map_err(|e| e.to_string()) + }) + .await +} + +#[tauri::command] +pub fn sync_dismiss_notice(id: i64) -> ApiResponse<()> { + respond(open_store().and_then(|s| s.dismiss_notice(id))) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Regression (PR #4 review, finding 7): three commands joined unchecked ids into + /// `documents/.json` and the project folder path. + #[test] + fn commands_refuse_ids_that_could_leave_the_project() { + assert!(valid_ids("6f0e3a52-1b7c-4f43-9d55-0a1b2c3d4e5f", Some("ch-1")).is_ok()); + for bad in ["../other", r"..\other", "a/b", "", r"C:\Windows"] { + assert!(valid_ids(bad, None).is_err(), "project {bad:?}"); + assert!(valid_ids("6f0e3a52-1b7c-4f43-9d55-0a1b2c3d4e5f", Some(bad)).is_err(), "document {bad:?}"); + } + } +} diff --git a/app/src-tauri/src/sync/store.rs b/app/src-tauri/src/sync/store.rs new file mode 100644 index 0000000..3248e46 --- /dev/null +++ b/app/src-tauri/src/sync/store.rs @@ -0,0 +1,641 @@ +//! Durable MnemoSync state in SQLite (WAL). Project JSON files remain the source of truth; +//! this database only remembers revisions, what is on disk, what is still unsent, conflicts +//! and per-transport cursors. It lives outside every project folder and is never synced. +use super::model::{Batch, Revision}; +use rusqlite::{params, Connection, OptionalExtension}; +use serde_json::Value; +use std::path::Path; + +pub struct Store { + pub conn: Connection, +} + +pub type NoticeRow = (i64, String, String, String, String); + +fn err(e: impl std::fmt::Display) -> String { + e.to_string() +} + +const SCHEMA: &str = r#" +PRAGMA journal_mode = WAL; +PRAGMA synchronous = NORMAL; +PRAGMA foreign_keys = ON; +CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS projects ( + project_id TEXT PRIMARY KEY, + account TEXT NOT NULL, + fresh INTEGER NOT NULL DEFAULT 0, + last_sync TEXT, + last_error TEXT +); +CREATE TABLE IF NOT EXISTS revisions ( + project_id TEXT NOT NULL, rev TEXT NOT NULL, entity TEXT NOT NULL, + parents TEXT NOT NULL, payload TEXT, origin TEXT NOT NULL, + received_at INTEGER NOT NULL DEFAULT (strftime('%s','now')), + PRIMARY KEY (project_id, rev) +); +CREATE INDEX IF NOT EXISTS revisions_entity ON revisions (project_id, entity); +CREATE TABLE IF NOT EXISTS entity_state ( + project_id TEXT NOT NULL, entity TEXT NOT NULL, disk_rev TEXT NOT NULL, disk_hash TEXT NOT NULL, + PRIMARY KEY (project_id, entity) +); +CREATE TABLE IF NOT EXISTS conflicts ( + project_id TEXT NOT NULL, entity TEXT NOT NULL, rev TEXT NOT NULL, + PRIMARY KEY (project_id, entity, rev) +); +CREATE TABLE IF NOT EXISTS staged ( + project_id TEXT NOT NULL, entity TEXT NOT NULL, rev TEXT NOT NULL, + PRIMARY KEY (project_id, entity) +); +CREATE TABLE IF NOT EXISTS blobs (sha TEXT PRIMARY KEY, data BLOB NOT NULL); +CREATE TABLE IF NOT EXISTS outbox ( + id INTEGER PRIMARY KEY AUTOINCREMENT, project_id TEXT NOT NULL, transport TEXT NOT NULL, rev TEXT NOT NULL, + UNIQUE (project_id, transport, rev) +); +CREATE TABLE IF NOT EXISTS pending_batches ( + project_id TEXT NOT NULL, transport TEXT NOT NULL, seq INTEGER NOT NULL, body TEXT NOT NULL, + PRIMARY KEY (project_id, transport) +); +CREATE TABLE IF NOT EXISTS remote_blobs ( + project_id TEXT NOT NULL, transport TEXT NOT NULL, sha TEXT NOT NULL, + PRIMARY KEY (project_id, transport, sha) +); +CREATE TABLE IF NOT EXISTS applied_batches ( + project_id TEXT NOT NULL, transport TEXT NOT NULL, device TEXT NOT NULL, seq INTEGER NOT NULL, + PRIMARY KEY (project_id, transport, device, seq) +); +CREATE TABLE IF NOT EXISTS inbox ( + project_id TEXT NOT NULL, transport TEXT NOT NULL, device TEXT NOT NULL, seq INTEGER NOT NULL, body TEXT NOT NULL, + PRIMARY KEY (project_id, transport, device, seq) +); +CREATE TABLE IF NOT EXISTS devices (device_id TEXT PRIMARY KEY, name TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS notices ( + id INTEGER PRIMARY KEY AUTOINCREMENT, project_id TEXT NOT NULL, entity TEXT NOT NULL, + kind TEXT NOT NULL, detail TEXT NOT NULL, created_at TEXT NOT NULL +); +"#; + +impl Store { + pub fn open(path: &Path) -> Result { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(err)?; + } + let conn = Connection::open(path).map_err(err)?; + conn.busy_timeout(std::time::Duration::from_secs(10)).map_err(err)?; + conn.execute_batch(SCHEMA).map_err(err)?; + let store = Store { conn }; + store.migrate()?; + Ok(store) + } + + #[cfg(test)] + pub fn memory() -> Self { + let conn = Connection::open_in_memory().unwrap(); + conn.execute_batch(SCHEMA).unwrap(); + Store { conn } + } + + fn migrate(&self) -> Result<(), String> { + match self.get_meta("schema")?.as_deref() { + None => self.set_meta("schema", "1"), + Some("1") => Ok(()), + Some(other) => Err(format!("Sync data was written by a newer MnemoScript (schema {other}); update the app")), + } + } + + pub fn get_meta(&self, key: &str) -> Result, String> { + self.conn + .query_row("SELECT value FROM meta WHERE key = ?1", [key], |r| r.get(0)) + .optional() + .map_err(err) + } + + pub fn set_meta(&self, key: &str, value: &str) -> Result<(), String> { + self.conn + .execute("INSERT INTO meta (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value", [key, value]) + .map(|_| ()) + .map_err(err) + } + + pub fn delete_meta(&self, key: &str) -> Result<(), String> { + self.conn.execute("DELETE FROM meta WHERE key = ?1", [key]).map(|_| ()).map_err(err) + } + + /// Random per-install identity, created once. Never derived from hardware or the account. + pub fn device_id(&self) -> Result { + if let Some(id) = self.get_meta("device_id")? { + return Ok(id); + } + let id = uuid::Uuid::new_v4().to_string(); + self.set_meta("device_id", &id)?; + Ok(id) + } + + // ---- projects ------------------------------------------------------------------------- + + /// `fresh` marks an empty downloaded skeleton that must pull before its first scan. + /// + /// The batch counter and the last account survive turning sync off, so turning it back on + /// never reuses a published sequence number. Re-enabling under a *different* Google account + /// starts that account's namespace from scratch: the whole local history is queued again, + /// since nothing of it exists in the new account's Drive. + pub fn enable_project(&self, project_id: &str, account: &str, fresh: bool) -> Result<(), String> { + let last_key = format!("account.{project_id}"); + let previous = self.get_meta(&last_key)?; + let tx = self.conn.unchecked_transaction().map_err(err)?; + if previous.as_deref().is_some_and(|p| p != account) { + for table in ["outbox", "pending_batches", "remote_blobs", "applied_batches", "inbox"] { + tx.execute(&format!("DELETE FROM {table} WHERE project_id = ?1"), [project_id]).map_err(err)?; + } + for table in ["drive_files", "drive_blob_ids"] { + // Transport tables may not exist yet in a fresh database. + let _ = tx.execute(&format!("DELETE FROM {table} WHERE project_id = ?1"), [project_id]); + } + tx.execute( + "INSERT OR IGNORE INTO outbox (project_id, transport, rev) SELECT project_id, 'drive', rev FROM revisions WHERE project_id = ?1 ORDER BY rowid", + [project_id], + ) + .map_err(err)?; + tx.execute( + "DELETE FROM meta WHERE key IN (?1, ?2, ?3, ?4)", + params![format!("next_seq.{project_id}"), format!("drive.listed.{project_id}"), format!("drive.info.{project_id}"), format!("drive.info.{project_id}.name")], + ) + .map_err(err)?; + } + tx.execute( + "INSERT INTO projects (project_id, account, fresh) VALUES (?1, ?2, ?3) ON CONFLICT(project_id) DO UPDATE SET account = excluded.account", + params![project_id, account, fresh as i64], + ) + .map_err(err)?; + tx.execute( + "INSERT INTO meta (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value", + [last_key.as_str(), account], + ) + .map_err(err)?; + tx.commit().map_err(err) + } + + pub fn is_fresh(&self, project_id: &str) -> Result { + self.conn + .query_row("SELECT fresh FROM projects WHERE project_id = ?1", [project_id], |r| r.get::<_, i64>(0)) + .optional() + .map(|o| o == Some(1)) + .map_err(err) + } + + pub fn set_fresh(&self, project_id: &str, fresh: bool) -> Result<(), String> { + self.conn + .execute("UPDATE projects SET fresh = ?2 WHERE project_id = ?1", params![project_id, fresh as i64]) + .map(|_| ()) + .map_err(err) + } + + /// Destinations a project's new revisions are queued for. Only Google Drive exists today; + /// LAN sync will add its own id here without touching the engine. + pub fn project_transports(&self, project_id: &str) -> Result, String> { + Ok(if self.project_account(project_id)?.is_some() { vec!["drive"] } else { Vec::new() }) + } + + /// Stop syncing. Revisions are kept so turning sync back on resumes rather than duplicating. + pub fn disable_project(&self, project_id: &str) -> Result<(), String> { + self.conn.execute("DELETE FROM projects WHERE project_id = ?1", [project_id]).map(|_| ()).map_err(err) + } + + pub fn enabled_projects(&self) -> Result, String> { + let mut stmt = self.conn.prepare("SELECT project_id, account FROM projects ORDER BY project_id").map_err(err)?; + let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?))).map_err(err)?; + rows.collect::>().map_err(err) + } + + pub fn project_account(&self, project_id: &str) -> Result, String> { + self.conn + .query_row("SELECT account FROM projects WHERE project_id = ?1", [project_id], |r| r.get(0)) + .optional() + .map_err(err) + } + + pub fn set_project_result(&self, project_id: &str, error: Option<&str>) -> Result<(), String> { + let now = chrono::Utc::now().to_rfc3339(); + match error { + None => self.conn.execute( + "UPDATE projects SET last_sync = ?2, last_error = NULL WHERE project_id = ?1", + params![project_id, now], + ), + Some(e) => self.conn.execute("UPDATE projects SET last_error = ?2 WHERE project_id = ?1", params![project_id, e]), + } + .map(|_| ()) + .map_err(err) + } + + pub fn project_result(&self, project_id: &str) -> Result<(Option, Option), String> { + self.conn + .query_row("SELECT last_sync, last_error FROM projects WHERE project_id = ?1", [project_id], |r| Ok((r.get(0)?, r.get(1)?))) + .optional() + .map(|o| o.unwrap_or((None, None))) + .map_err(err) + } + + // ---- revisions ------------------------------------------------------------------------ + + pub fn insert_revision(&self, project_id: &str, rev: &Revision) -> Result { + let payload = rev.payload.as_ref().map(|p| p.to_string()); + let parents = serde_json::to_string(&rev.parents).map_err(err)?; + let n = self + .conn + .execute( + "INSERT OR IGNORE INTO revisions (project_id, rev, entity, parents, payload, origin) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![project_id, rev.rev, rev.entity, parents, payload, rev.origin], + ) + .map_err(err)?; + Ok(n > 0) + } + + pub fn revision(&self, project_id: &str, rev: &str) -> Result, String> { + self.conn + .query_row( + "SELECT entity, parents, payload, origin FROM revisions WHERE project_id = ?1 AND rev = ?2", + [project_id, rev], + |r| { + let parents: String = r.get(1)?; + let payload: Option = r.get(2)?; + Ok((r.get::<_, String>(0)?, parents, payload, r.get::<_, String>(3)?)) + }, + ) + .optional() + .map_err(err)? + .map(|(entity, parents, payload, origin)| { + Ok(Revision { + entity, + rev: rev.to_string(), + parents: serde_json::from_str(&parents).map_err(err)?, + payload: payload.map(|p| serde_json::from_str::(&p)).transpose().map_err(err)?, + origin, + }) + }) + .transpose() + } + + pub fn has_revision(&self, project_id: &str, rev: &str) -> Result { + self.conn + .query_row("SELECT 1 FROM revisions WHERE project_id = ?1 AND rev = ?2", [project_id, rev], |_| Ok(())) + .optional() + .map(|o| o.is_some()) + .map_err(err) + } + + /// True when `ancestor` is `rev` itself or reachable through parent links. + pub fn is_ancestor(&self, project_id: &str, ancestor: &str, rev: &str) -> Result { + let mut stack = vec![rev.to_string()]; + let mut seen = std::collections::HashSet::new(); + while let Some(current) = stack.pop() { + if current == ancestor { + return Ok(true); + } + if !seen.insert(current.clone()) { + continue; + } + if let Some(r) = self.revision(project_id, ¤t)? { + stack.extend(r.parents); + } + } + Ok(false) + } + + fn ancestors(&self, project_id: &str, rev: &str) -> Result, String> { + let mut order = Vec::new(); + let mut queue = std::collections::VecDeque::from([rev.to_string()]); + let mut seen = std::collections::HashSet::new(); + while let Some(current) = queue.pop_front() { + if !seen.insert(current.clone()) { + continue; + } + if let Some(r) = self.revision(project_id, ¤t)? { + order.push(current); + queue.extend(r.parents); + } + } + Ok(order) + } + + /// The nearest common ancestor (breadth-first from `a`), used as the merge base. + pub fn merge_base(&self, project_id: &str, a: &str, b: &str) -> Result, String> { + let theirs: std::collections::HashSet = self.ancestors(project_id, b)?.into_iter().collect(); + Ok(self.ancestors(project_id, a)?.into_iter().find(|r| theirs.contains(r))) + } + + // ---- what is on disk -------------------------------------------------------------------- + + pub fn disk_state(&self, project_id: &str, entity: &str) -> Result, String> { + self.conn + .query_row( + "SELECT disk_rev, disk_hash FROM entity_state WHERE project_id = ?1 AND entity = ?2", + [project_id, entity], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional() + .map_err(err) + } + + pub fn set_disk_state(&self, project_id: &str, entity: &str, rev: &str, hash: &str) -> Result<(), String> { + self.conn + .execute( + "INSERT INTO entity_state (project_id, entity, disk_rev, disk_hash) VALUES (?1, ?2, ?3, ?4) + ON CONFLICT(project_id, entity) DO UPDATE SET disk_rev = excluded.disk_rev, disk_hash = excluded.disk_hash", + params![project_id, entity, rev, hash], + ) + .map(|_| ()) + .map_err(err) + } + + pub fn entities(&self, project_id: &str) -> Result, String> { + let mut stmt = self + .conn + .prepare("SELECT entity, disk_rev, disk_hash FROM entity_state WHERE project_id = ?1") + .map_err(err)?; + let rows = stmt.query_map([project_id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))).map_err(err)?; + rows.collect::>().map_err(err) + } + + // ---- conflicts and staged updates ------------------------------------------------------- + + pub fn conflicts(&self, project_id: &str, entity: &str) -> Result, String> { + let mut stmt = self + .conn + .prepare("SELECT rev FROM conflicts WHERE project_id = ?1 AND entity = ?2 ORDER BY rev") + .map_err(err)?; + let rows = stmt.query_map([project_id, entity], |r| r.get(0)).map_err(err)?; + rows.collect::>().map_err(err) + } + + pub fn conflicted_entities(&self, project_id: &str) -> Result, String> { + let mut stmt = self + .conn + .prepare("SELECT DISTINCT entity FROM conflicts WHERE project_id = ?1 ORDER BY entity") + .map_err(err)?; + let rows = stmt.query_map([project_id], |r| r.get(0)).map_err(err)?; + rows.collect::>().map_err(err) + } + + pub fn set_conflicts(&self, project_id: &str, entity: &str, revs: &[String]) -> Result<(), String> { + self.conn + .execute("DELETE FROM conflicts WHERE project_id = ?1 AND entity = ?2", [project_id, entity]) + .map_err(err)?; + for rev in revs { + self.conn + .execute("INSERT OR IGNORE INTO conflicts (project_id, entity, rev) VALUES (?1, ?2, ?3)", [project_id, entity, rev]) + .map_err(err)?; + } + Ok(()) + } + + pub fn staged(&self, project_id: &str, entity: &str) -> Result, String> { + self.conn + .query_row("SELECT rev FROM staged WHERE project_id = ?1 AND entity = ?2", [project_id, entity], |r| r.get(0)) + .optional() + .map_err(err) + } + + pub fn staged_entities(&self, project_id: &str) -> Result, String> { + let mut stmt = self.conn.prepare("SELECT entity FROM staged WHERE project_id = ?1").map_err(err)?; + let rows = stmt.query_map([project_id], |r| r.get(0)).map_err(err)?; + rows.collect::>().map_err(err) + } + + pub fn set_staged(&self, project_id: &str, entity: &str, rev: Option<&str>) -> Result<(), String> { + match rev { + Some(rev) => self.conn.execute( + "INSERT INTO staged (project_id, entity, rev) VALUES (?1, ?2, ?3) ON CONFLICT(project_id, entity) DO UPDATE SET rev = excluded.rev", + [project_id, entity, rev], + ), + None => self.conn.execute("DELETE FROM staged WHERE project_id = ?1 AND entity = ?2", [project_id, entity]), + } + .map(|_| ()) + .map_err(err) + } + + // ---- blobs -------------------------------------------------------------------------------- + + pub fn put_blob(&self, sha: &str, data: &[u8]) -> Result<(), String> { + self.conn + .execute("INSERT OR IGNORE INTO blobs (sha, data) VALUES (?1, ?2)", params![sha, data]) + .map(|_| ()) + .map_err(err) + } + + pub fn blob(&self, sha: &str) -> Result>, String> { + self.conn + .query_row("SELECT data FROM blobs WHERE sha = ?1", [sha], |r| r.get(0)) + .optional() + .map_err(err) + } + + // ---- outbox and publication --------------------------------------------------------------- + + pub fn enqueue(&self, project_id: &str, transport: &str, rev: &str) -> Result<(), String> { + self.conn + .execute("INSERT OR IGNORE INTO outbox (project_id, transport, rev) VALUES (?1, ?2, ?3)", [project_id, transport, rev]) + .map(|_| ()) + .map_err(err) + } + + pub fn dequeue(&self, project_id: &str, transport: &str, rev: &str) -> Result<(), String> { + self.conn + .execute("DELETE FROM outbox WHERE project_id = ?1 AND transport = ?2 AND rev = ?3", [project_id, transport, rev]) + .map(|_| ()) + .map_err(err) + } + + pub fn outbox(&self, project_id: &str, transport: &str, limit: usize) -> Result, String> { + let mut stmt = self + .conn + .prepare("SELECT rev FROM outbox WHERE project_id = ?1 AND transport = ?2 ORDER BY id LIMIT ?3") + .map_err(err)?; + let rows = stmt.query_map(params![project_id, transport, limit as i64], |r| r.get(0)).map_err(err)?; + rows.collect::>().map_err(err) + } + + pub fn outbox_len(&self, project_id: &str, transport: &str) -> Result { + self.conn + .query_row("SELECT COUNT(*) FROM outbox WHERE project_id = ?1 AND transport = ?2", [project_id, transport], |r| r.get::<_, i64>(0)) + .map(|n| n as u64) + .map_err(err) + } + + /// Freeze the next batch before uploading it, so a crash mid-upload retries the *same* bytes + /// under the same sequence number instead of publishing two different batches as one. + pub fn pending_batch(&self, project_id: &str, transport: &str) -> Result, String> { + let body: Option = self + .conn + .query_row("SELECT body FROM pending_batches WHERE project_id = ?1 AND transport = ?2", [project_id, transport], |r| r.get(0)) + .optional() + .map_err(err)?; + body.map(|b| serde_json::from_str(&b).map_err(err)).transpose() + } + + pub fn freeze_batch(&self, batch: &Batch, transport: &str) -> Result<(), String> { + let tx = self.conn.unchecked_transaction().map_err(err)?; + tx.execute( + "INSERT INTO pending_batches (project_id, transport, seq, body) VALUES (?1, ?2, ?3, ?4)", + params![batch.project_id, transport, batch.seq as i64, serde_json::to_string(batch).map_err(err)?], + ) + .map_err(err)?; + tx.execute( + "INSERT INTO meta (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value", + params![format!("next_seq.{}", batch.project_id), (batch.seq + 1).to_string()], + ) + .map_err(err)?; + tx.commit().map_err(err) + } + + pub fn refreeze_batch(&self, batch: &Batch, transport: &str) -> Result<(), String> { + self.conn + .execute( + "UPDATE pending_batches SET body = ?3 WHERE project_id = ?1 AND transport = ?2", + params![batch.project_id, transport, serde_json::to_string(batch).map_err(err)?], + ) + .map(|_| ()) + .map_err(err) + } + + /// Kept in `meta` (not the `projects` row) so it outlives turning sync off and on. + pub fn next_seq(&self, project_id: &str) -> Result { + Ok(self.get_meta(&format!("next_seq.{project_id}"))?.and_then(|s| s.parse().ok()).unwrap_or(1)) + } + + pub fn publish_done(&self, batch: &Batch, transport: &str) -> Result<(), String> { + let tx = self.conn.unchecked_transaction().map_err(err)?; + for r in &batch.revisions { + tx.execute("DELETE FROM outbox WHERE project_id = ?1 AND transport = ?2 AND rev = ?3", params![batch.project_id, transport, r.rev]) + .map_err(err)?; + } + tx.execute("DELETE FROM pending_batches WHERE project_id = ?1 AND transport = ?2", params![batch.project_id, transport]) + .map_err(err)?; + tx.commit().map_err(err) + } + + pub fn remote_has_blob(&self, project_id: &str, transport: &str, sha: &str) -> Result { + self.conn + .query_row("SELECT 1 FROM remote_blobs WHERE project_id = ?1 AND transport = ?2 AND sha = ?3", [project_id, transport, sha], |_| Ok(())) + .optional() + .map(|o| o.is_some()) + .map_err(err) + } + + pub fn mark_remote_blob(&self, project_id: &str, transport: &str, sha: &str) -> Result<(), String> { + self.conn + .execute("INSERT OR IGNORE INTO remote_blobs (project_id, transport, sha) VALUES (?1, ?2, ?3)", [project_id, transport, sha]) + .map(|_| ()) + .map_err(err) + } + + // ---- inbox -------------------------------------------------------------------------------- + + pub fn batch_applied(&self, project_id: &str, transport: &str, device: &str, seq: u64) -> Result { + self.conn + .query_row( + "SELECT 1 FROM applied_batches WHERE project_id = ?1 AND transport = ?2 AND device = ?3 AND seq = ?4", + params![project_id, transport, device, seq as i64], + |_| Ok(()), + ) + .optional() + .map(|o| o.is_some()) + .map_err(err) + } + + pub fn mark_applied(&self, project_id: &str, transport: &str, device: &str, seq: u64) -> Result<(), String> { + self.conn + .execute( + "INSERT OR IGNORE INTO applied_batches (project_id, transport, device, seq) VALUES (?1, ?2, ?3, ?4)", + params![project_id, transport, device, seq as i64], + ) + .map_err(err)?; + self.conn + .execute( + "DELETE FROM inbox WHERE project_id = ?1 AND transport = ?2 AND device = ?3 AND seq = ?4", + params![project_id, transport, device, seq as i64], + ) + .map(|_| ()) + .map_err(err) + } + + pub fn hold(&self, batch: &Batch, transport: &str) -> Result<(), String> { + self.conn + .execute( + "INSERT OR IGNORE INTO inbox (project_id, transport, device, seq, body) VALUES (?1, ?2, ?3, ?4, ?5)", + params![batch.project_id, transport, batch.device_id, batch.seq as i64, serde_json::to_string(batch).map_err(err)?], + ) + .map(|_| ()) + .map_err(err) + } + + pub fn held(&self, project_id: &str, transport: &str) -> Result, String> { + let mut stmt = self + .conn + .prepare("SELECT body FROM inbox WHERE project_id = ?1 AND transport = ?2 ORDER BY device, seq") + .map_err(err)?; + let rows = stmt.query_map([project_id, transport], |r| r.get::<_, String>(0)).map_err(err)?; + rows.map(|b| b.map_err(err).and_then(|b| serde_json::from_str(&b).map_err(err))).collect() + } + + // ---- devices and notices ----------------------------------------------------------------- + + pub fn remember_device(&self, device_id: &str, name: &str) -> Result<(), String> { + self.conn + .execute( + "INSERT INTO devices (device_id, name) VALUES (?1, ?2) ON CONFLICT(device_id) DO UPDATE SET name = excluded.name", + [device_id, name], + ) + .map(|_| ()) + .map_err(err) + } + + pub fn device_name(&self, device_id: &str) -> Result, String> { + self.conn + .query_row("SELECT name FROM devices WHERE device_id = ?1", [device_id], |r| r.get(0)) + .optional() + .map_err(err) + } + + pub fn add_notice(&self, project_id: &str, entity: &str, kind: &str, detail: &str) -> Result<(), String> { + self.conn + .execute( + "INSERT INTO notices (project_id, entity, kind, detail, created_at) VALUES (?1, ?2, ?3, ?4, ?5)", + params![project_id, entity, kind, detail, chrono::Utc::now().to_rfc3339()], + ) + .map(|_| ()) + .map_err(err) + } + + /// Like `add_notice`, but only while the writer has not already got the same one: for + /// conditions found again every round (a damaged chapter file). + pub fn add_notice_once(&self, project_id: &str, entity: &str, kind: &str, detail: &str) -> Result<(), String> { + let exists: bool = self + .conn + .query_row( + "SELECT EXISTS(SELECT 1 FROM notices WHERE project_id = ?1 AND entity = ?2 AND kind = ?3 AND detail = ?4)", + params![project_id, entity, kind, detail], + |r| r.get(0), + ) + .map_err(err)?; + if exists { + return Ok(()); + } + self.add_notice(project_id, entity, kind, detail) + } + + /// Recent notices, newest first: `(id, entity, kind, detail, created_at)`. + pub fn notices(&self, project_id: &str, limit: usize) -> Result, String> { + let mut stmt = self + .conn + .prepare("SELECT id, entity, kind, detail, created_at FROM notices WHERE project_id = ?1 ORDER BY id DESC LIMIT ?2") + .map_err(err)?; + let rows = stmt + .query_map(params![project_id, limit as i64], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?))) + .map_err(err)?; + rows.collect::>().map_err(err) + } + + pub fn dismiss_notice(&self, id: i64) -> Result<(), String> { + self.conn.execute("DELETE FROM notices WHERE id = ?1", [id]).map(|_| ()).map_err(err) + } +} diff --git a/app/src/App.tsx b/app/src/App.tsx index a06b23c..bcd26e6 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -25,6 +25,13 @@ import { useShell, isTauri, isMobileOS } from './lib/platform'; import { THEMES } from './lib/prefs'; import type { Project, Document, DocType, Folder } from './types'; import type { Editor as TiptapEditor } from '@tiptap/react'; +import SyncSettings from './components/sync/SyncSettings'; +import SyncPill from './components/sync/SyncPill'; +import DocumentSyncBanner from './components/sync/DocumentSyncBanner'; +import ConflictReview from './components/sync/ConflictReview'; +import { useSyncApplied, useSyncStatus } from './lib/sync/useSync'; +import { authorizeDrive, reauthorizeDriveSilently } from './lib/sync/nativeAuth'; +import type { SyncAppliedEvent } from './lib/sync/types'; import { Plus, Settings, @@ -670,6 +677,109 @@ function App() { refreshProjects(); }; + // ── MnemoSync (Google Drive). The backend saves and syncs; the app only tells it which + // chapter is open (that chapter's text is never replaced under the writer) and reloads + // what other devices changed. + const { status: syncStatus, setStatus: setSyncStatus } = useSyncStatus(); + const [conflictDocId, setConflictDocId] = useState(null); + const selectedProjectId = selectedProject?.id ?? null; + const selectedDocumentId = selectedDocument?.id ?? null; + useEffect(() => { + // Runs after selectDocument() flushed the previous chapter, so leaving it is safe. + api.syncSetActive(selectedProjectId, selectedDocumentId).catch(() => {}); + }, [selectedProjectId, selectedDocumentId]); + + // Android keeps no refresh token: when the hour-long Google token lapses, ask Google's native + // API again silently (no UI unless consent changed). At most once every two minutes. + const lastSilentAuth = useRef(0); + useEffect(() => { + if (!isMobileOS || syncStatus.state !== 'needs-auth' || !syncStatus.account) return; + if (Date.now() - lastSilentAuth.current < 120_000) return; + lastSilentAuth.current = Date.now(); + reauthorizeDriveSilently() + .then((grant) => (grant ? api.driveSetAccessToken(grant.token, grant.expiresIn).then(setSyncStatus) : undefined)) + .catch(() => {}); + }, [syncStatus.state, syncStatus.account, setSyncStatus]); + + /** Re-read the open project from disk after sync wrote into it. */ + const reloadFromSync = useCallback(async (projectId: string, changed: string[]) => { + refreshProjects(); + const proj = selectedProjectRef.current; + if (!proj || proj.id !== projectId) return; + const full = await api.loadProject(projectId); + setSelectedProject(full); + setFolders(full.folders || []); + const current = selectedDocumentRef.current; + const fresh = current ? full.documents.find((d) => d.id === current.id) : undefined; + let next = current; + if (current && fresh) { + next = changed.includes(`text:${current.id}`) + ? fresh // the writer accepted new text (Load it / a resolved conflict) + : { ...current, title: fresh.title, folderId: fresh.folderId, order: fresh.order }; + if (next !== current) { + selectedDocumentRef.current = next; + setSelectedDocument(next); + if (next === fresh) { + isSavedRef.current = true; + setIsSaved(true); + if (fresh.docType !== 'text') setDocRevisions((r) => ({ ...r, [fresh.id]: (r[fresh.id] ?? 0) + 1 })); + } + } + } else if (current && !fresh) { + selectedDocumentRef.current = null; + setSelectedDocument(null); + } + const docs = full.documents.map((d) => (next && d.id === next.id ? next : d)); + documentsRef.current = docs; + setDocuments(docs); + }, [refreshProjects]); + + const onSyncApplied = useCallback((event: SyncAppliedEvent) => { + if (event.changed.length) void reloadFromSync(event.projectId, event.changed); + }, [reloadFromSync]); + useSyncApplied(onSyncApplied); + + const handleLoadSyncUpdate = useCallback(async () => { + const proj = selectedProjectRef.current; + const doc = selectedDocumentRef.current; + if (!proj || !doc) return; + flushCanvases(); + await flushIfDirty(); + const report = await api.syncApplyStaged(proj.id, doc.id); + await reloadFromSync(proj.id, report.changed); + setSyncStatus(await api.syncStatus()); + }, [flushIfDirty, reloadFromSync, setSyncStatus]); + + const conflictDoc = conflictDocId ? documents.find((d) => d.id === conflictDocId) : undefined; + const openConflict = useCallback(async () => { + flushCanvases(); + await flushIfDirty(); + setConflictDocId(selectedDocumentRef.current?.id ?? null); + }, [flushIfDirty]); + + const syncSettings = (variant: 'desktop' | 'mobile') => ( + setProjects((prev) => [project, ...prev.filter((p) => p.id !== project.id)])} + authorizeNative={isMobileOS ? authorizeDrive : undefined} + /> + ); + + const syncBanner = (variant: 'desktop' | 'mobile') => ( + void openConflict()} + /> + ); + // Desktop keyboard shortcuts: ⌘K / Ctrl+K toggles the command palette; ⌘S saves. useEffect(() => { if (isMobileShell) return; @@ -746,8 +856,29 @@ function App() { return `${kind} ${max + 1}`; } + const backupActions = { + projectName: selectedProject?.name, + projectId: selectedProject?.id, + onBackup: async () => { + flushCanvases(); + const project = selectedProjectRef.current; + if (!project) throw new Error('Open a project before creating a backup.'); + // The same save path as everywhere else: a backup never starts from an unsaved chapter. + if (!(await flushIfDirty())) throw new Error('The open chapter could not be saved, so no backup was made.'); + return api.backupProject(project.id); + }, + onRestore: async () => { + const restored = await api.restoreProjectBackup(); + if (!restored) return false; + setProjects((previous) => [restored, ...previous.filter((p) => p.id !== restored.id)]); + return true; + }, + }; + const settingsPanel = ( {isMobileShell ? ( setIsEditingSettings(true)} />} /> {isEditingSettings && !selectedProject ? ( @@ -941,6 +1077,7 @@ function App() { > {(chat) => (
+ {!isEditingSettings && syncBanner('desktop')} {isLeftSidebarOpen && (() => { const sidebar = ( @@ -1123,6 +1260,24 @@ function App() { /> {selectedProject && isCompilerOpen && setIsCompilerOpen(false)} project={selectedProject} documents={documents} />} + + {selectedProject && conflictDoc && ( + setConflictDocId(null)} + onResolved={() => { + const id = conflictDoc.id; + setConflictDocId(null); + void reloadFromSync(selectedProject.id, [`text:${id}`]); + api.syncStatus().then(setSyncStatus).catch(() => {}); + }} + /> + )}
); } diff --git a/app/src/components/DesktopTopBar.tsx b/app/src/components/DesktopTopBar.tsx index 5be85d4..3f77b27 100644 --- a/app/src/components/DesktopTopBar.tsx +++ b/app/src/components/DesktopTopBar.tsx @@ -1,3 +1,4 @@ +import type { ReactNode } from 'react'; import type { Project, Document } from '../types'; import { BookOpen, @@ -31,6 +32,8 @@ interface Props { /** An AI change is waiting for Apply / Reject. */ aiAttention?: boolean; setIsAiOpen: (v: boolean) => void; + /** Google Drive sync status for the open project (renders nothing when not synced). */ + sync?: ReactNode; } const isMac = typeof navigator !== 'undefined' && /Mac/i.test(navigator.platform); @@ -55,6 +58,7 @@ function DesktopTopBar({ isAiOpen, aiAttention = false, setIsAiOpen, + sync, }: Props) { const iconBtn = 'w-8 h-8 flex items-center justify-center rounded-lg text-muted-foreground hover:bg-secondary/60 hover:text-foreground active:scale-95 transition-all cursor-pointer disabled:opacity-35 disabled:pointer-events-none'; @@ -96,6 +100,8 @@ function DesktopTopBar({
+ {sync} + {/* Primary actions */} } right={ - +
+ {props.syncStatus && ( + goTab('settings')} /> + )} + +
} /> )} -
+
+ {activeTab === 'write' && props.syncBanner} {activeTab === 'library' && ( Promise; + /** Pick a backup file and restore it. `false` when the writer cancelled the picker. */ + onRestore: () => Promise; +} + +/** Most recent backups kept per project (older ones are removed when a new one is made). */ +export const BACKUPS_KEPT = 5; + +function size(bytes: number): string { + if (bytes < 1_000_000) return `${Math.max(1, Math.round(bytes / 1000))} KB`; + return `${(bytes / 1_000_000).toFixed(bytes < 10_000_000 ? 1 : 0)} MB`; +} + +function when(iso: string): string { + const d = new Date(iso); + return Number.isNaN(d.getTime()) ? '' : d.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }); +} + +/** Recovery remains available without enabling sync or granting device access. */ +export default function BackupSettings({ variant, projectName, projectId, onBackup, onRestore }: BackupActions & { + variant: 'desktop' | 'mobile'; +}) { + const [busy, setBusy] = useState(null); + const [message, setMessage] = useState(''); + const [warnings, setWarnings] = useState([]); + const [error, setError] = useState(''); + const [backups, setBackups] = useState(null); + const [confirmDelete, setConfirmDelete] = useState(null); + // Ref closes the double-click window before React commits the disabled state. + const inFlight = useRef(false); + const desktop = variant === 'desktop'; + + const refresh = useCallback(async () => { + if (!isTauri) return; + try { + const list = await api.listBackups(); + setBackups(Array.isArray(list) ? list : []); + } catch { + setBackups([]); + } + }, []); + + useEffect(() => { + if (!isTauri) return; + let live = true; + void (async () => { + try { + const list = await api.listBackups(); + if (live) setBackups(Array.isArray(list) ? list : []); + } catch { + if (live) setBackups([]); + } + })(); + return () => { live = false; }; + }, []); + + async function run(key: string, action: () => Promise) { + if (inFlight.current) return; + inFlight.current = true; + setBusy(key); + setMessage(''); + setError(''); + try { await action(); } + catch (e) { setError(e instanceof Error ? e.message : String(e)); } + finally { inFlight.current = false; setBusy(null); } + } + + const button = desktop + ? 'inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg border border-border/40 bg-secondary/40 text-sm hover:border-primary/50 disabled:opacity-50 cursor-pointer transition-all' + : 'mn-row justify-center gap-2 min-h-11 disabled:opacity-50'; + const small = 'inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-xs text-muted-foreground hover:text-foreground hover:bg-secondary/60 disabled:opacity-50 cursor-pointer transition-colors'; + const label = 'text-3xs font-semibold tracking-[0.12em] text-muted-foreground/70 uppercase'; + const shown = (backups ?? []).filter((b) => !projectId || b.projectId === projectId); + const others = (backups ?? []).length - shown.length; + + return ( +
+

+ Project backups +

+

+ {isTauri ? 'Create a checked ZIP of your saved chapters, maps, images, exports and AI conversations. Restore opens a separate local copy and keeps your originals.' + : 'Project ZIP backup and restore are available in the installed app. Browser storage backup is planned.'} +

+ {isTauri && <> +

{projectName ? `Current project: ${projectName}` : 'Open a project to create a backup. You can restore a backup at any time.'}

+

+ Backups are unencrypted and may contain private writing and AI conversations. Save a copy outside this device for recovery after device loss. + A restored copy brings its AI conversations back but not the AI connection; choose a provider again in that project. +

+
+ + +
+ + {warnings.length > 0 && ( +
+

+ The backup is complete, with {warnings.length === 1 ? 'one note' : `${warnings.length} notes`}: +

+
    + {warnings.map((w) =>
  • {w}
  • )} +
+
+ )} + + {shown.length > 0 && ( +
+

{projectId ? 'Backups of this project' : 'Backups on this device'}

+
    + {shown.map((b) => ( +
  • +
    +
    +
    {projectId ? when(b.createdAt) : `${b.projectName || 'Project'} · ${when(b.createdAt)}`}
    +
    {size(b.size)} · {b.fileName}
    +
    + + +
    + {confirmDelete === b.path && ( +
    + Delete this backup from this device? This can't be undone. + + +
    + )} +
  • + ))} +
+

+ The newest {BACKUPS_KEPT} backups of each project are kept; older ones are removed when you create a new one. + {projectId && others > 0 ? ` ${others} ${others === 1 ? 'backup belongs' : 'backups belong'} to other projects.` : ''} +

+
+ )} + } + {busy &&

{busy === 'restore' ? 'Restoring…' : busy === 'create' ? 'Preparing project backup…' : 'Working…'}

} + {message &&

{message}

} + {error &&

{error}

} +
+ ); +} diff --git a/app/src/components/sync/ConflictReview.tsx b/app/src/components/sync/ConflictReview.tsx new file mode 100644 index 0000000..5995b9c --- /dev/null +++ b/app/src/components/sync/ConflictReview.tsx @@ -0,0 +1,102 @@ +import { useEffect, useMemo, useState } from 'react'; +import { Check, Loader2, Merge, X } from 'lucide-react'; +import { api } from '../../lib/api'; +import type { ConflictVersion } from '../../lib/sync/types'; +import type { DocType } from '../../types'; +import { paragraphs, wordCount as words } from '../../lib/sync/preview'; + +/** + * Side-by-side review of a chapter edited on two devices. The writer picks the version to keep + * in place; by default every other version is saved as its own chapter, so nothing is lost. + */ +export default function ConflictReview({ projectId, documentId, title, docType, variant, onClose, onResolved }: { + projectId: string; + documentId: string; + title: string; + docType: DocType; + variant: 'desktop' | 'mobile'; + onClose: () => void; + onResolved: (copies: string[]) => void; +}) { + const [versions, setVersions] = useState(null); + const [error, setError] = useState(''); + const [keepCopies, setKeepCopies] = useState(true); + const [busy, setBusy] = useState(null); + + useEffect(() => { + let live = true; + api.syncConflict(projectId, documentId) + .then((v) => live && setVersions(v)) + .catch((e) => live && setError(e instanceof Error ? e.message : String(e))); + return () => { live = false; }; + }, [projectId, documentId]); + + const parsed = useMemo(() => (versions ?? []).map((v) => ({ ...v, paras: paragraphs(v.content, docType) })), [versions, docType]); + const everyPara = useMemo(() => parsed.map((v) => new Set(v.paras)), [parsed]); + + const keep = (rev: string) => { + setBusy(rev); + setError(''); + api.syncResolveConflict(projectId, documentId, rev, keepCopies) + .then(onResolved) + .catch((e) => setError(e instanceof Error ? e.message : String(e))) + .finally(() => setBusy(null)); + }; + + const desktop = variant === 'desktop'; + return ( +
+
+
+
+
+

{title}

+

Edited on two devices before they could sync. Choose the version to keep in place. Highlighted paragraphs differ.

+
+ +
+ +
+ {!versions && !error && ( +
Loading both versions…
+ )} + {parsed.map((v, i) => ( +
+
+
+
{v.local ? 'On this device' : `From ${v.device}`}
+
{docType === 'text' ? `${words(v.paras)} words` : 'Map version'}{v.local ? ` · ${v.device}` : ''}
+
+ +
+
+ {v.paras.map((p, k) => { + const unique = everyPara.some((set, j) => j !== i && !set.has(p)); + return ( +

{p}

+ ); + })} +
+
+ ))} +
+ +
+ + {error &&

{error}

} +
+
+
+ ); +} diff --git a/app/src/components/sync/DocumentSyncBanner.tsx b/app/src/components/sync/DocumentSyncBanner.tsx new file mode 100644 index 0000000..5bb0bee --- /dev/null +++ b/app/src/components/sync/DocumentSyncBanner.tsx @@ -0,0 +1,57 @@ +import { useState } from 'react'; +import { Loader2, Merge, RefreshCw } from 'lucide-react'; +import { projectSync } from '../../lib/sync/useSync'; +import type { SyncStatus } from '../../lib/sync/types'; + +/** + * A floating note over the open chapter when another device changed it. Incoming text is never + * swapped in under the writer: they choose when to load it, and parallel edits go to review. + */ +export default function DocumentSyncBanner({ status, projectId, documentId, onLoadUpdate, onReview, variant }: { + status: SyncStatus; + projectId?: string; + documentId?: string; + onLoadUpdate: () => Promise; + onReview: () => void; + variant: 'desktop' | 'mobile'; +}) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + const project = projectSync(status, projectId); + if (!project || !documentId) return null; + const conflict = project.conflicts.some((c) => c.docId === documentId); + const staged = project.staged.includes(documentId); + if (!conflict && !staged) return null; + + const shell = variant === 'desktop' + ? 'absolute top-3 left-1/2 -translate-x-1/2 z-20 max-w-[min(36rem,calc(100%-2rem))]' + : 'absolute top-2 inset-x-3 z-20'; + return ( +
+
+ {conflict ? : } +

+ {conflict + ? 'This chapter was also changed on another device. Both versions are safe.' + : 'A newer version of this chapter arrived from another device.'} + {error && {error}} +

+ +
+
+ ); +} diff --git a/app/src/components/sync/SyncDot.tsx b/app/src/components/sync/SyncDot.tsx new file mode 100644 index 0000000..26bda91 --- /dev/null +++ b/app/src/components/sync/SyncDot.tsx @@ -0,0 +1,9 @@ +/** A small status dot shared by the sync pill and settings rows. */ +export default function SyncDot({ tone }: { tone: 'ok' | 'busy' | 'warn' | 'muted' }) { + const color = + tone === 'ok' ? 'bg-emerald-500/80' + : tone === 'busy' ? 'bg-primary/80 animate-pulse' + : tone === 'warn' ? 'bg-amber-500' + : 'bg-muted-foreground/40'; + return ; +} diff --git a/app/src/components/sync/SyncPill.tsx b/app/src/components/sync/SyncPill.tsx new file mode 100644 index 0000000..1892496 --- /dev/null +++ b/app/src/components/sync/SyncPill.tsx @@ -0,0 +1,35 @@ +import { Cloud, CloudOff, RefreshCw, TriangleAlert } from 'lucide-react'; +import { describe, projectSync } from '../../lib/sync/useSync'; +import type { SyncStatus } from '../../lib/sync/types'; + +/** + * Quiet sync indicator for the open project. Hidden entirely when the project isn't synced + * and no account is connected, so local-only writers never see sync chrome. + */ +export default function SyncPill({ status, projectId, onClick, compact = false }: { + status: SyncStatus; + projectId?: string; + onClick: () => void; + compact?: boolean; +}) { + const project = projectSync(status, projectId); + if (!project && status.state !== 'needs-auth') return null; + const { label, tone } = describe(status, project); + const Icon = tone === 'busy' && project?.state === 'syncing' ? RefreshCw + : tone === 'warn' ? TriangleAlert + : project?.state === 'offline' || status.state === 'offline' ? CloudOff + : Cloud; + const color = tone === 'warn' ? 'text-amber-500' : tone === 'ok' ? 'text-primary' : 'text-muted-foreground'; + return ( + + ); +} diff --git a/app/src/components/sync/SyncSettings.tsx b/app/src/components/sync/SyncSettings.tsx new file mode 100644 index 0000000..dc5bd26 --- /dev/null +++ b/app/src/components/sync/SyncSettings.tsx @@ -0,0 +1,310 @@ +import { useEffect, useRef, useState, type ReactNode } from 'react'; +import { Archive, Cloud, CloudOff, Download, Loader2, LogOut, RefreshCw, ShieldCheck, X } from 'lucide-react'; +import { api } from '../../lib/api'; +import { describe, projectSync } from '../../lib/sync/useSync'; +import type { RemoteProject, SyncStatus } from '../../lib/sync/types'; +import type { Project } from '../../types'; +import SyncDot from './SyncDot'; + +export interface SyncSettingsProps { + status: SyncStatus; + setStatus: (s: SyncStatus) => void; + projects: Project[]; + currentProjectId?: string; + /** A project was downloaded from Drive: add it to the library (and offer to open it). */ + onDownloaded: (project: Project) => void; + /** Android only: run Google's native authorization prompt and return an access token. */ + authorizeNative?: () => Promise<{ token: string; expiresIn: number }>; +} + +function when(iso: string | null): string { + if (!iso) return 'not yet'; + const minutes = Math.round((Date.now() - new Date(iso).getTime()) / 60_000); + if (minutes < 1) return 'just now'; + if (minutes < 60) return `${minutes} min ago`; + const hours = Math.round(minutes / 60); + if (hours < 24) return `${hours} h ago`; + return new Date(iso).toLocaleDateString(); +} + +function size(bytes: number): string { + if (bytes < 1_000_000) return `${Math.max(1, Math.round(bytes / 1000))} KB`; + if (bytes < 1_000_000_000) return `${(bytes / 1_000_000).toFixed(bytes < 10_000_000 ? 1 : 0)} MB`; + return `${(bytes / 1_000_000_000).toFixed(1)} GB`; +} + +/** + * Google Drive sync settings. Same component for both shells; `variant` only changes density. + * Sync is optional and per project: nothing leaves the device until the writer turns it on. + */ +export default function SyncSettings({ variant, status, setStatus, projects, currentProjectId, onDownloaded, authorizeNative }: SyncSettingsProps & { + variant: 'desktop' | 'mobile'; +}) { + const [busy, setBusy] = useState(null); + const [error, setError] = useState(''); + const [remote, setRemote] = useState(null); + /** Project waiting for the writer's "back up first?" answer before its first sync. */ + const [confirming, setConfirming] = useState(null); + const [note, setNote] = useState(''); + const [usage, setUsage] = useState(null); + const inFlight = useRef(false); + const desktop = variant === 'desktop'; + const accountId = status.account?.id; + + // Drive space used by MnemoScript. Old versions are not pruned yet, so the writer sees it grow. + useEffect(() => { + if (!accountId) return; + let live = true; + void (async () => { + try { + const bytes = await api.driveUsage(); + if (live && typeof bytes === 'number') setUsage(bytes); + } catch { /* offline or signed out: the line stays hidden */ } + })(); + return () => { live = false; }; + }, [accountId]); + + async function run(key: string, action: () => Promise) { + if (inFlight.current) return; + inFlight.current = true; + setBusy(key); + setError(''); + try { await action(); } + catch (e) { setError(e instanceof Error ? e.message : String(e)); } + finally { inFlight.current = false; setBusy(null); } + } + + const connect = () => run('connect', async () => { + if (authorizeNative) { + const { token, expiresIn } = await authorizeNative(); + setStatus(await api.driveSetAccessToken(token, expiresIn)); + } else { + setStatus(await api.driveSignIn()); + } + }); + + const button = desktop + ? 'inline-flex items-center justify-center gap-2 px-3.5 py-2 rounded-lg border border-border/40 bg-secondary/40 text-sm hover:border-primary/50 disabled:opacity-50 cursor-pointer transition-all' + : 'mn-row justify-center gap-2 min-h-11 disabled:opacity-50'; + const primary = desktop + ? 'inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg bg-primary text-primary-foreground text-sm font-medium shadow-sm hover:opacity-90 disabled:opacity-60 cursor-pointer transition-all' + : 'mn-btn mn-btn-primary justify-center gap-2 min-h-11 disabled:opacity-60'; + const label = 'text-3xs font-semibold tracking-[0.12em] text-muted-foreground/70 uppercase'; + + const intro = ( +

+ Keep projects in step across your computer and phone through your own Google Drive. MnemoScript only uses its own + hidden app folder there: it can't see your other files, and there is no MnemoScript server in between. +

+ ); + + let body: ReactNode; + if (status.state === 'unsupported') { + body =

Google Drive sync is available in the MnemoScript desktop and Android apps.

; + } else if (status.state === 'unconfigured') { + body = ( + <> + {intro} + {status.message + ?

{status.message}

+ :

This build has no Google sign-in set up yet. Add an OAuth client to app/src-tauri/.env.local and rebuild.

} + + ); + } else if (!status.account) { + body = ( + <> + {intro} +
    +
  • You sign in on Google's own page. Your password never passes through MnemoScript.
  • +
  • Writing is saved on this device first and always works offline.
  • +
  • Drive stores projects in your account, protected in transit but not end-to-end encrypted. Sync is not a backup: keep project backups too.
  • +
+
+ + {busy === 'connect' && !authorizeNative && ( + + )} +
+ + ); + } else { + const account = status.account; + const synced = new Set(status.projects.map((p) => p.projectId)); + const current = projectSync(status, currentProjectId); + const headline = + status.state === 'syncing' ? 'Syncing…' + : status.state === 'offline' ? 'Offline. Changes are kept on this device and sent later.' + : status.state === 'busy' ? 'Google Drive asked to slow down; retrying shortly.' + : status.state === 'needs-auth' ? 'Google sign-in expired. Reconnect to keep syncing.' + : status.state === 'error' ? (status.message ?? 'Sync paused') + : `Up to date · checked ${when(status.lastRound)}`; + body = ( + <> +
+
+ {(account.name || account.email || 'G').slice(0, 1).toUpperCase()} +
+
+
{account.name || 'Google account'}
+
{account.email}
+
+ +
+ + {usage !== null && ( +

+ Uses about {size(usage)} of your Google Drive. Every saved version is kept there for now. +

+ )} + +
+ {status.state === 'syncing' ? + : status.state === 'offline' ? + : } + {headline} + {status.state === 'needs-auth' + ? + : } +
+ +
+

Projects on this device

+ {projects.length === 0 &&

No projects yet.

} +
    + {projects.map((p) => { + const ps = projectSync(status, p.id); + const d = describe(status, ps); + const on = synced.has(p.id); + return ( +
  • +
    +
    +
    {p.name}
    +
    + {on ? <>{d.label}{ps?.lastSync && ps.state === 'synced' ? ` · ${when(ps.lastSync)}` : ''} : 'Only on this device'} +
    + {on && ps?.error && ps.state !== 'synced' &&
    {ps.error}
    } +
    + +
    + {confirming === p.id && !on && ( +
    +

    + Sync is not a backup. Save a backup of this project first, so you can always return to today's version. +

    +
    + + + +
    +
    + )} +
  • + ); + })} +
+ {note &&

{note}

} +

Turning sync off keeps every file here and on Drive; turning it back on resumes without duplicates.

+
+ +
+
+

On Google Drive

+ +
+ {remote && remote.filter((r) => !r.local).length === 0 && ( +

Every synced project is already on this device.

+ )} + {remote && remote.filter((r) => !r.local).map((r) => { + const sameName = projects.some((p) => p.name.trim().toLowerCase() === r.name.trim().toLowerCase()); + return ( +
+
+
{r.name}
+
From {r.deviceName} · {when(r.updatedAt)}
+ {sameName && ( +
+ A separate project with this name is already here. Downloading keeps both; nothing is merged automatically. +
+ )} +
+ +
+ ); + })} +
+ + {current && current.notices.length > 0 && ( +
+

Recent sync notes

+ {current.notices.slice(0, 5).map((n) => ( +
+ {n.detail} + +
+ ))} +
+ )} + + ); + } + + return ( +
+

+ Sync with Google Drive + Beta +

+ {body} + {error &&

{error}

} +
+ ); +} diff --git a/app/src/lib/api.ts b/app/src/lib/api.ts index 3dd0bcf..43b4605 100644 --- a/app/src/lib/api.ts +++ b/app/src/lib/api.ts @@ -1,5 +1,6 @@ import { invoke, Channel } from '@tauri-apps/api/core'; import type { Project, Document, DocType } from '../types'; +import type { BackupCreated, BackupInfo } from './backupTypes'; import type { AiEvent, AiSession, @@ -12,6 +13,9 @@ import type { PairStatus, KeyStatus, } from './ai/types'; +import { UNSUPPORTED_STATUS } from './sync/types'; +import { mockSync, syncMockEnabled } from './sync/devMock'; +import type { ConflictVersion, RemoteProject, SyncReport, SyncStatus } from './sync/types'; /** * Typed wrapper around the Tauri backend commands defined in @@ -146,6 +150,53 @@ export const api = { selectDirectory: () => call('select_directory'), + /** Native recovery archives are stored outside the project (never recursively backed up). */ + backupProject: (projectId: string) => call('backup_project', { projectId }), + /** Backups in this device's backups folder, newest first (the newest 5 per project are kept). */ + listBackups: () => call('list_backups'), + deleteBackup: (path: string) => call('delete_backup', { path }), + /** Pick a backup ZIP and restore it as a separate project. `null` when the picker is cancelled. + * Only the chosen file's location crosses to the backend, which reads the archive itself. */ + restoreProjectBackup: async (): Promise => { + const { open } = await import('@tauri-apps/plugin-dialog'); + const picked = await open({ multiple: false, directory: false, filters: [{ name: 'Project backup', extensions: ['zip'] }] }); + if (!picked || typeof picked !== 'string') return null; + return call('restore_project_backup', { path: picked }); + }, + + /** A separate user-selected copy, suitable for moving off this device (copied by the backend). */ + saveBackupCopy: async (backupPath: string, suggestedName = 'MnemoScript-backup.zip'): Promise => { + const { save } = await import('@tauri-apps/plugin-dialog'); + const destination = await save({ defaultPath: suggestedName, filters: [{ name: 'Project backup', extensions: ['zip'] }] }); + if (!destination) return null; + await call('save_backup_copy', { source: backupPath, destination }); + return destination; + }, + + /* ------------------------- MnemoSync (Google Drive) ------------------------- */ + // Sync runs in the native backend; tokens never reach the web view. A plain browser reports + // `unsupported` so the UI can explain where sync lives. + syncStatus: () => call('sync_status'), + driveSignIn: () => call('drive_sign_in'), + driveCancelSignIn: () => call('drive_cancel_sign_in'), + /** Android: hand the backend an access token from Google's native authorization prompt. */ + driveSetAccessToken: (token: string, expiresIn: number) => call('drive_set_access_token', { token, expiresIn }), + driveSignOut: () => call('drive_sign_out'), + syncEnableProject: (projectId: string) => call('sync_enable_project', { projectId }), + syncDisableProject: (projectId: string) => call('sync_disable_project', { projectId }), + driveRemoteProjects: () => call('drive_remote_projects'), + syncDownloadProject: (projectId: string, name: string) => call('sync_download_project', { projectId, name }), + syncNow: () => call('sync_now'), + syncSetActive: (projectId: string | null, documentId: string | null) => + call('sync_set_active', { projectId, documentId }), + syncApplyStaged: (projectId: string, documentId: string) => call('sync_apply_staged', { projectId, documentId }), + syncConflict: (projectId: string, documentId: string) => call('sync_conflict', { projectId, documentId }), + syncResolveConflict: (projectId: string, documentId: string, keep: string, keepCopies: boolean) => + call('sync_resolve_conflict', { projectId, documentId, keep, keepCopies }), + syncDismissNotice: (id: number) => call('sync_dismiss_notice', { id }), + /** Bytes MnemoScript keeps in the writer's Google Drive (all devices and projects). */ + driveUsage: () => call('drive_usage'), + /* ---------------------------- AI assistant ---------------------------- */ // Sessions are stored per project (`/ai/sessions/`), so one project never sees another's. @@ -278,6 +329,9 @@ function findProject(projects: Project[], id: string): Project { async function browserBackend(cmd: string, args: Record): Promise { const projects = loadStore(); const now = () => new Date().toISOString(); + if ((cmd.startsWith('sync_') || cmd.startsWith('drive_')) && syncMockEnabled()) { + return mockSync(cmd, args, projects) as T; + } switch (cmd) { case 'create_project': { @@ -449,6 +503,27 @@ async function browserBackend(cmd: string, args: Record): Pr case 'select_directory': return null as T; + // MnemoSync lives in the installed apps (OAuth tokens never enter the web view). + case 'sync_status': + return UNSUPPORTED_STATUS as T; + case 'sync_set_active': + case 'sync_now': + return undefined as T; + case 'drive_sign_in': + case 'drive_set_access_token': + case 'drive_sign_out': + case 'sync_enable_project': + case 'sync_disable_project': + case 'drive_remote_projects': + case 'sync_download_project': + case 'sync_apply_staged': + case 'sync_conflict': + case 'sync_resolve_conflict': + case 'sync_dismiss_notice': + case 'drive_cancel_sign_in': + case 'drive_usage': + throw new Error('Google Drive sync is available in the MnemoScript desktop and Android apps.'); + default: throw new Error(`Browser fallback: unsupported command "${cmd}"`); } diff --git a/app/src/lib/backupTypes.ts b/app/src/lib/backupTypes.ts new file mode 100644 index 0000000..9f7f78a --- /dev/null +++ b/app/src/lib/backupTypes.ts @@ -0,0 +1,17 @@ +/** A backup just made (`backup_project`). */ +export interface BackupCreated { + path: string; + fileName: string; + /** Problems that did not stop the backup: damaged chapters copied as-is, images left out. */ + warnings: string[]; +} + +/** A backup in this device's backups folder (`list_backups`). */ +export interface BackupInfo { + path: string; + fileName: string; + projectId: string; + projectName: string; + size: number; + createdAt: string; +} diff --git a/app/src/lib/sync/devMock.ts b/app/src/lib/sync/devMock.ts new file mode 100644 index 0000000..d112a1e --- /dev/null +++ b/app/src/lib/sync/devMock.ts @@ -0,0 +1,95 @@ +/** + * Browser-only preview of the sync UI (`?syncMock=1`), so the settings card, status pill, + * banner and conflict review can be designed without a Google account. Never used in the + * installed apps, which always talk to the Rust backend. + */ +import type { ConflictVersion, RemoteProject, SyncStatus } from './types'; + +export function syncMockEnabled(): boolean { + if (typeof window === 'undefined') return false; + try { + if (new URLSearchParams(window.location.search).has('syncMock')) { + window.localStorage.setItem('mnemo_sync_mock', '1'); + } + return window.localStorage.getItem('mnemo_sync_mock') === '1'; + } catch { + return false; + } +} + +const state: { signedIn: boolean; enabled: Set; conflictDoc: string | null } = { + signedIn: true, + enabled: new Set(), + conflictDoc: null, +}; + +export function mockSync(cmd: string, args: Record, projects: { id: string; documents?: { id: string; title: string }[] }[]): unknown { + const first = projects[0]; + if (state.enabled.size === 0 && first) { + state.enabled.add(first.id); + state.conflictDoc = first.documents?.[0]?.id ?? null; + } + const status = (): SyncStatus => ({ + configured: true, + platform: 'desktop', + account: state.signedIn ? { id: 'mock', email: 'writer@example.com', name: 'A. Writer' } : null, + state: state.signedIn ? 'idle' : 'signed-out', + message: null, + lastRound: new Date().toISOString(), + deviceName: 'WRITING-PC', + projects: state.signedIn + ? projects + .filter((p) => state.enabled.has(p.id)) + .map((p) => { + const doc = p.documents?.find((d) => d.id === state.conflictDoc); + return { + projectId: p.id, + state: doc ? 'conflict' : 'synced', + pending: 0, + conflicts: doc ? [{ docId: doc.id, title: doc.title }] : [], + staged: [], + lastSync: new Date(Date.now() - 4 * 60_000).toISOString(), + error: null, + notices: doc ? [{ id: 1, kind: 'merged', detail: '"Volume 1" was renamed on two devices; one name was kept', createdAt: new Date().toISOString() }] : [], + }; + }) + : [], + }); + switch (cmd) { + case 'sync_status': + return status(); + case 'drive_sign_in': + state.signedIn = true; + return status(); + case 'drive_sign_out': + state.signedIn = false; + return status(); + case 'sync_enable_project': + state.enabled.add(String(args.projectId)); + return status(); + case 'sync_disable_project': + state.enabled.delete(String(args.projectId)); + return status(); + case 'drive_remote_projects': + return [ + { projectId: 'remote-1', name: 'Salt & Lantern', deviceName: 'Pixel 8', updatedAt: new Date(Date.now() - 86_400_000).toISOString(), local: false, syncing: false }, + ] satisfies RemoteProject[]; + case 'sync_conflict': + return [ + { rev: 'local', local: true, device: 'WRITING-PC', content: '

The bells rang at dawn, and nobody in Ashford slept again.

Mara counted them anyway.

' }, + { rev: 'phone', local: false, device: 'Pixel 8', content: '

The bells rang at dawn.

Mara counted each one, as her mother had taught her, and stopped at nine.

' }, + ] satisfies ConflictVersion[]; + case 'sync_resolve_conflict': + state.conflictDoc = null; + return []; + case 'drive_usage': + return 18_400_000; + case 'sync_dismiss_notice': + case 'sync_now': + case 'sync_set_active': + case 'drive_cancel_sign_in': + return undefined; + default: + throw new Error('Not available in the sync preview.'); + } +} diff --git a/app/src/lib/sync/nativeAuth.ts b/app/src/lib/sync/nativeAuth.ts new file mode 100644 index 0000000..c00cac2 --- /dev/null +++ b/app/src/lib/sync/nativeAuth.ts @@ -0,0 +1,22 @@ +import { invoke } from '@tauri-apps/api/core'; + +/** + * Android: ask Google's native authorization API (Google Play services) for a Drive + * `drive.appdata` access token. Google shows its own account/consent sheet the first time and + * answers silently afterwards. No password or refresh token ever reaches MnemoScript. + */ +export async function authorizeDrive(): Promise<{ token: string; expiresIn: number }> { + const result = await invoke<{ accessToken?: string; expiresIn?: number }>('plugin:google-auth|authorize', { interactive: true }); + if (!result?.accessToken) throw new Error('Google did not grant Drive access.'); + return { token: result.accessToken, expiresIn: result.expiresIn ?? 3000 }; +} + +/** Silent re-authorization when the short-lived token expired (no UI unless consent is needed). */ +export async function reauthorizeDriveSilently(): Promise<{ token: string; expiresIn: number } | null> { + try { + const result = await invoke<{ accessToken?: string; expiresIn?: number }>('plugin:google-auth|authorize', { interactive: false }); + return result?.accessToken ? { token: result.accessToken, expiresIn: result.expiresIn ?? 3000 } : null; + } catch { + return null; + } +} diff --git a/app/src/lib/sync/preview.ts b/app/src/lib/sync/preview.ts new file mode 100644 index 0000000..826008a --- /dev/null +++ b/app/src/lib/sync/preview.ts @@ -0,0 +1,30 @@ +import type { DocType } from '../../types'; + +/** + * Plain paragraphs for the conflict preview. HTML is parsed inertly by DOMParser (no scripts + * run, no images load) and only text is shown, so a version from another device can never + * inject markup into the app. + */ +export function paragraphs(content: string, docType: DocType): string[] { + if (docType !== 'text') { + try { + const graph = JSON.parse(content) as Record; + const count = (k: string) => (Array.isArray(graph[k]) ? (graph[k] as unknown[]).length : 0); + return docType === 'mindmap' + ? [`${count('nodes')} ideas · ${count('edges')} links`] + : [`${count('regions')} regions · ${count('items')} map items · ${count('labels')} labels`]; + } catch { + return ['(This version could not be previewed)']; + } + } + const doc = new DOMParser().parseFromString(content, 'text/html'); + const blocks = Array.from(doc.body.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, blockquote, pre')) + .filter((el) => !el.querySelector('p, li')) + .map((el) => (el.textContent ?? '').replace(/\s+/g, ' ').trim()) + .filter(Boolean); + return blocks.length ? blocks : [(doc.body.textContent ?? '').trim() || '(Empty)']; +} + +export function wordCount(ps: string[]): number { + return ps.join(' ').split(/\s+/).filter(Boolean).length; +} diff --git a/app/src/lib/sync/types.ts b/app/src/lib/sync/types.ts new file mode 100644 index 0000000..4dc3f62 --- /dev/null +++ b/app/src/lib/sync/types.ts @@ -0,0 +1,102 @@ +/** MnemoSync (Google Drive) shapes returned by the Rust backend (`src-tauri/src/sync/service.rs`). */ + +export type SyncGlobalState = + | 'unsupported' // plain browser: sync lives in the installed apps + | 'unconfigured' // this build has no Google OAuth client + | 'signed-out' + | 'needs-auth' + | 'idle' + | 'syncing' + | 'offline' + | 'busy' + | 'error'; + +export type SyncProjectState = + | 'synced' + | 'pending' + | 'syncing' + | 'conflict' + | 'offline' + | 'needs-auth' + | 'error' + | 'account-mismatch'; + +export interface DriveAccount { + id: string; + email: string; + name: string; +} + +export interface SyncNotice { + id: number; + kind: 'deleted' | 'kept' | 'merged' | 'rejected' | string; + detail: string; + createdAt: string; +} + +export interface SyncProjectStatus { + projectId: string; + state: SyncProjectState; + /** Revisions saved here but not yet on Google Drive. */ + pending: number; + conflicts: { docId: string; title: string }[]; + /** Open chapters with an update from another device waiting for the writer. */ + staged: string[]; + lastSync: string | null; + error: string | null; + notices: SyncNotice[]; +} + +export interface SyncStatus { + configured: boolean; + platform: 'desktop' | 'android' | 'ios' | 'web'; + account: DriveAccount | null; + state: SyncGlobalState; + message: string | null; + lastRound: string | null; + deviceName: string; + projects: SyncProjectStatus[]; +} + +export interface RemoteProject { + projectId: string; + name: string; + deviceName: string; + updatedAt: string; + /** The same project already exists on this device. */ + local: boolean; + syncing: boolean; +} + +export interface ConflictVersion { + rev: string; + /** The version currently in this device's chapter file. */ + local: boolean; + device: string; + content: string; +} + +export interface SyncReport { + changed: string[]; + staged: string[]; + published: number; + held: number; +} + +export interface SyncAppliedEvent { + projectId: string; + /** Entity keys, e.g. `doc:`, `text:`, `folder:`, `project`. */ + changed: string[]; + staged: string[]; +} + +export const UNSUPPORTED_STATUS: SyncStatus = { + configured: false, + platform: 'web', + account: null, + state: 'unsupported', + message: null, + lastRound: null, + deviceName: 'This browser', + projects: [], +}; diff --git a/app/src/lib/sync/useSync.ts b/app/src/lib/sync/useSync.ts new file mode 100644 index 0000000..6bb71d1 --- /dev/null +++ b/app/src/lib/sync/useSync.ts @@ -0,0 +1,71 @@ +import { useCallback, useEffect, useState } from 'react'; +import { api } from '../api'; +import { isTauri } from '../platform'; +import { syncMockEnabled } from './devMock'; +import type { SyncAppliedEvent, SyncProjectStatus, SyncStatus } from './types'; +import { UNSUPPORTED_STATUS } from './types'; + +/** Subscribe to a backend event (Tauri only). Returns an unsubscribe function. */ +export function onSyncEvent(name: 'sync://status' | 'sync://applied', handler: (payload: T) => void): () => void { + if (!isTauri) return () => {}; + let unlisten: (() => void) | undefined; + let cancelled = false; + import('@tauri-apps/api/event') + .then(({ listen }) => listen(name, (e) => handler(e.payload))) + .then((u) => { + if (cancelled) u(); + else unlisten = u; + }) + .catch(() => {}); + return () => { + cancelled = true; + unlisten?.(); + }; +} + +/** Live MnemoSync status for the whole app (initial fetch + backend pushes). */ +export function useSyncStatus() { + const [status, setStatus] = useState(UNSUPPORTED_STATUS); + const refresh = useCallback(() => { + if (!isTauri && !syncMockEnabled()) return; + api.syncStatus().then(setStatus).catch(() => {}); + }, []); + useEffect(() => { + refresh(); + return onSyncEvent('sync://status', setStatus); + }, [refresh]); + return { status, setStatus, refresh }; +} + +/** Call `handler` when another device's changes were written into a project on this device. */ +export function useSyncApplied(handler: (event: SyncAppliedEvent) => void) { + useEffect(() => onSyncEvent('sync://applied', handler), [handler]); +} + +export function projectSync(status: SyncStatus, projectId: string | undefined): SyncProjectStatus | undefined { + return projectId ? status.projects.find((p) => p.projectId === projectId) : undefined; +} + +/** Short, calm wording for the status pill and settings rows. */ +export function describe(status: SyncStatus, project?: SyncProjectStatus): { label: string; tone: 'ok' | 'busy' | 'warn' | 'muted' } { + if (status.state === 'needs-auth') return { label: 'Sign in to sync', tone: 'warn' }; + if (!project) return { label: 'Not synced', tone: 'muted' }; + switch (project.state) { + case 'synced': + return { label: 'Synced', tone: 'ok' }; + case 'syncing': + return { label: 'Syncing…', tone: 'busy' }; + case 'pending': + return { label: status.state === 'offline' ? 'Offline · saved here' : 'Waiting to sync', tone: 'busy' }; + case 'conflict': + return { label: project.conflicts.length === 1 ? '1 chapter to review' : `${project.conflicts.length} chapters to review`, tone: 'warn' }; + case 'offline': + return { label: 'Offline · saved here', tone: 'muted' }; + case 'needs-auth': + return { label: 'Sign in to sync', tone: 'warn' }; + case 'account-mismatch': + return { label: 'Different Google account', tone: 'warn' }; + default: + return { label: 'Sync paused', tone: 'warn' }; + } +} diff --git a/app/src/regression/ai.regression.test.tsx b/app/src/regression/ai.regression.test.tsx index f3982b3..8aceaed 100644 --- a/app/src/regression/ai.regression.test.tsx +++ b/app/src/regression/ai.regression.test.tsx @@ -62,7 +62,7 @@ describe('AI assistant — desktop panel (regression)', () => { fireEvent.change(box, { target: { value: 'What is in this project?' } }); fireEvent.keyDown(box, { key: 'Enter' }); - expect(await within(panel).findByText(/want me to draft the change/i, {}, { timeout: 6000 })).toBeInTheDocument(); + expect(await within(panel).findByText(/want me to draft the change/i, {}, { timeout: 12000 })).toBeInTheDocument(); expect(within(panel).getByText('Looked through the project')).toBeInTheDocument(); expect(within(panel).getByText('Claude Sonnet 5')).toBeInTheDocument(); @@ -100,13 +100,13 @@ describe('AI assistant — edits (regression)', () => { fireEvent.keyDown(box, { key: 'Enter' }); // The proposal waits; nothing is written until the writer applies it. - const apply = await within(panel).findByRole('button', { name: /^apply$/i }, { timeout: 6000 }); + const apply = await within(panel).findByRole('button', { name: /^apply$/i }, { timeout: 12000 }); expect(within(panel).getByText('Needs your OK')).toBeInTheDocument(); expect(within(panel).getByText(/waiting for you to apply or reject/i)).toBeInTheDocument(); expect(liveEditor().getText()).not.toContain('sharpened'); fireEvent.click(apply); - await within(panel).findByText(/done \(mock\)/i, {}, { timeout: 6000 }); + await within(panel).findByText(/done \(mock\)/i, {}, { timeout: 12000 }); expect(within(panel).getByText('Applied')).toBeInTheDocument(); await waitFor(() => expect(liveEditor().getText()).toContain('The tavern roared and Mara slipped — sharpened through the crowd.')); expect(liveEditor().getHTML()).toContain('Mara'); // formatting outside the edit survives @@ -137,7 +137,7 @@ describe('AI assistant — edits (regression)', () => { const box = await within(panel).findByPlaceholderText(/ask about your story/i); fireEvent.change(box, { target: { value: 'fix the opening' } }); fireEvent.keyDown(box, { key: 'Enter' }); - expect(await within(panel).findByText(/want me to draft the change/i, {}, { timeout: 6000 })).toBeInTheDocument(); + expect(await within(panel).findByText(/want me to draft the change/i, {}, { timeout: 12000 })).toBeInTheDocument(); expect(within(panel).queryByRole('button', { name: /^apply$/i })).toBeNull(); expect(liveEditor().getText()).toBe('The tavern roared and the crowd surged.'); }, 20000); @@ -166,8 +166,8 @@ describe('AI assistant — inline commands (regression)', () => { expect(within(popup).getByText('Polish')).toBeInTheDocument(); fireEvent.keyDown(document.querySelector('.ProseMirror')!, { key: 'Enter' }); - const card = await screen.findByRole('dialog', { name: /ai polish/i }, { timeout: 6000 }); - const accept = await within(card).findByRole('button', { name: /accept/i }, { timeout: 6000 }); + const card = await screen.findByRole('dialog', { name: /ai polish/i }, { timeout: 12000 }); + const accept = await within(card).findByRole('button', { name: /accept/i }, { timeout: 12000 }); expect(document.querySelector('.mn-ai-target')).toBeTruthy(); // the passage is highlighted expect(ed.getText()).toContain('very loud'); // nothing changed yet fireEvent.click(accept); @@ -190,7 +190,7 @@ describe('AI assistant — settings (regression)', () => { const App = await loadApp(); render(); fireEvent.click((await screen.findByText('Settings', { selector: 'h3, span, p, div' })).closest('button')!); - expect(await screen.findByText('writer@example.com', {}, { timeout: 6000 })).toBeInTheDocument(); + expect(await screen.findByText('writer@example.com', {}, { timeout: 12000 })).toBeInTheDocument(); expect(screen.getByText('Pro plan')).toBeInTheDocument(); const bars = await screen.findAllByRole('progressbar'); expect(bars.map((b) => [b.getAttribute('aria-label'), b.getAttribute('aria-valuenow')])).toEqual([ diff --git a/app/src/regression/backup-app.regression.test.tsx b/app/src/regression/backup-app.regression.test.tsx new file mode 100644 index 0000000..c9c3975 --- /dev/null +++ b/app/src/regression/backup-app.regression.test.tsx @@ -0,0 +1,56 @@ +import { beforeAll, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import type { Editor } from '@tiptap/react'; +import type { BackupActions } from '../components/sync/BackupSettings'; + +// Expose the App's backup boundary in a browser fixture; real native controls are tested separately. +vi.mock('../components/sync/BackupSettings', () => ({ default: ({ onBackup }: BackupActions) => + , +})); + +beforeAll(async () => { await import('../App'); }, 60000); + +async function openDirtyChapter() { + const { default: App } = await import('../App'); + const { api } = await import('../lib/api'); + render(); + fireEvent.click(screen.getByText(/start a novel/i).closest('button')!); + const input = await screen.findByPlaceholderText(/ashen crown/i); + fireEvent.change(input, { target: { value: 'Backup Novel' } }); + fireEvent.submit(input.closest('form')!); + fireEvent.click(await screen.findByRole('button', { name: /new chapter/i })); + await waitFor(() => expect(document.querySelector('.ProseMirror')).toBeTruthy()); + const editor = (document.querySelector('.ProseMirror') as HTMLElement & { editor: Editor }).editor; + act(() => { editor.commands.setContent('

Unsaved manuscript for backup

', { emitUpdate: true }); }); + // The desktop Settings command is reachable without depending on toolbar icon placement. + fireEvent.click(within(screen.getByRole('banner')).getByRole('button', { name: /Search commands/ })); + fireEvent.change(await screen.findByPlaceholderText(/type a command/i), { target: { value: 'Settings' } }); + fireEvent.click(await screen.findByRole('button', { name: /Settings/i })); + return api; +} + +describe('Backup save boundary (regression)', () => { + it('persists the latest chapter before requesting a snapshot', async () => { + const api = await openDirtyChapter(); + const snapshots: string[] = []; + const backup = vi.spyOn(api, 'backupProject').mockImplementation(async () => { + snapshots.push(localStorage.getItem('mnemoscript:projects')!); + return { path: '/backup.zip', fileName: 'backup.zip', warnings: [] }; + }); + fireEvent.click(screen.getByRole('button', { name: 'Test backup boundary' })); + await waitFor(() => expect(backup).toHaveBeenCalledOnce()); + expect(JSON.parse(snapshots[0])[0].documents[0].content).toContain('Unsaved manuscript for backup'); + backup.mockRestore(); + }); + + it('never produces a successful backup after a failed local save', async () => { + const api = await openDirtyChapter(); + const save = vi.spyOn(api, 'saveDocument').mockRejectedValueOnce(new Error('Disk full')); + const backup = vi.spyOn(api, 'backupProject').mockResolvedValue({ path: '/backup.zip', fileName: 'backup.zip', warnings: [] }); + fireEvent.click(screen.getByRole('button', { name: 'Test backup boundary' })); + await waitFor(() => expect(save).toHaveBeenCalledOnce()); + expect(backup).not.toHaveBeenCalled(); + save.mockRestore(); + backup.mockRestore(); + }); +}); diff --git a/app/src/regression/backup.regression.test.tsx b/app/src/regression/backup.regression.test.tsx new file mode 100644 index 0000000..9b6037d --- /dev/null +++ b/app/src/regression/backup.regression.test.tsx @@ -0,0 +1,131 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import BackupSettings from '../components/sync/BackupSettings'; +import type { BackupCreated, BackupInfo } from '../lib/backupTypes'; + +const state = vi.hoisted(() => ({ native: true, saveCopy: vi.fn(), list: vi.fn(), remove: vi.fn() })); +vi.mock('../lib/platform', () => ({ get isTauri() { return state.native; } })); +vi.mock('../lib/api', () => ({ api: { saveBackupCopy: state.saveCopy, listBackups: state.list, deleteBackup: state.remove } })); + +const backup = (over: Partial = {}): BackupInfo => ({ + path: 'C:/data/backups/Novel-2026-11-15-1200.zip', fileName: 'Novel-2026-11-15-1200.zip', projectId: 'p1', + projectName: 'Novel', size: 2_400_000, createdAt: '2026-11-15T12:00:00Z', ...over, +}); +const created = (warnings: string[] = []): BackupCreated => ({ path: backup().path, fileName: backup().fileName, warnings }); + +beforeEach(() => { + state.native = true; + state.saveCopy.mockReset(); + state.remove.mockReset().mockResolvedValue(undefined); + state.list.mockReset().mockResolvedValue([]); +}); + +function setup(variant: 'desktop' | 'mobile' = 'desktop', projectName: string | undefined = 'Novel') { + const onBackup = vi.fn(async () => created()); + const onRestore = vi.fn<() => Promise>().mockResolvedValue(true); + render(); + return { onBackup, onRestore }; +} + +describe('Project backup recovery UX (regression)', () => { + it.each(['desktop', 'mobile'] as const)('creates a backup on the %s surface, lists it and saves a copy', async (variant) => { + const { onBackup } = setup(variant); + expect(screen.getByText(/unencrypted/)).toBeVisible(); + state.list.mockResolvedValue([backup()]); + fireEvent.click(screen.getByRole('button', { name: 'Create backup' })); + expect(screen.getByRole('button', { name: 'Restore backup' })).toBeDisabled(); + expect(await screen.findByText(/Backup saved on this device as Novel-2026-11-15-1200\.zip/)).toBeVisible(); + expect(onBackup).toHaveBeenCalledOnce(); + const list = await screen.findByRole('list', { name: 'Backups on this device' }); + expect(within(list).getByText(/2\.4 MB/)).toBeVisible(); + state.saveCopy.mockResolvedValueOnce(null); + fireEvent.click(screen.getByRole('button', { name: /Save a copy of Novel-2026/ })); + expect(await screen.findByText(/Save cancelled.*still on this device/)).toBeVisible(); + state.saveCopy.mockResolvedValueOnce('D:/safe/novel.zip'); + fireEvent.click(screen.getByRole('button', { name: /Save a copy of Novel-2026/ })); + expect(await screen.findByText(/Backup copy saved: D:/)).toBeVisible(); + expect(state.saveCopy).toHaveBeenLastCalledWith(backup().path, backup().fileName); + }); + + it('keeps restore available with no selected project', () => { + render(); + expect(screen.getByRole('button', { name: 'Create backup' })).toBeDisabled(); + expect(screen.getByRole('button', { name: 'Restore backup' })).toBeEnabled(); + }); + + it('gives browser users an accurate availability message', () => { + state.native = false; + setup(); + expect(screen.getByText(/available in the installed app/)).toBeVisible(); + expect(screen.queryByRole('button', { name: 'Create backup' })).toBeNull(); + }); + + // PR #3 review item 4: the archive is no longer read into the web view; the picker hands its + // location to the backend. Cancelling the picker is not an error and says nothing. + it('restores through the file picker and stays quiet when it is cancelled', async () => { + const { onRestore } = setup('mobile'); + onRestore.mockResolvedValueOnce(false); + fireEvent.click(screen.getByRole('button', { name: 'Restore backup' })); + await waitFor(() => expect(onRestore).toHaveBeenCalledOnce()); + expect(screen.queryByText(/restored as a separate project/)).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'Restore backup' })); + expect(await screen.findByText(/restored as a separate project/)).toBeVisible(); + expect(screen.getByText(/brings its AI conversations back but not the AI connection/)).toBeVisible(); + }); + + it('shows checksum/save failures and permits retry without success messaging', async () => { + const { onBackup, onRestore } = setup(); + onRestore.mockRejectedValueOnce(new Error('Backup checksum mismatch')); + fireEvent.click(screen.getByRole('button', { name: 'Restore backup' })); + expect(await screen.findByRole('alert')).toHaveTextContent('checksum mismatch'); + expect(screen.queryByText(/restored as a separate project/)).toBeNull(); + onBackup.mockRejectedValueOnce(new Error('Disk full')); + fireEvent.click(screen.getByRole('button', { name: 'Create backup' })); + expect(await screen.findByRole('alert')).toHaveTextContent('Disk full'); + fireEvent.click(screen.getByRole('button', { name: 'Create backup' })); + expect(await screen.findByText(/Backup saved on this device/)).toBeVisible(); + expect(screen.queryByRole('alert')).toBeNull(); + }); + + it('prevents duplicate backup requests while one is pending', async () => { + let finish!: (c: BackupCreated) => void; + const onBackup = vi.fn(() => new Promise((resolve) => { finish = resolve; })); + render(); + const button = screen.getByRole('button', { name: 'Create backup' }); + fireEvent.click(button); + fireEvent.click(button); + expect(onBackup).toHaveBeenCalledOnce(); + await act(async () => finish(created())); + expect(await screen.findByText(/Backup saved on this device/)).toBeVisible(); + }); + + // PR #3 review item 1: problems no longer block the backup; the writer sees what was left out. + it('lists what a completed backup could not include', async () => { + const { onBackup } = setup(); + onBackup.mockResolvedValueOnce(created(['chapter-9.json could not be read and was copied as it is.', '2 images outside this project were not included.'])); + fireEvent.click(screen.getByRole('button', { name: 'Create backup' })); + expect(await screen.findByText(/The backup is complete, with 2 notes/)).toBeVisible(); + expect(screen.getByText(/chapter-9\.json could not be read/)).toBeVisible(); + expect(screen.getByText(/2 images outside this project/)).toBeVisible(); + }); + + // PR #3 review item 3: backups were invisible and piled up; they are listed and can be deleted. + it('deletes a backup only after confirming, and lists only this project with a count of others', async () => { + state.list.mockResolvedValue([backup(), backup({ path: 'C:/data/backups/Salt-2026.zip', fileName: 'Salt-2026.zip', projectId: 'p2', projectName: 'Salt' })]); + setup(); + const list = await screen.findByRole('list', { name: 'Backups on this device' }); + expect(within(list).queryByText(/Salt-2026/)).toBeNull(); + expect(screen.getByText(/1 backup belongs to other projects/)).toBeVisible(); + expect(screen.getByText(/newest 5 backups of each project are kept/)).toBeVisible(); + fireEvent.click(screen.getByRole('button', { name: /Delete Novel-2026/ })); + const confirm = screen.getByRole('group', { name: /Confirm deleting Novel-2026/ }); + fireEvent.click(within(confirm).getByRole('button', { name: 'Keep' })); + expect(state.remove).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button', { name: /Delete Novel-2026/ })); + state.list.mockResolvedValue([]); + fireEvent.click(within(screen.getByRole('group', { name: /Confirm deleting/ })).getByRole('button', { name: 'Delete' })); + await waitFor(() => expect(state.remove).toHaveBeenCalledWith(backup().path)); + expect(await screen.findByText('Backup deleted.')).toBeVisible(); + await waitFor(() => expect(screen.queryByRole('list', { name: 'Backups on this device' })).toBeNull()); + }); +}); diff --git a/app/src/regression/sync-app.regression.test.tsx b/app/src/regression/sync-app.regression.test.tsx new file mode 100644 index 0000000..b42bd4a --- /dev/null +++ b/app/src/regression/sync-app.regression.test.tsx @@ -0,0 +1,102 @@ +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import type { Editor } from '@tiptap/react'; +import type { SyncAppliedEvent, SyncStatus } from '../lib/sync/types'; + +// Drive the App's sync boundary directly: status pushes and "applied" events from the backend. +const sync = vi.hoisted(() => ({ + status: null as SyncStatus | null, + applied: null as ((e: SyncAppliedEvent) => void) | null, +})); +vi.mock('../lib/sync/useSync', async (importOriginal) => { + const actual = await importOriginal(); + const { UNSUPPORTED_STATUS } = await import('../lib/sync/types'); + return { + ...actual, + useSyncStatus: () => ({ status: sync.status ?? UNSUPPORTED_STATUS, setStatus: vi.fn(), refresh: vi.fn() }), + useSyncApplied: (handler: (e: SyncAppliedEvent) => void) => { sync.applied = handler; }, + }; +}); + +beforeAll(async () => { await import('../App'); }, 60000); +beforeEach(() => { sync.status = null; sync.applied = null; localStorage.clear(); }); + +type Stored = { id: string; documents: { id: string; title: string; content: string }[] }[]; +const stored = () => JSON.parse(localStorage.getItem('mnemoscript:projects')!) as Stored; +function writeStored(f: (p: Stored) => void) { + const projects = stored(); + f(projects); + localStorage.setItem('mnemoscript:projects', JSON.stringify(projects)); +} + +async function openChapter(text: string) { + const { default: App } = await import('../App'); + const { api } = await import('../lib/api'); + const view = render(); + // Generous waits: the full suite mounts many TipTap trees in parallel on slow machines. + const slow = { timeout: 10000 }; + fireEvent.click(screen.getByText(/start a novel/i).closest('button')!); + const input = await screen.findByPlaceholderText(/ashen crown/i, {}, slow); + fireEvent.change(input, { target: { value: 'Synced Novel' } }); + fireEvent.submit(input.closest('form')!); + fireEvent.click(await screen.findByRole('button', { name: /new chapter/i }, slow)); + await waitFor(() => expect(document.querySelector('.ProseMirror')).toBeTruthy(), slow); + const editor = (document.querySelector('.ProseMirror') as HTMLElement & { editor: Editor }).editor; + act(() => { editor.commands.setContent(text, { emitUpdate: true }); }); + const project = stored()[0]; + return { api, editor, view, projectId: project.id, docId: project.documents[0].id }; +} + +describe('Sync boundary in the app (regression)', () => { + it('tells the backend which chapter is open so its text is never replaced under the editor', async () => { + const { api } = await import('../lib/api'); + const active = vi.spyOn(api, 'syncSetActive'); + const { projectId, docId } = await openChapter('

Draft

'); + await waitFor(() => expect(active).toHaveBeenCalledWith(projectId, docId)); + active.mockRestore(); + }); + + it('takes a remote rename of the open chapter without losing unsaved typing or reverting the title', async () => { + const { editor, projectId, docId } = await openChapter('

Unsaved words typed here

'); + // Another device renamed the chapter; sync wrote it to disk (the browser store here). + writeStored((p) => { p[0].documents[0].title = 'The Bells'; }); + await act(async () => sync.applied!({ projectId, changed: [`doc:${docId}`], staged: [] })); + await waitFor(() => expect(within(screen.getByRole('banner')).getByText('The Bells')).toBeVisible()); + expect(editor.getHTML()).toContain('Unsaved words typed here'); + // The next save keeps both: the writer's text and the synced title. + await act(async () => { fireEvent.keyDown(window, { key: 's', ctrlKey: true }); }); + await waitFor(() => expect(stored()[0].documents[0].content).toContain('Unsaved words typed here')); + expect(stored()[0].documents[0].title).toBe('The Bells'); + }); + + it('saves the open chapter before loading a held-back update, then shows the new text', async () => { + const { api, editor, projectId, docId } = await openChapter('

Local edit before loading

'); + sync.status = { + configured: true, platform: 'desktop', account: { id: 'a', email: '', name: '' }, state: 'idle', message: null, + lastRound: null, deviceName: 'PC', + projects: [{ projectId, state: 'synced', pending: 0, conflicts: [], staged: [docId], lastSync: null, error: null, notices: [] }], + }; + const order: string[] = []; + const save = vi.spyOn(api, 'saveDocument'); + save.mockImplementation(async (_pid, doc) => { + order.push('save'); + writeStored((p) => { p[0].documents[0].content = doc.content; }); + }); + const apply = vi.spyOn(api, 'syncApplyStaged').mockImplementation(async () => { + order.push('apply'); + writeStored((p) => { p[0].documents[0].content = '

Text from the phone

'; }); + return { changed: [`text:${docId}`], staged: [], published: 0, held: 0 }; + }); + const statusCall = vi.spyOn(api, 'syncStatus').mockResolvedValue(sync.status); + // More typing re-renders the App with the new status (the update is staged for this chapter). + act(() => { editor.commands.insertContent(' more'); }); + const load = await screen.findByRole('button', { name: 'Load it' }); + fireEvent.click(load); + await waitFor(() => expect(apply).toHaveBeenCalledWith(projectId, docId)); + expect(order).toEqual(['save', 'apply']); + await waitFor(() => expect(editor.getHTML()).toContain('Text from the phone')); + save.mockRestore(); + apply.mockRestore(); + statusCall.mockRestore(); + }); +}); diff --git a/app/src/regression/sync.regression.test.tsx b/app/src/regression/sync.regression.test.tsx new file mode 100644 index 0000000..07a8db2 --- /dev/null +++ b/app/src/regression/sync.regression.test.tsx @@ -0,0 +1,247 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import SyncSettings from '../components/sync/SyncSettings'; +import DocumentSyncBanner from '../components/sync/DocumentSyncBanner'; +import ConflictReview from '../components/sync/ConflictReview'; +import SyncPill from '../components/sync/SyncPill'; +import { paragraphs } from '../lib/sync/preview'; +import type { SyncStatus } from '../lib/sync/types'; +import type { Project } from '../types'; + +const api = vi.hoisted(() => ({ + driveSignIn: vi.fn(), + driveCancelSignIn: vi.fn(), + driveSetAccessToken: vi.fn(), + driveSignOut: vi.fn(), + syncEnableProject: vi.fn(), + syncDisableProject: vi.fn(), + driveRemoteProjects: vi.fn(), + syncDownloadProject: vi.fn(), + syncStatus: vi.fn(), + syncNow: vi.fn(), + syncDismissNotice: vi.fn(), + syncConflict: vi.fn(), + syncResolveConflict: vi.fn(), + driveUsage: vi.fn(), + backupProject: vi.fn(), +})); +vi.mock('../lib/api', () => ({ api })); + +const project = (id: string, name: string): Project => ({ id, name, created_at: '2026-11-01', documents: [], folders: [] }); +const projects = [project('p1', 'The Ashen Crown'), project('p2', 'Salt Notes')]; + +function status(over: Partial = {}): SyncStatus { + return { + configured: true, + platform: 'desktop', + account: { id: 'acct', email: 'writer@example.com', name: 'A. Writer' }, + state: 'idle', + message: null, + lastRound: new Date().toISOString(), + deviceName: 'WRITING-PC', + projects: [{ projectId: 'p1', state: 'synced', pending: 0, conflicts: [], staged: [], lastSync: new Date().toISOString(), error: null, notices: [] }], + ...over, + }; +} + +beforeEach(() => { + Object.values(api).forEach((f) => f.mockReset()); +}); + +function settings(s: SyncStatus, extra: Partial[0]> = {}) { + const setStatus = vi.fn(); + const onDownloaded = vi.fn(); + render(); + return { setStatus, onDownloaded }; +} + +describe('Google Drive sync settings (regression)', () => { + it('explains where sync lives in a plain browser and in builds without a Google client', () => { + const { unmount } = render(); + expect(screen.getByText(/available in the MnemoScript desktop and Android apps/)).toBeVisible(); + expect(screen.queryByRole('button', { name: /Connect Google Drive/ })).toBeNull(); + unmount(); + settings(status({ state: 'unconfigured', configured: false, account: null, projects: [] })); + expect(screen.getByText(/no Google sign-in set up/)).toBeVisible(); + }); + + // Regression (PR #4 review): on Linux the sign-in could not be stored, and sync asked to sign + // in again every hour. The backend now reports why sync is off there; the card says so. + it('explains why sync is unavailable on this platform instead of build instructions', () => { + settings(status({ state: 'unconfigured', configured: false, account: null, projects: [], + message: "Google Drive sync isn't available on Linux yet: MnemoScript can't keep your Google sign-in securely there." })); + expect(screen.getByText(/isn't available on Linux yet/)).toBeVisible(); + expect(screen.queryByText(/\.env\.local/)).toBeNull(); + }); + + it('signs in through the browser with a cancel option, and states the privacy limits first', async () => { + let finish!: (s: SyncStatus) => void; + api.driveSignIn.mockReturnValue(new Promise((r) => { finish = r; })); + const { setStatus } = settings(status({ state: 'signed-out', account: null, projects: [] })); + expect(screen.getByText(/not end-to-end encrypted/)).toBeVisible(); + expect(screen.getByText(/password never passes through MnemoScript/)).toBeVisible(); + const connect = screen.getByRole('button', { name: /Connect Google Drive/ }); + fireEvent.click(connect); + fireEvent.click(connect); + expect(api.driveSignIn).toHaveBeenCalledOnce(); + fireEvent.click(await screen.findByRole('button', { name: /Cancel/ })); + expect(api.driveCancelSignIn).toHaveBeenCalledOnce(); + const signedIn = status(); + await act(async () => finish(signedIn)); + expect(setStatus).toHaveBeenCalledWith(signedIn); + }); + + it('uses the native Google prompt on Android and hands the token to the backend', async () => { + const authorizeNative = vi.fn().mockResolvedValue({ token: 'ya29.token', expiresIn: 3599 }); + api.driveSetAccessToken.mockResolvedValue(status()); + settings(status({ state: 'signed-out', account: null, projects: [] }), { authorizeNative }); + fireEvent.click(screen.getByRole('button', { name: /Connect Google Drive/ })); + await waitFor(() => expect(api.driveSetAccessToken).toHaveBeenCalledWith('ya29.token', 3599)); + expect(api.driveSignIn).not.toHaveBeenCalled(); + }); + + it('turns sync on and off per project and shows each project state', async () => { + api.syncEnableProject.mockResolvedValue(status()); + api.syncDisableProject.mockResolvedValue(status()); + settings(status({ projects: [{ projectId: 'p1', state: 'pending', pending: 3, conflicts: [], staged: [], lastSync: null, error: null, notices: [] }] })); + expect(screen.getByText('Waiting to sync')).toBeVisible(); + expect(screen.getByText('Only on this device')).toBeVisible(); + fireEvent.click(screen.getByLabelText('Sync Salt Notes')); + fireEvent.click(await screen.findByRole('button', { name: 'Sync without a backup' })); + await waitFor(() => expect(api.syncEnableProject).toHaveBeenCalledWith('p2')); + expect(api.backupProject).not.toHaveBeenCalled(); + fireEvent.click(screen.getByLabelText('Sync The Ashen Crown')); + await waitFor(() => expect(api.syncDisableProject).toHaveBeenCalledWith('p1')); + }); + + // PR #4 review: sync is not a backup, so turning it on offers one first. + it('offers a backup before a project starts syncing, and can be cancelled', async () => { + const order: string[] = []; + api.backupProject.mockImplementation(async () => { order.push('backup'); return '/backups/salt.zip'; }); + api.syncEnableProject.mockImplementation(async () => { order.push('enable'); return status(); }); + settings(status()); + fireEvent.click(screen.getByLabelText('Sync Salt Notes')); + const offer = await screen.findByRole('group', { name: 'Start syncing Salt Notes' }); + expect(within(offer).getByText(/Sync is not a backup/)).toBeVisible(); + fireEvent.click(within(offer).getByRole('button', { name: 'Cancel' })); + expect(screen.queryByRole('group', { name: 'Start syncing Salt Notes' })).toBeNull(); + expect(api.syncEnableProject).not.toHaveBeenCalled(); + fireEvent.click(screen.getByLabelText('Sync Salt Notes')); + fireEvent.click(await screen.findByRole('button', { name: /Back up, then sync/ })); + expect(await screen.findByText(/Backup saved\. Salt Notes now syncs/)).toBeVisible(); + expect(order).toEqual(['backup', 'enable']); + expect(api.backupProject).toHaveBeenCalledWith('p2'); + }); + + it('does not start syncing when the backup fails', async () => { + api.backupProject.mockRejectedValue(new Error('Disk full')); + settings(status()); + fireEvent.click(screen.getByLabelText('Sync Salt Notes')); + fireEvent.click(await screen.findByRole('button', { name: /Back up, then sync/ })); + expect(await screen.findByRole('alert')).toHaveTextContent('Disk full'); + expect(api.syncEnableProject).not.toHaveBeenCalled(); + }); + + // PR #4 review: old versions are not pruned yet, so the card shows the Drive space used. + it('shows how much Google Drive space MnemoScript uses', async () => { + api.driveUsage.mockResolvedValue(18_400_000); + settings(status()); + expect(await screen.findByText(/Uses about 18 MB of your Google Drive/)).toBeVisible(); + }); + + it('downloads a project from another device and never merges same-name projects silently', async () => { + api.driveRemoteProjects.mockResolvedValue([ + { projectId: 'r1', name: 'the ashen crown', deviceName: 'Pixel 8', updatedAt: new Date().toISOString(), local: false, syncing: false }, + { projectId: 'p1', name: 'The Ashen Crown', deviceName: 'Laptop', updatedAt: new Date().toISOString(), local: true, syncing: true }, + ]); + const downloaded = project('r1', 'the ashen crown'); + api.syncDownloadProject.mockResolvedValue(downloaded); + api.syncStatus.mockResolvedValue(status()); + const { onDownloaded } = settings(status()); + fireEvent.click(screen.getByRole('button', { name: /Find projects from other devices/ })); + expect(await screen.findByText(/From Pixel 8/)).toBeVisible(); + expect(screen.getByText(/Downloading keeps both; nothing is merged automatically/)).toBeVisible(); + expect(screen.queryByText(/From Laptop/)).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: /Download/ })); + await waitFor(() => expect(onDownloaded).toHaveBeenCalledWith(downloaded)); + expect(api.syncDownloadProject).toHaveBeenCalledWith('r1', 'the ashen crown'); + }); + + it('reports failures accessibly and offers reconnect when sign-in expired', async () => { + api.driveSignIn.mockRejectedValueOnce(new Error('Google sign-in was cancelled')); + settings(status({ state: 'needs-auth' })); + expect(screen.getByText(/Google sign-in expired/)).toBeVisible(); + fireEvent.click(screen.getByRole('button', { name: 'Reconnect' })); + expect(await screen.findByRole('alert')).toHaveTextContent('cancelled'); + }); +}); + +describe('Open chapter sync banner (regression)', () => { + it('offers to load a held-back update and reports a failed load', async () => { + const onLoadUpdate = vi.fn().mockRejectedValueOnce(new Error('Disk full')).mockResolvedValue(undefined); + const s = status({ projects: [{ ...status().projects[0], staged: ['ch1'] }] }); + render(); + expect(screen.getByText(/newer version of this chapter arrived/)).toBeVisible(); + fireEvent.click(screen.getByRole('button', { name: 'Load it' })); + expect(await screen.findByText('Disk full')).toBeVisible(); + fireEvent.click(screen.getByRole('button', { name: 'Load it' })); + await waitFor(() => expect(onLoadUpdate).toHaveBeenCalledTimes(2)); + }); + + it('sends parallel edits to review, and stays hidden for other chapters', () => { + const onReview = vi.fn(); + const s = status({ projects: [{ ...status().projects[0], state: 'conflict', conflicts: [{ docId: 'ch3', title: 'Chapter 3' }] }] }); + const { rerender } = render(); + expect(screen.getByText(/Both versions are safe/)).toBeVisible(); + fireEvent.click(screen.getByRole('button', { name: 'Compare versions' })); + expect(onReview).toHaveBeenCalledOnce(); + rerender(); + expect(screen.queryByRole('status')).toBeNull(); + }); + + it('keeps sync chrome away from local-only projects', () => { + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + render(); + expect(screen.getByRole('button', { name: 'Sync: Synced' })).toBeVisible(); + }); +}); + +describe('Conflict review (regression)', () => { + const versions = [ + { rev: 'r-local', local: true, device: 'WRITING-PC', content: '

The bells rang at dawn.

Desktop ending.

' }, + { rev: 'r-phone', local: false, device: 'Pixel 8', content: '

The bells rang at dawn.

Phone ending.

' }, + ]; + + it('shows both versions as plain text, marks differences, and keeps the other version by default', async () => { + api.syncConflict.mockResolvedValue(versions); + api.syncResolveConflict.mockResolvedValue(['copy-1']); + const onResolved = vi.fn(); + render(); + const phone = (await screen.findByText('From Pixel 8')).closest('article')!; + expect(within(phone).getByText('Phone ending.')).toHaveClass('bg-primary/10'); + expect(within(phone).getByText('The bells rang at dawn.')).not.toHaveClass('bg-primary/10'); + expect(document.querySelector('[role="dialog"] img, [role="dialog"] script')).toBeNull(); + expect((window as unknown as { __pwned?: boolean }).__pwned).toBeUndefined(); + fireEvent.click(within(phone).getByRole('button', { name: /Keep this/ })); + await waitFor(() => expect(api.syncResolveConflict).toHaveBeenCalledWith('p1', 'ch3', 'r-phone', true)); + expect(onResolved).toHaveBeenCalledWith(['copy-1']); + }); + + it('can drop the copy, and surfaces a failed resolution', async () => { + api.syncConflict.mockResolvedValue(versions); + api.syncResolveConflict.mockRejectedValueOnce(new Error('That version is no longer part of the conflict')); + render(); + fireEvent.click(await screen.findByRole('checkbox')); + expect(screen.getByText(/stays in sync history/)).toBeVisible(); + fireEvent.click(within(screen.getByText('On this device').closest('article')!).getByRole('button', { name: /Keep this/ })); + expect(await screen.findByRole('alert')).toHaveTextContent('no longer part'); + expect(api.syncResolveConflict).toHaveBeenCalledWith('p1', 'ch3', 'r-local', false); + }); + + it('summarises map versions instead of dumping JSON', () => { + expect(paragraphs('{"nodes":[1,2],"edges":[1]}', 'mindmap')).toEqual(['2 ideas · 1 links']); + expect(paragraphs('not json', 'fantasymap')).toEqual(['(This version could not be previewed)']); + expect(paragraphs('
  • One

Two

', 'text')).toEqual(['One', 'Two']); + }); +}); diff --git a/app/vitest.config.ts b/app/vitest.config.ts index 29c2a8c..b70f954 100644 --- a/app/vitest.config.ts +++ b/app/vitest.config.ts @@ -21,5 +21,8 @@ export default defineConfig({ unstubGlobals: true, // TipTap / React Flow mount real DOM trees; give slow CI boxes some headroom. testTimeout: 15000, + // Several suites mount the whole App. One worker per core starves them on a busy desktop + // and the streamed AI mock then times out; half the cores keeps runs fast and stable. + maxWorkers: '50%', }, }); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5c2c795..b66b554 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -11,6 +11,30 @@ The serverless sync strategy and dependency gates live in and [test matrix](./MNEMOSYNC_TEST_MATRIX.md). Start from current AI feature HEAD, not stale main. Phase 0 introduces recovery archives; LAN/Drive and Smart Merge remain later gated phases. +- `src-tauri/src/backup.rs` streams allowlisted files to `-.zip` + in app-level `backups/` (the newest 5 per project are kept), records SHA-256/lengths of the + archived bytes, validates paths and bounds, and stages restores as independent copies. Image + references are archived as portable `mnemo-asset:` (no source folder recorded); damaged + chapter files are copied as-is and reported as warnings. Commands: `backup_project` (returns + path + warnings), `list_backups`, `delete_backup`, `save_backup_copy` (file to file) and + `restore_project_backup({path})`, which opens the dialog-picked file (desktop path in the fs + scope, or an Android content URI) in Rust, so the archive never passes through the web view. + Restored projects are registered only after activation. `src/components/sync/BackupSettings.tsx` + is shared by the two settings shells. `App.tsx` saves through `flushIfDirty` before a backup. +- Recovery rewrites image attributes and known map asset fields (including fantasy-map + "My Imports" paths), preserving manuscript/graph identity and the original archive. Browser + ZIP recovery remains explicitly native-only. +- **Google Drive sync** ([MNEMOSYNC_DRIVE.md](./MNEMOSYNC_DRIVE.md)): `src-tauri/src/sync/` holds the + transport-neutral engine (`model.rs` entity revisions, `engine.rs` scan/apply/merge/conflicts, + `store.rs` SQLite state in `/sync/mnemosync.db`, `portable.rs` `mnemo-asset:` refs), + the Drive transport and OAuth (`drive/api.rs`, `drive/auth.rs`) and the worker + commands + (`service.rs`). Save commands in `lib.rs` only call `sync::service::nudge`; the worker scans + disk, pulls, applies and publishes. Frontend: `src/lib/sync/*` (types, `useSyncStatus`, events + `sync://status` / `sync://applied`, Android `google-auth` plugin calls) and + `src/components/sync/*` (settings card for both shells, `SyncPill`, `DocumentSyncBanner`, + `ConflictReview`). `App.tsx` reports the open chapter (`sync_set_active`), reloads changed + projects, and merges remote title/folder/order into the open document without losing typing. + ## Stack - **Shell:** Tauri 2 (Rust backend + system WebView). - **Frontend:** React 19 + TypeScript + Vite 8, Tailwind CSS v4. @@ -42,7 +66,10 @@ A project is a folder (custom path, or `~/.mnemoscript/projects/` by default assets/. # imported images ai/sessions/.json # AI chat sessions (per project — see "AI assistant") ``` -A global registry at `~/.mnemoscript/registry.json` maps project id → folder path. +A global registry at `~/.mnemoscript/registry.json` maps project id → folder path. Sync state +(revisions, outbox, conflicts, Drive cursors) lives in `~/.mnemoscript/sync/mnemosync.db`, never in a +project folder; the Google refresh token is in the OS keychain (`MnemoScript[-dev]` / +`google-drive-refresh`). **Debug builds use `~/.mnemoscript-dev`** (Android: `/dev`), so `tauri dev` never reads or rewrites the installed app's projects. `list_projects` reads metadata only; **opening a project uses `load_project`**, which reads the @@ -55,10 +82,17 @@ All return an `ApiResponse` = `{ success, data, error }` envelope. `save_document` · `load_document` · `delete_document` · **`save_asset`** (raw binary body + `x-project-id` / `x-ext` headers → copies into `assets/`, returns the absolute path) · **`export_file`** (raw body → `/exports/`) · `select_directory`. +Sync (`sync::service`): `sync_status` · `drive_sign_in` / `drive_cancel_sign_in` / +`drive_set_access_token` (Android) / `drive_sign_out` · `sync_enable_project` / `sync_disable_project` · +`drive_remote_projects` · `sync_download_project` · `sync_now` · `sync_set_active` · `sync_apply_staged` · +`sync_conflict` / `sync_resolve_conflict` · `sync_dismiss_notice` · `drive_usage`. Forgetting/deleting a +project stops syncing it on this device. `project::files_lock` serialises project file writes between +the save commands and the sync engine (the engine re-checks a file under it before replacing it). +Chapters removed by sync go to `/sync-trash/` (30 days; not synced or backed up). **Webview limits:** the `fs` plugin may read/write only paths the writer picked in a dialog (no `**` scope), and `tauri.conf.json` sets a CSP (self, `wasm-unsafe-eval`, blob workers, asset/IPC hosts, LanguageTool). Add a host there before the webview may contact it. -All file writes go through `write_atomic` (tmp + rename). `project.json` stores folders + a +All file writes go through `write_atomic` (tmp + rename); imported images use a temp file + rename too. `project.json` stores folders + a **content-free** document index; document bodies live only in `documents/.json`. Unreadable or corrupt document files are skipped with a warning so one bad file never blocks a project. diff --git a/docs/DEVLOG.md b/docs/DEVLOG.md index 763548c..eba30b2 100644 --- a/docs/DEVLOG.md +++ b/docs/DEVLOG.md @@ -3,6 +3,25 @@ A running log of substantive changes, so future work needs less re-discovery. Newest entries first. Dates are absolute. +## 2026-11-15 — Backups: fixes from the PR #3 review + +Each fix has a regression test (`cargo test backup::`, `regression/backup*.regression.test.tsx`). +- **A problem no longer blocks the backup.** A damaged chapter file is copied as-is and named in a + warning; images outside the project or missing are counted in warnings. Restore stays strict + about integrity (sizes, checksums, paths, folder tree, every chapter that was valid) and restores + the chapters the backup itself recorded as damaged byte for byte, so such a backup still restores. +- **No source path in archives.** Schema 2 archives store images as `mnemo-asset:` and drop + `sourceRoot` (which carried the OS user name). Schema 1 archives still restore. +- **Backups are visible.** Files are named `-.zip`; the settings card + lists this project's backups with date and size, "Save a copy…" and a confirmed delete; the newest + 5 per project are kept. +- **No whole archive in memory.** Restore and "Save a copy" pass file locations; Rust opens the + picked file (desktop path in the fs scope, Android content URI). This also keeps "Save a copy" + working with 2.1.1's narrowed webview file access. +- **One save path.** The backup saves through `flushIfDirty` (the 2.1.1 `persistCurrent` with its + guard and error result) instead of its own copy. +- The card says a restored copy brings AI conversations back but not the AI connection. + ## 2026-11-15 — 2.1.1: fixes from the PR #1 review (security and lost edits) Items 1–3 were in the released 2.1.0; each fix has a regression test. @@ -30,6 +49,74 @@ Items 1–3 were in the released 2.1.0; each fix has a regression test. byte-identical, from `node_modules`, no network). - Version 2.1.1 in `package.json`, `Cargo.toml`, `tauri.conf.json` (not tagged). +## 2026-11-15 — Drive sync: review fixes (no lost saves) + +Addressed the PR #4 reviews (`50e4beb`, `5444c1c`); each fix has a regression test. +- **Data loss.** A chapter that one device could not read (or a missing `documents/` folder) was + recorded as a delete and removed everywhere: unreadable now keeps the last good state with one + note. Remote writes could overwrite a save made after the round's scan: every engine write now + re-checks the file under `project::files_lock` (also taken by `Document::save/delete` and + `Project::save`) and captures a newer save first. Conflict review and resolve scan first, so the + latest typing is a version. Delete + two different edits kept only one edit: both stay, as a + conflict. Remote deletes and replaced damaged copies go to `/sync-trash/` (30 days). +- **Sign-in.** A stray request to the loopback port no longer ends the sign-in (error page, keep + waiting). Retrying Connect keeps a valid grant unless Google rejects it, so an early retry does + not open Google's pages again. Linux desktop is off for Drive sync until a keyring backend exists. +- **Drive client.** The newer error shape (`error.details[].reason`, e.g. `SERVICE_DISABLED`) is + read; release builds say "isn't set up correctly in this build" instead of Cloud console steps. + An expired change cursor is detected by status, not message text. The catalogue entry's date + moves forward when a round publishes (at most hourly). +- **Smaller.** Sync commands validate project and document ids. Android names itself by model + (`ro.product.model`). The settings card shows the Drive space used, offers "Back up, then sync" + when a project is turned on, and carries a Beta label. The live test names its project + `zz-live-test-…`, prints its id, and fails when cleanup fails. + + +## 2026-11-15 — First live Google Drive run + +- Desktop sign-in worked against the writer's own Cloud project (Testing mode, test user added). + First setup surfaced a raw `403: accessNotConfigured` (Drive API not enabled): it now reads as + a plain instruction, and a retry reuses the stored grant instead of sending the writer through + Google's pages again. +- New ignored live test `cargo test live_drive -- --ignored --nocapture` plays two devices on the + real `appDataFolder` under a throwaway project id: upload with an image, download (image and + portable reference intact), edit back through the changes feed, then deletes its files. Passed + in 29 s. Android sign-in and real desktop ↔ phone sync are still to be tried. + + +## 2026-11-13 — Google Drive sync (MnemoDrive) on the shared sync engine + +- Reviewed PRs #2 (strategy, Node 24 CI, AI undo) and #3 (Phase 0 backup/restore): sound, but + the plan's local sync (Phases 1–4) was not built, so Drive could not "reuse" it. Built the + transport-neutral engine first (`src-tauri/src/sync/`): per-entity revisions with + content-derived ids, SQLite WAL state outside project folders, disk-scan change capture, + causal fast-forward, deterministic field merge, preserved text conflicts, edit-beats-delete, + tree repair, staged updates for the open chapter, frozen batches for crash-safe publishing, + and portable `mnemo-asset:` image references (disk format unchanged). +- Google Drive transport on the hidden `appDataFolder` (`drive.appdata` only): gzip blobs before + immutable batch files, changes feed + listing fallback, duplicate/forged file handling, + 401/403/429/5xx/quota classes with backoff. Desktop sign-in = loopback + PKCE in the system + browser, refresh token in the OS keychain; Android = Google Play services AuthorizationClient via + an inline `google-auth` plugin (no refresh token stored). Account switches are refused while + projects are bound to the previous account. OAuth client comes from git-ignored `.env.local`. +- UI: "Sync with Google Drive" card in both settings shells (connect, per-project toggles, + download from other devices with a same-name notice, sync notes), a quiet status pill for synced + projects only, a floating banner when the open chapter changed elsewhere ("Load it" saves first), + and a side-by-side conflict review that keeps the other version as its own chapter by default. +- Stray fixes: restore left fantasy-map "My Imports" paths on the original project; imported images + were written non-atomically (a crash or scan could see half a file); forgotten projects kept + syncing; App-mounting Vitest suites and the streamed AI mock timed out with one worker per core. +- Self-review fixes before the PR: turning a project's sync off and on reset its batch counter + (new batches collided with published numbers and were skipped), and re-enabling under another + Google account published nothing; both have engine regressions. Desktop status now reports + "needs-auth" after signing out while projects stay bound to the account. +- Checks: `npm run check` (145 tests, 56 regressions, lint, types, build), `cargo test` (90 pass, + 3 live-AI ignored; 32 sync tests), `cargo clippy -- -D warnings`. `npx tauri android build --apk + --debug --target aarch64` builds (Kotlin `GoogleAuthPlugin` + play-services-auth 21.3.0); the + three Android-only dead-code warnings in `ai/pair_crypto.rs` are now marked desktop-only. + Not verified: live Google OAuth and real desktop ↔ Android sync (needs the writer's own OAuth + clients; see `MNEMOSYNC_DRIVE.md`). Browser visual preview is still blocked by permission policy. + ## 2026-11-12 — MnemoSync strategy and initial recovery slice - Extracted the supplied development plan and MEMORY.md under `docs/mnemosync/`; treated as @@ -38,6 +125,15 @@ Items 1–3 were in the released 2.1.0; each fix has a regression test. and an honest automated/device/visual acceptance matrix. Preserve current AI work and UI shells. - Phase 0 implementation begins with checked native ZIP recovery; transports and Smart Merge remain gated follow-on work. Baseline `npm run check`: 116 tests, lint/types/build pass. +- Implemented backup/restore commands, a versioned SHA-256 manifest, defensive bounded extraction, + private staging, fresh recovered project identities and image-path relocation with HTML entity + handling. Includes saved chapters/maps/assets/sessions/exports; excludes app credentials/grants. +- Added settings controls using the existing desktop cards and phone rows: create locally, save a + separate copy, restore a selected ZIP, progress/errors and retry. Failed local save aborts backup. +- Final checks after integrating the runtime and undo fixes: 130 frontend tests, 41 regressions, production build/lint/types; cargo check, + 56 backend tests (3 existing live-AI tests ignored), and Clippy with warnings denied pass. + Visual preview remains permission-blocked; packaged Windows/real Android acceptance pending. + ## 2026-11-12 — Isolate AI revisions from nearby typing in undo history diff --git a/docs/IMPROVEMENT_PLAN.md b/docs/IMPROVEMENT_PLAN.md index ab0fef1..b1a7eb4 100644 --- a/docs/IMPROVEMENT_PLAN.md +++ b/docs/IMPROVEMENT_PLAN.md @@ -11,6 +11,31 @@ First deliverable is native checked backup/restore with existing desktop/phone s then SQLite/IndexedDB and portable assets, Smart Merge, shared replay engine, LAN, Drive, hybrid and recovery UX. The Android/installed-app gate remains pending until actual device evidence. +**Implemented Phase 0 slice:** native ZIP backup/restore, corruption/path/size validation, fresh +recovered copies and asset relocation, with desktop/phone settings controls. Automated checks +pass (130 frontend, 41 regression, 56 backend tests; lint/types/build/check/Clippy). +No transport or existing-project linking is enabled. Finish manual device acceptance before +advancing the Phase 0 gate; the following schemas remain design-only. + +**Google Drive sync (2026-11-13, `codex/mnemosync-drive`):** implemented the shared sync engine +(entity revisions, SQLite state, merge/conflicts, staged open-chapter updates, portable images), +the Drive `appDataFolder` transport, desktop loopback+PKCE sign-in with keychain storage, Android +native authorization, and the sync UI for both shells ([MNEMOSYNC_DRIVE.md](./MNEMOSYNC_DRIVE.md)). +Automated checks pass. Live desktop sign-in and a real Drive round trip passed 2026-11-15; the PR +review's data-loss findings are fixed with regressions. **Android sign-in and real desktop ↔ Android +sync are not yet verified.** Still open: Smart Merge, LAN, web sync, history pruning, restoring from +`sync-trash/` in the app, Linux secret storage. + +| MnemoSync phase | Status | +|---|---| +| 0 Strategy + checked backup/restore | ✅ code; device acceptance pending | +| 1 Sync state + portable assets | ✅ native SQLite + `mnemo-asset:` refs; web IndexedDB not done | +| 2 Smart Merge | ⏳ not started (downloads create separate copies; same-name notice only) | +| 3 Revision engine + transport interface | ✅ with multi-device simulations | +| 4 LAN (MnemoLink) | ⏳ not started | +| 5 Google Drive | ✅ code + tests; live desktop OAuth + Drive round trip ✅; Android/device proof pending | +| 6–8 Hybrid, recovery UX, hardening | ⏳ partial (conflict review, notices) | + **Stack:** Tauri 2 (Rust) · React 19 + TypeScript 6 · Vite 8 · Tailwind v4 · TipTap 3 · React Flow 12 · Konva 10. Three targets share one codebase: Windows desktop (WebView2), Android (Tauri mobile), and the web build (browser fallback backend in `lib/api.ts` → localStorage). diff --git a/docs/MNEMOSYNC_ARCHITECTURE.md b/docs/MNEMOSYNC_ARCHITECTURE.md index 4677141..31bcb70 100644 --- a/docs/MNEMOSYNC_ARCHITECTURE.md +++ b/docs/MNEMOSYNC_ARCHITECTURE.md @@ -22,6 +22,13 @@ The requested work authorizes implementation, testing and new PRs. | 5 | Same-account Google OAuth and immutable Drive transport | Real cross-client appData access, secure native tokens, web expiry recovery | | 6–8 | Hybrid receipts, conflict/recovery UX, fault/security/performance tests | No false Synced state, account isolation, real hardware soak and rollback | +**2026-11-13:** slices 1 (native part), 3 and 5 are implemented on `codex/mnemosync-drive`; see +[MNEMOSYNC_DRIVE.md](MNEMOSYNC_DRIVE.md) for the design as built and what remains unverified. +Two refinements to ADR 001/002: change capture is a disk scan against the last known state (the +disk stays authoritative, so no separate write-intent journal is needed for crash safety), and +revisions are per-entity snapshots (`project`, `folder:`, `doc:`, `text:`, `asset:`) rather than +per-keystroke operations. Batches carry device sequence numbers; ids stay content-derived. + Each slice gets its own reviewable PR. Where prerequisites are still open, use stacked PRs; retarget dependent PRs after their bases merge. Do not represent Phase 0 as working synchronization. diff --git a/docs/MNEMOSYNC_DRIVE.md b/docs/MNEMOSYNC_DRIVE.md new file mode 100644 index 0000000..77c3606 --- /dev/null +++ b/docs/MNEMOSYNC_DRIVE.md @@ -0,0 +1,153 @@ +# MnemoDrive: Google Drive sync + +Implemented 2026-11-13 on `codex/mnemosync-drive` (stacked on the Phase 0 backup branch). +Optional and per project: nothing leaves the device until the writer connects Google Drive and +turns sync on for a project. Local saves never wait for, or depend on, sync. + +## What is built + +| Piece | Where | Notes | +|---|---|---| +| Sync engine (transport-neutral) | `src-tauri/src/sync/{model,engine,store,portable}.rs` | Revisions, merge, conflicts, outbox; LAN can plug in through the same `Transport` trait | +| Google Drive transport | `src-tauri/src/sync/drive/api.rs` | `appDataFolder`, immutable files, changes feed, error classes | +| Desktop sign-in | `src-tauri/src/sync/drive/auth.rs` | Loopback + PKCE in the system browser, refresh token in the OS keychain | +| Android sign-in | `gen/android/.../GoogleAuthPlugin.kt` + inline `google-auth` plugin | Google Play services AuthorizationClient, no refresh token stored | +| Worker + commands | `src-tauri/src/sync/service.rs` | Debounced after saves, polls every 90 s, backoff to 15 min | +| UI | `src/components/sync/*`, `src/lib/sync/*` | Settings card (both shells), status pill, open-chapter banner, conflict review | + +Not built (deliberately): Smart Merge of independently created copies, LAN sync, web/browser sync, +IndexedDB storage, sync of AI conversations, history pruning. See "Follow-ups". + +## Model (how this reuses the local-sync design) + +The plan's local-sync design (ADR 001–002) is implemented as the shared engine, not as Drive code: + +- **Entities.** A project is split into `project` (name/description/author), `folder:`, + `doc:` (title/type/order/folder), `text:` (body, by SHA-256) and `asset:` + (image bytes, by SHA-256). A move on one device and a text edit on another touch different + entities, so both apply. Per-device project settings (`ai`, `path`) are never synced. +- **Revisions.** `rev = sha256(entity, sorted parents, canonical payload)`: independent of device + and clock, so two devices that reach the same merge produce the same id and deduplicate. + Received revisions are re-hashed and rejected if they do not match. A payload of `null` is a + tombstone. +- **Capture.** After every round's start, `scan` compares the files on disk with the engine's + last known state and records each difference as a revision (parent = previous disk revision). + The disk stays the source of truth, so a crash between a save and the next scan loses nothing: + the next scan sees the change. Save commands only *nudge* the worker. +- **Apply.** Batches wait until all parents and blobs are present. Per entity, the maximal heads + decide: one head = fast-forward; metadata = deterministic three-way field merge (same result on + every device, a note when a field truly collided); text = keep this device's version in place + and preserve the others as conflict heads; edit beats delete for both text and chapters. After + applying, `repair` keeps the tree valid (no chapter in a deleted folder, no folder cycles). +- **Open chapter.** The app reports the open chapter. Its text (and its removal) is staged, never + written under the editor; title/folder/order changes do apply and the app merges them into the + open document without touching unsaved typing. "Load it" saves first, then applies; typing + before accepting turns into a conflict, never a silent overwrite. +- **Conflicts.** The writer compares versions side by side (plain text, parsed inertly) and keeps + one in place; by default every other version becomes its own chapter named after its device. + The resolution is a merge revision whose parents are all heads. +- **Never lose a save (2026-11-15, from the PR #4 review).** + - *Unreadable is not deleted.* A chapter file that exists but cannot be parsed (damaged, + locked, id ≠ file name), or a missing `documents/` folder, keeps its last synced state; the + writer gets one note. Only a file that is really gone, in a readable folder, becomes a delete. + - *Check before write.* Every engine write first re-reads the entity and compares it with what + the round scanned, under one files lock shared with the app's save commands + (`project::files_lock`), so the check and the write are atomic. A save that landed after the + scan (an autosave, the assistant editing a closed chapter, a late map flush) is captured as a + local revision first and then merges or becomes a conflict. Differences the engine made + itself (the downloaded skeleton's `project.json`, an empty chapter file built before its text + arrived, a chapter sync just removed) are recognised as such. + - *Removed means trashed.* A chapter deleted on another device, or a damaged copy replaced by + the good version, moves to `/sync-trash/` for 30 days instead of being deleted. The + trash is not part of the project (not synced, not in backups). + - *Conflict review is current.* Opening the review and resolving both scan first, so the latest + typing is "this device's version"; choosing it from an older screen keeps the latest text. + - *Delete + two different edits* stays a conflict between the two edits (both kept). +- **Portable images.** Synced text replaces `/assets/` references with + `mnemo-asset:` (`` in chapters, whole string values in map JSON, including + "My Imports"), and each device turns them back into its own absolute path. Disk format is + unchanged, so no migration of existing projects is needed. + +State lives in `/sync/mnemosync.db` (SQLite, WAL), outside every project folder and +never synced or backed up. Debug builds use `~/.mnemoscript-dev`, so development never touches +the installed app's sync state. + +## Google Drive layout + +Only the hidden `appDataFolder` (scope `https://www.googleapis.com/auth/drive.appdata`). Files +are flat; `appProperties` carry the query keys (`m=1`, `k`, `p`, `d`, `s`, `h`): + +``` +mnemo-b-- gzip blob: chapter text or image bytes k=b +mnemo-o--- gzip JSON batch of revisions k=o (commit marker) +mnemo-i-- JSON catalogue entry (name, device) k=i (own file only) +``` + +- Blobs are uploaded and recorded before the batch that references them; a batch is frozen in + SQLite before upload, so a crash retries the *same* bytes under the same sequence number. +- `put_batch` checks for an existing `(device, seq)` file first; receivers keep the first file for + a `(device, seq)` and ignore duplicates and files whose content contradicts their labels. +- New batches are found through `changes.list` (one cursor per Google account, taken *before* + the first listing); an expired cursor falls back to a full listing, never to deletion. +- Downloads are capped at 256 MiB decompressed; uploads above 4 MiB use a resumable session. +- 401 refreshes once, then pauses as `needs-auth`; 403 quota = "Drive full"; 403 rate limits, + 429 and 5xx back off (30 s doubling to 15 min); network errors keep everything queued. +- The Google account is identified by Drive's `permissionId`. A device refuses to switch to a + different account while projects are synced with the previous one. + +Drive data is protected in transit and at rest by Google but **not end-to-end encrypted**, and +sync is **not a backup** (the Settings card says so; keep project backups). + +## Setting up Google sign-in (your own Google Cloud project) + +MnemoScript has no server and ships no OAuth client. Each build uses an OAuth client from the +writer's (or publisher's) own Google Cloud project. + +1. In the [Google Cloud console](https://console.cloud.google.com/), create a project (e.g. + "MnemoScript") and enable the **Google Drive API** (APIs & Services → Library). +2. Google Auth Platform → **Branding**: app name, support email. **Audience**: External; while in + *Testing*, add your own Google account as a test user. **Data access**: add the scope + `https://www.googleapis.com/auth/drive.appdata` (non-sensitive; no other scope is needed). +3. **Clients → Create client → Desktop app.** Copy the client ID and secret into + `app/src-tauri/.env.local` (git-ignored; template in `.env.local.example`): + ``` + MNEMO_GOOGLE_CLIENT_ID=1234-abc.apps.googleusercontent.com + MNEMO_GOOGLE_CLIENT_SECRET=GOCSPX-... + ``` + Google documents an installed-app client secret as not confidential, but keep it out of git. + Rebuild (`npm run tauri dev` / `tauri build`). Settings → *Sync with Google Drive* → Connect. +4. **Android:** in the *same* Cloud project, create an **Android** client for package + `com.mnemoscript.app` with the SHA-1 of the certificate that signs the APK. For debug builds: + `keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android`. + Release builds need the release certificate's SHA-1 (run `keytool` yourself; never paste + keystore passwords anywhere). No client ID is compiled into the Android app. +5. **Testing-mode limit:** Google expires refresh tokens after 7 days for apps in *Testing* that + use non-basic scopes. Expect a weekly "Reconnect" on desktop until the consent screen is + published (non-sensitive scope: no security assessment, but Google may verify branding). + +All clients must belong to one Cloud project: the hidden app folder is shared between them for +the same Google account. Confirm this on real devices before relying on it. + +**Platforms.** Windows and macOS desktop (refresh token in Credential Manager / Keychain) and +Android. **Linux is off** (`auth::unavailable_reason`): the `keyring` crate is built without a +Linux backend, so the grant would not persist; the card says so instead of offering Connect. + +**Opening it to every Google user.** Keep the *External* audience and publish the app (Audience → +Publish app). "Internal" is only for one Google Workspace organisation. Creating the project and +client is free and the Drive API has no charge within its quotas; each writer's sync files count +against their own Drive storage. The settings card shows how much space MnemoScript uses +(`drive_usage`), since old versions are not pruned yet. + +## Follow-ups + +- Real-device acceptance: desktop ↔ Android with one account, offline catch-up, expiry and + quota behaviour, account switch. Live so far: desktop OAuth and a two-engine round trip on + the real `appDataFolder` (`live_drive`, which runs the engine directly, not `service.rs`, open- + chapter staging or a conflict). +- A way to restore from `sync-trash/` in the app (on Android the folder is app-private). +- Linux secret storage (Secret Service), then enable Drive sync there. +- Smart Merge (Phase 2) to link projects that were created separately on two devices. +- LAN transport (Phase 4) reusing `engine::Transport` and the same revision ids. +- History/blob pruning with per-device acknowledgements (local `blobs` table and Drive files + grow with every synced revision today). +- Web sync (GIS token model + IndexedDB) and opt-in AI-conversation sync. diff --git a/docs/MNEMOSYNC_MIGRATIONS.md b/docs/MNEMOSYNC_MIGRATIONS.md index 246c657..6669a10 100644 --- a/docs/MNEMOSYNC_MIGRATIONS.md +++ b/docs/MNEMOSYNC_MIGRATIONS.md @@ -1,5 +1,14 @@ # MnemoSync schema and migration contract +## Recovery ZIP v2 (2026-11-15) + +Schema 2 drops `sourceRoot`: chapters and maps refer to project images as `mnemo-asset:`, so an archive never records where (or under which OS user) the project lived. Restore +maps those to the new folder; unknown ones stay as harmless references. An optional `damaged` +list names chapter files that could not be read at backup time; they are archived and restored +byte for byte. Every other chapter is still validated strictly on restore. Readers accept schema +1 (below) unchanged. + ## Recovery ZIP v1 File `mnemoscript-backup.json` has `format: "mnemoscript-project-backup"`, `schemaVersion: 1`, @@ -18,11 +27,12 @@ Restore is a separate local copy, not adoption of the original sync identity. A must explicitly link these identities. No SQLite, IndexedDB, asset-URI or sync-schema migration runs in Phase 0. There is no change to existing project save/open APIs or AI pairing permissions. -Native command boundary: `backup_project({projectId}) -> ApiResponse` creates a unique -archive in the app's sibling `backups/` directory; `restore_project_backup` accepts a raw ZIP body -and returns the registered Project. Compression/extraction run on a worker. Frontend `lib/api.ts` -unwraps envelopes and uses plugin filesystem/dialog APIs for an optional user-selected archive -copy. The restore picker reads a user-selected ZIP as binary, with an early size check. +Native command boundary (2026-11-15): `backup_project({projectId}) -> {path, fileName, +warnings}` writes a named archive in the app's sibling `backups/` directory and keeps the newest +5 per project; `list_backups` / `delete_backup({path})` only name files directly in that folder; +`save_backup_copy({source, destination})` copies file to file; `restore_project_backup({path})` +opens the dialog-picked ZIP in Rust (bounded reads, no whole-archive copy in memory) and returns +the registered Project. Compression/extraction run on a worker. Backend tooling now requires Rust 1.88 or newer for ZIP 9.5; CI already installs stable. Lockfile records exact dependency resolutions. ZIP only enables pure-Rust deflate, without unrelated diff --git a/docs/MNEMOSYNC_TEST_MATRIX.md b/docs/MNEMOSYNC_TEST_MATRIX.md index de4ee68..c81b155 100644 --- a/docs/MNEMOSYNC_TEST_MATRIX.md +++ b/docs/MNEMOSYNC_TEST_MATRIX.md @@ -3,6 +3,24 @@ Baseline on 2026-11-12: `npm run check` passed lint, types, 116 existing tests and production build. Large-bundle warnings predate this change. Run required checks again after the implementation. +Implementation verification, 2026-11-12: `npm run check` passes lint, typecheck, all **130 tests** +and production build; `npm run test:regression` passes **41 regressions** (including the clean +Node worker runtime test and three fixed-clock AI history regressions). `cargo check` +passes; `cargo test` passes **56 tests** (including 11 new archive tests), with the 3 existing +live-AI tests intentionally ignored; `cargo clippy -- -D warnings` passes. The existing pairing +test needs permission for loopback network access. No live provider usage was consumed. +Visual preview was retried after user authorization but a saved permission policy still blocks +the local origin. Generated Rust app artifacts were cleaned after E: filled up; sources and +saved projects were unaffected. Filesystem hard-link fallback warnings are environmental. + +Remote CI initially failed before collection on the inherited Node 20 configuration. Locked +jsdom/undici require newer APIs; both workflows now read the Node 24.15.0 pin in `.node-version`. +The fresh-worker regression exercises that startup path; the complete implementation suite +was rerun after integrating the runtime fix. New remote runs must be checked independently. +Once CI could start, Linux exposed adjacent typing being grouped into a fast AI rewrite's undo +event. Shared fix `8b4977b` explicitly closes history before/after AI revisions and continuations; +fixed-clock regressions exercise the timing window. The combined frontend checks were rerun. + | Layer | Required evidence | Scope | |---|---|---| | Native archive unit | Exact bytes, hierarchy, Unicode/HTML marks, graph IDs, paths, sessions/exports, repeated restore | `cargo test backup::` | @@ -14,6 +32,23 @@ Large-bundle warnings predate this change. Run required checks again after the i | Installed Windows | Custom-path project, image and map render after restore, library includes original and copy, external ZIP copy | Pending real app acceptance | | Real Android | App-private backup, ZIP chooser, Save a copy provider access, restore, reopen, image/map render | Pending real device acceptance | +### Google Drive sync (2026-11-13) + +| Layer | Evidence | Status | +|---|---|---| +| Engine simulations | `cargo test sync::engine` — 2–3 devices, reorder/duplicate/offline/held blobs, conflicts, deletes, cycles, forged data | ✅ automated | +| No-lost-save rules (2026-11-15) | Damaged chapter / missing documents folder never deleted elsewhere; save after scan never overwritten; review and resolve include the latest typing; delete + two edits keeps both; remote delete goes to `sync-trash/` | ✅ automated (engine regressions) | +| Drive client units | PKCE, scope, redirect state, error classes, gzip, duplicate files | ✅ automated | +| Mounted UI + App boundary | `sync.regression`, `sync-app.regression` | ✅ automated | +| Android compile | `npx tauri android build --apk --debug --target aarch64` | ✅ builds 2026-11-13 (not run on a device) | +| Live Google OAuth (desktop) | Real consent in the browser, loopback + PKCE, keychain grant, account check | ✅ 2026-11-15 on Windows (writer's own Cloud project, Testing mode); Linux is off by design | +| Live Drive round trip | `cargo test live_drive -- --ignored`: two engines on the real appDataFolder; upload with image, download, edit back through the changes feed, cleanup | ✅ 2026-11-15 (29 s), happy path only: runs the engine directly, so not the worker (`service.rs`), account binding, open-chapter staging or conflicts | +| Live Google OAuth (Android) | Native AuthorizationClient prompt, silent refresh | ⏳ pending Android OAuth client + device | +| Real cross-device sync | Same account, desktop ↔ Android, shared appDataFolder across clients | ⏳ pending | +| 7-day Testing expiry, revoke | Reconnect flow after expiry | ⏳ pending | +| Quotas / outages | Real 403/429/5xx, Drive full, cursor expiry | ⏳ pending (only classified in unit tests) | +| Visual layout | Settings card, pill, banner, review on both shells | ⏳ browser preview blocked by permission policy | + ## Synthetic corpus for every storage/merge phase Use synthetic writing only, never the user's manuscripts in committed fixtures. diff --git a/docs/MNEMOSYNC_THREAT_MODEL.md b/docs/MNEMOSYNC_THREAT_MODEL.md index c14ed92..2c3f5c3 100644 --- a/docs/MNEMOSYNC_THREAT_MODEL.md +++ b/docs/MNEMOSYNC_THREAT_MODEL.md @@ -54,6 +54,16 @@ namespaces and pending queues stay isolated. Publish blobs before batches; valid reference application; back off on errors; never turn missing cloud data into mass local deletion. Drive transport is not automatically end-to-end encryption or independent backup. +Implemented Drive controls (2026-11-13): scope `drive.appdata` only; desktop PKCE S256 + state +check on a 127.0.0.1 loopback, refresh token in the OS keychain (debug builds use a separate +service), access tokens memory-only, nothing token-related in logs, project files or the web +view; Android keeps no refresh token. Remote revisions are re-hashed and rejected on mismatch; +entity ids and asset names are validated before they become file names; blobs are hash-checked, +downloads capped at 256 MiB decompressed; batch files whose labels contradict their content are +ignored. Expired change cursors trigger a re-listing, never deletion. Remote deletes of the open +chapter are staged; edit beats delete. Conflict previews render plain text from an inert parse. +Account switches are refused while projects are bound to the previous account. + Merge/replay: preserve all concurrent heads, reject mismatched operation identities, retain tombstones and source snapshots; journal interrupted merges; never overwrite active editor content during composition. Test malicious HTML and graph payloads at rendering boundaries. diff --git a/docs/TESTING.md b/docs/TESTING.md index dc6a83b..3c1407b 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -45,6 +45,16 @@ Three layers, all run by CI (`.github/workflows/ci.yml`) on every push: with content-free `project.json`, registry add/forget, corrupt document tolerance, ordering + idempotent delete, legacy `project.json` without new fields, missing-document errors. +**Project backups** (Phase 0; review fixes 2026-11-15) +- Backend `cargo test backup::` — round trip of text/maps/assets/sessions/exports, tamper/missing/ + extra/truncated files, newer schema, unsafe paths, symlinks, folder cycles, entity escaping; + damaged chapters archived as-is with a warning (and restored only when the manifest says so), + missing/outside images as warnings, no source folder in schema 2 archives, schema 1 still + restores, names + listing + keep-5 pruning per project, only files in the backups folder named. +- Regression `regression/backup.regression.test.tsx` (create, list, save a copy, confirmed delete, + warnings, picker restore and cancel, failures, double click) and + `backup-app.regression.test.tsx` (the backup saves through the shared save path first). + **AI assistant** (added 2026-11-12) - Unit `lib/ai/ai.test.ts` — model labels/vendors, phone provider list, document → text, tool mode enforcement, context replay across models, session reducer, `runTurn` tool round trip, per-project @@ -85,6 +95,38 @@ delete, legacy `project.json` without new fields, missing-document errors. - The App-mounting suites warm `import('../App')` in `beforeAll`: a cold parallel import could exceed the 15 s test timeout and cascade into duplicate-render failures. +**MnemoSync / Google Drive** (added 2026-11-13) +- Backend `cargo test sync::` (42 tests) — canonical JSON and content-derived revision ids, entity-key + validation, symmetric field merge and edit-beats-delete, portable `mnemo-asset:` round trips + (Windows paths, map JSON incl. "My Imports", untouched bytes, hostile names), PKCE (RFC 7636 vector), + authorize URL scope, redirect state check, Drive error classification, gzip, duplicate batch files. + `sync::engine::tests` simulate 2–3 devices over an in-memory transport: download with images, move + + edit, concurrent edits → preserved conflict → resolve with copy, delete vs edit, offline delete + without resurrection, duplicated/reordered deliveries, staged open chapter (accept / typing → conflict + / remote delete), missing blobs held then applied, frozen batch retry, folder cycles, shuffled + three-device convergence, forged revisions rejected. Review regressions (2026-11-15): a damaged + chapter or missing documents folder is never deleted elsewhere, a save made after the scan is + never overwritten, conflict review/resolve include the latest typing, delete + two edits keeps + both, remote deletes go to `sync-trash/`; stray loopback requests, the newer Google error shape, + cursor expiry by status, Linux off, id validation in sync commands. +- Live (ignored, needs the dev app signed in to Drive): `cargo test live_drive -- --ignored --nocapture` + runs two engines against the real `appDataFolder` under a throwaway `zz-live-test-…` project and + deletes its files (a failed cleanup fails the test). Windows/macOS only. +- Backend `cargo test backup::` adds the restore regression for fantasy-map "My Imports" paths and + rejection of imports outside the project. +- Regression `sync.regression.test.tsx` — settings states (browser, unconfigured, signed out with + privacy notes, sign-in with cancel and no double submit, Android token hand-off, per-project toggles, + download with same-name notice, reconnect + errors, Linux reason, Drive space used, "Back up, + then sync" with cancel and a failed backup), open-chapter banner, pill hidden for local-only + projects, conflict review (inert plain-text preview, differences marked, keep with/without copy). +- Regression `sync-app.regression.test.tsx` — App reports the open chapter, merges a remote rename into + the open chapter without losing unsaved typing (and the next save keeps both), and saves before + loading a held-back update. +- UI in a browser: `?syncMock=1` turns on `lib/sync/devMock.ts` (signed-in account, one synced project + with a conflict, a remote project). Browser fallback only, never in the installed apps. +- Vitest runs on half the cores (`maxWorkers: '50%'`); the App-mounting suites and the streamed AI mock + timed out when a busy desktop ran one worker per core. + ## jsdom notes `src/test/setup.ts` stubs `ResizeObserver`, `matchMedia`, `fetch` (LanguageTool is never contacted), `scrollIntoView` and `elementFromPoint` (ProseMirror's viewport plugin). Konva needs a real canvas, so @@ -101,3 +143,7 @@ Things jsdom cannot prove — run on Windows (packaged app) and an Android phone PNG export lands in `/exports/`. Desktop: export opens Save-as. 4. Read-aloud and dictation still start (WebView permission prompts). 5. Web build in a phone browser gets the bottom-tab shell; a narrow desktop window keeps the desktop UI. +6. Google Drive sync (needs your own OAuth clients, see `MNEMOSYNC_DRIVE.md`): connect on desktop and + phone with the same account; sync a project, download it on the other device (images and maps + render); edit while offline and reconnect; edit the same chapter on both → review; rename/move on + one while typing on the other; disconnect and reconnect without duplicates. diff --git a/docs/mnemosync/MEMORY.md b/docs/mnemosync/MEMORY.md index 453fa3e..80001ec 100644 --- a/docs/mnemosync/MEMORY.md +++ b/docs/mnemosync/MEMORY.md @@ -42,16 +42,27 @@ Implement optional, secure, low-cost **local-first project synchronization** for ## Concrete next work, in order -- [ ] Verify current branch/PR #1 again, merge or branch from its integrated HEAD. -- [ ] Add architecture ADR, threat model and a lossless ZIP backup/restore command. -- [ ] Implement SQLite sync state + web IndexedDB storage and migrations. -- [ ] Build asset path-to-hash migration, portable resolver and test corpus. +- [x] Verify current branch/PR #1 again, merge or branch from its integrated HEAD. +- [x] Add architecture ADR, threat model and a lossless ZIP backup/restore command (device acceptance pending). +- [~] Implement SQLite sync state + web IndexedDB storage and migrations. *(native SQLite done; web not)* +- [x] Build asset portability: `mnemo-asset:` refs in synced content, disk format unchanged (no migration). - [ ] Implement Smart Merge candidate matching, desktop Volume 1 vs mobile root mapping, side-by-side chapter conflicts, alias IDs and non-destructive commit. -- [ ] Implement revision DAG, durable outbox/inbox, tombstones, generic SyncTransport and randomized replay tests. +- [x] Implement revision DAG, durable outbox/inbox, tombstones, generic SyncTransport and randomized replay tests. - [ ] Add separate LAN sync handshake/crypto/authorization and test Windows + Android on real Wi-Fi. -- [ ] Implement Google OAuth on three platforms; validate same user's `appDataFolder` access from all clients. -- [ ] Implement Drive change feed, immutable batches, blobs, resumable uploads, quota backoff and account switch handling. -- [ ] Implement hybrid fan-out/dedupe, sync status UI, recovery, conflict review and full reliability/security tests. +- [~] Implement Google OAuth: desktop loopback+PKCE and Android native authorization done; web not; live cross-client `appDataFolder` proof pending. +- [x] Implement Drive change feed, immutable batches, blobs, resumable uploads, quota backoff and account switch handling. +- [~] Sync status UI and conflict review done; hybrid fan-out, recovery UX and hardware reliability tests open. + +## Implementation update — 2026-11-13 (Google Drive) + +- Branch `codex/mnemosync-drive` (stacked on `codex/mnemosync-backup`). Design as built, setup + steps and open items: `docs/MNEMOSYNC_DRIVE.md`. Review of PRs #2/#3 found local sync + (Phases 1–4) unbuilt; the engine was built here, transport-neutral, before the Drive transport. +- Fixed: restore left fantasy-map `imports[].path` pointing at the original project; imported + images were written non-atomically; forgotten projects kept syncing; Vitest one-worker-per-core + starved App-mounting suites (AI mock waits widened, workers capped at 50%). +- Not verified: live Google OAuth, real desktop ↔ Android sync, quotas. Needs the writer's own + Desktop + Android OAuth clients in one Cloud project (`app/src-tauri/.env.local`). ## Implementation update — 2026-11-12 @@ -75,6 +86,20 @@ Implement optional, secure, low-cost **local-first project synchronization** for via alternate browser tooling. Installed Windows/real Android acceptance remains pending. - Next: finish Phase 0 device acceptance, then Phase 1 durable SQLite/IndexedDB intents and portable assets. Google client setup and real LAN/Drive tests are still future work. +- Final local checks: 130 frontend tests, 41 regression tests, frontend lint/types/build, + cargo check, 56 Rust tests (3 existing live-AI tests ignored), Clippy -D warnings pass. + Strategy baseline commit: `5b34ff1` on `codex/mnemosync-foundation`; implementation branch: + `codex/mnemosync-backup`. PR publication status must be checked, not inferred from a push. +- Published [strategy/runtime PR #2](https://github.com/ehitimum/MnemoScript/pull/2) against + `feature/ai-assistant`, and [draft recovery PR #3](https://github.com/ehitimum/MnemoScript/pull/3) + against `codex/mnemosync-foundation`. Preserve this stack until prerequisites merge. +- CI exposed inherited Node 20 incompatibility with locked jsdom/undici. Shared fix `2fb06b5` + pins Node 24.15.0 in `.node-version`, updates CI/release/package engines and adds a clean-worker + DOM startup regression; integrated into the implementation branch. Remote runs are separate + from local verification and need independent status review. +- The now-running Linux tests exposed a pre-existing fast-response AI undo grouping bug. + Shared fix `8b4977b` isolates rewrites/continuations from adjacent typing; three fixed-clock + regressions verify both history boundaries. Integrated into both PRs; no UI format change. ## Critical scenario / regression test