diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 276ed0b2..696a3dbd 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -5729,28 +5729,44 @@ clients keep them in one machine-local document, read it, and publish the validates the document and applies every edit. `remote.connections` accepts `{ document: string|null }` and returns -`{ connections, storage: { relativePath: "remote/connections.json", +`{ connections, sections, storage: { relativePath: "remote/connections.json", maximumBytes: 262144 } }`. `connections` is the list in the user's order; -each entry is `{ id, name, connection, recentFolders? }`, where `connection` -is the object `remote.probe` takes and `recentFolders` holds at most 10 -normalized absolute host paths, most recent first. +each entry is `{ id, name, connection, color?, group?, recentFolders? }`, +where `connection` is the object `remote.probe` takes and `recentFolders` +holds at most 10 normalized absolute host paths, most recent first. `color` +is one of `red`, `orange`, `yellow`, `green`, `blue` and `purple`; clients +pick the shade for their light and dark themes. `group` is the name of the +group the window lists the entry under. Neither field reaches SSH. + +`sections` is the order the window shows the entries in: +`[{ group: string|null, ids: [id] }]`, one section per group in the order the +groups first appear in the list, then a `null` section for the entries +without a group. Groups that differ only in letter case share a section, +named with the first entry's spelling. An empty list has no sections; a list +without groups has the single `null` section. Clients render the sections as +given and do not regroup or reorder the entries. `remote.editConnections` accepts `{ document }` with exactly one of: -- `save: { id?, name, connection }` normalizes and checks the connection, - then adds an entry with a new id or replaces the entry `id` in place. - `name` is trimmed, 1 to 128 characters without control characters, and - unique among the entries regardless of case. Replacing an entry with - another `host`, `port`, `user` or `proxyJump` clears its recent folders, - which belong to the target and not to the name. +- `save: { id?, name, connection, color?, group? }` normalizes and checks + the connection, then adds an entry with a new id or replaces the entry `id` + in place. `name` is trimmed, 1 to 128 characters without control + characters, and unique among the entries regardless of case. Replacing an + entry with another `host`, `port`, `user` or `proxyJump` clears its recent + folders, which belong to the target and not to the name. A missing `color` + or `group` saves the entry without one, so a save always carries the + entry's current values. `group` is trimmed, and a blank group is no group; + otherwise it is at most 64 characters without control characters, and it + takes the spelling of another entry's group that differs only in letter + case. - `remove: { id }` removes the entry; an absent id changes nothing. - `rememberFolder: { id, path }` moves `path` to the front of the entry's recent folders and keeps 10. -The result is `{ changed, document: string|null, connections, id? }`; `id` -names the entry a save wrote. An unchanged edit returns a `null` document and -must not create a source. Requests never carry a secret: a password field is -an unknown field and is rejected. +The result is `{ changed, document: string|null, connections, sections, +id? }`; `id` names the entry a save wrote. An unchanged edit returns a `null` +document and must not create a source. Requests never carry a secret: a +password field is an unknown field and is rejected. Bounds: 256 KiB per document and 128 entries. A document that cannot be decoded, has duplicate keys, unknown fields, another version, a malformed @@ -5759,6 +5775,10 @@ refused edit is `invalid_request`. Both carry `details` as the JSON `{ field, reason }`, where `reason` is `required`, `invalid`, `tooLong`, `duplicate`, `full` (128 entries) or `unknown` (no entry has the id). +The document stays at version 1 and omits `color` and `group` when they are +unset. A build from before these fields refuses a document that sets one as +having an unknown field. + Native clients keep the document below their platform user-preference directory, never on a host, in a workspace or in an installed package. This user-settings resource does not affect code signatures or update deltas. diff --git a/rust/crates/remote/src/client/connections.rs b/rust/crates/remote/src/client/connections.rs index 0b17aec7..3800dcad 100644 --- a/rust/crates/remote/src/client/connections.rs +++ b/rust/crates/remote/src/client/connections.rs @@ -16,6 +16,10 @@ //! validates and edits it; the platform adapter reads it and publishes edits //! atomically. //! +//! - An entry may carry a [`Label`]: an accent color and a group. Neither +//! reaches SSH; [`Connections::sections`] turns the groups into the +//! headings the window lists the entries under. +//! //! Every refusal names the field and the reason, so a client can explain each //! one in the user's language next to the field it concerns. @@ -39,6 +43,9 @@ const MAX_CONNECTIONS: usize = 128; /// Longest connection name, in characters. const MAX_NAME_CHARS: usize = 128; +/// Longest group name, in characters. +const MAX_GROUP_CHARS: usize = 64; + /// Longest host, user, private key path or jump host list, in bytes. const MAX_FIELD_BYTES: usize = 1024; @@ -81,6 +88,46 @@ impl Authentication { } } +/// Accent color the window marks an entry with. Clients pick the shade for +/// their light and dark themes. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Color { + /// Red. + Red, + /// Orange. + Orange, + /// Yellow. + Yellow, + /// Green. + Green, + /// Blue. + Blue, + /// Purple. + Purple, +} + +/// How the window marks and groups an entry. `None` leaves the entry +/// without a color or outside every group. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct Label { + /// Accent color of the entry. + pub color: Option, + /// Group the entry is listed under. Trimmed before it is saved; a blank + /// group is no group. + pub group: Option, +} + +/// The entries listed under one heading, in the user's order. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Section<'a> { + /// The group's name; `None` for the entries without a group. + pub group: Option<&'a str>, + /// Ids of the entries in the section. + pub ids: Vec<&'a str>, +} + /// One SSH connection: the host, the account and how to authenticate. /// Names stay in [`SavedConnection`]; secrets are never part of it. #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] @@ -338,6 +385,12 @@ pub struct SavedConnection { /// Name the user gave, unique among the saved connections. name: String, connection: SshConnection, + /// Accent color the window marks the entry with. + #[serde(default, skip_serializing_if = "Option::is_none")] + color: Option, + /// Group the entry is listed under. Groups compare regardless of case. + #[serde(default, skip_serializing_if = "Option::is_none")] + group: Option, /// Host folders opened over this connection, most recent first. #[serde(default, skip_serializing_if = "Vec::is_empty")] recent_folders: Vec, @@ -347,6 +400,9 @@ impl SavedConnection { fn check(&self) -> Result<(), ConnectionError> { check_id(&self.id)?; check_name(&self.name)?; + if let Some(group) = &self.group { + check_group(group)?; + } self.connection.check()?; if self.recent_folders.len() > MAX_RECENT_FOLDERS { return Err(ConnectionError::at("recentFolders", Reason::Full)); @@ -440,21 +496,71 @@ impl Connections { self.connections.iter().find(|entry| entry.id == id) } - /// Saves `connection` under `name`, replacing the entry `id` or, without - /// one, appending a new entry with an id from `new_id`. Returns the id. + /// The entries by group: one section per group, in the order the groups + /// first appear, then the entries without a group. An empty list has no + /// sections. Groups that differ only in case share the section, which + /// shows the first entry's spelling. + pub fn sections(&self) -> Vec> { + let mut sections: Vec> = Vec::new(); + let mut ungrouped = Vec::new(); + for entry in &self.connections { + let Some(group) = entry.group.as_deref() else { + ungrouped.push(entry.id.as_str()); + continue; + }; + match sections + .iter_mut() + .find(|section| section.group.is_some_and(|name| same_name(name, group))) + { + Some(section) => section.ids.push(&entry.id), + None => sections.push(Section { + group: Some(group), + ids: vec![&entry.id], + }), + } + } + if !ungrouped.is_empty() { + sections.push(Section { + group: None, + ids: ungrouped, + }); + } + sections + } + + /// Saves `connection` under `name` with `label`, replacing the entry + /// `id` or, without one, appending a new entry with an id from `new_id`. + /// Returns the id. /// /// Renaming keeps the remembered folders; pointing the entry at another - /// host, port, user or jump host forgets them. `new_id` is called until - /// it returns an unused valid id, at most 16 times. + /// host, port, user or jump host forgets them. A group that another entry + /// already uses with other letter case takes that entry's spelling, so + /// the window shows one heading. `new_id` is called until it returns an + /// unused valid id, at most 16 times. pub fn save( &mut self, id: Option<&str>, name: &str, connection: SshConnection, + label: Label, mut new_id: impl FnMut() -> String, ) -> Result { let name = name.trim(); check_name(name)?; + let group = match label.group.as_deref().map(str::trim) { + None | Some("") => None, + Some(group) => { + check_group(group)?; + let spelling = self + .connections + .iter() + .filter(|other| Some(other.id.as_str()) != id) + .filter_map(|other| other.group.as_deref()) + .find(|other| same_name(other, group)) + .unwrap_or(group); + Some(spelling.to_owned()) + } + }; let connection = connection.normalized(); connection.check()?; if self @@ -476,6 +582,8 @@ impl Connections { } entry.name = name.to_owned(); entry.connection = connection; + entry.color = label.color; + entry.group = group; Ok(entry.id.clone()) } None => { @@ -490,6 +598,8 @@ impl Connections { id: id.clone(), name: name.to_owned(), connection, + color: label.color, + group, recent_folders: Vec::new(), }); Ok(id) @@ -546,6 +656,20 @@ fn check_name(name: &str) -> Result<(), ConnectionError> { Ok(()) } +/// A trimmed group of at most 64 characters without control characters. +fn check_group(group: &str) -> Result<(), ConnectionError> { + if group.is_empty() { + return Err(ConnectionError::at("group", Reason::Required)); + } + if group.chars().count() > MAX_GROUP_CHARS { + return Err(ConnectionError::at("group", Reason::TooLong)); + } + if group.trim() != group || group.chars().any(char::is_control) { + return Err(ConnectionError::at("group", Reason::Invalid)); + } + Ok(()) +} + /// Names that differ only in letter case would look the same in a title. fn same_name(left: &str, right: &str) -> bool { left.to_lowercase() == right.to_lowercase() diff --git a/rust/crates/remote/src/client/connections/tests.rs b/rust/crates/remote/src/client/connections/tests.rs index ee84314c..2476f8f3 100644 --- a/rust/crates/remote/src/client/connections/tests.rs +++ b/rust/crates/remote/src/client/connections/tests.rs @@ -41,9 +41,13 @@ fn ids() -> impl FnMut() -> String { /// Saves a connection to `host`, with an id derived from the host. fn saved(connections: &mut Connections, name: &str, host: &str) -> String { connections - .save(None, name, connection(json!({ "host": host })), || { - format!("id-{host}") - }) + .save( + None, + name, + connection(json!({ "host": host })), + Label::default(), + || format!("id-{host}"), + ) .expect("saved") } @@ -249,6 +253,7 @@ fn saved_connections_round_trip_through_the_document() { None, " Build box ", connection(json!({ "host": "build.example", "user": "ci", "port": 2222 })), + Label::default(), ids(), ) .unwrap(); @@ -274,6 +279,111 @@ fn saved_connections_round_trip_through_the_document() { ); } +#[test] +fn labels_are_saved_and_groups_become_sections_in_first_use_order() { + let mut connections = Connections::default(); + assert!(connections.sections().is_empty()); + let label = |color: Option, group: &str| Label { + color, + group: Some(group.to_owned()), + }; + let save = |connections: &mut Connections, name: &str, label: Label| { + connections + .save(None, name, connection(json!({ "host": "h" })), label, ids()) + .unwrap() + }; + let web = save( + &mut connections, + "Web", + label(Some(Color::Green), " Production "), + ); + let lab = save(&mut connections, "Lab", label(Some(Color::Purple), " ")); + let db = save(&mut connections, "Db", label(None, "PRODUCTION")); + let ci = save(&mut connections, "Ci", label(None, "Build")); + let section = |group: Option<&'static str>, ids: Vec<&str>| (group, ids.join(",")); + fn listed(connections: &Connections) -> Vec<(Option<&str>, String)> { + connections + .sections() + .into_iter() + .map(|section| (section.group, section.ids.join(","))) + .collect() + } + // A blank group is no group; another case takes the first spelling. + assert_eq!( + listed(&connections), + vec![ + section(Some("Production"), vec![&web, &db]), + section(Some("Build"), vec![&ci]), + section(None, vec![&lab]), + ] + ); + let text = connections.text().unwrap(); + let stored: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(stored["connections"][0]["color"], json!("green")); + assert_eq!(stored["connections"][0]["group"], json!("Production")); + assert_eq!(stored["connections"][1]["color"], json!("purple")); + assert!(stored["connections"][1].get("group").is_none()); + assert!(stored["connections"][2].get("color").is_none()); + assert_eq!(stored["connections"][2]["group"], json!("Production")); + assert_eq!(Connections::parse(Some(&text)).unwrap(), connections); + + // An entry alone in its group may change the group's case; saving + // without a label clears both fields. + connections + .save( + Some(&ci), + "Ci", + connection(json!({ "host": "h" })), + label(None, "BUILD"), + ids(), + ) + .unwrap(); + connections + .save( + Some(&web), + "Web", + connection(json!({ "host": "h" })), + Label::default(), + ids(), + ) + .unwrap(); + assert_eq!(connections.get(&web).unwrap().color, None); + assert_eq!( + listed(&connections), + vec![ + section(Some("Production"), vec![&db]), + section(Some("BUILD"), vec![&ci]), + section(None, vec![&web, &lab]), + ] + ); + + for (group, reason) in [ + ("tab\there".to_owned(), Reason::Invalid), + ("组".repeat(65), Reason::TooLong), + ] { + assert_eq!( + connections.save( + None, + "Other", + connection(json!({ "host": "h" })), + label(None, &group), + ids() + ), + Err(ConnectionError::at("group", reason)), + "{group:?}" + ); + } + assert!(connections + .save( + None, + "Other", + connection(json!({ "host": "h" })), + label(None, &"组".repeat(64)), + ids() + ) + .is_ok()); +} + #[test] fn saving_refuses_names_that_only_differ_in_case_and_unknown_ids() { let mut connections = Connections::default(); @@ -283,6 +393,7 @@ fn saving_refuses_names_that_only_differ_in_case_and_unknown_ids() { None, "devbox", connection(json!({ "host": "other" })), + Label::default(), ids() ), Err(ConnectionError::at("name", Reason::Duplicate)) @@ -293,6 +404,7 @@ fn saving_refuses_names_that_only_differ_in_case_and_unknown_ids() { Some(&first), "DEVBOX", connection(json!({ "host": "devbox" })), + Label::default(), ids() ), Ok(first.clone()) @@ -302,6 +414,7 @@ fn saving_refuses_names_that_only_differ_in_case_and_unknown_ids() { Some("missing"), "Other", connection(json!({ "host": "h" })), + Label::default(), ids() ), Err(ConnectionError::at("id", Reason::Unknown)) @@ -312,14 +425,26 @@ fn saving_refuses_names_that_only_differ_in_case_and_unknown_ids() { ("tab\there", Reason::Invalid), ] { assert_eq!( - connections.save(None, name, connection(json!({ "host": "h" })), ids()), + connections.save( + None, + name, + connection(json!({ "host": "h" })), + Label::default(), + ids() + ), Err(ConnectionError::at("name", reason)), "{name:?}" ); } let long = "名".repeat(129); assert_eq!( - connections.save(None, &long, connection(json!({ "host": "h" })), ids()), + connections.save( + None, + &long, + connection(json!({ "host": "h" })), + Label::default(), + ids() + ), Err(ConnectionError::at("name", Reason::TooLong)) ); assert_eq!(connections.entries().len(), 1); @@ -363,6 +488,7 @@ fn recent_folders_follow_the_target_not_the_name() { connection( json!({ "host": "devbox", "authentication": "agent", "keepAliveSeconds": 30 }), ), + Label::default(), ids(), ) .unwrap(); @@ -376,7 +502,13 @@ fn recent_folders_follow_the_target_not_the_name() { ] { connections.remember_folder(&id, "/srv").unwrap(); connections - .save(Some(&id), "Renamed", connection(target.clone()), ids()) + .save( + Some(&id), + "Renamed", + connection(target.clone()), + Label::default(), + ids(), + ) .unwrap(); assert!( connections.get(&id).unwrap().recent_folders.is_empty(), @@ -395,6 +527,7 @@ fn removing_keeps_the_order_and_ignores_absent_ids() { None, "Two", connection(json!({ "host": "two" })), + Label::default(), &mut second_ids, ) .unwrap(); @@ -404,6 +537,7 @@ fn removing_keeps_the_order_and_ignores_absent_ids() { None, "Three", connection(json!({ "host": "three" })), + Label::default(), &mut third_ids, ) .unwrap(); @@ -429,6 +563,7 @@ fn new_ids_are_drawn_until_one_is_valid_and_unused() { None, "One", connection(json!({ "host": "one" })), + Label::default(), &mut first, ) .unwrap(); @@ -436,9 +571,13 @@ fn new_ids_are_drawn_until_one_is_valid_and_unused() { .into_iter() .map(str::to_owned); let id = connections - .save(None, "Two", connection(json!({ "host": "two" })), || { - candidates.next().unwrap() - }) + .save( + None, + "Two", + connection(json!({ "host": "two" })), + Label::default(), + || candidates.next().unwrap(), + ) .unwrap(); assert_eq!(id, "fresh"); } @@ -454,7 +593,13 @@ fn the_list_holds_at_most_128_connections() { ); } assert_eq!( - connections.save(None, "One more", connection(json!({ "host": "h" })), ids()), + connections.save( + None, + "One more", + connection(json!({ "host": "h" })), + Label::default(), + ids() + ), Err(ConnectionError::at("connections", Reason::Full)) ); // Editing an entry still works when the list is full. @@ -464,6 +609,7 @@ fn the_list_holds_at_most_128_connections() { Some(&id), "Host 0", connection(json!({ "host": "h0", "port": 22 })), + Label::default(), ids() ) .is_ok()); @@ -550,6 +696,27 @@ fn stored_documents_are_checked_like_edits() { "connections", Reason::Full, ), + ( + document( + json!([{ "id": "a", "name": "One", "connection": { "host": "h" }, "group": " Prod" }]), + ), + "group", + Reason::Invalid, + ), + ( + document( + json!([{ "id": "a", "name": "One", "connection": { "host": "h" }, "group": "" }]), + ), + "group", + Reason::Required, + ), + ( + document( + json!([{ "id": "a", "name": "One", "connection": { "host": "h" }, "color": "pink" }]), + ), + "document", + Reason::Invalid, + ), (" ".repeat(MAX_BYTES + 1), "document", Reason::TooLong), ] { assert_eq!( diff --git a/rust/crates/workspace/src/connections.rs b/rust/crates/workspace/src/connections.rs index 47e75d16..01d85e82 100644 --- a/rust/crates/workspace/src/connections.rs +++ b/rust/crates/workspace/src/connections.rs @@ -9,7 +9,7 @@ use crate::sessions::nonce; use lithe_protocol::{CoreError, ErrorCode}; use lithe_remote::client::connections::{ - self, ConnectionError, Connections, Reason, SshConnection, + self, Color, ConnectionError, Connections, Label, Reason, SshConnection, }; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -37,7 +37,8 @@ pub struct EditRequest { remember_folder: Option, } -/// Adds a connection, or replaces the entry `id`. +/// Adds a connection, or replaces the entry `id`. A missing `color` or +/// `group` saves the entry without one. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct SaveRequest { @@ -45,6 +46,10 @@ struct SaveRequest { id: Option, name: String, connection: SshConnection, + #[serde(default)] + color: Option, + #[serde(default)] + group: Option, } #[derive(Deserialize)] @@ -74,10 +79,15 @@ const STORAGE: Storage = Storage { maximum_bytes: connections::MAX_BYTES, }; -/// Reads the document. +/// Reads the document. `sections` lists the entry ids by group, in the +/// order the window shows them. pub fn list(request: ListRequest) -> Result { let connections = parse(request.document.as_deref())?; - Ok(json!({ "connections": connections.entries(), "storage": STORAGE })) + Ok(json!({ + "connections": connections.entries(), + "sections": connections.sections(), + "storage": STORAGE, + })) } /// Applies one edit. An edit that changes nothing returns a `null` @@ -89,9 +99,19 @@ pub fn edit(request: EditRequest) -> Result { let mut id = None; match (request.save, request.remove, request.remember_folder) { (Some(save), None, None) => { + let label = Label { + color: save.color, + group: save.group, + }; id = Some( after - .save(save.id.as_deref(), &save.name, save.connection, nonce) + .save( + save.id.as_deref(), + &save.name, + save.connection, + label, + nonce, + ) .map_err(invalid_request)?, ); } @@ -116,6 +136,7 @@ pub fn edit(request: EditRequest) -> Result { "changed": changed, "document": document, "connections": after.entries(), + "sections": after.sections(), }); if let Some(id) = id { result["id"] = json!(id); diff --git a/rust/crates/workspace/src/connections/tests.rs b/rust/crates/workspace/src/connections/tests.rs index 37dee133..66a8432d 100644 --- a/rust/crates/workspace/src/connections/tests.rs +++ b/rust/crates/workspace/src/connections/tests.rs @@ -16,6 +16,7 @@ fn details(error: &CoreError) -> Value { fn a_missing_document_lists_nothing_and_says_where_to_keep_one() { let result = list(list_request(json!({ "document": null }))).unwrap(); assert_eq!(result["connections"], json!([])); + assert_eq!(result["sections"], json!([])); assert_eq!( result["storage"], json!({ "relativePath": "remote/connections.json", "maximumBytes": 262144 }) @@ -40,6 +41,53 @@ fn saving_returns_the_document_to_write_and_the_new_id() { assert_eq!(listed["connections"], result["connections"]); } +#[test] +fn colors_and_groups_are_saved_and_listed_by_section() { + let first = edit(edit_request(json!({ + "document": null, + "save": { + "name": "Web", + "connection": { "host": "web.example" }, + "color": "green", + "group": " Production ", + }, + }))) + .unwrap(); + let web = first["id"].as_str().expect("id").to_owned(); + assert_eq!(first["connections"][0]["color"], json!("green")); + assert_eq!(first["connections"][0]["group"], json!("Production")); + let second = edit(edit_request(json!({ + "document": first["document"], + "save": { "name": "Lab", "connection": { "host": "lab.example" } }, + }))) + .unwrap(); + let lab = second["id"].as_str().expect("id").to_owned(); + assert!(second["connections"][1].get("color").is_none()); + assert!(second["connections"][1].get("group").is_none()); + let sections = json!([ + { "group": "Production", "ids": [web] }, + { "group": null, "ids": [lab] }, + ]); + assert_eq!(second["sections"], sections); + let listed = list(list_request(json!({ "document": second["document"] }))).unwrap(); + assert_eq!(listed["sections"], sections); + + let error = edit(edit_request(json!({ + "document": null, + "save": { "name": "Box", "connection": { "host": "box" }, "group": "a\u{7}b" }, + }))) + .expect_err("control character"); + assert_eq!( + details(&error), + json!({ "field": "group", "reason": "invalid" }) + ); + assert!(serde_json::from_value::(json!({ + "document": null, + "save": { "name": "Box", "connection": { "host": "box" }, "color": "pink" }, + })) + .is_err()); +} + #[test] fn an_edit_that_changes_nothing_returns_no_document() { let result = edit(edit_request(json!({