1use collections::{HashMap, IndexMap};
2use schemars::{JsonSchema, json_schema};
3use serde::{Deserialize, Serialize};
4use settings_macros::{MergeFrom, with_fallible_options};
5use std::sync::Arc;
6use std::{borrow::Cow, path::PathBuf};
7
8use crate::ExtendingVec;
9
10use crate::DockPosition;
11
12#[with_fallible_options]
13#[derive(Clone, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom, Debug, Default)]
14pub struct AgentSettingsContent {
15 /// Whether the Agent is enabled.
16 ///
17 /// Default: true
18 pub enabled: Option<bool>,
19 /// Whether to show the agent panel button in the status bar.
20 ///
21 /// Default: true
22 pub button: Option<bool>,
23 /// Where to dock the agent panel.
24 ///
25 /// Default: right
26 pub dock: Option<DockPosition>,
27 /// Default width in pixels when the agent panel is docked to the left or right.
28 ///
29 /// Default: 640
30 #[serde(serialize_with = "crate::serialize_optional_f32_with_two_decimal_places")]
31 pub default_width: Option<f32>,
32 /// Default height in pixels when the agent panel is docked to the bottom.
33 ///
34 /// Default: 320
35 #[serde(serialize_with = "crate::serialize_optional_f32_with_two_decimal_places")]
36 pub default_height: Option<f32>,
37 /// The default model to use when creating new chats and for other features when a specific model is not specified.
38 pub default_model: Option<LanguageModelSelection>,
39 /// Favorite models to show at the top of the model selector.
40 #[serde(default)]
41 pub favorite_models: Vec<LanguageModelSelection>,
42 /// Model to use for the inline assistant. Defaults to default_model when not specified.
43 pub inline_assistant_model: Option<LanguageModelSelection>,
44 /// Model to use for the inline assistant when streaming tools are enabled.
45 ///
46 /// Default: true
47 pub inline_assistant_use_streaming_tools: Option<bool>,
48 /// Model to use for generating git commit messages. Defaults to default_model when not specified.
49 pub commit_message_model: Option<LanguageModelSelection>,
50 /// Model to use for generating thread summaries. Defaults to default_model when not specified.
51 pub thread_summary_model: Option<LanguageModelSelection>,
52 /// Additional models with which to generate alternatives when performing inline assists.
53 pub inline_alternatives: Option<Vec<LanguageModelSelection>>,
54 /// The default profile to use in the Agent.
55 ///
56 /// Default: write
57 pub default_profile: Option<Arc<str>>,
58 /// Which view type to show by default in the agent panel.
59 ///
60 /// Default: "thread"
61 pub default_view: Option<DefaultAgentView>,
62 /// The available agent profiles.
63 pub profiles: Option<IndexMap<Arc<str>, AgentProfileContent>>,
64 /// Where to show a popup notification when the agent is waiting for user input.
65 ///
66 /// Default: "primary_screen"
67 pub notify_when_agent_waiting: Option<NotifyWhenAgentWaiting>,
68 /// Whether to play a sound when the agent has either completed its response, or needs user input.
69 ///
70 /// Default: false
71 pub play_sound_when_agent_done: Option<bool>,
72 /// Whether to display agent edits in single-file editors in addition to the review multibuffer pane.
73 ///
74 /// Default: true
75 pub single_file_review: Option<bool>,
76 /// Additional parameters for language model requests. When making a request
77 /// to a model, parameters will be taken from the last entry in this list
78 /// that matches the model's provider and name. In each entry, both provider
79 /// and model are optional, so that you can specify parameters for either
80 /// one.
81 ///
82 /// Default: []
83 #[serde(default)]
84 pub model_parameters: Vec<LanguageModelParameters>,
85 /// Whether to show thumb buttons for feedback in the agent panel.
86 ///
87 /// Default: true
88 pub enable_feedback: Option<bool>,
89 /// Whether to have edit cards in the agent panel expanded, showing a preview of the full diff.
90 ///
91 /// Default: true
92 pub expand_edit_card: Option<bool>,
93 /// Whether to have terminal cards in the agent panel expanded, showing the whole command output.
94 ///
95 /// Default: true
96 pub expand_terminal_card: Option<bool>,
97 /// Whether clicking the stop button on a running terminal tool should also cancel the agent's generation.
98 /// Note that this only applies to the stop button, not to ctrl+c inside the terminal.
99 ///
100 /// Default: true
101 pub cancel_generation_on_terminal_stop: Option<bool>,
102 /// Whether to always use cmd-enter (or ctrl-enter on Linux or Windows) to send messages in the agent panel.
103 ///
104 /// Default: false
105 pub use_modifier_to_send: Option<bool>,
106 /// Minimum number of lines of height the agent message editor should have.
107 ///
108 /// Default: 4
109 pub message_editor_min_lines: Option<usize>,
110 /// Whether to show turn statistics (elapsed time during generation, final turn duration).
111 ///
112 /// Default: false
113 pub show_turn_stats: Option<bool>,
114 /// Per-tool permission rules for granular control over which tool actions
115 /// require confirmation.
116 ///
117 /// The global `default` applies when no tool-specific rules match.
118 /// For external agent servers (e.g. Claude Agent) that define their own
119 /// permission modes, "deny" and "confirm" still take precedence — the
120 /// external agent's permission system is only used when Zed would allow
121 /// the action. Per-tool regex patterns (`always_allow`, `always_deny`,
122 /// `always_confirm`) match against the tool's text input (command, path,
123 /// URL, etc.).
124 pub tool_permissions: Option<ToolPermissionsContent>,
125}
126
127impl AgentSettingsContent {
128 pub fn set_dock(&mut self, dock: DockPosition) {
129 self.dock = Some(dock);
130 }
131
132 pub fn set_model(&mut self, language_model: LanguageModelSelection) {
133 self.default_model = Some(language_model)
134 }
135
136 pub fn set_inline_assistant_model(&mut self, provider: String, model: String) {
137 self.inline_assistant_model = Some(LanguageModelSelection {
138 provider: provider.into(),
139 model,
140 enable_thinking: false,
141 effort: None,
142 });
143 }
144
145 pub fn set_profile(&mut self, profile_id: Arc<str>) {
146 self.default_profile = Some(profile_id);
147 }
148
149 pub fn add_favorite_model(&mut self, model: LanguageModelSelection) {
150 if !self.favorite_models.contains(&model) {
151 self.favorite_models.push(model);
152 }
153 }
154
155 pub fn remove_favorite_model(&mut self, model: &LanguageModelSelection) {
156 self.favorite_models.retain(|m| m != model);
157 }
158
159 pub fn set_tool_default_permission(&mut self, tool_id: &str, mode: ToolPermissionMode) {
160 let tool_permissions = self.tool_permissions.get_or_insert_default();
161 let tool_rules = tool_permissions
162 .tools
163 .entry(Arc::from(tool_id))
164 .or_default();
165 tool_rules.default = Some(mode);
166 }
167
168 pub fn add_tool_allow_pattern(&mut self, tool_name: &str, pattern: String) {
169 let tool_permissions = self.tool_permissions.get_or_insert_default();
170 let tool_rules = tool_permissions
171 .tools
172 .entry(Arc::from(tool_name))
173 .or_default();
174 let always_allow = tool_rules.always_allow.get_or_insert_default();
175 if !always_allow.0.iter().any(|r| r.pattern == pattern) {
176 always_allow.0.push(ToolRegexRule {
177 pattern,
178 case_sensitive: None,
179 });
180 }
181 }
182
183 pub fn add_tool_deny_pattern(&mut self, tool_name: &str, pattern: String) {
184 let tool_permissions = self.tool_permissions.get_or_insert_default();
185 let tool_rules = tool_permissions
186 .tools
187 .entry(Arc::from(tool_name))
188 .or_default();
189 let always_deny = tool_rules.always_deny.get_or_insert_default();
190 if !always_deny.0.iter().any(|r| r.pattern == pattern) {
191 always_deny.0.push(ToolRegexRule {
192 pattern,
193 case_sensitive: None,
194 });
195 }
196 }
197}
198
199#[with_fallible_options]
200#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, JsonSchema, MergeFrom)]
201pub struct AgentProfileContent {
202 pub name: Arc<str>,
203 #[serde(default)]
204 pub tools: IndexMap<Arc<str>, bool>,
205 /// Whether all context servers are enabled by default.
206 pub enable_all_context_servers: Option<bool>,
207 #[serde(default)]
208 pub context_servers: IndexMap<Arc<str>, ContextServerPresetContent>,
209 /// The default language model selected when using this profile.
210 pub default_model: Option<LanguageModelSelection>,
211}
212
213#[with_fallible_options]
214#[derive(Debug, PartialEq, Clone, Default, Serialize, Deserialize, JsonSchema, MergeFrom)]
215pub struct ContextServerPresetContent {
216 pub tools: IndexMap<Arc<str>, bool>,
217}
218
219#[derive(Copy, Clone, Default, Debug, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
220#[serde(rename_all = "snake_case")]
221pub enum DefaultAgentView {
222 #[default]
223 Thread,
224 TextThread,
225}
226
227#[derive(
228 Copy,
229 Clone,
230 Default,
231 Debug,
232 Serialize,
233 Deserialize,
234 JsonSchema,
235 MergeFrom,
236 PartialEq,
237 strum::VariantArray,
238 strum::VariantNames,
239)]
240#[serde(rename_all = "snake_case")]
241pub enum NotifyWhenAgentWaiting {
242 #[default]
243 PrimaryScreen,
244 AllScreens,
245 Never,
246}
247
248#[with_fallible_options]
249#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
250pub struct LanguageModelSelection {
251 pub provider: LanguageModelProviderSetting,
252 pub model: String,
253 #[serde(default)]
254 pub enable_thinking: bool,
255 pub effort: Option<String>,
256}
257
258#[with_fallible_options]
259#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, MergeFrom, PartialEq)]
260pub struct LanguageModelParameters {
261 pub provider: Option<LanguageModelProviderSetting>,
262 pub model: Option<String>,
263 #[serde(serialize_with = "crate::serialize_optional_f32_with_two_decimal_places")]
264 pub temperature: Option<f32>,
265}
266
267#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, MergeFrom)]
268pub struct LanguageModelProviderSetting(pub String);
269
270impl JsonSchema for LanguageModelProviderSetting {
271 fn schema_name() -> Cow<'static, str> {
272 "LanguageModelProviderSetting".into()
273 }
274
275 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
276 // list the builtin providers as a subset so that we still auto complete them in the settings
277 json_schema!({
278 "anyOf": [
279 {
280 "type": "string",
281 "enum": [
282 "amazon-bedrock",
283 "anthropic",
284 "copilot_chat",
285 "deepseek",
286 "google",
287 "lmstudio",
288 "mistral",
289 "ollama",
290 "openai",
291 "openrouter",
292 "vercel",
293 "vercel_ai_gateway",
294 "x_ai",
295 "zed.dev"
296 ]
297 },
298 {
299 "type": "string",
300 }
301 ]
302 })
303 }
304}
305
306impl From<String> for LanguageModelProviderSetting {
307 fn from(provider: String) -> Self {
308 Self(provider)
309 }
310}
311
312impl From<&str> for LanguageModelProviderSetting {
313 fn from(provider: &str) -> Self {
314 Self(provider.to_string())
315 }
316}
317
318#[with_fallible_options]
319#[derive(Default, PartialEq, Deserialize, Serialize, Clone, JsonSchema, MergeFrom, Debug)]
320#[serde(transparent)]
321pub struct AllAgentServersSettings(pub HashMap<String, CustomAgentServerSettings>);
322
323impl std::ops::Deref for AllAgentServersSettings {
324 type Target = HashMap<String, CustomAgentServerSettings>;
325
326 fn deref(&self) -> &Self::Target {
327 &self.0
328 }
329}
330
331impl std::ops::DerefMut for AllAgentServersSettings {
332 fn deref_mut(&mut self) -> &mut Self::Target {
333 &mut self.0
334 }
335}
336
337#[with_fallible_options]
338#[derive(Deserialize, Serialize, Clone, JsonSchema, MergeFrom, Debug, PartialEq)]
339#[serde(tag = "type", rename_all = "snake_case")]
340pub enum CustomAgentServerSettings {
341 Custom {
342 #[serde(rename = "command")]
343 path: PathBuf,
344 #[serde(default, skip_serializing_if = "Vec::is_empty")]
345 args: Vec<String>,
346 /// Default: {}
347 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
348 env: HashMap<String, String>,
349 /// The default mode to use for this agent.
350 ///
351 /// Note: Not only all agents support modes.
352 ///
353 /// Default: None
354 default_mode: Option<String>,
355 /// The default model to use for this agent.
356 ///
357 /// This should be the model ID as reported by the agent.
358 ///
359 /// Default: None
360 default_model: Option<String>,
361 /// The favorite models for this agent.
362 ///
363 /// These are the model IDs as reported by the agent.
364 ///
365 /// Default: []
366 #[serde(default, skip_serializing_if = "Vec::is_empty")]
367 favorite_models: Vec<String>,
368 /// Default values for session config options.
369 ///
370 /// This is a map from config option ID to value ID.
371 ///
372 /// Default: {}
373 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
374 default_config_options: HashMap<String, String>,
375 /// Favorited values for session config options.
376 ///
377 /// This is a map from config option ID to a list of favorited value IDs.
378 ///
379 /// Default: {}
380 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
381 favorite_config_option_values: HashMap<String, Vec<String>>,
382 },
383 Extension {
384 /// Additional environment variables to pass to the agent.
385 ///
386 /// Default: {}
387 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
388 env: HashMap<String, String>,
389 /// The default mode to use for this agent.
390 ///
391 /// Note: Not only all agents support modes.
392 ///
393 /// Default: None
394 default_mode: Option<String>,
395 /// The default model to use for this agent.
396 ///
397 /// This should be the model ID as reported by the agent.
398 ///
399 /// Default: None
400 default_model: Option<String>,
401 /// The favorite models for this agent.
402 ///
403 /// These are the model IDs as reported by the agent.
404 ///
405 /// Default: []
406 #[serde(default, skip_serializing_if = "Vec::is_empty")]
407 favorite_models: Vec<String>,
408 /// Default values for session config options.
409 ///
410 /// This is a map from config option ID to value ID.
411 ///
412 /// Default: {}
413 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
414 default_config_options: HashMap<String, String>,
415 /// Favorited values for session config options.
416 ///
417 /// This is a map from config option ID to a list of favorited value IDs.
418 ///
419 /// Default: {}
420 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
421 favorite_config_option_values: HashMap<String, Vec<String>>,
422 },
423 Registry {
424 /// Additional environment variables to pass to the agent.
425 ///
426 /// Default: {}
427 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
428 env: HashMap<String, String>,
429 /// The default mode to use for this agent.
430 ///
431 /// Note: Not only all agents support modes.
432 ///
433 /// Default: None
434 default_mode: Option<String>,
435 /// The default model to use for this agent.
436 ///
437 /// This should be the model ID as reported by the agent.
438 ///
439 /// Default: None
440 default_model: Option<String>,
441 /// The favorite models for this agent.
442 ///
443 /// These are the model IDs as reported by the agent.
444 ///
445 /// Default: []
446 #[serde(default, skip_serializing_if = "Vec::is_empty")]
447 favorite_models: Vec<String>,
448 /// Default values for session config options.
449 ///
450 /// This is a map from config option ID to value ID.
451 ///
452 /// Default: {}
453 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
454 default_config_options: HashMap<String, String>,
455 /// Favorited values for session config options.
456 ///
457 /// This is a map from config option ID to a list of favorited value IDs.
458 ///
459 /// Default: {}
460 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
461 favorite_config_option_values: HashMap<String, Vec<String>>,
462 },
463}
464
465#[with_fallible_options]
466#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
467pub struct ToolPermissionsContent {
468 /// Global default permission when no tool-specific rules match.
469 /// Individual tools can override this with their own default.
470 /// Default: confirm
471 #[serde(alias = "default_mode")]
472 pub default: Option<ToolPermissionMode>,
473
474 /// Per-tool permission rules.
475 /// Keys are tool names (e.g. terminal, edit_file, fetch) including MCP
476 /// tools (e.g. mcp:server_name:tool_name). Any tool name is accepted;
477 /// even tools without meaningful text input can have a `default` set.
478 #[serde(default)]
479 pub tools: HashMap<Arc<str>, ToolRulesContent>,
480}
481
482#[with_fallible_options]
483#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
484pub struct ToolRulesContent {
485 /// Default mode when no regex rules match.
486 /// When unset, inherits from the global `tool_permissions.default`.
487 #[serde(alias = "default_mode")]
488 pub default: Option<ToolPermissionMode>,
489
490 /// Regexes for inputs to auto-approve.
491 /// For terminal: matches command. For file tools: matches path. For fetch: matches URL.
492 /// For `copy_path` and `move_path`, patterns are matched independently against each
493 /// path (source and destination).
494 /// Patterns accumulate across settings layers (user, project, profile) and cannot be
495 /// removed by a higher-priority layer—only new patterns can be added.
496 /// Default: []
497 pub always_allow: Option<ExtendingVec<ToolRegexRule>>,
498
499 /// Regexes for inputs to auto-reject.
500 /// **SECURITY**: These take precedence over ALL other rules, across ALL settings layers.
501 /// For `copy_path` and `move_path`, patterns are matched independently against each
502 /// path (source and destination).
503 /// Patterns accumulate across settings layers (user, project, profile) and cannot be
504 /// removed by a higher-priority layer—only new patterns can be added.
505 /// Default: []
506 pub always_deny: Option<ExtendingVec<ToolRegexRule>>,
507
508 /// Regexes for inputs that must always prompt.
509 /// Takes precedence over always_allow but not always_deny.
510 /// For `copy_path` and `move_path`, patterns are matched independently against each
511 /// path (source and destination).
512 /// Patterns accumulate across settings layers (user, project, profile) and cannot be
513 /// removed by a higher-priority layer—only new patterns can be added.
514 /// Default: []
515 pub always_confirm: Option<ExtendingVec<ToolRegexRule>>,
516}
517
518#[with_fallible_options]
519#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)]
520pub struct ToolRegexRule {
521 /// The regex pattern to match.
522 #[serde(default)]
523 pub pattern: String,
524
525 /// Whether the regex is case-sensitive.
526 /// Default: false (case-insensitive)
527 pub case_sensitive: Option<bool>,
528}
529
530#[derive(
531 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema, MergeFrom,
532)]
533#[serde(rename_all = "snake_case")]
534pub enum ToolPermissionMode {
535 /// Auto-approve without prompting.
536 Allow,
537 /// Auto-reject with an error.
538 Deny,
539 /// Always prompt for confirmation (default behavior).
540 #[default]
541 Confirm,
542}
543
544impl std::fmt::Display for ToolPermissionMode {
545 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
546 match self {
547 ToolPermissionMode::Allow => write!(f, "Allow"),
548 ToolPermissionMode::Deny => write!(f, "Deny"),
549 ToolPermissionMode::Confirm => write!(f, "Confirm"),
550 }
551 }
552}
553
554#[cfg(test)]
555mod tests {
556 use super::*;
557
558 #[test]
559 fn test_set_tool_default_permission_creates_structure() {
560 let mut settings = AgentSettingsContent::default();
561 assert!(settings.tool_permissions.is_none());
562
563 settings.set_tool_default_permission("terminal", ToolPermissionMode::Allow);
564
565 let tool_permissions = settings.tool_permissions.as_ref().unwrap();
566 let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
567 assert_eq!(terminal_rules.default, Some(ToolPermissionMode::Allow));
568 }
569
570 #[test]
571 fn test_set_tool_default_permission_updates_existing() {
572 let mut settings = AgentSettingsContent::default();
573
574 settings.set_tool_default_permission("terminal", ToolPermissionMode::Confirm);
575 settings.set_tool_default_permission("terminal", ToolPermissionMode::Allow);
576
577 let tool_permissions = settings.tool_permissions.as_ref().unwrap();
578 let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
579 assert_eq!(terminal_rules.default, Some(ToolPermissionMode::Allow));
580 }
581
582 #[test]
583 fn test_set_tool_default_permission_for_mcp_tool() {
584 let mut settings = AgentSettingsContent::default();
585
586 settings.set_tool_default_permission("mcp:github:create_issue", ToolPermissionMode::Allow);
587
588 let tool_permissions = settings.tool_permissions.as_ref().unwrap();
589 let mcp_rules = tool_permissions
590 .tools
591 .get("mcp:github:create_issue")
592 .unwrap();
593 assert_eq!(mcp_rules.default, Some(ToolPermissionMode::Allow));
594 }
595
596 #[test]
597 fn test_add_tool_allow_pattern_creates_structure() {
598 let mut settings = AgentSettingsContent::default();
599 assert!(settings.tool_permissions.is_none());
600
601 settings.add_tool_allow_pattern("terminal", "^cargo\\s".to_string());
602
603 let tool_permissions = settings.tool_permissions.as_ref().unwrap();
604 let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
605 let always_allow = terminal_rules.always_allow.as_ref().unwrap();
606 assert_eq!(always_allow.0.len(), 1);
607 assert_eq!(always_allow.0[0].pattern, "^cargo\\s");
608 }
609
610 #[test]
611 fn test_add_tool_allow_pattern_appends_to_existing() {
612 let mut settings = AgentSettingsContent::default();
613
614 settings.add_tool_allow_pattern("terminal", "^cargo\\s".to_string());
615 settings.add_tool_allow_pattern("terminal", "^npm\\s".to_string());
616
617 let tool_permissions = settings.tool_permissions.as_ref().unwrap();
618 let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
619 let always_allow = terminal_rules.always_allow.as_ref().unwrap();
620 assert_eq!(always_allow.0.len(), 2);
621 assert_eq!(always_allow.0[0].pattern, "^cargo\\s");
622 assert_eq!(always_allow.0[1].pattern, "^npm\\s");
623 }
624
625 #[test]
626 fn test_add_tool_allow_pattern_does_not_duplicate() {
627 let mut settings = AgentSettingsContent::default();
628
629 settings.add_tool_allow_pattern("terminal", "^cargo\\s".to_string());
630 settings.add_tool_allow_pattern("terminal", "^cargo\\s".to_string());
631 settings.add_tool_allow_pattern("terminal", "^cargo\\s".to_string());
632
633 let tool_permissions = settings.tool_permissions.as_ref().unwrap();
634 let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
635 let always_allow = terminal_rules.always_allow.as_ref().unwrap();
636 assert_eq!(
637 always_allow.0.len(),
638 1,
639 "Duplicate patterns should not be added"
640 );
641 }
642
643 #[test]
644 fn test_add_tool_allow_pattern_for_different_tools() {
645 let mut settings = AgentSettingsContent::default();
646
647 settings.add_tool_allow_pattern("terminal", "^cargo\\s".to_string());
648 settings.add_tool_allow_pattern("fetch", "^https?://github\\.com".to_string());
649
650 let tool_permissions = settings.tool_permissions.as_ref().unwrap();
651
652 let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
653 assert_eq!(
654 terminal_rules.always_allow.as_ref().unwrap().0[0].pattern,
655 "^cargo\\s"
656 );
657
658 let fetch_rules = tool_permissions.tools.get("fetch").unwrap();
659 assert_eq!(
660 fetch_rules.always_allow.as_ref().unwrap().0[0].pattern,
661 "^https?://github\\.com"
662 );
663 }
664
665 #[test]
666 fn test_add_tool_deny_pattern_creates_structure() {
667 let mut settings = AgentSettingsContent::default();
668 assert!(settings.tool_permissions.is_none());
669
670 settings.add_tool_deny_pattern("terminal", "^rm\\s".to_string());
671
672 let tool_permissions = settings.tool_permissions.as_ref().unwrap();
673 let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
674 let always_deny = terminal_rules.always_deny.as_ref().unwrap();
675 assert_eq!(always_deny.0.len(), 1);
676 assert_eq!(always_deny.0[0].pattern, "^rm\\s");
677 }
678
679 #[test]
680 fn test_add_tool_deny_pattern_appends_to_existing() {
681 let mut settings = AgentSettingsContent::default();
682
683 settings.add_tool_deny_pattern("terminal", "^rm\\s".to_string());
684 settings.add_tool_deny_pattern("terminal", "^sudo\\s".to_string());
685
686 let tool_permissions = settings.tool_permissions.as_ref().unwrap();
687 let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
688 let always_deny = terminal_rules.always_deny.as_ref().unwrap();
689 assert_eq!(always_deny.0.len(), 2);
690 assert_eq!(always_deny.0[0].pattern, "^rm\\s");
691 assert_eq!(always_deny.0[1].pattern, "^sudo\\s");
692 }
693
694 #[test]
695 fn test_add_tool_deny_pattern_does_not_duplicate() {
696 let mut settings = AgentSettingsContent::default();
697
698 settings.add_tool_deny_pattern("terminal", "^rm\\s".to_string());
699 settings.add_tool_deny_pattern("terminal", "^rm\\s".to_string());
700 settings.add_tool_deny_pattern("terminal", "^rm\\s".to_string());
701
702 let tool_permissions = settings.tool_permissions.as_ref().unwrap();
703 let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
704 let always_deny = terminal_rules.always_deny.as_ref().unwrap();
705 assert_eq!(
706 always_deny.0.len(),
707 1,
708 "Duplicate patterns should not be added"
709 );
710 }
711
712 #[test]
713 fn test_add_tool_deny_and_allow_patterns_separate() {
714 let mut settings = AgentSettingsContent::default();
715
716 settings.add_tool_allow_pattern("terminal", "^cargo\\s".to_string());
717 settings.add_tool_deny_pattern("terminal", "^rm\\s".to_string());
718
719 let tool_permissions = settings.tool_permissions.as_ref().unwrap();
720 let terminal_rules = tool_permissions.tools.get("terminal").unwrap();
721
722 let always_allow = terminal_rules.always_allow.as_ref().unwrap();
723 assert_eq!(always_allow.0.len(), 1);
724 assert_eq!(always_allow.0[0].pattern, "^cargo\\s");
725
726 let always_deny = terminal_rules.always_deny.as_ref().unwrap();
727 assert_eq!(always_deny.0.len(), 1);
728 assert_eq!(always_deny.0[0].pattern, "^rm\\s");
729 }
730}