Visual Studio Code, rebuilt in Rust
Rust
fix(settings-import): install extensions like a profile import
rokartur7764f129feaf
diff --git a/native/crates/app/src/settings_import.rs b/native/crates/app/src/settings_import.rsindex f90173c394e..eab1cd45450 100644--- a/native/crates/app/src/settings_import.rs+++ b/native/crates/app/src/settings_import.rs@@ -38,10 +38,14 @@ pub struct Import {pub settings: Map<String, Value>,/// The `keybindings.json` entries.pub keybindings: Vec<Value>,+ /// `keybindings.json` as written, comments included.+ pub keybindings_text: String,/// Snippet files by their name in the snippets folder.pub snippets: Vec<(String, PathBuf)>,/// Gallery extension ids, lowercased.pub extensions: Vec<String>,+ /// The ones of `extensions` disabled there.+ pub disabled_extensions: Vec<String>,}/// Setting prefixes of removed features.@@ -101,7 +105,9 @@ pub fn read(source: &Source) -> Import {import.settings.insert(key, value);}}- if let Some(Value::Array(keybindings)) = parse(&source.user_dir.join("keybindings.json")) {+ let keybindings_text = std::fs::read_to_string(source.user_dir.join("keybindings.json")).unwrap_or_default();+ if let Some(Value::Array(keybindings)) = json::parse(&keybindings_text, &mut Vec::new(), parse_options()) {+ import.keybindings_text = keybindings_text;let removed = |entry: &Value| entry["command"].as_str().is_some_and(|command| command.trim_start_matches('-').starts_with("github.copilot") || command.contains(".chat.") || command.starts_with("inlineChat."));import.keybindings = keybindings.into_iter().filter(|entry| !removed(entry)).collect();}@@ -113,6 +119,12 @@ pub fn read(source: &Source) -> Import {}import.snippets.sort();import.extensions = extension_ids(&source.extensions_dir).into_iter().filter(|id| !is_removed_extension(id)).collect();+ // The default profile's `extensionsIdentifiers/disabled` (extensionEnablementService.ts).+ let disabled = storage::read_item(&source.user_dir.join("globalStorage/state.vscdb"), "extensionsIdentifiers/disabled");+ if let Some(Ok(Value::Array(disabled))) = disabled.map(|disabled| serde_json::from_str(&disabled)) {+ let ids: Vec<String> = disabled.iter().filter_map(|identifier| identifier["id"].as_str().map(str::to_lowercase)).collect();+ import.disabled_extensions = import.extensions.iter().filter(|id| ids.contains(id)).cloned().collect();+ }import}@@ -164,10 +176,15 @@ pub fn write(import: &Import, target: &Target, configuration: &Configuration) ->}if !import.keybindings.is_empty() {let mut text = std::fs::read_to_string(target.keybindings).unwrap_or_else(|_| "[]".into());- let existing = match json::parse(&text, &mut Vec::new(), parse_options()) {+ let mut existing = match json::parse(&text, &mut Vec::new(), parse_options()) {Some(Value::Array(existing)) => existing,_ => Vec::new(),};+ if existing.is_empty() {+ // A profile without keybindings takes the file as written, comments included, less the left-out entries.+ (text, existing) = without_left_out_keybindings(import, configuration, target.keybindings);+ written.keybindings += existing.len();+ }let options = formatting_options(&text, configuration, target.keybindings);for entry in import.keybindings.iter().filter(|entry| !existing.contains(entry)) {// jsonEdit.ts appends with index -1; the port's index is clamped to the array's length.@@ -189,6 +206,21 @@ pub fn write(import: &Import, target: &Target, configuration: &Configuration) ->Ok(written)}+/// The source's `keybindings.json` text without the entries `import.keybindings` left out, and the entries it keeps.+fn without_left_out_keybindings(import: &Import, configuration: &Configuration, path: &Path) -> (String, Vec<Value>) {+ let mut text = import.keybindings_text.clone();+ let Some(Value::Array(entries)) = json::parse(&text, &mut Vec::new(), parse_options()) else { return ("[]".into(), Vec::new()) };+ let options = formatting_options(&text, configuration, path);+ for (index, entry) in entries.iter().enumerate().rev() {+ if !import.keybindings.contains(entry) {+ let edits = set_property(&text, &[Segment::Index(index)], None, &options);+ text = apply_edits(&text, &edits);+ }+ }+ let kept = entries.into_iter().filter(|entry| import.keybindings.contains(entry)).collect();+ (text, kept)+}+fn parse(path: &Path) -> Option<Value> {json::parse(&std::fs::read_to_string(path).ok()?, &mut Vec::new(), parse_options())}diff --git a/native/crates/app/src/settings_import/tests.rs b/native/crates/app/src/settings_import/tests.rsindex b162c5af36d..606c8cd2a95 100644--- a/native/crates/app/src/settings_import/tests.rs+++ b/native/crates/app/src/settings_import/tests.rs@@ -68,3 +68,42 @@ fn writes_into_the_profile_keeping_what_it_has() {assert!(root.join("snippets/rust.json").is_file());std::fs::remove_dir_all(&root).unwrap();}++/// A profile without keybindings gets `keybindings.json` as the user wrote it: its comments stay.+#[test]+fn an_empty_profile_takes_keybindings_json_with_its_comments() {+ let root = std::env::temp_dir().join(format!("app-settings-import-comments-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ std::fs::create_dir_all(&root).unwrap();+ let configuration = config::service::Settings::load(config::registry::Registry::core(), root.join("User"), None).configuration;+ let target = Target { settings: &root.join("settings.json"), keybindings: &root.join("keybindings.json"), snippets_home: &root.join("snippets") };++ let written = write(&Import { snippets: Vec::new(), ..read(&source("VS Code")) }, &target, &configuration).unwrap();+ assert_eq!(written.keybindings, 1);+ let keybindings = std::fs::read_to_string(root.join("keybindings.json")).unwrap();+ // jsonEdit.ts `removeProperty` formats the lines it touches: the entry before the removed one.+ let expected = "// Place your key bindings in this file to override the defaults\n[\n\t{\n\t\t\"key\": \"cmd+k cmd+t\",\n\t\t\"command\": \"workbench.action.selectTheme\"\n\t}\n]";+ assert_eq!(keybindings.trim_end(), expected);+ std::fs::remove_dir_all(&root).unwrap();+}++/// The extensions VS Code has disabled (`extensionsIdentifiers/disabled` in its global storage) are read, and the+/// database is opened read-only.+#[test]+fn reads_the_disabled_extensions() {+ let home = std::env::temp_dir().join(format!("app-settings-import-disabled-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&home);+ let source = Source { name: "VS Code", user_dir: home.join("Code/User"), extensions_dir: home.join(".vscode/extensions") };+ std::fs::create_dir_all(source.user_dir.join("globalStorage")).unwrap();+ std::fs::create_dir_all(&source.extensions_dir).unwrap();+ std::fs::write(source.extensions_dir.join("extensions.json"), r#"[{ "identifier": { "id": "alpha.one" } }, { "identifier": { "id": "Beta.Two" } }]"#).unwrap();+ let database = source.user_dir.join("globalStorage/state.vscdb");+ storage::Storage::open(&database).set("extensionsIdentifiers/disabled", r#"[{ "id": "beta.two" }, { "id": "github.copilot-chat" }]"#.into());+ let modified = std::fs::metadata(&database).unwrap().modified().unwrap();++ let import = read(&source);+ assert_eq!(import.extensions, ["alpha.one", "beta.two"]);+ assert_eq!(import.disabled_extensions, ["beta.two"]);+ assert_eq!(std::fs::metadata(&database).unwrap().modified().unwrap(), modified);+ std::fs::remove_dir_all(&home).unwrap();+}diff --git a/native/crates/app/src/workbench.rs b/native/crates/app/src/workbench.rsindex ed4d07cbd27..49847afb767 100644--- a/native/crates/app/src/workbench.rs+++ b/native/crates/app/src/workbench.rs@@ -324,6 +324,8 @@ pub struct Workbench {pub(crate) extension_commands: HashMap<String, crate::commands::Registration>,/// Extension tests run: dialogs answer their default without showing (abstractFileDialogService.ts skipDialogs).pub skip_dialogs: bool,+ /// product.json `extensionsGallery.serviceUrl` of the installs; tests point it at a local gallery.+ pub(crate) gallery_url: String,pub host_colors: themes::HostColorScheme,/// The Dock icon last set for `window.appIcon`; `None` is the bundle's, what the app starts with.pub app_icon: Option<&'static [u8]>,@@ -719,6 +721,7 @@ impl Workbench {commands: Commands::default(),extension_commands: HashMap::new(),skip_dialogs: false,+ gallery_url: exthost::gallery::SERVICE_URL.into(),host_colors: themes::host_color_scheme(),app_icon: None,wait_files: Vec::new(),diff --git a/native/crates/app/src/workbench/configuration.rs b/native/crates/app/src/workbench/configuration.rsindex 0c5388985a4..555047a99f4 100644--- a/native/crates/app/src/workbench/configuration.rs+++ b/native/crates/app/src/workbench/configuration.rs@@ -123,6 +123,19 @@ impl Workbench {}}+ /// `restoreFileIconTheme`.+ pub(super) fn restore_file_icon_theme(&mut self) {+ match crate::settings_file_icons(&self.extensions, &self.settings.lock().unwrap()) {+ Ok(file_icons) => self.file_icons = file_icons,+ Err(error) => eprintln!("loading the file icon theme: {error:#}"),+ }+ }++ /// `restoreProductIconTheme`.+ pub(super) fn restore_product_icon_theme(&mut self) {+ self.product_icons = crate::product_icons::settings_product_icons(&self.extensions, &self.settings.lock().unwrap());+ }+/// `onDidChangeConfiguration` listeners of the workbench for a change already in the settings model.pub(super) fn configuration_changed(&mut self, change: &Change, before: Vec<CreationOptions>, cx: &mut Context<Self>) {self.host.send_configuration_change(&self.settings.lock().unwrap(), change);@@ -130,17 +143,11 @@ impl Workbench {if theme_keys.iter().any(|key| affects(change, key)) {self.restore_color_theme(cx);}- // `restoreFileIconTheme`if affects(change, "workbench.iconTheme") {- let file_icons = crate::settings_file_icons(&self.extensions, &self.settings.lock().unwrap());- match file_icons {- Ok(file_icons) => self.file_icons = file_icons,- Err(error) => eprintln!("loading the file icon theme: {error:#}"),- }+ self.restore_file_icon_theme();}- // `restoreProductIconTheme`if affects(change, "workbench.productIconTheme") {- self.product_icons = crate::product_icons::settings_product_icons(&self.extensions, &self.settings.lock().unwrap());+ self.restore_product_icon_theme();}if ["workbench.colorCustomizations", "editor.tokenColorCustomizations", "editor.semanticTokenColorCustomizations"].iter().any(|key| affects(change, key)) {self.customize_theme();diff --git a/native/crates/app/src/workbench/configuration/tests.rs b/native/crates/app/src/workbench/configuration/tests.rsindex e3776ad92d3..bfe2d0c5966 100644--- a/native/crates/app/src/workbench/configuration/tests.rs+++ b/native/crates/app/src/workbench/configuration/tests.rs@@ -64,6 +64,29 @@ fn an_edit_of_settings_json_on_disk_reaches_the_host_the_theme_and_the_models(cxstd::fs::remove_dir_all(dir).unwrap();}+/// workbenchThemeService.ts: the theme registries' `onDidChange` restores the themes the settings name, so themes+/// named before their extension is installed (an import) apply once it is.+#[gpui::test]+fn installed_extensions_bring_the_themes_the_settings_name(cx: &mut TestAppContext) {+ let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();+ let defaults = scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();+ let theme = load_theme(std::slice::from_ref(&defaults), "Dark 2026").unwrap();+ let dir = std::env::temp_dir().join(format!("code-gpui-configuration-install-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(dir.join("User")).unwrap();+ std::fs::write(dir.join("User/settings.json"), r#"{ "workbench.colorTheme": "Abyss", "workbench.iconTheme": "vs-seti" }"#).unwrap();+ let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), dir.join("User"), None)));+ let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx));+ let looks = |cx: &mut gpui::VisualTestContext| workbench.read_with(cx, |workbench, _| (workbench.theme.settings_id.clone(), workbench.file_icons.is_some()));+ assert_eq!(looks(cx), ("Dark 2026".to_owned(), false));++ let mut running = vec![defaults];+ running.extend(["theme-abyss", "theme-seti"].map(|name| scan_extension(&app_root.join("extensions").join(name), true).unwrap()));+ workbench.update(cx, |workbench, cx| workbench.set_running_extensions(running, cx));+ assert_eq!(looks(cx), ("Abyss".to_owned(), true));+ std::fs::remove_dir_all(dir).unwrap();+}+#[gpui::test]#[cfg(target_os = "macos")]fn the_app_icon_setting_swaps_the_dock_icon_and_follows_the_appearance(cx: &mut TestAppContext) {diff --git a/native/crates/app/src/workbench/extension_management.rs b/native/crates/app/src/workbench/extension_management.rsindex 8c454c99af1..136bf658aa0 100644--- a/native/crates/app/src/workbench/extension_management.rs+++ b/native/crates/app/src/workbench/extension_management.rs@@ -5,10 +5,10 @@ use std::path::PathBuf;use config::configuration::Overrides;use exthost::extension_management::Job;-use exthost::gallery::{Gallery, Operation};+use exthost::gallery::{ExtensionInfo, Gallery, Operation};use exthost::scan::ScannedExtension;use futures::channel::oneshot;-use gpui::{Context, PromptLevel, Window};+use gpui::{Context, PromptLevel, Task, Window};use serde_json::Value;use super::Workbench;@@ -16,7 +16,7 @@ use super::host_requests::uri_parts;use crate::commands::Outcome;use crate::file_dialog::FileDialog;use exthost::main_thread::serialized_error;-use crate::notifications::Severity;+use crate::notifications::{Notification, Progress, Severity};/// `SELECT_INSTALL_VSIX_EXTENSION_COMMAND_ID`.const SELECT_INSTALL_VSIX: &str = "workbench.extensions.action.installVSIX";@@ -153,11 +153,12 @@ impl Workbench {self.refresh_extensions_views(cx);}let trusted = self.user_trusted_publishers();+ let gallery = self.gallery();+ let download_gallery = self.gallery();let lookup = cx.background_executor().spawn(async move {if builtin {anyhow::bail!("The extension '{id}' cannot be installed because it was not found.");}- let gallery = Gallery::open_vsx(&crate::VERSION);let extension = gallery.installable_extension(&id, version.as_deref(), pre_release)?;let others = super::trusted_publishers::other_untrusted_publishers(&gallery, &extension, &trusted);Ok((extension, others))@@ -167,13 +168,13 @@ impl Workbench {// `installFromGallery`: `checkForTrustedPublishers` runs before the download.let download = async {let (extension, others) = lookup.await?;- let trust = workbench.update(cx, |workbench, cx| workbench.check_trusted_publishers(&extension, others, cx))??;+ let trust = workbench.update(cx, |workbench, cx| workbench.check_trusted_publishers(std::slice::from_ref(&extension), others, cx))??;if let Some(trust) = trust&& !trust.await.unwrap_or(false){anyhow::bail!(super::trusted_publishers::CANCELED);}- let gallery = Gallery::open_vsx(&crate::VERSION);+ let gallery = download_gallery;cx.background_executor().spawn(async move { gallery.download(&extension, operation, &downloads, verify_signature).map(|vsix| (vsix, extension)) }).await};let installed = match download.await {@@ -206,6 +207,71 @@ impl Workbench {Outcome::Pending(receiver)}+ /// The gallery the installs query: Open VSX unless a test points `gallery_url` elsewhere.+ pub(super) fn gallery(&self) -> Gallery {+ Gallery { service_url: self.gallery_url.clone(), product_version: crate::VERSION.clone() }+ }++ /// `ExtensionsResource.apply` with a token (userDataProfileImportExport.ts): the gallery extensions of `ids`, one+ /// `requestPublisherTrust` dialog for all their publishers, then `installFromGallery` one at a time with the+ /// progress in a notification. Answers the ids that did not install, each with why.+ pub(crate) fn install_gallery_extensions(&mut self, ids: Vec<String>, window: &mut Window, cx: &mut Context<Self>) -> Task<Vec<(String, String)>> {+ let gallery = self.gallery();+ let infos: Vec<ExtensionInfo> = ids.iter().map(|id| ExtensionInfo { id: id.clone(), ..ExtensionInfo::default() }).collect();+ let lookup = cx.background_executor().spawn(async move { gallery.get_extensions(&infos, false) });+ let mut notification = Notification::new(Severity::Info, "Installing Extensions...");+ notification.progress = Some(Progress { total: Some(ids.len() as f64), worked: Some(0.), ..Progress::default() });+ let progress = self.notify(notification);+ cx.spawn_in(window, async move |workbench, cx| {+ let mut failed = Vec::new();+ let found = match lookup.await {+ Ok(found) => found,+ Err(error) => {+ failed.extend(ids.iter().map(|id| (id.clone(), format!("{error:#}"))));+ Vec::new()+ }+ };+ for id in ids.iter().filter(|id| !found.iter().any(|extension| extension.id == **id)) {+ failed.push((id.clone(), format!("The extension '{id}' cannot be installed because it was not found.")));+ }+ let trust = workbench.update(cx, |workbench, cx| workbench.check_trusted_publishers(&found, Vec::new(), cx));+ let trusted = match trust {+ Ok(Ok(None)) => Ok(()),+ Ok(Ok(Some(answer))) => match answer.await.unwrap_or(false) {+ true => Ok(()),+ false => Err(super::trusted_publishers::CANCELED.to_owned()),+ },+ Ok(Err(error)) => Err(format!("{error:#}")),+ Err(_) => return failed,+ };+ if let Err(error) = trusted {+ failed.extend(found.iter().map(|extension| (extension.id.clone(), error.clone())));+ } else {+ for (index, extension) in found.iter().enumerate() {+ let installed = workbench.update(cx, |workbench, cx| {+ if let Some(item) = progress.and_then(|key| workbench.notifications.model.item_mut(key)) {+ item.update_message(&format!("Installing extension {}...", extension.display_name_or_id()));+ item.progress = Some(Progress { total: Some(found.len() as f64), worked: Some(index as f64), ..Progress::default() });+ }+ workbench.install_from_gallery(extension.id.clone(), None, false, cx)+ });+ let result = match installed {+ Ok(Outcome::Ready(result)) => result,+ Ok(Outcome::Pending(pending)) => pending.await.unwrap_or(Ok(Value::Null)),+ Err(_) => return failed,+ };+ if let Err(error) = result {+ failed.push((extension.id.clone(), error["message"].as_str().unwrap_or_default().to_owned()));+ }+ }+ }+ if let Some(key) = progress {+ let _ = workbench.update_in(cx, |workbench, window, cx| workbench.close_notification(key, window, cx));+ }+ failed+ })+ }+/// `MainThreadDownloadService.$download`, downloadService.ts: a file is copied, anything else is fetched with a GET.pub(crate) fn download_resource(&mut self, resource: &Value, target: &Value, cx: &mut Context<Self>) -> Outcome {let target = match uri_parts(target) {@@ -296,6 +362,10 @@ impl Workbench {crate::extension_point_messages::report(&running);self.host.set_running_extensions(&running);self.extensions = running;+ // workbenchThemeService.ts: a theme registry change restores the themes the settings name, which an install may have brought.+ self.restore_color_theme(cx);+ self.restore_file_icon_theme();+ self.restore_product_icon_theme();self.register_webview_view_commands();self.refresh_extensions_views(cx);cx.notify();diff --git a/native/crates/app/src/workbench/settings_import.rs b/native/crates/app/src/workbench/settings_import.rsindex bba8147ff58..821f9804639 100644--- a/native/crates/app/src/workbench/settings_import.rs+++ b/native/crates/app/src/workbench/settings_import.rs@@ -7,6 +7,7 @@ use serde_json::Value;use super::Workbench;use crate::commands::Outcome;+use crate::extension_enablement::{Enablement, EnablementState, Identifier};use crate::notifications::Severity;use crate::quick_input::{Entry, Item, Kind, QuickInput};use crate::settings_import::{self, Import, Source, Target};@@ -94,14 +95,16 @@ impl Workbench {settings: if chosen.contains(&0) { import.settings } else { Default::default() },keybindings: if chosen.contains(&1) { import.keybindings } else { Vec::new() },snippets: if chosen.contains(&2) { import.snippets } else { Vec::new() },+ keybindings_text: import.keybindings_text,extensions: if chosen.contains(&3) { import.extensions } else { Vec::new() },+ disabled_extensions: if chosen.contains(&3) { import.disabled_extensions } else { Vec::new() },};- let _ = workbench.update(cx, |workbench, cx| workbench.write_settings_import(source.name, import, cx));+ let _ = workbench.update_in(cx, |workbench, window, cx| workbench.write_settings_import(source.name, import, window, cx));}).detach();}- fn write_settings_import(&mut self, name: &str, import: Import, cx: &mut Context<Self>) {+ fn write_settings_import(&mut self, name: &'static str, import: Import, window: &mut Window, cx: &mut Context<Self>) {let Some(profile) = self.user_data_profiles.state.as_ref().map(|state| state.current.clone()) else { return };let settings_file = self.settings.lock().unwrap().user_files().settings.clone();let target = Target { settings: &settings_file, keybindings: &profile.keybindings_resource, snippets_home: &profile.snippets_home };@@ -113,8 +116,14 @@ impl Workbench {self.reload_changed_settings_files(cx);let installed: Vec<String> = self.extensions.iter().map(|extension| extension.id.to_lowercase()).collect();let missing: Vec<String> = import.extensions.into_iter().filter(|id| !installed.contains(id)).collect();- for id in &missing {- drop(self.install_from_gallery(id.clone(), None, false, cx));+ // extensionsResource.ts: an extension disabled there is disabled here before it is installed and started.+ let disabled: Vec<&String> = import.disabled_extensions.iter().filter(|id| missing.contains(id)).collect();+ if !disabled.is_empty() {+ let mut profile = self.profile_storage.lock().unwrap();+ let mut enablement = Enablement { profile: &mut profile, workspace: None };+ for id in disabled {+ enablement.set_user_state(&Identifier { id: id.clone(), uuid: None }, EnablementState::DisabledGlobally);+ }}let message = format!("Imported from {name}: {} settings, {} keyboard shortcuts, {} snippet files; installing {} extensions from Open VSX.",@@ -125,6 +134,20 @@ impl Workbench {);drop(self.prompt_notification(Severity::Info, message, &[]));cx.notify();+ if missing.is_empty() {+ return;+ }+ let failed = self.install_gallery_extensions(missing, window, cx);+ cx.spawn(async move |workbench, cx| {+ let failed = failed.await;+ if failed.is_empty() {+ return;+ }+ let lines: Vec<String> = failed.iter().map(|(id, reason)| format!("{id}: {reason}")).collect();+ let message = format!("Extensions from {name} that were not installed:\n{}", lines.join("\n"));+ let _ = workbench.update(cx, |workbench, _| workbench.notify_error(message));+ })+ .detach();}}@@ -175,4 +198,58 @@ mod tests {assert!(std::fs::read_to_string(keybindings).unwrap().contains("cmd+alt+7"));std::fs::remove_dir_all(dir).unwrap();}++ /// A gallery on localhost that answers every request with `body`.+ fn serve_gallery(body: String) -> String {+ use std::io::{Read, Write};+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ std::thread::spawn(move || {+ for mut stream in listener.incoming().flatten() {+ let _ = stream.read(&mut [0; 65536]);+ let reply = format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());+ let _ = stream.write_all(reply.as_bytes());+ }+ });+ url+ }++ /// extensionManagementService.ts `installGalleryExtensions`: the extensions of two untrusted publishers ask for+ /// trust once, in one dialog that names both.+ #[gpui::test]+ fn imported_extensions_ask_for_publisher_trust_once(cx: &mut TestAppContext) {+ let yaml: Value = serde_json::from_str(include_str!("../../../exthost/src/gallery/vscode-yaml-latest.json")).unwrap();+ let mut other = yaml.clone();+ other["publisher"]["publisherName"] = "beta".into();+ other["publisher"]["displayName"] = "Beta".into();+ other["extensionId"] = "00000000-0000-0000-0000-000000000002".into();+ let body = serde_json::json!({ "results": [{ "extensions": [yaml, other], "resultMetadata": [{ "metadataType": "ResultCount", "metadataItems": [{ "name": "TotalCount", "count": 2 }] }] }] });+ let gallery_url = serve_gallery(body.to_string());+ let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();+ let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();+ let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();+ let dir = std::env::temp_dir().join(format!("code-gpui-settings-import-trust-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ let user = dir.join("data/User");+ std::fs::create_dir_all(&user).unwrap();+ let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), user.clone(), None)));+ let (workbench, cx) = cx.add_window_view(|_, cx| {+ let mut profiles = crate::user_data_profile::UserDataProfilesService::load(&dir.join("data"), &dir.join("extensions"));+ let profile = profiles.resolve(None, None, false, false);+ cx.set_global(profiles);+ let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx);+ workbench.set_user_data_profiles(profile, cx);+ workbench.gallery_url = gallery_url;+ workbench+ });+ let ids = vec!["redhat.vscode-yaml".to_owned(), "beta.vscode-yaml".to_owned()];+ let import = Import { extensions: ids, disabled_extensions: vec!["beta.vscode-yaml".into()], ..Import::default() };+ workbench.update_in(cx, |workbench, window, cx| workbench.write_settings_import("VS Code", import, window, cx));+ cx.run_until_parked();+ let messages: Vec<String> = workbench.read_with(cx, |workbench, _| workbench.dialogs.iter().map(|shown| shown.dialog.message.clone()).collect());+ assert_eq!(messages, ["Do you trust publishers \"Red Hat\" and \"Beta\"?"]);+ let disabled = workbench.read_with(cx, |workbench, _| crate::extension_enablement::identifiers(&workbench.profile_storage.lock().unwrap(), crate::extension_enablement::DISABLED_EXTENSIONS_STORAGE_PATH));+ assert_eq!(disabled.iter().map(|identifier| identifier.id.as_str()).collect::<Vec<_>>(), ["beta.vscode-yaml"]);+ std::fs::remove_dir_all(dir).unwrap();+ }}diff --git a/native/crates/app/src/workbench/trusted_publishers.rs b/native/crates/app/src/workbench/trusted_publishers.rsindex 45414d51025..e6dca239de9 100644--- a/native/crates/app/src/workbench/trusted_publishers.rs+++ b/native/crates/app/src/workbench/trusted_publishers.rs@@ -86,14 +86,21 @@ impl Workbench {self.application_storage.lock().unwrap().set(STORAGE_KEY, Value::Object(trusted).to_string());}- /// `checkForTrustedPublishers` of one extension with its pack and dependencies: `None` when its publisher is- /// trusted, else the dialog's answer, true once "Trust Publisher & Install" trusted every publisher it names.- /// While extension tests run, DialogService.prompt refuses the dialog and the install fails.- pub(super) fn check_trusted_publishers(&mut self, extension: &GalleryExtension, others: Vec<Publisher>, cx: &mut Context<Self>) -> anyhow::Result<Option<oneshot::Receiver<bool>>> {- if extension.private || self.user_trusted_publishers().contains(&extension.publisher.to_lowercase()) {+ /// `checkForTrustedPublishers` of the extensions, `others` the publishers of one extension's pack and dependencies:+ /// `None` when every publisher is trusted, else the one dialog's answer, true once "Trust Publisher & Install"+ /// trusted every publisher it names. While extension tests run, DialogService.prompt refuses the dialog.+ pub(super) fn check_trusted_publishers(&mut self, extensions: &[GalleryExtension], others: Vec<Publisher>, cx: &mut Context<Self>) -> anyhow::Result<Option<oneshot::Receiver<bool>>> {+ let trusted = self.user_trusted_publishers();+ let untrusted: Vec<&GalleryExtension> = extensions.iter().filter(|extension| !extension.private && !trusted.contains(&extension.publisher.to_lowercase())).collect();+ if untrusted.is_empty() {return Ok(None);}- let mut publishers = vec![Publisher::of(extension)];+ let mut publishers: Vec<Publisher> = Vec::new();+ for extension in &untrusted {+ if !publishers.iter().any(|publisher| publisher.publisher == extension.publisher) {+ publishers.push(Publisher::of(extension));+ }+ }publishers.extend(others.iter().cloned());if self.skip_dialogs {anyhow::bail!("DialogService: refused to show dialog in tests. Contents: {}", title(&publishers));@@ -103,7 +110,7 @@ impl Workbench {icon: "warning",message: title(&publishers),detail: None,- details: details(extension, &others, &publishers),+ details: details(&untrusted, &others, &publishers),inputs: Vec::new(),checkbox: None,checkbox_checked: false,@@ -179,7 +186,12 @@ fn title(publishers: &[Publisher]) -> String {}/// The dialog's markdown, one paragraph per `appendText('\n')`.-fn details(extension: &GalleryExtension, others: &[Publisher], publishers: &[Publisher]) -> Vec<String> {+fn details(untrusted: &[&GalleryExtension], others: &[Publisher], publishers: &[Publisher]) -> Vec<String> {+ let [extension] = untrusted else {+ let (first, last) = (&publishers[0], &publishers[publishers.len() - 1]);+ let first = format!("This is the first time you're installing extensions from publishers {} and {}.", publisher_link(first), publisher_link(last));+ return publisher_paragraphs(first, publishers);+ };let mut first = format!("The extension {} is published by {}.", extension_link(extension), publisher_link(&Publisher::of(extension)));if others.is_empty() {first.push_str(" This is the first extension you're installing from this publisher.");@@ -194,6 +206,11 @@ fn details(extension: &GalleryExtension, others: &[Publisher], publishers: &[Pub};first.push_str(&format!(" Installing this extension will also install [extensions]({command}) published by {named}. This is the first time you're installing extensions from these publishers."));}+ publisher_paragraphs(first, publishers)+}++/// The first paragraph, then the publishers' verification and the closing warning.+fn publisher_paragraphs(first: String, publishers: &[Publisher]) -> Vec<String> {let mut paragraphs = vec![first];let verified: Vec<&Publisher> = publishers.iter().filter(|publisher| publisher.domain.as_ref().is_some_and(|(_, verified)| *verified)).collect();let unverified: Vec<&Publisher> = publishers.iter().filter(|publisher| !publisher.domain.as_ref().is_some_and(|(_, verified)| *verified)).collect();@@ -302,7 +319,7 @@ mod tests {let publishers = [Publisher::of(&extension)];assert_eq!(title(&publishers), "Do you trust the publisher \"MS-CEINTL\"?");assert_eq!(- details(&extension, &[], &publishers),+ details(&[&extension], &[], &publishers),["The extension [Deutsch Language Pack](https://open-vsx.org/extension/MS-CEINTL/pack) is published by MS\\-CEINTL. This is the first extension you're installing from this publisher.","$(unverified) MS\\-CEINTL is [**not** verified](https://aka.ms/vscode-verify-publisher).",@@ -311,6 +328,17 @@ mod tests {);}+ /// extensionManagementService.ts `multiInstallMessage`: several extensions name the first and the last publisher.+ #[test]+ fn several_extensions_name_their_first_and_last_publisher() {+ let extensions = [extension("alpha", "Alpha", None), extension("beta", "Beta", None), extension("gamma", "Gamma", None)];+ let publishers: Vec<Publisher> = extensions.iter().map(Publisher::of).collect();+ assert_eq!(title(&publishers), "Do you trust the publisher \"Alpha\" and 2 others?");+ let details = details(&extensions.iter().collect::<Vec<_>>(), &[], &publishers);+ assert_eq!(details[0], "This is the first time you're installing extensions from publishers [Alpha](https://open-vsx.org/namespace/alpha) and [Gamma](https://open-vsx.org/namespace/gamma).");+ assert_eq!(details[1], "$(unverified) All publishers are [**not** verified](https://aka.ms/vscode-verify-publisher).");+ }+#[test]fn gallery_links_cannot_add_command_links() {assert_eq!(gallery_href("command:workbench.action.quit"), None);@@ -327,7 +355,7 @@ mod tests {let mut publishers = vec![Publisher::of(&pack)];publishers.extend(others.iter().cloned());assert_eq!(title(&publishers), "Do you trust the publisher \"Alpha\" and 2 others?");- let details = details(&pack, &others, &publishers);+ let details = details(&[&pack], &others, &publishers);assert!(details[0].contains("Installing this extension will also install [extensions](command:extension.open?%5B%22alpha.pack%22%2C%22extensionPack%22%5D) published by [Beta](https://open-vsx.org/namespace/beta) and [Gamma Inc\\.](https://open-vsx.org/namespace/gamma)."));assert_eq!(details[1], "$(verified-filled) [Alpha](https://open-vsx.org/namespace/alpha) has verified ownership of [$(link-external) example\\.com](https://example.com).");assert_eq!(details[2], "$(unverified) [Beta](https://open-vsx.org/namespace/beta) and [Gamma Inc\\.](https://open-vsx.org/namespace/gamma) are [**not** verified](https://aka.ms/vscode-verify-publisher).");@@ -346,7 +374,7 @@ mod tests {workbench.skip_dialogs = true;workbench});- let refused = workbench.update(cx, |workbench, cx| workbench.check_trusted_publishers(&extension("ms-vscode", "ms-vscode", None), Vec::new(), cx)).unwrap_err();+ let refused = workbench.update(cx, |workbench, cx| workbench.check_trusted_publishers(&[extension("ms-vscode", "ms-vscode", None)], Vec::new(), cx)).unwrap_err();assert_eq!(refused.to_string(), "DialogService: refused to show dialog in tests. Contents: Do you trust the publisher \"ms-vscode\"?");workbench.read_with(cx, |workbench, _| assert!(workbench.dialogs.is_empty()));}diff --git a/native/crates/exthost/src/gallery.rs b/native/crates/exthost/src/gallery.rsindex 1179acd754c..fdb1669581d 100644--- a/native/crates/exthost/src/gallery.rs+++ b/native/crates/exthost/src/gallery.rs@@ -92,7 +92,7 @@ pub struct GalleryExtension {}impl GalleryExtension {- fn display_name_or_id(&self) -> &str {+ pub fn display_name_or_id(&self) -> &str {if self.display_name.is_empty() { &self.id } else { &self.display_name }}}diff --git a/native/crates/storage/src/lib.rs b/native/crates/storage/src/lib.rsindex 096e5c39a21..9ba7f83fd3d 100644--- a/native/crates/storage/src/lib.rs+++ b/native/crates/storage/src/lib.rs@@ -127,6 +127,13 @@ impl Drop for Storage {}}+/// One item of a database another app owns (an import): opened read-only, so neither the file nor its journal+/// changes; `None` when the file or the key is missing or the database is locked.+pub fn read_item(path: &Path, key: &str) -> Option<String> {+ let connection = Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX).ok()?;+ connection.query_row("SELECT value FROM ItemTable WHERE key = ?1", params![key], |row| row.get_ref(0).map(text)).ok()+}+fn connect(path: &Path) -> (Connection, bool) {let error = match do_connect(path) {Ok(connection) => return (connection, false),diff --git a/port/ledger.md b/port/ledger.mdindex 393f4da69e1..54af0643242 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -662,6 +662,6 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston| telemetry/source-search | cross-cutting check | M19 | verified | | port/tools/telemetry-source-check: no telemetry or experimentation endpoint in the release binary, out-exthost and the 86 shipped built-ins with their 339 resolved packages (18370 files); SELF_TEST=1 finds 9 files in the inert packages || telemetry/network-capture | cross-cutting check | M19 | verified | | port/tools/network-capture, 600 s with no user action, fresh user data: folder window (eager git, npm, github activated) and empty window, no outbound traffic from the app's process tree; the control curl is seen each run. An earlier folder run with traffic was another session's keystrokes opening JSON files (json-language-features schema downloads), so runs take the Studio GUI lock || gallery/open-vsx | cross-cutting check | M18 | verified | | exthost/src/gallery.rs: query, latest-version resource, version choice, download with signature check; cargo test -p exthost gallery (upstream extensionGalleryService.test.ts sorting and filterLatestExtensionVersionsForTargetPlatform cases, Open VSX resource fixture); `workbench.extensions.installExtension redhat.vscode-yaml` downloads 2.0.0 from open-vsx.org, verifies it and activates without restart, not-found errors as upstream: PORT_GALLERY=1 port/tools/extensions-check |-| port/settings-import | port feature | M10 | verified | | app/src/settings_import.rs and workbench/settings_import.rs: `Preferences: Import from VS Code, Cursor or VSCodium...` and a first-run offer read `~/Library/Application Support/{Code,Cursor,VSCodium}/User` (settings.json, keybindings.json, snippets, the theme ids with the settings) and `~/.vscode/extensions`, `~/.cursor/extensions`, `~/.vscode-oss/extensions`, show the parts with their counts, write into the current profile and install the extensions from Open VSX; AI, sign-in, telemetry, remote and the editors' own settings and extensions are left out. The contents pick starts with every part checked (`picked` selects with `canSelectMany`, quickInputController.ts `pick`). cargo test -p app settings_import (5 passed, `accepting_the_contents_pick_imports_every_part` fails when the checked items do not start selected) on port/fixtures/settings-import; release GUI on the host lane, one import each from VS Code, Cursor and VSCodium fixtures under a scratch HOME through the command palette: settings, keybindings and snippets land in the profile's User folder, `cursor.*` dropped |+| port/settings-import | port feature | M10 | verified | | app/src/settings_import.rs and workbench/settings_import.rs: `Preferences: Import from VS Code, Cursor or VSCodium...` and a first-run offer read `~/Library/Application Support/{Code,Cursor,VSCodium}/User` (settings.json, keybindings.json, snippets, the theme ids with the settings) and `~/.vscode/extensions`, `~/.cursor/extensions`, `~/.vscode-oss/extensions`, show the parts with their counts, write into the current profile and install the extensions from Open VSX as a profile import does (userDataProfileImportExportService.ts, extensionsResource.ts `apply`): one gallery query, one publisher trust dialog for all publishers (extensionManagementService.ts `installGalleryExtensions`), an "Installing Extensions..." progress notification and an error that names each extension not installed with why; the extensions VS Code has disabled (`extensionsIdentifiers/disabled` in its `globalStorage/state.vscdb`, read-only) are disabled before they install; a profile without keybindings gets `keybindings.json` as written, comments included; the color, file icon and product icon themes the settings name apply once their extension is installed (workbenchThemeService.ts registry `onDidChange`); AI, sign-in, telemetry, remote and the editors' own settings and extensions are left out. The contents pick starts with every part checked (`picked` selects with `canSelectMany`, quickInputController.ts `pick`). cargo test -p app settings_import installed_extensions_bring (9 passed, `accepting_the_contents_pick_imports_every_part` fails when the checked items do not start selected, `imported_extensions_ask_for_publisher_trust_once` fails with one dialog per extension, `installed_extensions_bring_the_themes_the_settings_name` fails without the restore on `set_running_extensions`, `an_empty_profile_takes_keybindings_json_with_its_comments` and `reads_the_disabled_extensions` fail without their fixes) on port/fixtures/settings-import; release GUI on the host lane, one import each from VS Code, Cursor and VSCodium fixtures under a scratch HOME through the command palette: settings, keybindings and snippets land in the profile's User folder, `cursor.*` dropped || look/screenshot-diff | cross-cutting check | | verified | | port/tools/pixel-check: CDP reference capture and Metal readback in 3 themes, pixeldiff reference vs itself 0 different; baseline in port/results/pixels.md || perf/memory-benchmark | cross-cutting check | | verified | | port/tools/bench (Wu method), 3 runs on Studio; port/results/benchmark.md: exthost Bun 57 MiB, Node 98 MiB, reference 151 MiB |diff --git a/port/notes.md b/port/notes.mdindex ca73f193e2d..7d8b7c61578 100644--- a/port/notes.md+++ b/port/notes.md@@ -174,7 +174,7 @@ Done when: api-tests `configuration.test` and `state.test` pass as in the refere- Profiles at startup (`app/src/user_data_profile.rs`, windowsMainService.ts `resolveProfileForBrowserWindow`): `--profile <name>` (created when missing), `--profile-temp` (main.rs `CliProfile`, `forceProfile`/`forceTempProfile`: only the window a command line opens, the first start's or a second instance's; without paths that start opens just its new empty window, as app.ts and launchMainService.ts; windows from the menu take the workspace's profile), else the workspace's association, else `window.newWindowProfile`, else the default; the choice is associated with the workspace unless the window develops an extension. The profile gives the settings, tasks and mcp files (`config::service::UserFiles`), the keybindings file, `state.vscdb` of its global storage and its `extensions.json` (`UserExtensions::extensions_file`; an uninstalled folder stays while another profile's extensions.json lists it). A profile with its own settings reads the default profile's application settings and `workbench.settings.applyToAllProfiles` as the application layer, its own file with PROFILE_SCOPES (cargo test -p config profile_tests). The user snippets folder is not read by the port yet (no user snippets loader); the profile's `snippets` folder is used by export, import and settings import.- Switching profiles (`workbench/user_data_profile.rs` `change_current_profile`): the settings layers, keybindings, profile storage and user extensions move to the new profile's files, then `workbench/extension_host_restart.rs` restarts the host, since the port has no window reload: the session thread sends Terminate, the workbench drops what the host registered (commands, language features, SCM, webview views, URI handlers and openers, the host's markers), and a new session starts with the current extensions, settings and storage. `workbench.action.restartExtensionHost` uses the same path. StorageScope.APPLICATION keys stay in the default profile's state.vscdb across switches (`application_storage`, the same storage as `profile_storage` in the default profile). The extension under development runs again without its tests.- Profiles editor (`workbench/profiles_editor_view.rs`): the modal part with the sidebar and the contents view, rename, Use for Current/New Windows, Contents, Folders & Workspaces, the new profile form (Copy from a profile or an imported template, the Copy, Default or None source of each resource) and Export/Import of `.code-profile` files from a file or a URL (`app/src/profile_template.rs`). A non-default profile's Source radio writes its `useDefaultFlags`; for the current profile the window switches to the updated profile. The Icon row opens the icon picker (`workbench/icon_select_box.rs`, iconSelectBox.ts with the `iconSelectBox.*` commands): Search icons over the 83 `ICONS` in 36px cells, 12 a row, in a sticky hover under the icon. The activity bar's Manage item shows the current profile's icon, or the two-letter profile badge when it has none (globalCompositeBar.ts). The new profile form is named `Untitled N`, keeps Cancel, Preview and Create (Replace when a copy takes an existing name) under its scrolling body and validates as `NewProfileElement.validate`; its sidebar row has the dirty dot, Cancel and, while copying a profile, Export.... shortcut: Preview stores its profile instead of a transient one (each window is its own process, a transient profile would not reach the preview window); Cancel removes it. port/results/profiles.md.-- Settings import (`app/src/settings_import.rs`, `workbench/settings_import.rs`; Artur, no upstream counterpart): Preferences: Import from VS Code, Cursor or VSCodium..., and an offer on the first start with the default user data (no `--user-data-dir`) and no settings.json yet, shown once (`settingsImport.offered` in application storage). Keybindings already present are not duplicated; existing snippet files are kept; extensions are installed from Open VSX. Fixtures in port/fixtures/settings-import.+- Settings import (`app/src/settings_import.rs`, `workbench/settings_import.rs`; Artur, no upstream counterpart): Preferences: Import from VS Code, Cursor or VSCodium..., and an offer on the first start with the default user data (no `--user-data-dir`) and no settings.json yet, shown once (`settingsImport.offered` in application storage). Keybindings already present are not duplicated; existing snippet files are kept; extensions are installed from Open VSX. The first import installed one extension at a time, each with its own publisher trust dialog queued behind the others, and dropped their results; it now runs like a profile import (one query, one trust dialog, progress, the failures listed), disables what VS Code has disabled, keeps keybindings.json comments when the profile has no keybindings yet, and the theme settings apply when their extension arrives. Settings the port removed (chat.*, github.copilot.*, the AI search toggle) stay left out by design. Fixtures in port/fixtures/settings-import.- configuration-editing's own tests run with `port/tools/extension-tests configuration-editing` (a built-in extension's out/test from the reference checkout, against vsrustium): 18 passing. They needed `_executeCompletionItemProvider` and `_executeLinkProvider` to send cancellation tokens (`host.call_cancellable`, as rpcProtocol.ts does for a method whose last parameter is a token), `$acceptLanguageIds` at host start and restart (`vscode.languages.getLanguages`), `getContextKeyInfo` (the reference's `RawContextKey.all()`, dumped by `port/tools/ref-commands` into `contextkey/reference-context-keys.json`; rerun it when the reference moves) and the development copy of a built-in keeping `isBuiltin` (`scanExtensionsUnderDevelopment`), which `@vscode/internal-github`'s allowlist checks. The extensions.json cases expect `ms-vscode.js-debug`: the Studio mirror needs `port/tools/fetch-builtin-extensions` once.### Milestone 10 handoff (next session)