From 1be45f87f7883e647e674531cac3c254c6d5a46b Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:27:48 -0600 Subject: [PATCH 1/2] id: show file origin node + upload time in listings (#4973) Stamp the writing node as a set-if-absent origin tag in FileOps::stamp (wired from LocalNode::ops and MetaProtocol::handle with the requesting node) and in the three web save/upload paths. MetaResponse::List now carries ListEntry { hash, name, origin, uploaded_at }, enriched server-side from the origin/created metadata tags; files written before the tags existed list with origin unknown, never guessed. CLI list and REPL list print hash/name/origin/uploaded_at columns; the web file list shows origin + uploaded per file, adds origin to FileInfo, and supports ?sort=uploaded|origin and ?origin= with controls in the filter bar and pagination preserving both params. --- pkgs/id/src/commands/list.rs | 33 ++++-- pkgs/id/src/commands/repl.rs | 61 +++++++--- pkgs/id/src/commands/text.rs | 37 +++++++ pkgs/id/src/fileops.rs | 28 ++++- pkgs/id/src/local.rs | 5 +- pkgs/id/src/meta_client.rs | 13 ++- pkgs/id/src/protocol.rs | 160 +++++++++++++++++++++++++-- pkgs/id/src/web/routes.rs | 141 +++++++++++++++++++++-- pkgs/id/src/web/templates.rs | 83 +++++++++++++- pkgs/id/tests/remote_write_access.rs | 4 +- 10 files changed, 512 insertions(+), 53 deletions(-) diff --git a/pkgs/id/src/commands/list.rs b/pkgs/id/src/commands/list.rs index 1e7ad94b7d..b8d2444720 100644 --- a/pkgs/id/src/commands/list.rs +++ b/pkgs/id/src/commands/list.rs @@ -7,12 +7,15 @@ //! //! Each line contains: //! ```text -//! \t +//! \t\t\t //! ``` //! //! Where: //! - `hash` is the 64-character BLAKE3 content hash //! - `name` is the tag name assigned to the blob +//! - `origin` is the node that first wrote the file, or `unknown` for +//! files written before origin stamping existed (#4973) +//! - `uploaded_at` is the upload time (unix seconds), or `unknown` //! //! # Examples //! @@ -30,7 +33,7 @@ use iroh_base::EndpointId; use crate::commands::client::create_local_client_endpoint; use crate::commands::serve::get_serve_info; -use crate::commands::text::tsv_row; +use crate::commands::text::list_tsv_row; use crate::protocol::{MetaRequest, MetaResponse}; use crate::store::{load_or_create_keypair, open_store}; use crate::{CLIENT_KEY_FILE, META_ALPN, is_node_id}; @@ -88,8 +91,16 @@ pub async fn cmd_list(node: Option, no_relay: bool) -> Result<()> { if items.is_empty() { println!("(no files stored)"); } else { - for (hash, name) in items { - println!("{}", tsv_row(hash, &name)); + for entry in &items { + println!( + "{}", + list_tsv_row( + entry.hash, + &entry.name, + entry.origin.as_deref(), + entry.uploaded_at + ) + ); } } Ok(()) @@ -108,7 +119,7 @@ pub async fn cmd_list(node: Option, no_relay: bool) -> Result<()> { while let Some(item) = list.next().await { let item = item?; let name = String::from_utf8_lossy(item.name.as_ref()); - println!("{}", tsv_row(item.hash, &name)); + println!("{}", list_tsv_row(item.hash, &name, None, None)); count += 1; } if count == 0 { @@ -154,8 +165,16 @@ pub async fn cmd_list_remote(server_node_id: EndpointId, no_relay: bool) -> Resu if items.is_empty() { println!("(no files stored)"); } else { - for (hash, name) in items { - println!("{}", tsv_row(hash, &name)); + for entry in &items { + println!( + "{}", + list_tsv_row( + entry.hash, + &entry.name, + entry.origin.as_deref(), + entry.uploaded_at + ) + ); } } Ok(()) diff --git a/pkgs/id/src/commands/repl.rs b/pkgs/id/src/commands/repl.rs index 509a86186a..bb58e3d6b2 100644 --- a/pkgs/id/src/commands/repl.rs +++ b/pkgs/id/src/commands/repl.rs @@ -92,7 +92,7 @@ use crate::commands::client::create_local_client_endpoint; use crate::commands::put::{add_raw, push_and_name}; use crate::commands::serve::get_serve_info; use crate::commands::tag::{self as tag, TagDisplayOptions}; -use crate::commands::text::{plain_field, tsv_row}; +use crate::commands::text::{list_tsv_row, plain_field}; use crate::discovery::PeerAnnouncement; use crate::local::LocalNode; use crate::meta_client::{MetaRequester, expect_ok, read_capped_response, request_over}; @@ -441,8 +441,9 @@ impl ReplContext { /// List all stored blobs. /// - /// Prints a tab-separated list of hash and name for each stored blob. - /// Output format: `\t` + /// Prints a tab-separated list for each stored blob with its origin + /// node and upload time (#4973; `unknown` when not recorded). + /// Output format: `\t\t\t` /// /// In connected modes, sends `MetaRequest::List` to the server. /// In local mode, directly iterates the store's tags. @@ -464,25 +465,41 @@ impl ReplContext { if items.is_empty() { println!("(no files stored)"); } else { - for (hash, name) in items { - println!("{}", tsv_row(hash, &name)); + for entry in &items { + println!( + "{}", + list_tsv_row( + entry.hash, + &entry.name, + entry.origin.as_deref(), + entry.uploaded_at + ) + ); } } } _ => bail!("unexpected response"), } } else if let ReplContextInner::Local { node } = &self.inner { - let store_handle = node.blobs(); - let mut list = store_handle.tags().list().await?; - let mut count = 0; - while let Some(item) = list.next().await { - let item = item?; - let name = String::from_utf8_lossy(item.name.as_ref()); - println!("{}", tsv_row(item.hash, &name)); - count += 1; - } - if count == 0 { - println!("(no files stored)"); + match node.request(MetaRequest::List).await { + MetaResponse::List { items } => { + if items.is_empty() { + println!("(no files stored)"); + } else { + for entry in &items { + println!( + "{}", + list_tsv_row( + entry.hash, + &entry.name, + entry.origin.as_deref(), + entry.uploaded_at + ) + ); + } + } + } + _ => bail!("unexpected response"), } } Ok(()) @@ -873,8 +890,16 @@ impl ReplContext { if items.is_empty() { println!("(no files stored on @{})", &node_str[..8]); } else { - for (hash, name) in items { - println!("{}", tsv_row(hash, &name)); + for entry in &items { + println!( + "{}", + list_tsv_row( + entry.hash, + &entry.name, + entry.origin.as_deref(), + entry.uploaded_at + ) + ); } } } diff --git a/pkgs/id/src/commands/text.rs b/pkgs/id/src/commands/text.rs index b3af78ac04..0b56d370df 100644 --- a/pkgs/id/src/commands/text.rs +++ b/pkgs/id/src/commands/text.rs @@ -144,6 +144,27 @@ pub fn tsv_row(hash: impl Display, name: &str) -> String { format!("{hash}\t{}", plain_field(name)) } +/// Formats one file-listing row (#4973): +/// `\t\t\t`. +/// +/// `origin` is the node that first wrote the file and `uploaded_at` its +/// upload time (unix seconds), both from the file's metadata tags. A file +/// written before those tags existed renders both as `unknown` — the +/// listing never guesses an origin. +pub fn list_tsv_row( + hash: impl Display, + name: &str, + origin: Option<&str>, + uploaded_at: Option, +) -> String { + format!( + "{}\t{}\t{}", + tsv_row(hash, name), + origin.map_or_else(|| "unknown".to_owned(), plain_field), + uploaded_at.map_or_else(|| "unknown".to_owned(), |ts| ts.to_string()) + ) +} + #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { @@ -253,6 +274,22 @@ mod tests { } #[test] + #[test] + fn list_tsv_row_shows_origin_and_upload_time() { + assert_eq!( + list_tsv_row("hash", "a.txt", Some("node-a"), Some(1_700_000_000)), + "hash\ta.txt\tnode-a\t1700000000" + ); + } + + #[test] + fn list_tsv_row_unknown_for_pre_change_files() { + assert_eq!( + list_tsv_row("hash", "old.txt", None, None), + "hash\told.txt\tunknown\tunknown" + ); + } + fn tsv_row_keeps_control_characters_inside_the_name_field() { let row = tsv_row("hash", "x\nforged\tcolumn"); assert_eq!(row, format!("hash\t{}", r#""x\nforged\tcolumn""#)); diff --git a/pkgs/id/src/fileops.rs b/pkgs/id/src/fileops.rs index 7aa2b0092d..2a508b43e9 100644 --- a/pkgs/id/src/fileops.rs +++ b/pkgs/id/src/fileops.rs @@ -104,11 +104,15 @@ pub struct DeleteOutcome { } /// File operations over a blob [`Store`] and a [`TagStore`]. -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone)] pub struct FileOps<'a> { store: &'a Store, tags: &'a TagStore, blob_wait: Duration, + /// Node that originated a write, stamped as the file's `origin` tag + /// (#4973). `None` when the caller does not know its node id: no + /// origin is stamped and listings show the file's origin as unknown. + origin: Option, } /// Serialises archive-name resolve+claim within this process (#2462). @@ -182,6 +186,7 @@ impl<'a> FileOps<'a> { store, tags, blob_wait: Duration::ZERO, + origin: None, } } @@ -198,6 +203,16 @@ impl<'a> FileOps<'a> { self } + /// Stamp writes with `origin` (a node id) as the file's origin node + /// (#4973). The stamp is set-if-absent: the node that first wrote a + /// file stays its origin across later writes and renames, and files + /// written before origin stamping existed simply have no origin tag. + #[must_use] + pub fn with_origin(mut self, origin: String) -> Self { + self.origin = Some(origin); + self + } + /// Whether the blob is complete, waiting up to `blob_wait` for it. async fn blob_present(&self, hash: Hash) -> Result { let deadline = Instant::now() + self.blob_wait; @@ -303,7 +318,8 @@ impl<'a> FileOps<'a> { /// Name `hash` as `name`, after verifying the blob is complete in the store. /// /// Sets the `created` tag only if absent and always refreshes `modified`, - /// then auto-tags `name`/`file`. + /// stamps the `origin` node if one is configured and none is recorded + /// yet, then auto-tags `name`/`file`. pub async fn put(&self, name: &str, hash: Hash) -> Result<(), FileOpError> { Self::validate_name(name)?; if !self.blob_present(hash).await? { @@ -346,6 +362,14 @@ impl<'a> FileOps<'a> { { tracing::warn!("failed to set modified tag for {name}: {e:#}"); } + if let Some(origin) = &self.origin + && let Err(e) = self + .tags + .set_if_absent(ns, subject, b"origin", Some(origin.as_bytes()), b"") + .await + { + tracing::warn!("failed to set origin tag for {name}: {e:#}"); + } if let Err(e) = self.tags.auto_tag(ns, subject, None).await { tracing::warn!("failed to auto-tag {name}: {e:#}"); } diff --git a/pkgs/id/src/local.rs b/pkgs/id/src/local.rs index d40c1f5216..6e74468e6b 100644 --- a/pkgs/id/src/local.rs +++ b/pkgs/id/src/local.rs @@ -156,8 +156,11 @@ impl LocalNode { } /// File operations (put/rename/copy/delete) over this node's stores. + /// + /// Writes through this handle stamp this node as the file's origin + /// (#4973). pub fn ops(&self) -> FileOps<'_> { - FileOps::new(&self.blobs, &self.tags) + FileOps::new(&self.blobs, &self.tags).with_origin(self.node_id.to_string()) } /// Answer a meta-protocol request in-process, exactly as a server would. diff --git a/pkgs/id/src/meta_client.rs b/pkgs/id/src/meta_client.rs index 8a97eef860..2bdb047cf6 100644 --- a/pkgs/id/src/meta_client.rs +++ b/pkgs/id/src/meta_client.rs @@ -182,7 +182,7 @@ impl MetaRequester for MetaClient { mod tests { use super::*; use crate::MatchKind; - use crate::protocol::FindMatch; + use crate::protocol::{FindMatch, ListEntry}; use iroh::{RelayMode, TransportAddr, endpoint::presets}; use iroh_blobs::Hash; use std::net::Ipv4Addr; @@ -341,8 +341,13 @@ mod tests { /// the shape of store (15–25k items) that could not be listed at all. #[tokio::test(flavor = "multi_thread")] async fn list_response_larger_than_1_mib_reads_through() { - let items: Vec<(Hash, String)> = (0..30_000) - .map(|i| (Hash::from_bytes([9u8; 32]), format!("file-{i:05}.txt"))) + let items: Vec = (0..30_000) + .map(|i| ListEntry { + hash: Hash::from_bytes([9u8; 32]), + name: format!("file-{i:05}.txt"), + origin: None, + uploaded_at: None, + }) .collect(); let payload = postcard::to_allocvec(&MetaResponse::List { items }).unwrap(); assert!( @@ -363,7 +368,7 @@ mod tests { match resp { MetaResponse::List { items } => { assert_eq!(items.len(), 30_000); - assert_eq!(items[29_999].1, "file-29999.txt"); + assert_eq!(items[29_999].name, "file-29999.txt"); } _ => panic!("unexpected response"), } diff --git a/pkgs/id/src/protocol.rs b/pkgs/id/src/protocol.rs index 0d7ae41cd1..ed7eeb9903 100644 --- a/pkgs/id/src/protocol.rs +++ b/pkgs/id/src/protocol.rs @@ -376,6 +376,25 @@ impl MetaRequest { /// Each variant corresponds to a [`MetaRequest`] variant. Any request may also /// be answered with [`MetaResponse::Error`]. The same append-only rule as /// [`MetaRequest`] applies. +/// One entry of a [`MetaResponse::List`] response (#4973). +/// +/// `origin` is the node that first wrote the file, recorded by the +/// `origin` metadata tag at write time; `uploaded_at` is the file's +/// upload time (unix seconds) from its `created` tag. Files written +/// before those tags existed carry `None` for both and list with +/// origin unknown — the values are never guessed. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ListEntry { + /// The content hash. + pub hash: Hash, + /// The tag name. + pub name: String, + /// Node id of the file's origin node, if recorded. + pub origin: Option, + /// Upload time (unix seconds), if recorded. + pub uploaded_at: Option, +} + #[derive(Debug, Serialize, Deserialize)] pub enum MetaResponse { /// Response to [`MetaRequest::Put`]. @@ -390,8 +409,8 @@ pub enum MetaResponse { }, /// Response to [`MetaRequest::List`]. List { - /// All names as (hash, name) pairs. - items: Vec<(Hash, String)>, + /// All names with their origin node and upload time (#4973). + items: Vec, }, /// Response to [`MetaRequest::Delete`]. Delete { @@ -541,7 +560,9 @@ impl MetaProtocol { ), }; } - let ops = FileOps::new(&self.store, &self.tag_store).with_blob_wait(self.blob_wait); + let ops = FileOps::new(&self.store, &self.tag_store) + .with_blob_wait(self.blob_wait) + .with_origin(remote.to_string()); let ts = &self.tag_store; let ns = &ts.global; match req { @@ -567,7 +588,41 @@ impl MetaProtocol { if let Ok(mut list) = self.store.tags().list().await { while let Some(Ok(item)) = list.next().await { let name = String::from_utf8_lossy(item.name.as_ref()).into_owned(); - items.push((item.hash, name)); + items.push(ListEntry { + hash: item.hash, + name, + origin: None, + uploaded_at: None, + }); + } + } + // Enrich with origin + upload time from the metadata tags + // (#4973): `origin` is stamped at write time by FileOps, + // `created` is the upload time. Files written before the + // tags existed keep `None` and list as origin unknown. + if let Ok(tags) = self.tag_store.list_all(ns).await { + let mut origins: std::collections::HashMap = + std::collections::HashMap::new(); + let mut created: std::collections::HashMap = + std::collections::HashMap::new(); + for tag in &tags { + if tag.key == "origin" { + if let Some(value) = tag.value.as_ref().and_then(|v| v.as_str()) { + origins.insert(tag.subject.display_lossy(), value.to_owned()); + } + } else if tag.key == "created" + && let Some(ts) = tag + .value + .as_ref() + .and_then(|v| v.as_str()) + .and_then(|v| v.parse::().ok()) + { + created.insert(tag.subject.display_lossy(), ts); + } + } + for item in &mut items { + item.origin = origins.get(&item.name).cloned(); + item.uploaded_at = created.get(&item.name).copied(); } } MetaResponse::List { items } @@ -1083,8 +1138,18 @@ mod tests { let hash2 = Hash::from_bytes([2u8; 32]); let resp = MetaResponse::List { items: vec![ - (hash1, "file1.txt".to_owned()), - (hash2, "file2.txt".to_owned()), + ListEntry { + hash: hash1, + name: "file1.txt".to_owned(), + origin: Some("node-a".to_owned()), + uploaded_at: Some(1_700_000_000), + }, + ListEntry { + hash: hash2, + name: "file2.txt".to_owned(), + origin: None, + uploaded_at: None, + }, ], }; let bytes = postcard::to_allocvec(&resp).unwrap(); @@ -1092,8 +1157,12 @@ mod tests { match decoded { MetaResponse::List { items } => { assert_eq!(items.len(), 2); - assert_eq!(items[0].1, "file1.txt"); - assert_eq!(items[1].1, "file2.txt"); + assert_eq!(items[0].name, "file1.txt"); + assert_eq!(items[0].origin.as_deref(), Some("node-a")); + assert_eq!(items[0].uploaded_at, Some(1_700_000_000)); + assert_eq!(items[1].name, "file2.txt"); + assert_eq!(items[1].origin, None); + assert_eq!(items[1].uploaded_at, None); } _ => panic!("Wrong variant"), } @@ -1448,11 +1517,84 @@ mod tests { async fn names(node: &LocalNode) -> Vec { match node.request(MetaRequest::List).await { - MetaResponse::List { items } => items.into_iter().map(|(_, n)| n).collect(), + MetaResponse::List { items } => items.into_iter().map(|e| e.name).collect(), + other => panic!("unexpected {other:?}"), + } + } + + async fn list_entries(node: &LocalNode) -> Vec { + match node.request(MetaRequest::List).await { + MetaResponse::List { items } => items, other => panic!("unexpected {other:?}"), } } + /// #4973: a file written through the meta protocol lists with the + /// writing node as its origin and its `created` stamp as the upload + /// time. + #[tokio::test] + async fn list_shows_origin_node_and_upload_time_for_new_files() { + let node = LocalNode::open(true).await.unwrap(); + let guard = node + .blobs() + .add_bytes(b"hello origin".to_vec()) + .temp_tag() + .await + .unwrap(); + let resp = node + .request(MetaRequest::Put { + filename: "origin.txt".to_owned(), + hash: guard.hash(), + }) + .await; + assert!( + matches!(resp, MetaResponse::Put { success: true }), + "{resp:?}" + ); + + let entries = list_entries(&node).await; + let entry = entries + .iter() + .find(|e| e.name == "origin.txt") + .expect("written file must list"); + assert_eq!( + entry.origin.as_deref(), + Some(node.node_id().to_string().as_str()), + "origin must be the writing node" + ); + assert!( + entry.uploaded_at.is_some_and(|ts| ts > 0), + "upload time must come from the created stamp: {entry:?}" + ); + } + + /// #4973: a file that predates origin stamping (name tag only, no + /// metadata tags) lists cleanly with origin/upload time unknown — + /// never guessed. + #[tokio::test] + async fn list_shows_unknown_origin_for_pre_change_files() { + let node = LocalNode::open(true).await.unwrap(); + let guard = node + .blobs() + .add_bytes(b"old file".to_vec()) + .temp_tag() + .await + .unwrap(); + node.blobs() + .tags() + .set("legacy.txt", guard.hash()) + .await + .unwrap(); + + let entries = list_entries(&node).await; + let entry = entries + .iter() + .find(|e| e.name == "legacy.txt") + .expect("legacy file must list"); + assert_eq!(entry.origin, None); + assert_eq!(entry.uploaded_at, None); + } + #[tokio::test] async fn put_refuses_a_blob_the_store_does_not_have() { let node = LocalNode::open(true).await.unwrap(); diff --git a/pkgs/id/src/web/routes.rs b/pkgs/id/src/web/routes.rs index 9ddf46a3f0..83e89c217d 100644 --- a/pkgs/id/src/web/routes.rs +++ b/pkgs/id/src/web/routes.rs @@ -91,6 +91,12 @@ pub struct FileListQuery { pub search: Option, /// Whether to show soft-deleted files. Defaults to false. pub show_deleted: Option, + /// Sort order (#4973): `uploaded` (newest upload first) or `origin` + /// (origin node A-Z, unknown last). Absent keeps the default order. + pub sort: Option, + /// Filter to one origin node id, or `unknown` for files with no + /// recorded origin (#4973). + pub origin: Option, } /// Paginated file list result. @@ -107,6 +113,10 @@ pub struct FileListPage { pub search: Option, /// Whether deleted files are shown. pub show_deleted: bool, + /// The sort order applied, echoed for rendering (#4973). + pub sort: Option, + /// The origin filter applied, echoed for rendering (#4973). + pub origin_filter: Option, } /// Classification of a file based on its tag name pattern. @@ -143,6 +153,10 @@ pub struct FileInfo { pub created_at: Option, /// Last modification timestamp from metadata tags (unix seconds). pub modified_at: Option, + /// Node that first wrote the file (#4973), from the `origin` metadata + /// tag. `None` for files written before origin stamping existed; + /// listings render it as unknown and never guess. + pub origin_node: Option, /// User-visible tags (excludes system tags like created/modified/deleted/archive.*). pub tags: Vec<(String, Option)>, /// Whether this file is soft-deleted. @@ -223,9 +237,8 @@ fn parse_iso_timestamp(s: &str) -> Option { // only (#4329). parse::() alone accepts any width and a leading // '+', so non-canonical spellings like "2026-3-2T6:4:2Z" or a // "+2026" year used to map onto the canonical instant. - let canonical = |s: &str, width: usize| { - s.len() == width && s.bytes().all(|b| b.is_ascii_digit()) - }; + let canonical = + |s: &str, width: usize| s.len() == width && s.bytes().all(|b| b.is_ascii_digit()); if !canonical(date_strs[0], 4) || !date_strs[1..].iter().all(|p| canonical(p, 2)) || !time_strs.iter().all(|p| canonical(p, 2)) @@ -821,7 +834,9 @@ async fn assets_handler(Path(path): Path) -> impl IntoResponse { } /// System tag keys that are excluded from user-visible tags display. -const SYSTEM_TAG_KEYS: &[&str] = &["created", "modified", "deleted", "name", "file", "path"]; +const SYSTEM_TAG_KEYS: &[&str] = &[ + "created", "modified", "deleted", "name", "file", "path", "origin", +]; /// Check if a tag key is a system/internal key that shouldn't be shown in tag pills. fn is_system_tag_key(key: &[u8]) -> bool { @@ -861,6 +876,7 @@ async fn get_file_list(state: &AppState) -> Vec { .unwrap_or_default(); let mut created_map: HashMap = HashMap::new(); let mut modified_map: HashMap = HashMap::new(); + let mut origin_map: HashMap = HashMap::new(); let mut deleted_set: std::collections::HashSet = std::collections::HashSet::new(); let mut user_tags_map: HashMap)>> = HashMap::new(); let mut display_name_map: HashMap = HashMap::new(); @@ -872,6 +888,12 @@ async fn get_file_list(state: &AppState) -> Vec { { created_map.insert(tag.subject.display_lossy(), ts); } + } else if tag.key == "origin" { + if let Some(ref v) = tag.value + && let Some(s) = v.as_str() + { + origin_map.insert(tag.subject.display_lossy(), s.to_owned()); + } } else if tag.key == "modified" { if let Some(ref v) = tag.value && let Some(s) = v.as_str() @@ -943,6 +965,7 @@ async fn get_file_list(state: &AppState) -> Vec { let created_at = created_map.get(&name).copied(); let modified_at = modified_map.get(&name).copied(); + let origin_node = origin_map.get(&name).cloned(); let tags = user_tags_map.remove(&name).unwrap_or_default(); let display_name = display_name_map .get(&name) @@ -958,6 +981,7 @@ async fn get_file_list(state: &AppState) -> Vec { timestamp, created_at, modified_at, + origin_node, tags, is_deleted, }); @@ -1102,6 +1126,58 @@ async fn get_file_list_page(state: &AppState, query: &FileListQuery) -> FileList }); } + // Origin filter (#4973): an exact node id, or `unknown` for files + // with no recorded origin. + let origin_filter = query + .origin + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(ToOwned::to_owned); + if let Some(ref origin) = origin_filter { + if origin == "unknown" { + files.retain(|f| f.origin_node.is_none()); + } else { + files.retain(|f| f.origin_node.as_deref() == Some(origin.as_str())); + } + } + + // Sort (#4973): the default order from get_file_list stands unless a + // sort is requested. `uploaded` is the file's created stamp (falling + // back to modified, then the tag-parsed timestamp), newest first; + // `origin` is A-Z with unknown origins last. + let sort = query + .sort + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(ToOwned::to_owned); + match sort.as_deref() { + Some("uploaded") => { + files.sort_by(|a, b| { + let ta = a.created_at.or(a.modified_at).or(a.timestamp).unwrap_or(0); + let tb = b.created_at.or(b.modified_at).or(b.timestamp).unwrap_or(0); + tb.cmp(&ta) + .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())) + }); + } + Some("origin") => { + files.sort_by(|a, b| { + let ka = ( + a.origin_node.is_none(), + a.origin_node.as_deref().unwrap_or(""), + ); + let kb = ( + b.origin_node.is_none(), + b.origin_node.as_deref().unwrap_or(""), + ); + ka.cmp(&kb) + .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())) + }); + } + _ => {} + } + let total = files.len(); let (page_files, page, per_page) = paginate(&files, query.page, query.per_page); @@ -1112,6 +1188,8 @@ async fn get_file_list_page(state: &AppState, query: &FileListQuery) -> FileList per_page, search, show_deleted, + sort, + origin_filter, } } @@ -1402,6 +1480,22 @@ async fn save_handler(State(state): State, Json(req): Json, mut multipart: Multipart) { tracing::warn!("[routes] Failed to set created tag: {:#}", err); } + + // Stamp this node as the file's origin (#4973), set-if-absent like + // `created`: the first writer stays the origin. + if let Err(err) = state + .tag_store + .set_if_absent( + &state.tag_store.global, + filename.as_bytes(), + b"origin", + Some(state.node_id.as_bytes()), + b"", + ) + .await + { + tracing::warn!("[routes] Failed to set origin tag: {:#}", err); + } if let Err(err) = state .tag_store .set_singleton( @@ -2619,11 +2745,8 @@ mod upload_router_tests { state.world = Some(crate::world_hub::WorldHub::single( crate::world_session::WorldService::new( crate::world::WorldHandle::spawn( - crate::world::WorldCore::new( - "lobby", - crate::world::WorldLimits::default(), - ) - .unwrap(), + crate::world::WorldCore::new("lobby", crate::world::WorldLimits::default()) + .unwrap(), ), None, ), diff --git a/pkgs/id/src/web/templates.rs b/pkgs/id/src/web/templates.rs index 8b80d87be8..d452ef1789 100644 --- a/pkgs/id/src/web/templates.rs +++ b/pkgs/id/src/web/templates.rs @@ -165,6 +165,42 @@ pub fn render_file_list(page: &FileListPage) -> String { search_value ); html.push_str(""); + // Sort + origin filter (#4973): a plain GET form to /files so sorting + // and filtering by origin node and upload time work without JS. + let sort_current = page.sort.as_deref().unwrap_or(""); + let origin_value = page + .origin_filter + .as_deref() + .map(html_escape) + .unwrap_or_default(); + html.push_str("
"); + html.push_str(""); + let _ = write!( + html, + "", + origin_value + ); + html.push_str( + "", + ); + html.push_str("
"); let _ = write!( html, "", @@ -291,6 +327,21 @@ pub fn render_file_list_content(page: &FileListPage) -> String { format!("{}", tag_pills) }; + // Origin + upload time (#4973): origin is the node that first + // wrote the file (`unknown` when unrecorded); uploaded is the + // `created` stamp. Refs only — bytes never travel in a surface. + let origin_str = file.origin_node.as_deref().unwrap_or("unknown"); + let uploaded_str = file + .created_at + .map(format_unix_timestamp) + .filter(|d| !d.is_empty()) + .unwrap_or_else(|| "unknown".to_owned()); + let origin_html = format!( + "origin {} \u{00b7} uploaded {}", + html_escape(origin_str), + uploaded_str + ); + // Timestamp display — prefer modified_at, fall back to created_at, then tag-parsed let display_ts = file.modified_at.or(file.created_at).or(file.timestamp); let date_str = display_ts.map(format_unix_timestamp).unwrap_or_default(); @@ -315,7 +366,7 @@ pub fn render_file_list_content(page: &FileListPage) -> String { \ [F]\ {}\ - {}{}{}{}\ + {}{}{}{}{}\ {}\ ", deleted_class, @@ -329,6 +380,7 @@ pub fn render_file_list_content(page: &FileListPage) -> String { deleted_badge, tags_html, date_html, + origin_html, short_hash, ); } @@ -344,6 +396,17 @@ pub fn render_file_list_content(page: &FileListPage) -> String { .as_deref() .map(|s| format!("&search={}", urlencoding::encode(s))) .unwrap_or_default(); + let sort_param = page + .sort + .as_deref() + .map(|s| format!("&sort={}", urlencoding::encode(s))) + .unwrap_or_default(); + let origin_param = page + .origin_filter + .as_deref() + .map(|s| format!("&origin={}", urlencoding::encode(s))) + .unwrap_or_default(); + let search_param = format!("{search_param}{sort_param}{origin_param}"); html.push_str("
"); @@ -1132,6 +1195,8 @@ mod tests { per_page: 50, search: None, show_deleted: false, + sort: None, + origin_filter: None, }; let html = render_file_list(&page); assert!(html.contains("No files stored yet")); @@ -1150,6 +1215,7 @@ mod tests { created_at: None, modified_at: None, tags: vec![], + origin_node: None, is_deleted: false, }]; let page = FileListPage { @@ -1159,6 +1225,8 @@ mod tests { per_page: 50, search: None, show_deleted: false, + sort: None, + origin_filter: None, }; let html = render_file_list(&page); assert!(html.contains("test.txt")); @@ -1182,6 +1250,7 @@ mod tests { created_at: None, modified_at: None, tags: vec![], + origin_node: None, is_deleted: false, }) .collect(); @@ -1192,6 +1261,8 @@ mod tests { per_page: 50, search: None, show_deleted: false, + sort: None, + origin_filter: None, }; let html = render_file_list_content(&page); assert!(html.contains("51-100 of 300"), "html: {html}"); @@ -1208,6 +1279,8 @@ mod tests { per_page: 50, search: None, show_deleted: false, + sort: None, + origin_filter: None, }; let html = render_file_list_content(&page); assert!(html.contains("0-0 of 300"), "html: {html}"); @@ -1222,6 +1295,8 @@ mod tests { per_page: 200, search: None, show_deleted: false, + sort: None, + origin_filter: None, }; let html = render_file_list_content(&page); assert!(html.contains("0-0 of 300"), "html: {html}"); @@ -1245,6 +1320,7 @@ mod tests { created_at: None, modified_at: None, tags: vec![("note".to_owned(), Some(value))], + origin_node: None, is_deleted: false, }]; let page = FileListPage { @@ -1254,6 +1330,8 @@ mod tests { per_page: 50, search: None, show_deleted: false, + sort: None, + origin_filter: None, }; let html = render_file_list(&page); // Truncated on the char boundary before 'é', with the ellipsis. @@ -1327,12 +1405,15 @@ mod tests { created_at: None, modified_at: None, tags: vec![], + origin_node: None, is_deleted: false, }], page: 1, per_page: 50, search: None, show_deleted: false, + sort: None, + origin_filter: None, }; let html = render_file_list_content(&page); assert!( diff --git a/pkgs/id/tests/remote_write_access.rs b/pkgs/id/tests/remote_write_access.rs index 3cf85ce791..8137d7c75f 100644 --- a/pkgs/id/tests/remote_write_access.rs +++ b/pkgs/id/tests/remote_write_access.rs @@ -38,7 +38,7 @@ async fn client() -> Client { async fn names_on(server: &LocalNode) -> Vec { match server.request(MetaRequest::List).await { - MetaResponse::List { items } => items.into_iter().map(|(_, n)| n).collect(), + MetaResponse::List { items } => items.into_iter().map(|e| e.name).collect(), other => panic!("{other:?}"), } } @@ -157,7 +157,7 @@ async fn reads_stay_open_to_unlisted_nodes() { match request_over(&conn, &MetaRequest::List).await.unwrap() { MetaResponse::List { items } => { assert_eq!(items.len(), 1); - assert_eq!(items[0].1, "pub.txt"); + assert_eq!(items[0].name, "pub.txt"); } other => panic!("{other:?}"), } From 98f780f3b90577756fcf12a82643ce1fa3937cb3 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:35:58 -0600 Subject: [PATCH 2/2] fix(id): disposition PR #5191 Codex findings - /iroh-meta/3 ALPN bump, offline list metadata, legacy origin guard, web refresh params, 4-col test assertions (#4973) --- pkgs/id/crates/id-core/src/discovery.rs | 2 +- pkgs/id/src/commands/list.rs | 44 +++++---- pkgs/id/src/fileops.rs | 19 +++- pkgs/id/src/lib.rs | 11 ++- pkgs/id/src/peer_announcement.rs | 2 +- pkgs/id/src/protocol.rs | 6 +- pkgs/id/src/web/routes.rs | 120 +++++++++++++++--------- pkgs/id/src/web/templates.rs | 19 +++- pkgs/id/tests/cli_integration.rs | 19 +++- pkgs/id/web/src/main.ts | 43 +++++---- 10 files changed, 188 insertions(+), 97 deletions(-) diff --git a/pkgs/id/crates/id-core/src/discovery.rs b/pkgs/id/crates/id-core/src/discovery.rs index 0c3d1f4c0e..4239d20fdb 100644 --- a/pkgs/id/crates/id-core/src/discovery.rs +++ b/pkgs/id/crates/id-core/src/discovery.rs @@ -338,7 +338,7 @@ pub const MAX_PEER_NAME_BYTES: usize = 256; // ============================================================================ /// A peer's presence claim. Gossip carries it inside the id crate's signed, -/// versioned envelope; this plain structure is also nested in `/iroh-meta/2`. +/// versioned envelope; this plain structure is also nested in `/iroh-meta/3`. /// /// Serialized with [postcard](https://docs.rs/postcard) for compact binary /// encoding. Typical size: ~50-100 bytes depending on name length. diff --git a/pkgs/id/src/commands/list.rs b/pkgs/id/src/commands/list.rs index b8d2444720..fb30c5eb5e 100644 --- a/pkgs/id/src/commands/list.rs +++ b/pkgs/id/src/commands/list.rs @@ -111,22 +111,34 @@ pub async fn cmd_list(node: Option, no_relay: bool) -> Result<()> { return result; } - let store = open_store(false).await?; - let store_handle = store.as_store(); - - let mut list = store_handle.tags().list().await?; - let mut count = 0; - while let Some(item) = list.next().await { - let item = item?; - let name = String::from_utf8_lossy(item.name.as_ref()); - println!("{}", list_tsv_row(item.hash, &name, None, None)); - count += 1; - } - if count == 0 { - println!("(no files stored)"); - } - store.shutdown().await?; - Ok(()) + // Offline: run the same in-process meta handler the REPL uses, so the + // listing is enriched with the recorded origin + upload time from the + // metadata tags instead of reporting `unknown` for files whose + // metadata exists locally (Codex review, PR #5191). + let node = crate::local::LocalNode::open(false).await?; + let result = match node.request(MetaRequest::List).await { + MetaResponse::List { items } => { + if items.is_empty() { + println!("(no files stored)"); + } else { + for entry in &items { + println!( + "{}", + list_tsv_row( + entry.hash, + &entry.name, + entry.origin.as_deref(), + entry.uploaded_at + ) + ); + } + } + Ok(()) + } + _ => Err(anyhow::anyhow!("unexpected response")), + }; + node.shutdown().await?; + result } /// Lists files on a remote node. diff --git a/pkgs/id/src/fileops.rs b/pkgs/id/src/fileops.rs index 2a508b43e9..b240ee30b8 100644 --- a/pkgs/id/src/fileops.rs +++ b/pkgs/id/src/fileops.rs @@ -318,8 +318,11 @@ impl<'a> FileOps<'a> { /// Name `hash` as `name`, after verifying the blob is complete in the store. /// /// Sets the `created` tag only if absent and always refreshes `modified`, - /// stamps the `origin` node if one is configured and none is recorded - /// yet, then auto-tags `name`/`file`. + /// stamps the `origin` node on a genuine first write (no `created` tag + /// recorded yet) if one is configured, then auto-tags `name`/`file`. + /// A legacy file that predates origin stamping keeps an unknown origin + /// when it is overwritten: absence of an `origin` tag alone does not + /// prove this write is the file's first. pub async fn put(&self, name: &str, hash: Hash) -> Result<(), FileOpError> { Self::validate_name(name)?; if !self.blob_present(hash).await? { @@ -342,6 +345,15 @@ impl<'a> FileOps<'a> { let ns = &self.tags.global; let now = now_unix().to_string(); let subject = name.as_bytes(); + // Origin is stamped only for a genuine first write: a name with a + // `created` tag but no `origin` tag is a legacy file whose true + // origin is unknown and must stay unknown (Codex review, PR #5191). + let first_write = self + .tags + .get_by_key(ns, subject, b"created") + .await + .map(|existing| existing.is_empty()) + .unwrap_or(false); let created = if reset_created { self.tags .set_singleton(ns, subject, b"created", Some(now.as_bytes()), b"") @@ -362,7 +374,8 @@ impl<'a> FileOps<'a> { { tracing::warn!("failed to set modified tag for {name}: {e:#}"); } - if let Some(origin) = &self.origin + if first_write + && let Some(origin) = &self.origin && let Err(e) = self .tags .set_if_absent(ns, subject, b"origin", Some(origin.as_bytes()), b"") diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 06498ced1f..fbd6960835 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -128,7 +128,7 @@ //! //! Two protocols are used: //! - **Blobs Protocol** (`/iroh-blobs/1`): For blob data transfer -//! - **Meta Protocol** (`/iroh-meta/2`): For metadata operations (list, find, delete, etc.) +//! - **Meta Protocol** (`/iroh-meta/3`): For metadata operations (list, find, delete, etc.) //! //! ## Features //! @@ -344,10 +344,15 @@ pub const SERVE_LOCK: &str = ".iroh-serve.lock"; /// and `Error`. It is not wire-compatible with `/iroh-meta/1`; the ALPN bump /// makes old and new nodes fail the handshake cleanly instead of mis-decoding. /// +/// **Version 3** changes the `List` response item from `(hash, name)` pairs +/// to `ListEntry` records carrying the file's origin node and upload time +/// (#4973). That payload change is not wire-compatible with `/iroh-meta/2` +/// under postcard, so it takes this ALPN bump per the rule below. +/// /// Compatibility rule: within a version, only **append** enum variants. Any /// other change to [`protocol::MetaRequest`] / [`protocol::MetaResponse`] /// requires a new ALPN. `protocol::tests` pins every discriminant. -pub const META_ALPN: &[u8] = b"/iroh-meta/2"; +pub const META_ALPN: &[u8] = b"/iroh-meta/3"; // ============================================================================ // Utility Functions @@ -731,7 +736,7 @@ mod tests { assert_eq!(CLIENT_KEY_FILE, ".iroh-key-client"); assert_eq!(STORE_PATH, ".iroh-store"); assert_eq!(SERVE_LOCK, ".iroh-serve.lock"); - assert_eq!(META_ALPN, b"/iroh-meta/2"); + assert_eq!(META_ALPN, b"/iroh-meta/3"); } #[tokio::test] diff --git a/pkgs/id/src/peer_announcement.rs b/pkgs/id/src/peer_announcement.rs index 7e748339e3..454782ebdd 100644 --- a/pkgs/id/src/peer_announcement.rs +++ b/pkgs/id/src/peer_announcement.rs @@ -13,7 +13,7 @@ const SIGNATURE_DOMAIN: &[u8] = b"developing-today/id/peer-announcement/v2\0"; const MAX_PEER_ANNOUNCEMENT_FRAME_BYTES: usize = 1_024; /// Signed gossip envelope. The plain `PeerAnnouncement` remains unchanged for the -/// `/iroh-meta/2` response format; only gossip uses this versioned wrapper. +/// `/iroh-meta/3` response format; only gossip uses this versioned wrapper. #[derive(Clone, Debug, Deserialize, Serialize)] pub(crate) struct SignedPeerAnnouncement { version: u8, diff --git a/pkgs/id/src/protocol.rs b/pkgs/id/src/protocol.rs index ed7eeb9903..fe15ebef42 100644 --- a/pkgs/id/src/protocol.rs +++ b/pkgs/id/src/protocol.rs @@ -29,7 +29,7 @@ //! # Protocol Identifier //! //! The meta protocol uses the ALPN identifier defined in [`crate::META_ALPN`]: -//! `b"/iroh-meta/2"`. This allows nodes to negotiate the correct protocol handler. +//! `b"/iroh-meta/3"`. This allows nodes to negotiate the correct protocol handler. //! //! # Usage Example //! @@ -252,7 +252,7 @@ pub const MAX_REQUEST_BYTES: usize = 1024 * 1024; /// `Put` naming it is refused. pub const DEFAULT_BLOB_WAIT: std::time::Duration = std::time::Duration::from_secs(5); -/// Requests to a remote node via the meta protocol (`/iroh-meta/2`). +/// Requests to a remote node via the meta protocol (`/iroh-meta/3`). /// /// **Compatibility rule:** postcard encodes enum variants by position. Within /// a protocol version, new variants may only be *appended*; reordering, @@ -1285,7 +1285,7 @@ mod tests { #[test] fn wire_format_is_pinned() { // postcard encodes the enum variant index as the first byte. These - // indices are the wire format of `/iroh-meta/2`: within a version only + // indices are the wire format of `/iroh-meta/3`: within a version only // append new variants; anything else needs a new ALPN. let h = Hash::from_bytes([0u8; 32]); let s = String::from("x"); diff --git a/pkgs/id/src/web/routes.rs b/pkgs/id/src/web/routes.rs index 83e89c217d..61baf73d76 100644 --- a/pkgs/id/src/web/routes.rs +++ b/pkgs/id/src/web/routes.rs @@ -1467,7 +1467,11 @@ async fn save_handler(State(state): State, Json(req): Json, Json(req): Json fresh, + Err(err) => { + tracing::warn!("[routes] Failed to set created tag: {:#}", err); + false + } + }; - // Stamp this node as the file's origin (#4973), set-if-absent like - // `created`: the first writer stays the origin. - if let Err(err) = state - .tag_store - .set_if_absent( - &state.tag_store.global, - req.name.as_bytes(), - b"origin", - Some(state.node_id.as_bytes()), - b"", - ) - .await + // Stamp this node as the file's origin (#4973) only on a genuine + // first write (`created` was absent): the first writer stays the + // origin, and legacy files keep an unknown origin. + if created_fresh + && let Err(err) = state + .tag_store + .set_if_absent( + &state.tag_store.global, + req.name.as_bytes(), + b"origin", + Some(state.node_id.as_bytes()), + b"", + ) + .await { tracing::warn!("[routes] Failed to set origin tag: {:#}", err); } @@ -1596,7 +1606,11 @@ async fn new_file_handler( // Set metadata tags: created + modified let now_str = crate::tags::now_unix().to_string(); - if let Err(err) = state + // `created_fresh` gates the origin stamp below: a legacy file + // (created before origin stamping existed) keeps an unknown + // origin on overwrite instead of claiming this node (Codex + // review, PR #5191). + let created_fresh = match state .tag_store .set_if_absent( &state.tag_store.global, @@ -1607,21 +1621,27 @@ async fn new_file_handler( ) .await { - tracing::warn!("[routes] Failed to set created tag: {:#}", err); - } + Ok(fresh) => fresh, + Err(err) => { + tracing::warn!("[routes] Failed to set created tag: {:#}", err); + false + } + }; - // Stamp this node as the file's origin (#4973), set-if-absent like - // `created`: the first writer stays the origin. - if let Err(err) = state - .tag_store - .set_if_absent( - &state.tag_store.global, - req.name.as_bytes(), - b"origin", - Some(state.node_id.as_bytes()), - b"", - ) - .await + // Stamp this node as the file's origin (#4973) only on a genuine + // first write (`created` was absent): the first writer stays the + // origin, and legacy files keep an unknown origin. + if created_fresh + && let Err(err) = state + .tag_store + .set_if_absent( + &state.tag_store.global, + req.name.as_bytes(), + b"origin", + Some(state.node_id.as_bytes()), + b"", + ) + .await { tracing::warn!("[routes] Failed to set origin tag: {:#}", err); } @@ -1857,7 +1877,11 @@ async fn upload_handler(State(state): State, mut multipart: Multipart) // Set metadata tags (created, modified, content-type) let now_str = crate::tags::now_unix().to_string(); - if let Err(err) = state + // `created_fresh` gates the origin stamp below: a legacy file + // (created before origin stamping existed) keeps an unknown + // origin on overwrite instead of claiming this node (Codex + // review, PR #5191). + let created_fresh = match state .tag_store .set_if_absent( &state.tag_store.global, @@ -1868,21 +1892,27 @@ async fn upload_handler(State(state): State, mut multipart: Multipart) ) .await { - tracing::warn!("[routes] Failed to set created tag: {:#}", err); - } + Ok(fresh) => fresh, + Err(err) => { + tracing::warn!("[routes] Failed to set created tag: {:#}", err); + false + } + }; - // Stamp this node as the file's origin (#4973), set-if-absent like - // `created`: the first writer stays the origin. - if let Err(err) = state - .tag_store - .set_if_absent( - &state.tag_store.global, - filename.as_bytes(), - b"origin", - Some(state.node_id.as_bytes()), - b"", - ) - .await + // Stamp this node as the file's origin (#4973) only on a genuine + // first write (`created` was absent): the first writer stays the + // origin, and legacy files keep an unknown origin. + if created_fresh + && let Err(err) = state + .tag_store + .set_if_absent( + &state.tag_store.global, + filename.as_bytes(), + b"origin", + Some(state.node_id.as_bytes()), + b"", + ) + .await { tracing::warn!("[routes] Failed to set origin tag: {:#}", err); } diff --git a/pkgs/id/src/web/templates.rs b/pkgs/id/src/web/templates.rs index d452ef1789..5a5ef83969 100644 --- a/pkgs/id/src/web/templates.rs +++ b/pkgs/id/src/web/templates.rs @@ -174,7 +174,22 @@ pub fn render_file_list(page: &FileListPage) -> String { .map(html_escape) .unwrap_or_default(); html.push_str("
"); - html.push_str("", + search_value + ); + } + if page.show_deleted { + html.push_str( + "", + ); + } + html.push_str(""); let _ = write!( html, - "", + "", origin_value ); html.push_str( diff --git a/pkgs/id/tests/cli_integration.rs b/pkgs/id/tests/cli_integration.rs index 5d0a6c4737..6393ef1d55 100644 --- a/pkgs/id/tests/cli_integration.rs +++ b/pkgs/id/tests/cli_integration.rs @@ -626,12 +626,25 @@ mod list_tests { let list_output = run_cmd_success(&["list"], tmp.path()); - // Output should be hashname format + // Output should be hashnameoriginuploaded_at format + // (#4973: listings carry origin node + upload time). for line in list_output.lines() { if line.contains("test.list-format.txt") { let parts: Vec<&str> = line.split('\t').collect(); - assert_eq!(parts.len(), 2, "List output should be hashname"); + assert_eq!( + parts.len(), + 4, + "List output should be hashnameoriginuploaded_at" + ); assert_eq!(parts[0].len(), 64, "Hash should be 64 hex chars"); + // The file was just stored by this node, so origin is this + // node's id and uploaded_at is a unix timestamp. + assert_eq!(parts[2].len(), 64, "Origin should be a node id"); + assert!( + parts[3].parse::().is_ok(), + "uploaded_at should be unix seconds, got {:?}", + parts[3] + ); } } } @@ -665,7 +678,7 @@ mod list_tests { let fields: Vec<_> = row.split('\t').collect(); assert_eq!( fields.len(), - 2, + 4, "the stored name must not forge a column: {output:?}" ); assert_eq!(fields[0].len(), 64); diff --git a/pkgs/id/web/src/main.ts b/pkgs/id/web/src/main.ts index 29d441bf0f..7eee8b8135 100644 --- a/pkgs/id/web/src/main.ts +++ b/pkgs/id/web/src/main.ts @@ -514,6 +514,26 @@ function onPartialSwapped(_targetSelector: string): void { * Initialize search debounce for file search input and show-deleted checkbox. * Search triggers after 300ms of inactivity; checkbox triggers immediately. */ +/** + * Current file-list query params: search + show-deleted + the #4973 + * sort/origin controls. Every partial refresh (search debounce, + * show-deleted toggle, tag WebSocket events) must carry all of them, or + * the refresh silently drops the sort order and origin filter while the + * controls still show them selected (Codex review, PR #5191). + */ +function currentFileListParams(): URLSearchParams { + const searchInput = document.getElementById("file-search") as HTMLInputElement | null; + const showDeletedCheckbox = document.getElementById("show-deleted") as HTMLInputElement | null; + const sortSelect = document.getElementById("file-sort") as HTMLSelectElement | null; + const originInput = document.getElementById("file-origin") as HTMLInputElement | null; + const params = new URLSearchParams(); + if (searchInput?.value) params.set("search", searchInput.value); + if (showDeletedCheckbox?.checked) params.set("show_deleted", "true"); + if (sortSelect?.value) params.set("sort", sortSelect.value); + if (originInput?.value) params.set("origin", originInput.value); + return params; +} + function initSearchDebounce(): void { const searchInput = document.getElementById("file-search") as HTMLInputElement | null; const showDeletedCheckbox = document.getElementById("show-deleted") as HTMLInputElement | null; @@ -523,12 +543,7 @@ function initSearchDebounce(): void { const doSearch = () => { if (searchDebounceTimer) clearTimeout(searchDebounceTimer); searchDebounceTimer = setTimeout(() => { - const query = searchInput?.value || ""; - const showDeleted = showDeletedCheckbox?.checked || false; - const params = new URLSearchParams(); - if (query) params.set("search", query); - if (showDeleted) params.set("show_deleted", "true"); - const qs = params.toString(); + const qs = currentFileListParams().toString(); const url = qs ? `/api/files?${qs}` : "/api/files"; fetchPartial(url, "#file-list-content"); }, 300); @@ -542,12 +557,7 @@ function initSearchDebounce(): void { showDeletedCheckbox.addEventListener("change", () => { // Immediate on checkbox change (no debounce) if (searchDebounceTimer) clearTimeout(searchDebounceTimer); - const query = searchInput?.value || ""; - const showDeleted = showDeletedCheckbox?.checked || false; - const params = new URLSearchParams(); - if (query) params.set("search", query); - if (showDeleted) params.set("show_deleted", "true"); - const qs = params.toString(); + const qs = currentFileListParams().toString(); const url = qs ? `/api/files?${qs}` : "/api/files"; fetchPartial(url, "#file-list-content"); }); @@ -665,14 +675,7 @@ async function init(): Promise { const lastRefresh = (window as unknown as Record).__tagRefreshTs || 0; if (now - lastRefresh > 500) { (window as unknown as Record).__tagRefreshTs = now; - const searchInput = document.getElementById("file-search") as HTMLInputElement | null; - const showDeletedCheckbox = document.getElementById("show-deleted") as HTMLInputElement | null; - const query = searchInput?.value || ""; - const showDeleted = showDeletedCheckbox?.checked || false; - const params = new URLSearchParams(); - if (query) params.set("search", query); - if (showDeleted) params.set("show_deleted", "true"); - const qs = params.toString(); + const qs = currentFileListParams().toString(); const url = qs ? `/api/files?${qs}` : "/api/files"; fetchPartial(url, "#file-list-content"); }