From 928e5cf1577d450daf6170957346f18deafebdd8 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 27 Nov 2026 10:20:48 +0800 Subject: [PATCH 1/3] feat(project): model pinned, tagged and remote recent projects --- rust/contracts/rust-core-api.md | 51 ++- rust/crates/project/src/recent_projects.rs | 316 +++++++++++++++++- .../workspace/recent-projects-v1.json | 103 +++++- 3 files changed, 438 insertions(+), 32 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 450e91c5..ea4dd106 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -631,7 +631,7 @@ or removing a command fails until the table changes in the same commit. | `workspace.reduceDirectoryAction` | Apply "set role", "exclude" or "cancel exclusion" to a root's persisted directory rules and return the complete state to persist | | `workspace.relocateDirectoryRules` | Move (or drop, after a delete) the directory rule keys of a renamed, moved or deleted subtree, optionally into another workspace root's rules | | `workspace.repositories` | Discover deterministic Git repository roots for an opened workspace | -| `workspace.recentProjects.reduce` | Apply one record, remove, pin, import, or normalize action to the recent project list and return the retained order | +| `workspace.recentProjects.reduce` | Apply one history mutation or compute a recent project filter projection | | `workspace.searchIndex.warm` | Build or reuses the workspace search index | | `workspace.searchIndex.update` | Apply changed paths to the search index | | `workspace.searchIndex.invalidate` | Drop a workspace's cached search index | @@ -947,21 +947,40 @@ opened workspace is a subdirectory of the repository; all Git change paths are relative to that repository root. `git.status.ahead` and `behind` report the current branch's tracking counts and are zero when no upstream is configured. `workspace.recentProjects.reduce` accepts `{ entries, action, capacity? }` and -returns `{ entries, added, removed }`. Entries are `{ path, lastOpenedAt, pinned }` -where `path` is the host's normalized root identity compared byte for byte and -`lastOpenedAt` is non-negative Unix milliseconds from the host clock (missing -means oldest). `action.kind` is `record { path, openedAt }` (moves the project -first and keeps its pin), `remove { paths }`, `togglePinned { path }` (unknown -paths are ignored), `import { paths, openedAt }` (adds only unlisted paths, the -first stamped `openedAt` and each later one a millisecond older), or `normalize`. -Core keeps the newest record of duplicated paths, orders pinned projects first -and then by descending `lastOpenedAt` with ties in caller order, and keeps at -most `capacity` unpinned projects (default 20, range 1–200); pins never count -against it. `added` and `removed` list paths the reduction introduced or dropped -so hosts attach or discard their own metadata (names, icons, branches). Empty, -NUL-containing or over-4,096-byte paths, negative times and out-of-range -capacities return `invalid_request`. Hosts own persistence and which roots are -worth recording; menus may show fewer rows than are retained. See +returns `{ entries, added, removed }`. A local entry has its normalized root +`path`, `lastOpenedAt` in Unix milliseconds (missing means oldest) and +`pinned`. Optional entry fields are `pinOrder`, `tags`, and `remote`. +The host treats remote `path` as opaque. Core derives it from the full +transport identity and the absolute POSIX folder. A `remote` record includes +`connectionId`, `name`, `folder`, and a combination of `sshConnectionId`, `wsl` +(distribution and optional user), and `container` (engine, identifier, +optional context and user). SSH records refer to the saved connection by ID. +Authentication settings and session tokens stay in their existing stores. + +`action.kind` accepts `record { path, openedAt }`, +`recordRemote { remote, openedAt }`, `remove { paths }`, `togglePinned { path }`, +`setPinned { path, pinned }`, +`setTags { path, tags }`, `import { paths, openedAt }`, +`importEntries { entries: [{ path, lastOpenedAt }] }`, `normalize`, or +`filter { query, tag }`. Setting a pin to its current state preserves its rank. Explicit pins sort by descending pin order. Existing +pins without one keep their recency order after explicit pins. Reopening +preserves pin order and tags. Setting tags trims and deduplicates labels +case-insensitively and supports clearing them with an empty array. At most 16 +non-empty, comma-free labels of up to 64 UTF-8 bytes each are retained per +entry. Importing dated local entries preserves metadata already in the list. + +The filter is read-only and returns `visible` offsets into the supplied entries +and the distinct `tags` across the entire list. It combines a case-insensitive +substring of path, connection display name, or tags with an optional +case-insensitive exact tag. With a filter, `entries`, `added`, and `removed` +are empty. + +Core keeps the newest record of duplicated paths, sorts unpinned projects by +most recently opened with ties in caller order, and keeps at most `capacity` +unpinned projects (default 20, range 1–200). Pins are exempt. `added` and +`removed` name the paths introduced or dropped by a mutation. Invalid paths, +timestamps, routes, labels, or capacities return `invalid_request`. Hosts own +persistence and decide which successfully opened projects to record. See `rust/fixtures/workspace/recent-projects-v1.json`. `workspace.rowSelection.reduce` accepts `{ rows, selection?, action }` and returns diff --git a/rust/crates/project/src/recent_projects.rs b/rust/crates/project/src/recent_projects.rs index bbe1da14..5612f460 100644 --- a/rust/crates/project/src/recent_projects.rs +++ b/rust/crates/project/src/recent_projects.rs @@ -20,6 +20,9 @@ const MAX_ENTRIES: usize = 1024; const MAX_ACTION_PATHS: usize = 1024; /// Upper bound for one path identity in UTF-8 bytes. const MAX_PATH_BYTES: usize = 4096; +const MAX_TAGS: usize = 16; +const MAX_TAG_BYTES: usize = 64; +const MAX_REMOTE_ID_BYTES: usize = 1024; /// One retained project identity. `path` is the host's normalized root path /// and is compared byte for byte; `lastOpenedAt` is milliseconds since the @@ -35,6 +38,63 @@ pub struct RecentProjectEntry { /// Pinned projects sort first and never count against the capacity. #[serde(default)] pub pinned: bool, + /// Explicit pin order. Older entries without an order retain their recency order. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pin_order: Option, + /// User-provided category names, in the order they entered them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tags: Vec, + /// Reopen information for a remote project. Local projects omit this field. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub remote: Option, +} + +/// A remote folder and its reconnect route. Credentials stay in the host's connection store. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RecentRemoteProject { + /// Stable identity of the full transport chain. + pub connection_id: String, + /// Display name of the connection at the time of the last open. + pub name: String, + /// Absolute path on the remote host. + pub folder: String, + /// Saved SSH connection ID, for SSH and containers on an SSH host. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ssh_connection_id: Option, + /// Windows distribution and optional account, when using a WSL transport. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wsl: Option, + /// Engine and container ID, when the folder is inside a container. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub container: Option, +} + +/// Host-owned WSL locator. Remote connection validation runs when the host reopens the item. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RecentWslRoute { + /// Name used by the platform to select a distribution. + pub distribution: String, + /// Optional account in that distribution. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub user: String, +} + +/// Host-owned container locator. Remote connection validation runs when the host reopens the item. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RecentContainerRoute { + /// CLI engine that owns the container. + pub engine: String, + /// Container identifier used by the engine. + pub container: String, + /// Optional engine context. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub context: String, + /// Optional account in the container. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub user: String, } /// One user or host action applied to the stored list. @@ -49,6 +109,21 @@ pub enum RecentProjectsAction { #[serde(rename = "openedAt")] opened_at: i64, }, + /// Record a successfully opened folder using its transport and remote path as identity. + RecordRemote { + /// The folder and reconnect route. + remote: RecentRemoteProject, + /// Open time in milliseconds since the Unix epoch. + #[serde(rename = "openedAt")] + opened_at: i64, + }, + /// Replace the tags on an existing project. + SetTags { + /// Entry identity returned by an earlier reduction. + path: String, + /// Raw labels to trim, validate, and deduplicate. + tags: Vec, + }, /// Projects removed by the user or found unavailable by the host. Remove { /// Root paths to drop. @@ -59,6 +134,13 @@ pub enum RecentProjectsAction { /// Root path whose pin flips. path: String, }, + /// Applies an explicit menu intent, even if its window was showing an older list. + SetPinned { + /// Entry identity returned by an earlier reduction. + path: String, + /// Desired pin state. + pinned: bool, + }, /// Adds projects discovered elsewhere (for example another IDE) that are /// not already listed. The first import is stamped `openedAt` and each /// later one a millisecond older, preserving the source order. @@ -69,10 +151,32 @@ pub enum RecentProjectsAction { #[serde(rename = "openedAt")] opened_at: i64, }, + /// Merge dated local entries from an older client while retaining current metadata. + ImportEntries { + /// Imported local project paths and their open times. + entries: Vec, + }, + /// Project a text and tag filter over the supplied entries, without mutating them. + Filter { + /// Case-insensitive substring matched against path, connection name and labels. + query: String, + /// Case-insensitive exact category, or empty to include all categories. + tag: String, + }, /// Re-applies ordering, deduplication, and capacity to a loaded list. Normalize, } +/// Local history imported from an earlier client. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ImportedRecentProject { + /// Host-normalized local project root. + pub path: String, + /// Open time recorded by the earlier client. + pub last_opened_at: i64, +} + /// `workspace.recentProjects.reduce` request. #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -97,6 +201,12 @@ pub struct RecentProjectsResponse { pub added: Vec, /// Paths this reduction dropped. pub removed: Vec, + /// Row offsets in the supplied list, present only for a filter. + #[serde(skip_serializing_if = "Option::is_none")] + pub visible: Option>, + /// Distinct category names across the supplied list, present only for a filter. + #[serde(skip_serializing_if = "Option::is_none")] + pub tags: Option>, } /// JSON entry point for `workspace.recentProjects.reduce`. @@ -122,6 +232,17 @@ pub fn reduce(request: RecentProjectsRequest) -> Result Result { validate_path(&path)?; validate_time(opened_at)?; - let pinned = match entries.iter().position(|entry| entry.path == path) { - Some(index) => entries.remove(index).pinned, - None => false, - }; - entries.insert( - 0, - RecentProjectEntry { - path, - last_opened_at: opened_at, - pinned, - }, - ); + record(&mut entries, path, opened_at, None); + } + RecentProjectsAction::RecordRemote { remote, opened_at } => { + validate_remote(&remote)?; + validate_time(opened_at)?; + let path = remote_identity(&remote); + record(&mut entries, path, opened_at, Some(remote)); + } + RecentProjectsAction::SetTags { path, tags } => { + validate_path(&path)?; + let tags = normalize_tags(tags)?; + if let Some(entry) = entries.iter_mut().find(|entry| entry.path == path) { + entry.tags = tags; + } } RecentProjectsAction::Remove { paths } => { validate_paths(&paths)?; @@ -151,8 +274,15 @@ pub fn reduce(request: RecentProjectsRequest) -> Result { validate_path(&path)?; - if let Some(entry) = entries.iter_mut().find(|entry| entry.path == path) { - entry.pinned = !entry.pinned; + if let Some(index) = entries.iter().position(|entry| entry.path == path) { + let pinned = !entries[index].pinned; + set_pinned(&mut entries, index, pinned); + } + } + RecentProjectsAction::SetPinned { path, pinned } => { + validate_path(&path)?; + if let Some(index) = entries.iter().position(|entry| entry.path == path) { + set_pinned(&mut entries, index, pinned); } } RecentProjectsAction::Import { paths, opened_at } => { @@ -166,12 +296,32 @@ pub fn reduce(request: RecentProjectsRequest) -> Result { + if imported.len() > MAX_ACTION_PATHS { + return Err(invalid("Too many imported recent projects")); + } + for entry in imported { + validate_path(&entry.path)?; + validate_time(entry.last_opened_at)?; + if let Some(known) = entries.iter_mut().find(|known| known.path == entry.path) { + if known.remote.is_none() { + known.last_opened_at = known.last_opened_at.max(entry.last_opened_at); + } + } else { + record(&mut entries, entry.path, entry.last_opened_at, None); + } + } + } RecentProjectsAction::Normalize => {} + RecentProjectsAction::Filter { .. } => unreachable!("filter returns before mutation"), } let retained = order_and_limit(entries, capacity); @@ -191,9 +341,140 @@ pub fn reduce(request: RecentProjectsRequest) -> Result, index: usize, pinned: bool) { + if entries[index].pinned == pinned { + return; + } + if !pinned { + entries[index].pinned = false; + entries[index].pin_order = None; + return; + } + let mut entry = entries.remove(index); + entry.pinned = true; + entry.pin_order = Some( + entries + .iter() + .filter_map(|item| item.pin_order) + .max() + .unwrap_or(0) + .saturating_add(1), + ); + entries.insert(0, entry); +} + +fn record( + entries: &mut Vec, + path: String, + opened_at: i64, + remote: Option, +) { + let mut entry = match entries.iter().position(|entry| entry.path == path) { + Some(index) => entries.remove(index), + None => RecentProjectEntry { + path, + last_opened_at: opened_at, + pinned: false, + pin_order: None, + tags: Vec::new(), + remote: None, + }, + }; + entry.last_opened_at = opened_at; + if remote.is_some() { + entry.remote = remote; + } + entries.insert(0, entry); +} + +fn filter(entries: Vec, query: &str, tag: &str) -> RecentProjectsResponse { + let query = query.trim().to_lowercase(); + let tag = tag.trim().to_lowercase(); + let mut tags = std::collections::BTreeMap::new(); + let mut visible = Vec::new(); + for (index, entry) in entries.iter().enumerate() { + let mut tag_matches = tag.is_empty(); + let mut query_matches = if let Some(remote) = &entry.remote { + remote.folder.to_lowercase().contains(&query) + || remote.name.to_lowercase().contains(&query) + } else { + entry.path.to_lowercase().contains(&query) + }; + for label in &entry.tags { + let key = label.to_lowercase(); + tag_matches |= key == tag; + query_matches |= key.contains(&query); + tags.entry(key).or_insert_with(|| label.clone()); + } + if tag_matches && query_matches { + visible.push(index); + } + } + RecentProjectsResponse { + entries: Vec::new(), + added: Vec::new(), + removed: Vec::new(), + visible: Some(visible), + tags: Some(tags.into_values().collect()), + } +} + +fn remote_identity(remote: &RecentRemoteProject) -> String { + // Length-prefix the transport to disambiguate delimiters inside IDs and paths. + format!( + "remote:{}:{}{}", + remote.connection_id.len(), + remote.connection_id, + remote.folder + ) +} + +fn validate_remote(remote: &RecentRemoteProject) -> Result<(), CoreError> { + if remote.connection_id.is_empty() + || remote.connection_id.len() > MAX_REMOTE_ID_BYTES + || remote.name.len() > MAX_REMOTE_ID_BYTES + || !remote.folder.starts_with('/') + || (remote.ssh_connection_id.is_none() + && remote.wsl.is_none() + && remote.container.is_none()) + || (remote.ssh_connection_id.is_some() && remote.wsl.is_some()) + { + return Err(invalid("Remote project route is invalid")); + } + validate_path(&remote_identity(remote)) +} + +fn normalize_tags(tags: Vec) -> Result, CoreError> { + let mut seen = HashSet::new(); + let tags: Vec = tags + .iter() + .map(|tag| tag.trim()) + .filter(|tag| !tag.is_empty() && seen.insert(tag.to_lowercase())) + .map(str::to_owned) + .collect(); + validate_tags(&tags)?; + Ok(tags) +} + +fn validate_tags(tags: &[String]) -> Result<(), CoreError> { + if tags.len() > MAX_TAGS + || tags.iter().any(|tag| { + tag.is_empty() + || tag.len() > MAX_TAG_BYTES + || tag.contains(',') + || tag.chars().any(char::is_control) + }) + { + return Err(invalid("Recent project tags are invalid")); + } + Ok(()) +} + /// Keeps the newest record of each path; the first occurrence wins a tie. fn deduplicate(entries: Vec) -> Vec { let mut result: Vec = Vec::with_capacity(entries.len()); @@ -211,7 +492,12 @@ fn order_and_limit(entries: Vec, capacity: usize) -> Vec, Vec<_>) = entries.into_iter().partition(|entry| entry.pinned); // `sort_by_key` is stable, so equal timestamps keep the caller's order. - pinned.sort_by_key(|entry| std::cmp::Reverse(entry.last_opened_at)); + pinned.sort_by_key(|entry| { + std::cmp::Reverse(( + entry.pin_order, + entry.pin_order.is_none().then_some(entry.last_opened_at), + )) + }); unpinned.sort_by_key(|entry| std::cmp::Reverse(entry.last_opened_at)); unpinned.truncate(capacity); // Pins are exempt from the capacity but still bounded by the input limit. diff --git a/rust/fixtures/workspace/recent-projects-v1.json b/rust/fixtures/workspace/recent-projects-v1.json index 34e275ea..896a9c14 100644 --- a/rust/fixtures/workspace/recent-projects-v1.json +++ b/rust/fixtures/workspace/recent-projects-v1.json @@ -65,13 +65,114 @@ }, "expected": { "entries": [ - { "path": "/work/old", "lastOpenedAt": 100, "pinned": true }, + { "path": "/work/old", "lastOpenedAt": 100, "pinned": true, "pinOrder": 1 }, { "path": "/work/new", "lastOpenedAt": 900, "pinned": false } ], "added": [], "removed": [] } }, + { + "name": "pinning an older project puts it before an existing pin", + "request": { + "entries": [ + { "path": "/work/new", "lastOpenedAt": 900, "pinned": true, "pinOrder": 4 }, + { "path": "/work/old", "lastOpenedAt": 100, "pinned": false } + ], + "action": { "kind": "togglePinned", "path": "/work/old" } + }, + "expected": { + "entries": [ + { "path": "/work/old", "lastOpenedAt": 100, "pinned": true, "pinOrder": 5 }, + { "path": "/work/new", "lastOpenedAt": 900, "pinned": true, "pinOrder": 4 } + ], + "added": [], + "removed": [] + } + }, + { + "name": "repeated pin intent leaves existing pin order alone", + "request": { + "entries": [ + { "path": "/work/new", "lastOpenedAt": 900, "pinned": true, "pinOrder": 5 }, + { "path": "/work/old", "lastOpenedAt": 100, "pinned": true, "pinOrder": 4 } + ], + "action": { "kind": "setPinned", "path": "/work/old", "pinned": true } + }, + "expected": { + "entries": [ + { "path": "/work/new", "lastOpenedAt": 900, "pinned": true, "pinOrder": 5 }, + { "path": "/work/old", "lastOpenedAt": 100, "pinned": true, "pinOrder": 4 } + ], + "added": [], + "removed": [] + } + }, + { + "name": "reopening a pin preserves its pin order and labels", + "request": { + "entries": [ + { "path": "/work/research", "lastOpenedAt": 60, "pinned": true, "pinOrder": 2 }, + { "path": "/work/docs", "lastOpenedAt": 100, "pinned": true, "pinOrder": 1, "tags": ["Docs"] } + ], + "action": { "kind": "record", "path": "/work/docs", "openedAt": 200 } + }, + "expected": { + "entries": [ + { "path": "/work/research", "lastOpenedAt": 60, "pinned": true, "pinOrder": 2 }, + { "path": "/work/docs", "lastOpenedAt": 200, "pinned": true, "pinOrder": 1, "tags": ["Docs"] } + ], + "added": [], + "removed": [] + } + }, + { + "name": "setting tags trims and folds duplicates", + "request": { + "entries": [{ "path": "/work/alpha", "lastOpenedAt": 100 }], + "action": { "kind": "setTags", "path": "/work/alpha", "tags": [" Work ", "work", "个人", " "] } + }, + "expected": { + "entries": [{ "path": "/work/alpha", "lastOpenedAt": 100, "pinned": false, "tags": ["Work", "个人"] }], + "added": [], + "removed": [] + } + }, + { + "name": "the same folder on two transports has distinct history entries", + "request": { + "entries": [ + { "path": "remote:4:west/repo", "lastOpenedAt": 100, "remote": { "connectionId": "west", "name": "West", "folder": "/repo", "sshConnectionId": "west" } } + ], + "action": { "kind": "recordRemote", "openedAt": 200, "remote": { "connectionId": "east", "name": "East", "folder": "/repo", "sshConnectionId": "east" } } + }, + "expected": { + "entries": [ + { "path": "remote:4:east/repo", "lastOpenedAt": 200, "pinned": false, "remote": { "connectionId": "east", "name": "East", "folder": "/repo", "sshConnectionId": "east" } }, + { "path": "remote:4:west/repo", "lastOpenedAt": 100, "pinned": false, "remote": { "connectionId": "west", "name": "West", "folder": "/repo", "sshConnectionId": "west" } } + ], + "added": ["remote:4:east/repo"], + "removed": [] + } + }, + { + "name": "tag and text filters compose across local and remote projects", + "request": { + "entries": [ + { "path": "/work/alpha", "lastOpenedAt": 300, "tags": ["Docs"] }, + { "path": "remote:4:east/repo", "lastOpenedAt": 200, "tags": ["docs", "Remote"], "remote": { "connectionId": "east", "name": "East", "folder": "/repo", "sshConnectionId": "east" } }, + { "path": "/work/east", "lastOpenedAt": 100, "tags": ["Research"] } + ], + "action": { "kind": "filter", "query": " EAST ", "tag": "DOCS" } + }, + "expected": { + "entries": [], + "added": [], + "removed": [], + "visible": [1], + "tags": ["Docs", "Remote", "Research"] + } + }, { "name": "unpinning beyond capacity evicts the oldest unpinned project", "request": { From eac266246b1982bd5765883535cd185a84a6de16 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 27 Nov 2026 11:16:21 +0800 Subject: [PATCH 2/3] fix(project): preserve recent history across stale opens and filters --- rust/contracts/rust-core-api.md | 9 ++-- rust/crates/core/src/tests/project.rs | 28 +++++++++++ rust/crates/project/src/recent_projects.rs | 47 +++++++++++++++---- .../workspace/recent-projects-v1.json | 33 ++++++++++++- 4 files changed, 103 insertions(+), 14 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index ea4dd106..a18f8ba1 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -951,7 +951,8 @@ returns `{ entries, added, removed }`. A local entry has its normalized root `path`, `lastOpenedAt` in Unix milliseconds (missing means oldest) and `pinned`. Optional entry fields are `pinOrder`, `tags`, and `remote`. The host treats remote `path` as opaque. Core derives it from the full -transport identity and the absolute POSIX folder. A `remote` record includes +transport identity (up to 1024 UTF-8 bytes) and the absolute POSIX folder (up to +4096 UTF-8 bytes). The derived key may be longer than a local path. A `remote` record includes `connectionId`, `name`, `folder`, and a combination of `sshConnectionId`, `wsl` (distribution and optional user), and `container` (engine, identifier, optional context and user). SSH records refer to the saved connection by ID. @@ -964,7 +965,8 @@ Authentication settings and session tokens stay in their existing stores. `importEntries { entries: [{ path, lastOpenedAt }] }`, `normalize`, or `filter { query, tag }`. Setting a pin to its current state preserves its rank. Explicit pins sort by descending pin order. Existing pins without one keep their recency order after explicit pins. Reopening -preserves pin order and tags. Setting tags trims and deduplicates labels +preserves pin order and tags, and an older open event cannot replace a newer +open time or its remote route. Setting tags trims and deduplicates labels case-insensitively and supports clearing them with an empty array. At most 16 non-empty, comma-free labels of up to 64 UTF-8 bytes each are retained per entry. Importing dated local entries preserves metadata already in the list. @@ -972,7 +974,8 @@ entry. Importing dated local entries preserves metadata already in the list. The filter is read-only and returns `visible` offsets into the supplied entries and the distinct `tags` across the entire list. It combines a case-insensitive substring of path, connection display name, or tags with an optional -case-insensitive exact tag. With a filter, `entries`, `added`, and `removed` +case-insensitive exact tag. If the requested tag exists, `selectedTag` returns +its current display spelling even when the text query matches no rows. With a filter, `entries`, `added`, and `removed` are empty. Core keeps the newest record of duplicated paths, sorts unpinned projects by diff --git a/rust/crates/core/src/tests/project.rs b/rust/crates/core/src/tests/project.rs index 67a6a73a..5eb9e4ff 100644 --- a/rust/crates/core/src/tests/project.rs +++ b/rust/crates/core/src/tests/project.rs @@ -2185,6 +2185,34 @@ fn recent_projects_default_capacity_keeps_the_newest_unpinned_projects() { assert_eq!(response["data"]["removed"], serde_json::json!(["/p0"])); } +#[test] +fn recent_project_remote_key_can_include_the_full_remote_path() { + use serde_json::json; + + let folder = format!("/{}", vec!["a".repeat(255); 16].join("/")); + assert_eq!(folder.len(), 4096); + let recorded = call( + "workspace.recentProjects.reduce", + json!({"entries": [], "action": {"kind": "recordRemote", "openedAt": 1, + "remote": {"connectionId": "saved-demo", "sshConnectionId": "saved-demo", + "name": "Synthetic host", "folder": folder}}}), + ); + assert_eq!(recorded["ok"], true, "{recorded}"); + let entries = &recorded["data"]["entries"]; + let key = &entries[0]["path"]; + assert!(key.as_str().unwrap().len() > 4096); + let pinned = call( + "workspace.recentProjects.reduce", + json!({"entries": entries, "action": {"kind": "setPinned", "path": key, "pinned": true}}), + ); + assert_eq!(pinned["data"]["entries"][0]["pinned"], true, "{pinned}"); + let removed = call( + "workspace.recentProjects.reduce", + json!({"entries": &pinned["data"]["entries"], "action": {"kind": "remove", "paths": [key]}}), + ); + assert_eq!(removed["data"]["entries"], json!([]), "{removed}"); +} + fn hex_bytes(hex: &str) -> Vec { (0..hex.len()) .step_by(2) diff --git a/rust/crates/project/src/recent_projects.rs b/rust/crates/project/src/recent_projects.rs index 5612f460..3d88c4ca 100644 --- a/rust/crates/project/src/recent_projects.rs +++ b/rust/crates/project/src/recent_projects.rs @@ -23,6 +23,8 @@ const MAX_PATH_BYTES: usize = 4096; const MAX_TAGS: usize = 16; const MAX_TAG_BYTES: usize = 64; const MAX_REMOTE_ID_BYTES: usize = 1024; +// The generated key also includes the length prefix: "remote:1024:" at most. +const MAX_RECENT_KEY_BYTES: usize = "remote:1024:".len() + MAX_REMOTE_ID_BYTES + MAX_PATH_BYTES; /// One retained project identity. `path` is the host's normalized root path /// and is compared byte for byte; `lastOpenedAt` is milliseconds since the @@ -207,6 +209,9 @@ pub struct RecentProjectsResponse { /// Distinct category names across the supplied list, present only for a filter. #[serde(skip_serializing_if = "Option::is_none")] pub tags: Option>, + /// Current display spelling of the requested tag, when that tag still exists. + #[serde(skip_serializing_if = "Option::is_none")] + pub selected_tag: Option, } /// JSON entry point for `workspace.recentProjects.reduce`. @@ -230,7 +235,6 @@ pub fn reduce(request: RecentProjectsRequest) -> Result Result Result { - validate_path(&path)?; + validate_recent_key(&path)?; let tags = normalize_tags(tags)?; if let Some(entry) = entries.iter_mut().find(|entry| entry.path == path) { entry.tags = tags; } } RecentProjectsAction::Remove { paths } => { - validate_paths(&paths)?; + validate_path_count(&paths)?; + paths + .iter() + .try_for_each(|path| validate_recent_key(path))?; let removed: HashSet<&str> = paths.iter().map(String::as_str).collect(); entries.retain(|entry| !removed.contains(entry.path.as_str())); } RecentProjectsAction::TogglePinned { path } => { - validate_path(&path)?; + validate_recent_key(&path)?; if let Some(index) = entries.iter().position(|entry| entry.path == path) { let pinned = !entries[index].pinned; set_pinned(&mut entries, index, pinned); } } RecentProjectsAction::SetPinned { path, pinned } => { - validate_path(&path)?; + validate_recent_key(&path)?; if let Some(index) = entries.iter().position(|entry| entry.path == path) { set_pinned(&mut entries, index, pinned); } } RecentProjectsAction::Import { paths, opened_at } => { - validate_paths(&paths)?; + validate_path_count(&paths)?; + paths.iter().try_for_each(|path| validate_path(path))?; validate_time(opened_at)?; let mut known: HashSet = entries.iter().map(|e| e.path.clone()).collect(); let mut offset = 0; @@ -343,6 +353,7 @@ pub fn reduce(request: RecentProjectsRequest) -> Result, ) { let mut entry = match entries.iter().position(|entry| entry.path == path) { + Some(index) if entries[index].last_opened_at > opened_at => return, Some(index) => entries.remove(index), None => RecentProjectEntry { path, @@ -415,12 +427,14 @@ fn filter(entries: Vec, query: &str, tag: &str) -> RecentPro visible.push(index); } } + let selected_tag = tags.get(&tag).cloned(); RecentProjectsResponse { entries: Vec::new(), added: Vec::new(), removed: Vec::new(), visible: Some(visible), tags: Some(tags.into_values().collect()), + selected_tag, } } @@ -446,7 +460,7 @@ fn validate_remote(remote: &RecentRemoteProject) -> Result<(), CoreError> { { return Err(invalid("Remote project route is invalid")); } - validate_path(&remote_identity(remote)) + validate_path(&remote.folder) } fn normalize_tags(tags: Vec) -> Result, CoreError> { @@ -506,15 +520,28 @@ fn order_and_limit(entries: Vec, capacity: usize) -> Vec Result<(), CoreError> { +fn validate_path_count(paths: &[String]) -> Result<(), CoreError> { if paths.len() > MAX_ACTION_PATHS { return Err(invalid("Too many recent project paths")); } - paths.iter().try_for_each(|path| validate_path(path)) + Ok(()) +} + +fn validate_recent_key(path: &str) -> Result<(), CoreError> { + let limit = if path.starts_with("remote:") { + MAX_RECENT_KEY_BYTES + } else { + MAX_PATH_BYTES + }; + validate_path_with_limit(path, limit) } fn validate_path(path: &str) -> Result<(), CoreError> { - if path.is_empty() || path.len() > MAX_PATH_BYTES || path.contains('\0') { + validate_path_with_limit(path, MAX_PATH_BYTES) +} + +fn validate_path_with_limit(path: &str, limit: usize) -> Result<(), CoreError> { + if path.is_empty() || path.len() > limit || path.contains('\0') { return Err(invalid("Recent project path is invalid")); } Ok(()) diff --git a/rust/fixtures/workspace/recent-projects-v1.json b/rust/fixtures/workspace/recent-projects-v1.json index 896a9c14..96b7cc2f 100644 --- a/rust/fixtures/workspace/recent-projects-v1.json +++ b/rust/fixtures/workspace/recent-projects-v1.json @@ -155,6 +155,36 @@ "removed": [] } }, + { + "name": "a stale local open keeps the newer time", + "request": { + "entries": [ + { "path": "/work/alpha", "lastOpenedAt": 300 } + ], + "action": { "kind": "record", "path": "/work/alpha", "openedAt": 100 } + }, + "expected": { + "entries": [{ "path": "/work/alpha", "lastOpenedAt": 300, "pinned": false }], + "added": [], + "removed": [] + } + }, + { + "name": "a stale remote open keeps the newest reported connection name", + "request": { + "entries": [ + { "path": "remote:4:east/repo", "lastOpenedAt": 300, "remote": { "connectionId": "east", "name": "Current name", "folder": "/repo", "sshConnectionId": "east" } } + ], + "action": { "kind": "recordRemote", "openedAt": 100, "remote": { "connectionId": "east", "name": "Earlier name", "folder": "/repo", "sshConnectionId": "east" } } + }, + "expected": { + "entries": [ + { "path": "remote:4:east/repo", "lastOpenedAt": 300, "pinned": false, "remote": { "connectionId": "east", "name": "Current name", "folder": "/repo", "sshConnectionId": "east" } } + ], + "added": [], + "removed": [] + } + }, { "name": "tag and text filters compose across local and remote projects", "request": { @@ -170,7 +200,8 @@ "added": [], "removed": [], "visible": [1], - "tags": ["Docs", "Remote", "Research"] + "tags": ["Docs", "Remote", "Research"], + "selectedTag": "Docs" } }, { From e03695d03dc6b4b446aedf24a7658398dd277813 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Fri, 27 Nov 2026 11:38:52 +0800 Subject: [PATCH 3/3] fix(project): reject NUL in remote recent connection IDs --- rust/contracts/rust-core-api.md | 3 ++- rust/crates/project/src/recent_projects.rs | 1 + rust/fixtures/workspace/recent-projects-v1.json | 11 +++++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index a18f8ba1..11294303 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -952,7 +952,8 @@ returns `{ entries, added, removed }`. A local entry has its normalized root `pinned`. Optional entry fields are `pinOrder`, `tags`, and `remote`. The host treats remote `path` as opaque. Core derives it from the full transport identity (up to 1024 UTF-8 bytes) and the absolute POSIX folder (up to -4096 UTF-8 bytes). The derived key may be longer than a local path. A `remote` record includes +4096 UTF-8 bytes). Both reject NUL. The derived key may be longer than a local +path. A `remote` record includes `connectionId`, `name`, `folder`, and a combination of `sshConnectionId`, `wsl` (distribution and optional user), and `container` (engine, identifier, optional context and user). SSH records refer to the saved connection by ID. diff --git a/rust/crates/project/src/recent_projects.rs b/rust/crates/project/src/recent_projects.rs index 3d88c4ca..70acd672 100644 --- a/rust/crates/project/src/recent_projects.rs +++ b/rust/crates/project/src/recent_projects.rs @@ -451,6 +451,7 @@ fn remote_identity(remote: &RecentRemoteProject) -> String { fn validate_remote(remote: &RecentRemoteProject) -> Result<(), CoreError> { if remote.connection_id.is_empty() || remote.connection_id.len() > MAX_REMOTE_ID_BYTES + || remote.connection_id.contains('\0') || remote.name.len() > MAX_REMOTE_ID_BYTES || !remote.folder.starts_with('/') || (remote.ssh_connection_id.is_none() diff --git a/rust/fixtures/workspace/recent-projects-v1.json b/rust/fixtures/workspace/recent-projects-v1.json index 96b7cc2f..5c14f733 100644 --- a/rust/fixtures/workspace/recent-projects-v1.json +++ b/rust/fixtures/workspace/recent-projects-v1.json @@ -309,6 +309,17 @@ } ], "invalid": [ + { + "name": "a remote connection identity cannot contain NUL", + "request": { + "entries": [], + "action": { + "kind": "recordRemote", + "openedAt": 1, + "remote": { "connectionId": "saved\u0000demo", "name": "Synthetic host", "folder": "/workspace", "sshConnectionId": "saved-demo" } + } + } + }, { "name": "empty path", "request": { "entries": [], "action": { "kind": "record", "path": "", "openedAt": 1 } }