Clarify managed resource approval notifications

This commit is contained in:
Piotr Osiewicz
2026-11-26 14:51:31 +01:00
parent 432d4c4b78
commit 1573b8fd89
6 changed files with 178 additions and 46 deletions
@@ -84,6 +84,57 @@ pub trait ManagedResource: Sized + Send + Sync + 'static {
) -> anyhow::Result<ResourceAcquisition<Self>>;
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PermissionText {
Plain(String),
Emphasis(String),
Code(String),
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PermissionDescription(pub Vec<PermissionText>);
impl PermissionDescription {
pub fn text(mut self, text: impl Into<String>) -> Self {
self.0.push(PermissionText::Plain(text.into()));
self
}
pub fn emphasis(mut self, text: impl Into<String>) -> Self {
self.0.push(PermissionText::Emphasis(text.into()));
self
}
pub fn code(mut self, text: impl Into<String>) -> Self {
self.0.push(PermissionText::Code(text.into()));
self
}
}
impl From<String> for PermissionDescription {
fn from(text: String) -> Self {
Self::default().text(text)
}
}
impl From<&str> for PermissionDescription {
fn from(text: &str) -> Self {
Self::default().text(text)
}
}
impl std::fmt::Display for PermissionDescription {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for span in &self.0 {
let (PermissionText::Plain(text)
| PermissionText::Emphasis(text)
| PermissionText::Code(text)) = span;
formatter.write_str(text)?;
}
Ok(())
}
}
pub trait ManagedResourceCommand<Resource: ManagedResource>: Sized + 'static {
type Output: 'static;
type PermissionSettings: serde::de::DeserializeOwned + Default;
@@ -93,7 +144,7 @@ pub trait ManagedResourceCommand<Resource: ManagedResource>: Sized + 'static {
fn permission(&self, settings: &Self::PermissionSettings) -> Option<ResourcePermission>;
/// Describe the specific operation for approval without performing it.
fn permission_description(&self, resource: &Resource) -> String;
fn permission_description(&self, resource: &Resource) -> PermissionDescription;
/// Await background work so completion, errors, and cancellation follow this command.
fn run(
@@ -111,18 +162,20 @@ pub enum ResourcePermissionRequest {
},
ExecuteCommand {
resource: ResourceId,
description: String,
description: PermissionDescription,
payload: serde_json::Value,
bill: ResourceExecutionBill,
},
}
impl ResourcePermissionRequest {
pub fn description(&self) -> String {
pub fn summary(&self) -> PermissionDescription {
let (resource, operation, bill) = match self {
Self::Manage { resource, bill } => (
resource,
"Let Zed manage this binary (including network checks, downloads, and updates)",
PermissionDescription::default()
.emphasis("manage this binary")
.text(" (check for updates, download and update)"),
bill,
),
Self::ExecuteCommand {
@@ -130,23 +183,44 @@ impl ResourcePermissionRequest {
description,
bill,
..
} => (resource, description.as_str(), bill),
} => (resource, description.clone(), bill),
};
let requester = match &bill.root {
ExecutionBillRoot::Extension { id } => format!("Extension {id}"),
ExecutionBillRoot::Debugger { name } => format!("Debugger {name}"),
ExecutionBillRoot::LanguageServer { name } => format!("Language server {name}"),
ExecutionBillRoot::Formatter { name } => format!("Formatter {name}"),
ExecutionBillRoot::AgentServer { name } => format!("Agent server {name}"),
};
let mut summary = PermissionDescription::default()
.text(requester)
.text(" wants to ");
summary.0.extend(operation.0);
if matches!(self, Self::Manage { .. }) {
let ResourceId::Npm { payload } = resource;
summary = summary.text(": ").code(&payload.name);
}
summary
}
pub fn details(&self) -> String {
let (resource, bill) = match self {
Self::Manage { resource, bill } | Self::ExecuteCommand { resource, bill, .. } => {
(resource, bill)
}
};
let ResourceId::Npm { payload } = resource;
let requester = match &bill.root {
ExecutionBillRoot::Extension { id } => format!("Extension: {id}"),
ExecutionBillRoot::Debugger { name } => format!("Debugger: {name}"),
ExecutionBillRoot::LanguageServer { name } => format!("Language server: {name}"),
ExecutionBillRoot::Formatter { name } => format!("Formatter: {name}"),
ExecutionBillRoot::AgentServer { name } => format!("Agent server: {name}"),
};
let mut description = format!("{operation}\n\nnpm runtime: {}\n{requester}", payload.name);
let mut description = format!("npm runtime: {}", payload.name);
for reason in &bill.reasoning {
description.push('\n');
description.push_str(reason);
}
description
}
pub fn description(&self) -> String {
format!("{}\n\n{}", self.summary(), self.details())
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -902,7 +976,7 @@ mod tests {
.map(|rule| rule.permission)
}
fn permission_description(&self, resource: &Counter<KIND>) -> String {
fn permission_description(&self, resource: &Counter<KIND>) -> PermissionDescription {
let operation = match self {
Self::Read => "Read".into(),
Self::Add(value) => format!("Add {value}"),
@@ -914,6 +988,7 @@ mod tests {
"{operation} (current value: {})",
resource.value.load(SeqCst)
)
.into()
}
async fn run(
@@ -1858,7 +1933,7 @@ mod tests {
panic!("a conflicting resource must not check command permissions")
}
fn permission_description(&self, _: &Self) -> String {
fn permission_description(&self, _: &Self) -> PermissionDescription {
panic!("a conflicting resource must not request command approval")
}
+43 -23
View File
@@ -168,8 +168,9 @@ impl ManagedResourceCommand<Npm> for NodeBinaryPath {
.map(|rule| rule.permission)
}
fn permission_description(&self, _: &Npm) -> String {
"Get the Node.js executable path".into()
fn permission_description(&self, _: &Npm) -> managed_resources::PermissionDescription {
managed_resources::PermissionDescription::default()
.emphasis("get the Node.js executable path")
}
async fn run(self, npm: &Npm, _: &gpui::BackgroundExecutor) -> Self::Output {
@@ -198,13 +199,13 @@ impl ManagedResourceCommand<Npm> for LatestNpmPackageVersion {
.map(|rule| rule.permission)
}
fn permission_description(&self, _: &Npm) -> String {
let description = format!(
"Query the npm registry for the latest version of {}",
self.package
);
fn permission_description(&self, _: &Npm) -> managed_resources::PermissionDescription {
let description = managed_resources::PermissionDescription::default()
.emphasis("query the npm registry")
.text(" for the latest version of ")
.code(&self.package);
match &self.requirement {
Some(requirement) => format!("{description} matching {requirement}"),
Some(requirement) => description.text(" matching ").code(requirement.to_string()),
None => description,
}
}
@@ -237,11 +238,13 @@ impl ManagedResourceCommand<Npm> for InstalledNpmPackageVersion {
.map(|rule| rule.permission)
}
fn permission_description(&self, _: &Npm) -> String {
format!(
"Look up the installed version of {} in {:?}",
self.package, self.directory
)
fn permission_description(&self, _: &Npm) -> managed_resources::PermissionDescription {
managed_resources::PermissionDescription::default()
.emphasis("look up the installed version")
.text(" of ")
.code(&self.package)
.text(" in ")
.code(self.directory.display().to_string())
}
async fn run(self, npm: &Npm, _: &gpui::BackgroundExecutor) -> Self::Output {
@@ -268,11 +271,19 @@ impl ManagedResourceCommand<Npm> for InstallNpmPackages {
.map(|rule| rule.permission)
}
fn permission_description(&self, _: &Npm) -> String {
format!(
"Install npm packages {:?} in {:?}",
self.packages, self.directory
)
fn permission_description(&self, _: &Npm) -> managed_resources::PermissionDescription {
let mut description = managed_resources::PermissionDescription::default()
.emphasis("install npm packages")
.text(" ");
for (index, (name, version)) in self.packages.iter().enumerate() {
if index > 0 {
description = description.text(", ");
}
description = description.code(format!("{name}@{version}"));
}
description
.text(" in ")
.code(self.directory.display().to_string())
}
async fn run(self, npm: &Npm, _: &gpui::BackgroundExecutor) -> Self::Output {
@@ -313,11 +324,20 @@ impl ManagedResourceCommand<Npm> for RunNpmSubcommand {
.map(|rule| rule.permission)
}
fn permission_description(&self, _: &Npm) -> String {
format!(
"Run npm {} {:?} in {:?}",
self.subcommand, self.args, self.directory
)
fn permission_description(&self, _: &Npm) -> managed_resources::PermissionDescription {
let mut description = managed_resources::PermissionDescription::default()
.emphasis("run npm")
.text(" ")
.code(&self.subcommand);
for argument in &self.args {
description = description.text(" ").code(argument);
}
if let Some(directory) = &self.directory {
description = description
.text(" in ")
.code(directory.display().to_string());
}
description
}
async fn run(self, npm: &Npm, executor: &gpui::BackgroundExecutor) -> Self::Output {
+1 -1
View File
@@ -229,7 +229,7 @@ fn managed_npm_obtains_and_installs_packages() -> Result<()> {
("another-package".into(), "4.5.6".into()),
],
};
let description = install().permission_description(&npm);
let description = install().permission_description(&npm).to_string();
for detail in [
"@example/server",
"1.2.3",
@@ -7660,7 +7660,7 @@ async fn managed_resource_approvals_reach_the_client(
fn permission(&self, _: &()) -> Option<ResourcePermission> {
None
}
fn permission_description(&self, _: &Self) -> String {
fn permission_description(&self, _: &Self) -> managed_resources::PermissionDescription {
"unused".into()
}
async fn run(self, _: &Self, _: &gpui::BackgroundExecutor) {
@@ -7728,7 +7728,7 @@ async fn managed_resource_approvals_reach_the_client(
assert!(title.contains("remote host"));
assert!(detail.contains("remote-runtime"));
assert!(detail.contains("remote-extension"));
assert!(detail.contains("network checks"));
assert!(detail.contains("check for updates"));
cx.simulate_prompt_answer(answer);
}
let result = task.await;
+27 -4
View File
@@ -16,7 +16,7 @@ use theme_settings::ThemeSettings;
use std::ops::Deref;
use std::sync::{Arc, LazyLock};
use std::{any::TypeId, time::Duration};
use ui::{CopyButton, SplitButton, SplitButtonStyle, TintColor, Tooltip, prelude::*};
use ui::{CopyButton, LabelLike, SplitButton, SplitButtonStyle, TintColor, Tooltip, prelude::*};
use util::ResultExt;
#[derive(Default)]
@@ -91,8 +91,24 @@ pub(crate) fn request_resource_approval(
let (sender, receiver) = futures::channel::oneshot::channel();
let sender = Arc::new(Mutex::new(Some(sender)));
let dismissed = sender.clone();
let expanded = std::rc::Rc::new(std::cell::Cell::new(false));
let notification = cx.new(|cx| {
simple_message_notification::MessageNotification::new_from_builder(cx, move |_, cx| {
simple_message_notification::MessageNotification::new_from_builder(cx, move |window, cx| {
let mut text = String::new();
let runs = request.summary().0.into_iter().map(|span| {
use managed_resources::PermissionText;
let (PermissionText::Plain(value) | PermissionText::Emphasis(value) | PermissionText::Code(value)) = &span;
let mut run = window.text_style().to_run(value.len());
match &span {
PermissionText::Emphasis(_) => run.font.weight = gpui::FontWeight::SEMIBOLD,
PermissionText::Code(_) => run.font = ThemeSettings::get_global(cx).buffer_font.clone(),
PermissionText::Plain(_) => {}
}
text.push_str(value);
run
}).collect();
let show_details = expanded.get();
let expanded = expanded.clone();
let controls = h_flex().gap_2().flex_wrap().children([
("Allow", ResourcePermission::Allowed),
("Deny", ResourcePermission::Denied),
@@ -138,11 +154,18 @@ pub(crate) fn request_resource_approval(
}));
v_flex()
.gap_2()
.child(Label::new(request.description()))
.child(LabelLike::new().child(gpui::StyledText::new(text).with_runs(runs)))
.child(div().debug_selector(|| "Permission details toggle".to_owned()).child(Button::new("permission-details", if show_details { "Hide details" } else { "Details" })
.label_size(LabelSize::Small).color(Color::Muted)
.on_click(cx.listener(move |_, _, _, cx| {
expanded.set(!expanded.get());
cx.notify();
}))))
.when(show_details, |this| this.child(div().debug_selector(|| "Permission details".to_owned()).child(Label::new(request.details()).size(LabelSize::Small).color(Color::Muted))))
.child(controls)
.into_any_element()
})
.with_title("Allow managed resource operation?")
.with_title("Permission required")
.show_suppress_button(false)
});
cx.subscribe(&notification, move |_, _: &DismissEvent, _| {
+15 -1
View File
@@ -13297,7 +13297,7 @@ mod tests {
serde_json::from_value(permission.clone()).expect("valid permission")
})
}
fn permission_description(&self, _: &Self) -> String {
fn permission_description(&self, _: &Self) -> managed_resources::PermissionDescription {
"Run test command".into()
}
async fn run(self, _: &Self, _: &gpui::BackgroundExecutor) -> bool {
@@ -13418,6 +13418,20 @@ mod tests {
if answer == "Dismiss" {
notification.update(cx, |notification, cx| notification.dismiss(cx));
} else {
assert!(cx.debug_bounds("Permission details").is_none());
let toggle = cx
.debug_bounds("Permission details toggle")
.expect("details toggle");
cx.simulate_click(toggle.center(), Modifiers::none());
cx.run_until_parked();
assert!(cx.debug_bounds("Permission details").is_some());
assert!((&mut task).now_or_never().is_none());
let toggle = cx
.debug_bounds("Permission details toggle")
.expect("details toggle");
cx.simulate_click(toggle.center(), Modifiers::none());
cx.run_until_parked();
assert!(cx.debug_bounds("Permission details").is_none());
let bounds = cx.debug_bounds(answer).expect("visible approval button");
let position = if answer.ends_with("Always") {
bounds.center()