Let Android pick which file in the synced folder is the library

Android grants a *folder* through SAF, not a file, and the document name was
hardcoded to "library.json". A library named anything else was therefore never
found: the phone created an empty second library beside it and the two devices
silently never synced, while appearing to work.

The Info tab now lists the .json files in the granted folder and lets you choose
one. Picking an existing file adopts it — the working copy is dropped and
rebuilt from it, matching what desktop does when opening a document — while a
name that isn't there yet keeps the current library and publishes it, matching
New Library. The name is validated as a plain filename, since a path would
escape the granted folder that the SAF grant exists to bound.

Two bugs found while testing this on-device:

load_config decided whether a config was the pre-document format by testing
whether document_path or legacy_library_path were set. An Android install has
neither — its folder is a grant, not a path, and there is no legacy library —
so a valid config's document_name was discarded on every launch and the chosen
library file silently reverted to the default. It no longer infers the format
from which fields happen to be populated; every field defaults, and the legacy
library_path is picked up as a separate additive step. Covered by tests,
including one built from the exact Android config shape, because a setting that
quietly resets itself is not something a careful read catches.

The Info tab's sync refresh fired at mount when the app relaunched onto that
tab — the active tab is persisted — which is before setup() calls manage(),
producing "state not managed for field db". Gated on statusLoaded like the
startup refresh already was; get_status retries until the backend is ready, so
waiting on it is what guarantees the state exists.
This commit is contained in:
2026-08-09 12:17:57 -05:00
parent ce2e556c52
commit dff52a9d83
5 changed files with 308 additions and 30 deletions

View File

@@ -24,10 +24,10 @@ use crate::state::AppState;
type Db<'a> = tauri::State<'a, std::sync::Mutex<AppState>>;
/// Document name used on Android, where the user grants a folder rather than
/// choosing a file. Desktop uses whatever they named their file.
/// Fallback name when the user has granted a folder but not yet said which file
/// in it is their library — i.e. a fresh setup with nothing to adopt.
#[cfg(target_os = "android")]
const ANDROID_DOC_NAME: &str = "library.json";
const DEFAULT_DOC_NAME: &str = "library.json";
/// Where transfers are staged across the SAF boundary. Inside the app data dir,
/// so it inherits the same private-storage guarantees as the working copy.
@@ -56,6 +56,9 @@ pub struct SyncStatus {
pub picker_based: bool,
/// A pre-document `library.db` waiting to be converted, if any.
pub legacy_library: Option<String>,
/// Which file in the granted folder is the library (Android). `None` on
/// desktop, where the whole path is chosen at once.
pub document_name: Option<String>,
}
#[cfg(target_os = "android")]
@@ -324,7 +327,12 @@ fn locate(#[allow(unused_variables)] app: &AppHandle, db: &Db) -> Result<Locatio
if status.granted {
return Ok(Location {
folder: Folder::Picker,
doc_name: ANDROID_DOC_NAME.into(),
doc_name: db
.lock()
.unwrap()
.document_name()
.unwrap_or(DEFAULT_DOC_NAME)
.to_string(),
});
}
}
@@ -356,12 +364,21 @@ pub fn sync_status(
{
let s = bridge::status(&app)?;
if s.chosen {
let name = db
.lock()
.unwrap()
.document_name()
.unwrap_or(DEFAULT_DOC_NAME)
.to_string();
return Ok(SyncStatus {
chosen: true,
granted: s.granted,
label: s.label,
// Show the folder *and* the file, since on Android they're
// chosen in two separate steps.
label: s.label.map(|l| format!("{l}/{name}")),
picker_based: true,
legacy_library,
document_name: Some(name),
});
}
// No folder picked: the library is in private storage and works, it
@@ -378,6 +395,7 @@ pub fn sync_status(
),
picker_based: true,
legacy_library,
document_name: None,
});
}
#[cfg(not(target_os = "android"))]
@@ -392,6 +410,7 @@ pub fn sync_status(
label: Some(path.display().to_string()),
picker_based: false,
legacy_library,
document_name: None,
})
}
}
@@ -466,6 +485,78 @@ pub fn sync_set_document(
}
}
/// The library files already sitting in the granted folder.
///
/// Android grants a folder, not a file, so the user has to say which of its
/// documents is theirs. Without this the app assumes "library.json" and would
/// silently create an empty second library beside one named anything else.
#[tauri::command]
pub fn sync_list_documents(
#[allow(unused_variables)] app: AppHandle,
db: Db,
) -> Result<Vec<String>, String> {
let location = locate(&app, &db)?;
let mut names: Vec<String> = location
.list(&app)?
.into_iter()
.filter(|n| n.ends_with(".json") && !n.ends_with(".json.tmp"))
.collect();
names.sort();
Ok(names)
}
/// Android only: choose which file in the granted folder is the library.
///
/// Switching to a different file means adopting a different library, so the
/// working copy is dropped and rebuilt from it — the same rule desktop applies
/// when opening an existing document.
#[tauri::command]
pub fn sync_set_document_name(
app: AppHandle,
db: Db,
#[allow(unused_variables)] name: String,
) -> Result<SyncStatus, String> {
#[cfg(not(target_os = "android"))]
{
let _ = (&app, &db, name);
return Err("This platform chooses the library file by full path.".into());
}
#[cfg(target_os = "android")]
{
let mut name = name.trim().to_string();
if name.is_empty() {
return Err("Give the library file a name.".into());
}
if !name.ends_with(".json") {
name.push_str(".json");
}
// Keep it a plain file name: a path would escape the granted folder,
// which is the whole boundary the SAF grant establishes.
if name.contains('/') || name.contains('\\') {
return Err("The library file must sit directly in the chosen folder.".into());
}
let existed = {
let data_dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
let location = locate(&app, &db)?;
location.read(&app, &data_dir, &name)?.is_some()
};
db.lock().unwrap().set_document_name(Some(name));
if existed {
// Adopting an existing library: start from it, not from whatever
// this device happened to be holding.
reset_working_copy(&app, &db)?;
} else {
let data_dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
let _ = std::fs::remove_file(base_path(&data_dir));
}
if let Err(e) = sync_now(app.clone(), db.clone()) {
crate::mlog!("sync_set_document_name: initial sync failed: {e}");
}
sync_status(app, db)
}
}
#[tauri::command]
pub fn sync_forget_document(app: AppHandle, db: Db) -> Result<SyncStatus, String> {
#[cfg(target_os = "android")]