Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
feat(protocol): a folder too big for one answer is listed in pages
Beeba2c11c5231e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 95239e2..e000619 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -174,6 +174,12 @@ has a Stop button. Choosing another### Fixed+- **A big phone folder showed only part of its files** in File Explorer (a+ camera folder of thousands of photos, say). Folders now come in pages, so+ every file shows, and listing one no longer holds up the connection.+- **A transfer too big for the receiving drive started anyway** and failed+ partway. The receiver now checks the space first and the sender says+ there isn't enough.- **The phone's keyboard didn't open after typing from the PC.** WithElevated, the PC's keys reach the phone through a virtual keyboard thatstayed connected, so Android hid the on-screen keyboard in every app. Itdiff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rsindex 8c4a8ce..31fc584 100644--- a/core/nectarlink-core/src/session.rs+++ b/core/nectarlink-core/src/session.rs@@ -458,6 +458,7 @@ fn is_background_rpc(t: &str) -> bool {| types::NOTIFY_ACTION| types::PC_POWER| types::LINK_OPEN+ | types::STORAGE_LIST| types::PHOTOS_ALBUMS| types::PHOTOS_LIST| types::PHOTOS_THUMBSdiff --git a/core/nectarlink-core/src/storage.rs b/core/nectarlink-core/src/storage.rsindex d6f070e..3146eda 100644--- a/core/nectarlink-core/src/storage.rs+++ b/core/nectarlink-core/src/storage.rs@@ -38,6 +38,9 @@ use crate::{/// Per-device toggle name (off by default on the phone).pub const TOGGLE: &str = "storage";++/// Most entries read from one folder (page after page).+const MAX_LISTED: usize = 100_000;/// Per-device toggle name for away-mode / relay file access (off by default).pub const REMOTE_FILES_TOGGLE: &str = "remote_files";@@ -279,14 +282,21 @@ pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &E.then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())).then_with(|| a.name.cmp(&b.name))});- // Ensure the frame fits within MAX_FRAME_LEN.+ // From `offset`, as many as fit one frame; the rest are+ // another page (`more`).+ let mut entries: Vec<StorageEntry> =+ entries.into_iter().skip(usize::try_from(req.offset).unwrap_or(usize::MAX)).collect();+ let left = entries.len();let reply = loop {- let body = StorageEntries { entries: entries.clone() };+ let more = entries.len() < left;+ let body = StorageEntries { entries: entries.clone(), more };let candidate = Envelope::new(types::STORAGE_ENTRIES, &body)?.reply_to(env.id);if candidate.to_cbor().len() <= MAX_FRAME_LEN || entries.is_empty() {break candidate;}- let new_len = (entries.len() * 3 / 4).max(entries.len().saturating_sub(1));+ // A quarter at a time: one at a time meant thousands of+ // 1 MiB encodings for a big folder.+ let new_len = (entries.len() * 3 / 4).min(entries.len().saturating_sub(1));entries.truncate(new_len);};session.send(reply).await?;@@ -700,10 +710,20 @@ pub(crate) async fn list(if !pc_allows(shared, &session.peer)? {return Err(Error::Denied);}- let req = Envelope::new(types::STORAGE_LIST, &StorageList { path })?;- let reply = session.request(req, REQUEST_TIMEOUT).await?;- let body: StorageEntries = reply.expect_body(types::STORAGE_ENTRIES)?;- Ok(body.entries.into_iter().filter_map(StorageEntry::sanitized).collect())+ // Page by page: a folder of thousands of photos doesn't fit one answer.+ let mut all: Vec<StorageEntry> = Vec::new();+ loop {+ let offset = all.len() as u64;+ let req = Envelope::new(types::STORAGE_LIST, &StorageList { path: path.clone(), offset })?;+ let reply = session.request(req, REQUEST_TIMEOUT).await?;+ let body: StorageEntries = reply.expect_body(types::STORAGE_ENTRIES)?;+ let got = body.entries.len();+ all.extend(body.entries);+ if !body.more || got == 0 || all.len() >= MAX_LISTED {+ break;+ }+ }+ Ok(all.into_iter().filter_map(StorageEntry::sanitized).collect())}pub(crate) async fn mkdir(shared: &Arc<Shared>, session: &Arc<Session>, path: String) -> Result<()> {diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex f3e62b0..d6b4c38 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -3340,6 +3340,33 @@ async fn a_phone_browses_a_pcs_shared_folders() {assert!(phone.node.storage_list(pc_id, "").await.is_err());}+/// A folder whose entries don't fit one answer comes back whole, page by+/// page (a camera folder of thousands of photos, say).+#[tokio::test(flavor = "multi_thread")]+async fn a_folder_too_big_for_one_answer_is_listed_whole() {+ use nectarlink_core::{FolderStorage, STORAGE_MOUNT, STORAGE_READ};++ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[STORAGE_MOUNT, STORAGE_READ]).await;+ let mut phone = device_with("Pixel", DeviceKind::Phone, &[STORAGE_READ]).await;+ let shared = tempfile::tempdir().unwrap();+ let camera = shared.path().join("Camera");+ std::fs::create_dir_all(&camera).unwrap();+ // Long names, so a few thousand entries pass one frame (1 MiB).+ let count = 8_000;+ for i in 0..count {+ std::fs::write(camera.join(format!("{i:05}-{}.jpg", "x".repeat(140))), b"").unwrap();+ }+ *pc.platform.storage.lock().unwrap() = Some(FolderStorage::new(shared.path()));+ pair_qr(&mut pc, &mut phone).await;+ let pc_id = pc.node.device_id();++ let listed = with_timeout("list a big folder", phone.node.storage_list(pc_id, "Camera")).await.unwrap();+ assert_eq!(listed.len(), count, "every entry, across pages");+ let mut names: Vec<_> = listed.iter().map(|e| e.name.clone()).collect();+ names.dedup();+ assert_eq!(names.len(), count, "no entry twice");+}+#[tokio::test(flavor = "multi_thread")]async fn phone_storage_lists_reads_ranges_writes_resumes_mutates_and_enforces_security() {use nectarlink_core::{FolderStorage, STORAGE_MOUNT, STORAGE_READ, STORAGE_WRITE};diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex 1342a83..8a7cc1f 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -4057,6 +4057,15 @@ pub fn is_valid_storage_id(id: &str) -> bool {#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct StorageList {pub path: String,+ /// Entries to skip, for the next page of a folder whose entries don't+ /// fit one answer. Absent (0) from devices before paging, which then get+ /// the first page only, as before.+ #[serde(default, skip_serializing_if = "is_zero_u64")]+ pub offset: u64,+}++fn is_zero_u64(n: &u64) -> bool {+ *n == 0}impl std::fmt::Debug for StorageList {@@ -4114,6 +4123,9 @@ impl StorageEntry {pub struct StorageEntries {#[serde(default)]pub entries: Vec<StorageEntry>,+ /// More entries follow: ask again with `offset` past these.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub more: bool,}/// Body of `storage.read` on a `storage/read` stream (`docs/protocol/storage.md` §4.1).@@ -5341,7 +5353,7 @@ mod tests {assert_eq!(dir_entry.size, 0);assert_eq!(dir_entry.modified, 0);- let entries = StorageEntries { entries: vec![entry, dir_entry] };+ let entries = StorageEntries { entries: vec![entry, dir_entry], more: false };let env = Envelope::new(types::STORAGE_ENTRIES, &entries).unwrap();let back: StorageEntries = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();assert_eq!(back, entries);diff --git a/docs/protocol/storage.md b/docs/protocol/storage.mdindex 5b8b9fb..23bd79a 100644--- a/docs/protocol/storage.md+++ b/docs/protocol/storage.md@@ -41,8 +41,8 @@ phone's shared storage root:## 3. Control-stream messages```-t = "storage.list" id = n b = { path: text }-t = "storage.entries" re = n b = { entries: [ StorageEntry, ... ] }+t = "storage.list" id = n b = { path: text, offset?: uint }+t = "storage.entries" re = n b = { entries: [ StorageEntry, ... ], more?: bool }t = "storage.mkdir" id = n b = { path: text }t = "storage.rename" id = n b = { from: text, to: text }t = "storage.delete" id = n b = { path: text, confirmed?: bool }@@ -61,8 +61,15 @@ StorageEntry = {### 3.1 `storage.list`Lists the immediate children of `path` (`""` for the root). Symlinks pointing-outside the shared root and unreadable/private entries are omitted. If the list-would exceed `MAX_FRAME_LEN`, entries are trimmed to fit.+outside the shared root and unreadable/private entries are omitted. Entries come+directories first, then by name, ignoring case.++A folder whose entries don't fit one frame (`MAX_FRAME_LEN`) comes in pages:+an answer holds as many as fit, from `offset` (default 0), with `more: true`+when entries follow. The requester asks again with `offset` past the ones it+has, until `more` is absent or false. A device from before paging ignores+`offset` and never sends `more`, so it answers with the first page only, as+it always did; a requester from before paging reads the first page.Errors: `NOT_FOUND` if `path` does not exist or is not a directory; `DENIED` if`storage` is off or permission is not granted; `INVALID` if `path` is malformed.