-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsettings.rs
More file actions
389 lines (340 loc) · 13.1 KB
/
Copy pathsettings.rs
File metadata and controls
389 lines (340 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
//! Settings commands for auto-start and system tray behavior
use serde::{Deserialize, Serialize};
use tauri::State;
use tauri_plugin_autostart::AutoLaunchManager;
use tracing::{debug, info};
use crate::state::AppState;
/// Startup and system tray settings
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StartupSettings {
/// Whether to launch the app at system startup
pub auto_launch: bool,
/// Whether to start minimized to tray
pub start_minimized: bool,
/// Whether to minimize to tray instead of closing
pub close_to_tray: bool,
}
impl Default for StartupSettings {
fn default() -> Self {
Self {
auto_launch: true,
start_minimized: true,
close_to_tray: true, // Default to close-to-tray behavior
}
}
}
/// Get current startup settings
#[tauri::command]
pub async fn get_startup_settings(
app_state: State<'_, AppState>,
manager: State<'_, AutoLaunchManager>,
) -> Result<StartupSettings, String> {
debug!("[Settings] Getting startup settings");
let settings_repo = &app_state.settings_repository;
// Get auto-launch status from the OS
let auto_launch = manager
.is_enabled()
.map_err(|e| format!("Failed to check auto-launch status: {}", e))?;
// Get other settings from database; use defaults when key is missing or DB read fails (e.g. no settings yet)
let start_minimized = settings_repo
.get("startup.start_minimized")
.await
.ok()
.flatten()
.map(|v| v == "true")
.unwrap_or(true);
let close_to_tray = settings_repo
.get("ui.close_to_tray")
.await
.ok()
.flatten()
.map(|v| v == "true")
.unwrap_or(true);
Ok(StartupSettings {
auto_launch,
start_minimized,
close_to_tray,
})
}
/// Update startup settings
#[tauri::command]
pub async fn update_startup_settings(
settings: StartupSettings,
app_state: State<'_, AppState>,
manager: State<'_, AutoLaunchManager>,
) -> Result<(), String> {
info!("[Settings] Updating startup settings: {:?}", settings);
let settings_repo = &app_state.settings_repository;
// Check if auto-launch setting has changed before modifying OS
let current_auto_launch = manager.is_enabled().unwrap_or(false);
if settings.auto_launch != current_auto_launch {
if settings.auto_launch {
manager
.enable()
.map_err(|e| format!("Failed to enable auto-launch: {}", e))?;
info!("[Settings] Auto-launch enabled");
} else {
manager
.disable()
.map_err(|e| format!("Failed to disable auto-launch: {}", e))?;
info!("[Settings] Auto-launch disabled");
}
} else {
info!("[Settings] Auto-launch unchanged, skipping OS update");
}
// Mark autostart as explicitly configured so first-launch logic won't re-enable it
settings_repo
.set("startup.autostart_configured", "true")
.await
.map_err(|e| format!("Failed to save autostart_configured flag: {}", e))?;
// Update other settings in database
settings_repo
.set(
"startup.start_minimized",
&settings.start_minimized.to_string(),
)
.await
.map_err(|e| format!("Failed to save start_minimized setting: {}", e))?;
settings_repo
.set("ui.close_to_tray", &settings.close_to_tray.to_string())
.await
.map_err(|e| format!("Failed to save close_to_tray setting: {}", e))?;
info!("[Settings] Startup settings updated successfully");
Ok(())
}
/// App-settings key for the "auto-install updates on launch" switch.
const AUTO_INSTALL_UPDATES_KEY: &str = "updates.auto_install";
/// Whether the app downloads + installs updates automatically on launch
/// (then relaunches into the new version). Default **true** — a missing
/// setting means auto-install is on.
#[tauri::command]
pub async fn get_auto_install_updates(app_state: State<'_, AppState>) -> Result<bool, String> {
let stored = app_state
.settings_repository
.get(AUTO_INSTALL_UPDATES_KEY)
.await
.map_err(|e| e.to_string())?;
Ok(stored.map(|v| v != "false").unwrap_or(true))
}
/// Enable/disable automatic update installation on launch. Persisted.
#[tauri::command]
pub async fn set_auto_install_updates(
enabled: bool,
app_state: State<'_, AppState>,
) -> Result<bool, String> {
app_state
.settings_repository
.set(AUTO_INSTALL_UPDATES_KEY, &enabled.to_string())
.await
.map_err(|e| e.to_string())?;
info!("[Settings] Auto-install updates set to {}", enabled);
Ok(enabled)
}
/// App-settings key for the update channel ("stable" | "prerelease").
const UPDATE_CHANNEL_KEY: &str = "updates.channel";
/// Default update channel when the setting is missing.
const UPDATE_CHANNEL_STABLE: &str = "stable";
const UPDATE_CHANNEL_PRERELEASE: &str = "prerelease";
/// Normalize an arbitrary stored/incoming value to a known channel, defaulting
/// to "stable". Keeps the gateway between the frontend and the updater header
/// strict so a corrupt setting can never select an unknown channel.
fn normalize_channel(raw: &str) -> &'static str {
if raw.eq_ignore_ascii_case(UPDATE_CHANNEL_PRERELEASE) {
UPDATE_CHANNEL_PRERELEASE
} else {
UPDATE_CHANNEL_STABLE
}
}
/// Which update channel the app follows. The frontend sends this as the
/// `X-Mcpmux-Channel` header on update checks so the resolver returns the
/// newest stable or pre-release manifest. Default **stable** — a missing
/// setting means the stable channel.
#[tauri::command]
pub async fn get_update_channel(app_state: State<'_, AppState>) -> Result<String, String> {
let stored = app_state
.settings_repository
.get(UPDATE_CHANNEL_KEY)
.await
.map_err(|e| e.to_string())?;
Ok(stored
.map(|v| normalize_channel(&v).to_string())
.unwrap_or_else(|| UPDATE_CHANNEL_STABLE.to_string()))
}
/// Set the update channel ("stable" | "prerelease"). Unknown values are
/// coerced to "stable". Persisted; returns the normalized value actually saved.
#[tauri::command]
pub async fn set_update_channel(
channel: String,
app_state: State<'_, AppState>,
) -> Result<String, String> {
let normalized = normalize_channel(&channel);
app_state
.settings_repository
.set(UPDATE_CHANNEL_KEY, normalized)
.await
.map_err(|e| e.to_string())?;
info!("[Settings] Update channel set to {}", normalized);
Ok(normalized.to_string())
}
/// App-settings key for the "ask to map new folders" prompt switch.
const WORKSPACE_MAPPING_PROMPT_KEY: &str = "workspaces.mapping_prompt_enabled";
/// Interpret a stored value for the workspace mapping-prompt toggle. Missing or
/// any non-`"false"` value means **enabled** — the prompt is on by default, so
/// only an explicit opt-out turns it off.
fn mapping_prompt_enabled_from(stored: Option<&str>) -> bool {
stored.map(|v| v != "false").unwrap_or(true)
}
/// Whether McpMux pops the "map this folder?" sheet when a connected client
/// opens a folder that has no explicit binding (it's on the default Starter
/// set). Default **true**. Users who find the prompt noisy can turn it off
/// here or via the link in the sheet itself.
#[tauri::command]
pub async fn get_workspace_mapping_prompt_enabled(
app_state: State<'_, AppState>,
) -> Result<bool, String> {
let stored = app_state
.settings_repository
.get(WORKSPACE_MAPPING_PROMPT_KEY)
.await
.map_err(|e| e.to_string())?;
Ok(mapping_prompt_enabled_from(stored.as_deref()))
}
/// Enable/disable the "map this folder?" prompt. Persisted; returns the value
/// actually saved.
#[tauri::command]
pub async fn set_workspace_mapping_prompt_enabled(
enabled: bool,
app_state: State<'_, AppState>,
) -> Result<bool, String> {
app_state
.settings_repository
.set(WORKSPACE_MAPPING_PROMPT_KEY, &enabled.to_string())
.await
.map_err(|e| e.to_string())?;
info!("[Settings] Workspace mapping prompt set to {}", enabled);
Ok(enabled)
}
/// Check if app should start hidden (for auto-launch with --hidden flag)
pub fn should_start_hidden() -> bool {
let args: Vec<String> = std::env::args().collect();
args.contains(&"--hidden".to_string())
}
// The meta-tools master switch moved out of global app-settings into per-Space
// built-in-server config — see `commands::builtin_servers`
// (`list_builtin_servers` / `set_builtin_server_enabled` /
// `set_builtin_tool_enabled`).
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_startup_settings_default() {
let settings = StartupSettings::default();
assert!(settings.auto_launch);
assert!(settings.start_minimized);
assert!(settings.close_to_tray);
}
#[test]
fn test_startup_settings_serialization() {
let settings = StartupSettings {
auto_launch: true,
start_minimized: false,
close_to_tray: true,
};
let json = serde_json::to_string(&settings).unwrap();
assert!(json.contains("\"autoLaunch\":true"));
assert!(json.contains("\"startMinimized\":false"));
assert!(json.contains("\"closeToTray\":true"));
}
#[test]
fn test_startup_settings_deserialization() {
let json = r#"{"autoLaunch":true,"startMinimized":true,"closeToTray":false}"#;
let settings: StartupSettings = serde_json::from_str(json).unwrap();
assert!(settings.auto_launch);
assert!(settings.start_minimized);
assert!(!settings.close_to_tray);
}
#[test]
fn test_should_start_hidden_without_flag() {
// This test might be tricky as it depends on actual process args
// In a real test environment, we'd mock std::env::args
// For now, we just verify the function exists and can be called
let _result = should_start_hidden();
// Can't assert the actual value since it depends on how tests are run
}
#[test]
fn test_startup_settings_clone() {
let settings = StartupSettings {
auto_launch: true,
start_minimized: false,
close_to_tray: true,
};
let cloned = settings.clone();
assert_eq!(settings.auto_launch, cloned.auto_launch);
assert_eq!(settings.start_minimized, cloned.start_minimized);
assert_eq!(settings.close_to_tray, cloned.close_to_tray);
}
#[test]
fn test_startup_settings_debug() {
let settings = StartupSettings::default();
let debug_str = format!("{:?}", settings);
assert!(debug_str.contains("StartupSettings"));
assert!(debug_str.contains("auto_launch"));
assert!(debug_str.contains("start_minimized"));
assert!(debug_str.contains("close_to_tray"));
}
#[test]
fn test_startup_settings_with_all_enabled() {
let settings = StartupSettings {
auto_launch: true,
start_minimized: true,
close_to_tray: true,
};
assert!(settings.auto_launch);
assert!(settings.start_minimized);
assert!(settings.close_to_tray);
}
#[test]
fn test_startup_settings_with_all_disabled() {
let settings = StartupSettings {
auto_launch: false,
start_minimized: false,
close_to_tray: false,
};
assert!(!settings.auto_launch);
assert!(!settings.start_minimized);
assert!(!settings.close_to_tray);
}
#[test]
fn test_normalize_channel_prerelease_variants() {
assert_eq!(normalize_channel("prerelease"), UPDATE_CHANNEL_PRERELEASE);
assert_eq!(normalize_channel("Prerelease"), UPDATE_CHANNEL_PRERELEASE);
assert_eq!(normalize_channel("PRERELEASE"), UPDATE_CHANNEL_PRERELEASE);
}
#[test]
fn test_normalize_channel_defaults_to_stable() {
assert_eq!(normalize_channel("stable"), UPDATE_CHANNEL_STABLE);
assert_eq!(normalize_channel(""), UPDATE_CHANNEL_STABLE);
assert_eq!(normalize_channel("beta"), UPDATE_CHANNEL_STABLE);
assert_eq!(normalize_channel("garbage"), UPDATE_CHANNEL_STABLE);
}
#[test]
fn test_normalize_channel_returns_canonical_static() {
// Always returns one of the two canonical lowercase tokens.
for input in ["StAbLe", "pre", "prerelease", "x"] {
let out = normalize_channel(input);
assert!(out == UPDATE_CHANNEL_STABLE || out == UPDATE_CHANNEL_PRERELEASE);
}
}
#[test]
fn test_mapping_prompt_enabled_defaults_on() {
// Missing setting → on by default.
assert!(mapping_prompt_enabled_from(None));
// Only an explicit "false" disables it.
assert!(!mapping_prompt_enabled_from(Some("false")));
assert!(mapping_prompt_enabled_from(Some("true")));
// Any unexpected value is treated as enabled (fail-open to the default).
assert!(mapping_prompt_enabled_from(Some("")));
assert!(mapping_prompt_enabled_from(Some("garbage")));
}
}