Skip to main content

toolblox_lib/
app_commands.rs

1//! Tauri command boundary and frontend-safe application state.
2
3use std::collections::{BTreeMap, BTreeSet, HashMap};
4use std::path::PathBuf;
5use std::sync::atomic::Ordering;
6use std::sync::{Arc, Mutex};
7use std::time::{SystemTime, UNIX_EPOCH};
8
9use serde::{Deserialize, Serialize};
10use serde_json::{Value, json};
11use tauri::{AppHandle, Emitter, Manager, State};
12
13use crate::credentials::{CredentialStore, OsCredentialStore, Secret};
14use crate::login::{AccountIdentity, LoginError, LoginNotice};
15use crate::models::{AccountDto, PresenceState, Settings, StoredAccount};
16use crate::storage::{Storage, StorageError};
17use crate::widget_process::WidgetProcessManager;
18use crate::widgets::{Catalogue, CatalogueEntry, InstalledWidget};
19
20/// The account and previous session to restore if saving a signed-in account fails.
21type CredentialRollback = Arc<Mutex<Option<(u64, Option<Secret>)>>>;
22
23/// Shared state for commands, managed by Tauri.
24pub struct Runtime {
25    pub storage: Arc<Storage>,
26    pub credentials: Arc<OsCredentialStore>,
27    pub client: reqwest::Client,
28    pub widgets_root: PathBuf,
29    /// The verified widget catalogue, once loaded.
30    pub catalogue: Mutex<Option<Catalogue>>,
31    /// Why the catalogue couldn't be loaded, shown on the Widgets screen.
32    pub catalogue_error: Mutex<Option<String>>,
33    /// When the catalogue was last requested, successfully or not.
34    pub catalogue_checked: Mutex<Option<std::time::Instant>>,
35    pub processes: Arc<Mutex<WidgetProcessManager>>,
36    /// Active widget frame sessions.
37    pub widget_sessions: Mutex<crate::widget_ipc::WidgetSessions>,
38    /// Bundled helper that closes Roblox's singleton handles, when installed.
39    pub multi_instance_helper: Option<PathBuf>,
40    /// Roblox processes the helper already handled.
41    pub cleared_roblox_pids: Mutex<std::collections::HashSet<u32>>,
42    /// Accounts whose session Roblox no longer accepts, or that have no stored session.
43    pub expired_sessions: Mutex<std::collections::HashSet<u64>>,
44    /// Bumped to stop joins in progress. Each join stops once it differs from the value it
45    /// started with.
46    pub join_generation: std::sync::atomic::AtomicU64,
47    /// Accounts whose join in progress is skipped. A join clears its own accounts when it starts.
48    pub cancelled_joins: Mutex<std::collections::HashSet<u64>>,
49    /// Widget modules and frames stay unloaded for this session.
50    pub safe_mode: bool,
51    /// Set when this launch is the first since an update, until the interface takes it.
52    pub updated: std::sync::atomic::AtomicBool,
53}
54
55impl Runtime {
56    /// Whether the account needs to sign in again.
57    pub(crate) fn session_expired(&self, account_id: u64) -> bool {
58        self.expired_sessions
59            .lock()
60            .is_ok_and(|expired| expired.contains(&account_id))
61    }
62
63    /// Marks an account's session as expired or valid.
64    pub(crate) fn set_session_expired(&self, account_id: u64, expired: bool) {
65        let Ok(mut sessions) = self.expired_sessions.lock() else {
66            return;
67        };
68        if expired && sessions.insert(account_id) {
69            log::info!("Session for account {account_id} has expired");
70        } else if !expired {
71            sessions.remove(&account_id);
72        }
73    }
74
75    /// Records what a Roblox request made with an account's session says about it. Success marks
76    /// it valid and a 401 marks it expired. Other failures say nothing about the session.
77    pub(crate) fn note_session<T>(
78        &self,
79        account_id: u64,
80        result: &Result<T, crate::roblox::RobloxError>,
81    ) {
82        if let Some(expired) = session_verdict(result) {
83            self.set_session_expired(account_id, expired);
84        }
85    }
86
87    /// Reads an account's session. A missing session marks the account expired.
88    pub(crate) fn session(
89        &self,
90        account_id: u64,
91    ) -> Result<Secret, crate::credentials::CredentialError> {
92        self.credentials.get(account_id).inspect_err(|error| {
93            if matches!(error, crate::credentials::CredentialError::Missing) {
94                self.set_session_expired(account_id, true);
95            }
96        })
97    }
98}
99
100/// The settings the interface reads and edits.
101#[derive(Clone, Debug, Deserialize, Serialize)]
102#[serde(rename_all = "camelCase")]
103pub struct SettingsDto {
104    sidebar_position: crate::models::SidebarPosition,
105    theme_mode: crate::models::ThemeMode,
106    show_avatars: bool,
107    compact_mode: bool,
108    sort_order: crate::models::SortOrder,
109    place_id: String,
110    multi_instance: bool,
111    auto_rejoin: bool,
112    open_on_launch: bool,
113    run_in_background: bool,
114    #[serde(default)]
115    ask_destination: bool,
116    minimize_on_join: bool,
117    notify_on_drop: bool,
118    always_on_top: bool,
119    show_animations: bool,
120    ignore_reduced_motion: bool,
121    #[serde(default)]
122    reduce_toasts: bool,
123    #[serde(default)]
124    friends_source: crate::models::FriendsSource,
125    #[serde(default)]
126    widgets_open_installed: bool,
127    #[serde(default)]
128    groups: Vec<crate::models::AccountGroup>,
129    #[serde(default)]
130    tags: Vec<crate::models::AccountTag>,
131}
132
133impl From<&Settings> for SettingsDto {
134    fn from(settings: &Settings) -> Self {
135        Self {
136            sidebar_position: settings.sidebar_pos.clone(),
137            theme_mode: settings.theme_mode.clone(),
138            show_avatars: settings.show_avatars,
139            compact_mode: settings.compact_mode,
140            sort_order: settings.sort_order.clone(),
141            place_id: settings.place_id.clone(),
142            multi_instance: settings.multi_instance,
143            auto_rejoin: settings.auto_rejoin,
144            open_on_launch: settings.open_on_launch,
145            run_in_background: settings.run_in_background,
146            ask_destination: settings.ask_destination,
147            minimize_on_join: settings.minimize_on_join,
148            notify_on_drop: settings.notify_on_drop,
149            always_on_top: settings.always_on_top,
150            show_animations: settings.show_animations,
151            ignore_reduced_motion: settings.ignore_reduced_motion,
152            reduce_toasts: settings.reduce_toasts,
153            friends_source: settings.friends_source,
154            widgets_open_installed: settings.widgets_open_installed,
155            groups: settings.groups.clone(),
156            tags: settings.tags.clone(),
157        }
158    }
159}
160
161/// An account with its presence, as shown in the interface.
162#[derive(Clone, Debug, Serialize)]
163#[serde(rename_all = "camelCase")]
164pub struct AccountView {
165    #[serde(flatten)]
166    account: AccountDto,
167    presence: FrontendPresence,
168    /// The account is in Roblox Studio rather than a game. Its presence is still `Playing`.
169    #[serde(skip_serializing_if = "std::ops::Not::not")]
170    in_studio: bool,
171    /// Name of the game the account is in, when game details are on.
172    #[serde(skip_serializing_if = "Option::is_none")]
173    game_name: Option<String>,
174    #[serde(skip_serializing_if = "Option::is_none")]
175    game_place_id: Option<u64>,
176    /// The account needs to sign in again.
177    session_expired: bool,
178}
179
180/// Presence as the interface shows it.
181#[derive(Clone, Copy, Debug, Serialize)]
182#[serde(rename_all = "snake_case")]
183enum FrontendPresence {
184    Offline,
185    Playing,
186    /// Presence couldn't be determined.
187    Warning,
188}
189
190/// An installed widget, as shown in the interface.
191#[derive(Clone, Debug, Serialize)]
192#[serde(rename_all = "camelCase")]
193pub struct WidgetSummary {
194    id: String,
195    name: String,
196    description: String,
197    icon: Option<String>,
198    logo_url: Option<String>,
199    banner_url: Option<String>,
200    enabled: bool,
201    version: String,
202    available_version: Option<String>,
203    permissions: Vec<crate::widgets::WidgetPermission>,
204    /// Permissions of the newer catalogue version, when one is available.
205    available_permissions: Option<Vec<crate::widgets::WidgetPermission>>,
206    /// Toolblox version the newer catalogue version needs, when this build is older.
207    available_needs_app: Option<String>,
208    has_settings: bool,
209    has_dashboard_tile: bool,
210    has_page_frame: bool,
211    module_url: Option<String>,
212    host_url: String,
213}
214
215/// A catalogue widget that isn't installed.
216#[derive(Clone, Debug, Serialize)]
217#[serde(rename_all = "camelCase")]
218pub struct CatalogueSummary {
219    id: String,
220    name: String,
221    description: String,
222    version: String,
223    logo_url: Option<String>,
224    banner_url: Option<String>,
225    permissions: Vec<crate::widgets::WidgetPermission>,
226    /// Oldest Toolblox version the widget runs on.
227    min_app_version: Option<String>,
228    /// Whether this build meets `min_app_version`.
229    supported: bool,
230}
231
232/// Everything the interface needs to render, without secrets.
233#[derive(Debug, Serialize)]
234#[serde(rename_all = "camelCase")]
235pub struct AppStateDto {
236    version: &'static str,
237    channel: &'static str,
238    platform: &'static str,
239    widgets_path: String,
240    /// Folder holding the log files, or empty when logging didn't start.
241    logs_path: String,
242    accounts: Vec<AccountView>,
243    installed_widgets: Vec<WidgetSummary>,
244    widget_errors: Vec<String>,
245    catalogue: Vec<CatalogueSummary>,
246    catalogue_error: Option<String>,
247    settings: SettingsDto,
248    recent_places: Vec<crate::models::RecentPlace>,
249    safe_mode: bool,
250    /// IDs of widgets open in their own window.
251    popouts: Vec<String>,
252}
253
254/// Whether a Roblox response shows the session expired (`Some(true)`), valid (`Some(false)`), or
255/// says nothing about it (`None`). Only a 401 means Roblox no longer accepts the session.
256fn session_verdict<T>(result: &Result<T, crate::roblox::RobloxError>) -> Option<bool> {
257    match result {
258        Ok(_) => Some(false),
259        Err(crate::roblox::RobloxError::Rejected(401)) => Some(true),
260        Err(_) => None,
261    }
262}
263
264/// Converts an error to the message returned to the interface.
265fn command_error(error: impl std::fmt::Display) -> String {
266    error.to_string()
267}
268
269/// Reads a response body, failing with `too_large` once it exceeds `maximum` bytes.
270pub(crate) async fn read_response_limited(
271    mut response: reqwest::Response,
272    maximum: usize,
273    too_large: &'static str,
274    read_error: &'static str,
275) -> Result<Vec<u8>, String> {
276    if response
277        .content_length()
278        .is_some_and(|length| length > maximum as u64)
279    {
280        return Err(too_large.into());
281    }
282    let mut bytes = Vec::with_capacity(
283        response
284            .content_length()
285            .unwrap_or_default()
286            .min(maximum as u64) as usize,
287    );
288    while let Some(chunk) = response.chunk().await.map_err(|_| read_error.to_string())? {
289        if bytes.len().saturating_add(chunk.len()) > maximum {
290            return Err(too_large.into());
291        }
292        bytes.extend_from_slice(&chunk);
293    }
294    Ok(bytes)
295}
296
297/// Current Unix time in seconds.
298fn now_seconds() -> f64 {
299    SystemTime::now()
300        .duration_since(UNIX_EPOCH)
301        .unwrap_or_default()
302        .as_secs_f64()
303}
304
305/// Checks every saved session with Roblox once, so expired ones show before they're used.
306/// Network failures leave the state unchanged.
307pub(crate) async fn check_sessions(runtime: &Runtime) {
308    let Ok(accounts) = runtime.storage.load_accounts() else {
309        return;
310    };
311    for account in accounts {
312        let Ok(secret) = runtime.session(account.id) else {
313            continue;
314        };
315        let result = crate::roblox::authenticated_profile(&runtime.client, &secret).await;
316        runtime.note_session(account.id, &result);
317    }
318}
319
320/// Fills in names and avatars for accounts saved without an avatar.
321pub(crate) async fn backfill_profiles(runtime: &Runtime) {
322    let Ok(accounts) = runtime.storage.load_accounts() else {
323        return;
324    };
325    let missing: Vec<_> = accounts
326        .iter()
327        .filter(|account| account.avatar_url.is_none())
328        .map(|account| account.id)
329        .collect();
330    for account_id in missing {
331        let profile = match crate::roblox::public_profile(&runtime.client, account_id).await {
332            Ok(profile) => profile,
333            Err(error) => {
334                log::warn!("Profile for account {account_id} couldn't be loaded: {error}");
335                continue;
336            }
337        };
338        let _ = runtime.storage.update_accounts(|accounts| {
339            if let Some(account) = accounts.iter_mut().find(|account| account.id == account_id) {
340                account.name = profile.name.clone();
341                account.display_name = profile.display_name.clone();
342                account.avatar_url = profile.avatar_url.clone();
343            }
344            Ok(())
345        });
346    }
347}
348
349/// Summarizes installed widgets, noting newer catalogue versions.
350fn installed_widgets(runtime: &Runtime, settings: &Settings) -> Vec<WidgetSummary> {
351    let catalogue_entries: HashMap<_, _> = runtime
352        .catalogue
353        .lock()
354        .ok()
355        .and_then(|value| value.clone())
356        .map(|catalogue| {
357            catalogue
358                .entries
359                .into_iter()
360                .map(|entry| (entry.id.clone(), entry))
361                .collect()
362        })
363        .unwrap_or_default();
364    crate::widgets::discover_installed(&runtime.widgets_root)
365        .into_iter()
366        .filter_map(Result::ok)
367        .map(|widget| widget_summary(widget, settings, &catalogue_entries))
368        .collect()
369}
370
371/// Summarizes one installed widget.
372fn widget_summary(
373    widget: InstalledWidget,
374    settings: &Settings,
375    catalogue_entries: &HashMap<String, crate::widgets::CatalogueEntry>,
376) -> WidgetSummary {
377    let id = widget.id;
378    let available = catalogue_entries.get(&id).filter(|entry| {
379        semver::Version::parse(&entry.version)
380            .ok()
381            .zip(semver::Version::parse(&widget.version).ok())
382            .is_some_and(|(available, installed)| available > installed)
383    });
384    WidgetSummary {
385        name: widget.manifest.name,
386        description: widget.manifest.description,
387        logo_url: widget
388            .manifest
389            .icon
390            .as_deref()
391            .map(|icon| widget_asset_url(&id, icon)),
392        banner_url: widget
393            .manifest
394            .banner
395            .as_deref()
396            .map(|banner| widget_asset_url(&id, banner)),
397        icon: widget.manifest.icon,
398        enabled: !settings.disabled_widgets.contains(&id),
399        available_version: available.map(|entry| entry.version.clone()),
400        permissions: widget.manifest.permissions.clone(),
401        available_permissions: available.map(|entry| entry.permissions.clone()),
402        available_needs_app: available
403            .and_then(|entry| entry.min_app_version.clone())
404            .filter(|minimum| !crate::widgets::app_supports(Some(minimum))),
405        has_settings: widget.manifest.settings_entry.is_some(),
406        has_dashboard_tile: widget.manifest.dashboard_entry.is_some(),
407        has_page_frame: widget.manifest.entry.is_some(),
408        module_url: widget
409            .manifest
410            .module
411            .as_deref()
412            .map(|module| module_url(&id, module, &widget.sha256, &widget.version)),
413        host_url: widget_asset_url(&id, "index.html"),
414        version: widget.version,
415        id,
416    }
417}
418
419/// Adds presence to each account.
420///
421/// Presence is fetched with the first session Roblox accepts. When game details are on, accounts
422/// whose place is hidden from others are checked with their own session, and game names are
423/// looked up.
424async fn account_views(runtime: &Runtime, accounts: &[StoredAccount]) -> Vec<AccountView> {
425    if accounts.is_empty() {
426        return Vec::new();
427    }
428    let ids: Vec<_> = accounts.iter().map(|account| account.id).collect();
429    let mut states = None;
430    for account in accounts {
431        let Ok(secret) = runtime.session(account.id) else {
432            continue;
433        };
434        let result = crate::roblox::fetch_presence_details(&runtime.client, &secret, &ids).await;
435        runtime.note_session(account.id, &result);
436        match result {
437            Ok(found) => {
438                states = Some(found);
439                break;
440            }
441            Err(crate::roblox::RobloxError::Rejected(_)) => continue,
442            Err(_) => break,
443        }
444    }
445    let mut game_names = BTreeMap::new();
446    if let Some(states) = states.as_mut() {
447        for account in accounts {
448            let hidden = states
449                .get(&account.id)
450                .is_some_and(|detail| detail.in_game() && detail.place_id.is_none());
451            if !hidden {
452                continue;
453            }
454            let Ok(secret) = runtime.session(account.id) else {
455                continue;
456            };
457            let own =
458                crate::roblox::fetch_presence_details(&runtime.client, &secret, &[account.id])
459                    .await;
460            runtime.note_session(account.id, &own);
461            if let Some(detail) = own.ok().and_then(|own| own.into_values().next()) {
462                states.insert(account.id, detail);
463            }
464        }
465        let unnamed: BTreeSet<_> = states
466            .values()
467            .filter(|detail| detail.in_game() && detail.location.is_none())
468            .filter_map(|detail| detail.universe_id)
469            .collect();
470        game_names = crate::roblox::fetch_game_names(&runtime.client, &unnamed).await;
471    }
472    accounts
473        .iter()
474        .map(|account| {
475            let detail = states.as_ref().and_then(|states| states.get(&account.id));
476            let presence = match detail.map(|detail| &detail.state) {
477                Some(PresenceState::Offline) => FrontendPresence::Offline,
478                Some(PresenceState::InGame | PresenceState::InStudio) => FrontendPresence::Playing,
479                Some(PresenceState::Online | PresenceState::Unknown) | None => {
480                    FrontendPresence::Warning
481                }
482            };
483            let in_studio = detail.is_some_and(|detail| detail.state == PresenceState::InStudio);
484            let detail = detail.filter(|detail| detail.in_game());
485            AccountView {
486                account: AccountDto::from(account),
487                presence,
488                in_studio,
489                game_name: detail.and_then(|detail| {
490                    detail.activity(detail.location.clone().or_else(|| {
491                        detail
492                            .universe_id
493                            .and_then(|id| game_names.get(&id).cloned())
494                    }))
495                }),
496                game_place_id: detail.and_then(|detail| detail.place_id),
497                session_expired: runtime.session_expired(account.id),
498            }
499        })
500        .collect()
501}
502
503/// Looks up names for recent places that don't have one yet and drops places Roblox doesn't
504/// know. Network failures leave the name unset so the next refresh tries again.
505async fn name_recent_places(runtime: &Runtime, settings: Settings) -> Settings {
506    let mut named = BTreeMap::new();
507    let mut missing = BTreeSet::new();
508    for place in settings
509        .recent_places
510        .iter()
511        .filter(|place| place.name.is_none() && !place.place_id.starts_with('@'))
512    {
513        let Ok(universe) =
514            crate::roblox::fetch_place_universe(&runtime.client, &place.place_id).await
515        else {
516            continue;
517        };
518        let Some(universe) = universe else {
519            missing.insert(place.place_id.clone());
520            continue;
521        };
522        let ids = BTreeSet::from([universe]);
523        let names = crate::roblox::fetch_game_names(&runtime.client, &ids).await;
524        if let Some(name) = names.get(&universe) {
525            named.insert(place.place_id.clone(), name.clone());
526        }
527    }
528    if named.is_empty() && missing.is_empty() {
529        return settings;
530    }
531    runtime
532        .storage
533        .update_settings(|saved| {
534            saved
535                .recent_places
536                .retain(|place| !missing.contains(&place.place_id));
537            for place in &mut saved.recent_places {
538                if let Some(name) = named.get(&place.place_id) {
539                    place.name = Some(name.clone());
540                }
541            }
542            Ok(saved.clone())
543        })
544        .unwrap_or(settings)
545}
546
547/// Returns whether this launch is the first since an update. Only the first call returns true.
548#[tauri::command]
549pub fn take_updated(runtime: State<'_, Runtime>) -> bool {
550    runtime
551        .updated
552        .swap(false, std::sync::atomic::Ordering::Relaxed)
553}
554
555/// How long a loaded catalogue is used before the next state request checks for newer widgets.
556const CATALOGUE_FRESH: std::time::Duration = std::time::Duration::from_secs(10 * 60);
557/// How soon a failed catalogue download is retried, such as when Toolblox starts before the
558/// network is up.
559const CATALOGUE_RETRY: std::time::Duration = std::time::Duration::from_secs(30);
560
561/// Whether the catalogue should be requested again.
562fn catalogue_due(
563    checked: Option<std::time::Instant>,
564    failed: bool,
565    now: std::time::Instant,
566) -> bool {
567    let wait = if failed {
568        CATALOGUE_RETRY
569    } else {
570        CATALOGUE_FRESH
571    };
572    checked.is_none_or(|at| now.saturating_duration_since(at) >= wait)
573}
574
575/// Records a catalogue check when one is due. Returns whether this is the first check.
576fn claim_catalogue_check(runtime: &Runtime) -> Option<bool> {
577    let failed = runtime
578        .catalogue_error
579        .lock()
580        .is_ok_and(|error| error.is_some());
581    let mut checked = runtime.catalogue_checked.lock().ok()?;
582    let now = std::time::Instant::now();
583    if !catalogue_due(*checked, failed, now) {
584        return None;
585    }
586    let first = checked.is_none();
587    *checked = Some(now);
588    Some(first)
589}
590
591/// Returns the full interface state. The first call waits for the catalogue; later calls recheck
592/// it in the background when it's stale and announce `WIDGETS_CHANGED` once it loads.
593/// Development builds without a catalogue URL rebuild it from the working tree on every call.
594#[tauri::command]
595pub async fn get_app_state(
596    app: AppHandle,
597    runtime: State<'_, Runtime>,
598) -> Result<AppStateDto, String> {
599    if cfg!(debug_assertions) && option_env!("TOOLBLOX_CATALOGUE_URL").is_none() {
600        let _ = refresh_catalogue_data(&runtime).await;
601    } else if let Some(first) = claim_catalogue_check(&runtime) {
602        if first {
603            let _ = refresh_catalogue_data(&runtime).await;
604        } else {
605            let app = app.clone();
606            tauri::async_runtime::spawn(async move {
607                if refresh_catalogue_data(&app.state::<Runtime>())
608                    .await
609                    .is_ok()
610                {
611                    let _ = app.emit(WIDGETS_CHANGED, ());
612                }
613            });
614        }
615    }
616    let settings = runtime.storage.load_settings().map_err(command_error)?;
617    let settings = name_recent_places(&runtime, settings).await;
618    let accounts = runtime.storage.load_accounts().map_err(command_error)?;
619    let catalogue = runtime
620        .catalogue
621        .lock()
622        .map_err(|_| "The widget catalogue is busy. Can you try again?".to_string())?
623        .clone()
624        .map(|catalogue| {
625            catalogue
626                .entries
627                .into_iter()
628                .filter(|entry| !runtime.widgets_root.join(&entry.id).exists())
629                .map(|entry| CatalogueSummary {
630                    id: entry.id,
631                    name: entry.name,
632                    description: entry.description,
633                    version: entry.version,
634                    logo_url: entry.icon_url,
635                    banner_url: entry.banner_url,
636                    permissions: entry.permissions,
637                    supported: crate::widgets::app_supports(entry.min_app_version.as_deref()),
638                    min_app_version: entry.min_app_version,
639                })
640                .collect()
641        })
642        .unwrap_or_default();
643    let catalogue_error = runtime
644        .catalogue_error
645        .lock()
646        .ok()
647        .and_then(|value| value.clone());
648    let widget_errors = crate::widgets::discover_installed(&runtime.widgets_root)
649        .into_iter()
650        .filter_map(Result::err)
651        .collect();
652    Ok(AppStateDto {
653        version: env!("CARGO_PKG_VERSION"),
654        channel: if cfg!(debug_assertions) {
655            "canary"
656        } else {
657            "stable"
658        },
659        platform: if cfg!(target_os = "macos") {
660            "macos"
661        } else {
662            "windows"
663        },
664        widgets_path: runtime.widgets_root.display().to_string(),
665        logs_path: crate::logs::directory()
666            .map(|path| path.display().to_string())
667            .unwrap_or_default(),
668        accounts: account_views(&runtime, &accounts).await,
669        installed_widgets: installed_widgets(&runtime, &settings),
670        widget_errors,
671        catalogue,
672        catalogue_error,
673        recent_places: settings
674            .recent_places
675            .iter()
676            .take(crate::models::RECENT_PLACES_LIMIT)
677            .cloned()
678            .collect(),
679        safe_mode: runtime.safe_mode,
680        popouts: open_popouts(&app, None),
681        settings: SettingsDto::from(&settings),
682    })
683}
684
685/// Validates and saves settings, applies always on top, and changes launch at login. The settings
686/// are restored if launch at login can't be changed.
687#[tauri::command]
688pub async fn save_settings(
689    app: AppHandle,
690    settings: SettingsDto,
691    runtime: State<'_, Runtime>,
692) -> Result<(), String> {
693    use tauri_plugin_autostart::ManagerExt;
694
695    let mut saved = runtime.storage.load_settings().map_err(command_error)?;
696    let previous = saved.clone();
697    saved.sidebar_pos = settings.sidebar_position;
698    saved.theme_mode = settings.theme_mode;
699    saved.show_avatars = settings.show_avatars;
700    saved.compact_mode = settings.compact_mode;
701    saved.sort_order = settings.sort_order;
702    saved.place_id = crate::roblox::parse_join_target(&settings.place_id)
703        .map(|target| target.to_string())
704        .or_else(|error| {
705            if settings.place_id.trim().is_empty() {
706                Ok(String::new())
707            } else {
708                Err(error)
709            }
710        })
711        .map_err(command_error)?;
712    saved.multi_instance = settings.multi_instance;
713    saved.auto_rejoin = settings.auto_rejoin;
714    saved.open_on_launch = settings.open_on_launch;
715    saved.run_in_background = settings.run_in_background;
716    saved.ask_destination = settings.ask_destination;
717    saved.minimize_on_join = settings.minimize_on_join;
718    saved.notify_on_drop = settings.notify_on_drop;
719    saved.always_on_top = settings.always_on_top;
720    saved.show_animations = settings.show_animations;
721    saved.ignore_reduced_motion = settings.ignore_reduced_motion;
722    saved.reduce_toasts = settings.reduce_toasts;
723    saved.friends_source = settings.friends_source;
724    saved.widgets_open_installed = settings.widgets_open_installed;
725    saved.groups = settings.groups;
726    saved.tags = settings.tags;
727    saved
728        .recent_places
729        .truncate(crate::models::RECENT_PLACES_LIMIT);
730    saved.validate()?;
731    runtime
732        .storage
733        .save_settings(&saved)
734        .map_err(command_error)?;
735    if saved.always_on_top != previous.always_on_top
736        && let Some(window) = app.get_webview_window(crate::lifecycle::MAIN_WINDOW_LABEL)
737    {
738        let _ = window.set_always_on_top(saved.always_on_top);
739    }
740    let autostart = app.autolaunch();
741    let result = if saved.open_on_launch == previous.open_on_launch {
742        Ok(())
743    } else if saved.open_on_launch {
744        autostart.enable()
745    } else {
746        autostart.disable()
747    };
748    if let Err(error) = result {
749        log::warn!("Launch at startup couldn't be changed: {error}");
750        let _ = runtime.storage.save_settings(&previous);
751        return Err(
752            "The startup setting couldn't be changed. Does the operating system allow startup apps?".into(),
753        );
754    }
755    if !saved.place_id.is_empty() && saved.place_id != previous.place_id {
756        remember_verified_place(&runtime, &saved.place_id).await?;
757    }
758    Ok(())
759}
760
761/// Adds a place or player to the recent list once Roblox confirms it exists. One that doesn't
762/// exist, or can't be checked, isn't added. Players are saved with their username.
763async fn remember_verified_place(runtime: &Runtime, place_id: &str) -> Result<(), String> {
764    if let Ok(crate::roblox::JoinTarget::User(user_id)) = crate::roblox::parse_join_target(place_id)
765    {
766        return match crate::roblox::public_profile(&runtime.client, user_id).await {
767            Ok(profile) => runtime
768                .storage
769                .update_settings(|settings| {
770                    settings.remember_place(place_id);
771                    settings.recent_places[0].name = Some(profile.name.chars().take(100).collect());
772                    Ok(())
773                })
774                .map_err(command_error),
775            Err(error) => {
776                log::warn!("Player {user_id} wasn't added to recent places: {error}");
777                Ok(())
778            }
779        };
780    }
781    match crate::roblox::fetch_place_universe(&runtime.client, place_id).await {
782        Ok(Some(_)) => runtime
783            .storage
784            .update_settings(|settings| {
785                settings.remember_place(place_id);
786                Ok(())
787            })
788            .map_err(command_error),
789        Ok(None) => Ok(()),
790        Err(error) => {
791            log::warn!("Place {place_id} wasn't added to recent places: {error}");
792            Ok(())
793        }
794    }
795}
796
797/// Removes a place from the recent list.
798#[tauri::command]
799pub fn forget_recent_place(place_id: String, runtime: State<'_, Runtime>) -> Result<(), String> {
800    runtime
801        .storage
802        .update_settings(|settings| {
803            settings
804                .recent_places
805                .retain(|place| place.place_id != place_id);
806            Ok(())
807        })
808        .map_err(command_error)
809}
810
811/// Reports whether Roblox knows the place. Network failures are errors, not a missing place.
812#[tauri::command]
813pub async fn place_exists(place_id: String, runtime: State<'_, Runtime>) -> Result<bool, String> {
814    crate::roblox::fetch_place_universe(&runtime.client, &place_id)
815        .await
816        .map(|universe| universe.is_some())
817        .map_err(command_error)
818}
819
820/// Searches Roblox for games by name, for the place fields.
821#[tauri::command]
822pub async fn search_places(
823    query: String,
824    runtime: State<'_, Runtime>,
825) -> Result<Vec<crate::roblox::PlaceMatch>, String> {
826    Ok(crate::roblox::search_places(&runtime.client, &query).await)
827}
828
829/// Returns an account's online friends, read with that account's session.
830#[tauri::command]
831pub async fn get_online_friends(
832    account_id: u64,
833    runtime: State<'_, Runtime>,
834) -> Result<Vec<crate::roblox::OnlineFriend>, String> {
835    let secret = runtime.session(account_id).map_err(command_error)?;
836    let result = crate::roblox::fetch_online_friends(&runtime.client, &secret, account_id).await;
837    runtime.note_session(account_id, &result);
838    result.map_err(command_error)
839}
840
841/// Sets or clears the place a single account joins instead of the default place.
842#[tauri::command]
843pub async fn set_account_place(
844    account_id: u64,
845    place_id: Option<String>,
846    runtime: State<'_, Runtime>,
847) -> Result<(), String> {
848    let place_id = match place_id.as_deref().map(str::trim) {
849        None | Some("") => None,
850        Some(input) => Some(
851            crate::roblox::parse_join_target(input)
852                .map_err(command_error)?
853                .to_string(),
854        ),
855    };
856    runtime
857        .storage
858        .update_accounts(|accounts| {
859            let account = accounts
860                .iter_mut()
861                .find(|account| account.id == account_id)
862                .ok_or_else(|| {
863                    StorageError::Invalid(
864                        "The account wasn't found. Can you refresh the list?".into(),
865                    )
866                })?;
867            account.place_id = place_id.clone();
868            Ok(())
869        })
870        .map_err(command_error)?;
871    if let Some(place_id) = place_id {
872        remember_verified_place(&runtime, &place_id).await?;
873    }
874    Ok(())
875}
876
877/// Replaces an account's notes, up to 10,000 characters: its note for the game at `place_id`
878/// when given, otherwise its general note. An empty game note is removed.
879#[tauri::command]
880pub fn update_account_notes(
881    account_id: u64,
882    notes: String,
883    place_id: Option<String>,
884    runtime: State<'_, Runtime>,
885) -> Result<(), String> {
886    if notes.chars().count() > crate::models::MAX_NOTE_CHARS {
887        return Err("The note is too long. Can you shorten it?".into());
888    }
889    if place_id
890        .as_deref()
891        .is_some_and(|id| !crate::models::is_place_id(id))
892    {
893        return Err("The game isn't valid. Can you set the destination again?".into());
894    }
895    runtime
896        .storage
897        .update_accounts(|accounts| {
898            let account = accounts
899                .iter_mut()
900                .find(|account| account.id == account_id)
901                .ok_or_else(|| {
902                    StorageError::Invalid(
903                        "The account wasn't found. Can you refresh the list?".into(),
904                    )
905                })?;
906            match place_id {
907                Some(place_id) if notes.is_empty() => {
908                    account.game_notes.remove(&place_id);
909                }
910                Some(place_id) => {
911                    account.game_notes.insert(place_id, notes);
912                }
913                None => account.notes = notes,
914            }
915            Ok(())
916        })
917        .map_err(command_error)
918}
919
920/// Removes an account and its stored session. The account is restored if the session can't be
921/// deleted.
922#[tauri::command]
923pub fn remove_account(account_id: u64, runtime: State<'_, Runtime>) -> Result<(), String> {
924    let removed = runtime
925        .storage
926        .update_accounts(|accounts| {
927            let index = accounts
928                .iter()
929                .position(|account| account.id == account_id)
930                .ok_or_else(|| {
931                    StorageError::Invalid(
932                        "The account wasn't found. Can you refresh the list?".into(),
933                    )
934                })?;
935            Ok((index, accounts.remove(index)))
936        })
937        .map_err(command_error)?;
938    if let Err(error) = runtime.credentials.delete(account_id) {
939        log::error!("Session for removed account {account_id} couldn't be deleted: {error}");
940        let rollback = runtime.storage.update_accounts(|accounts| {
941            if accounts.iter().all(|account| account.id != account_id) {
942                accounts.insert(removed.0.min(accounts.len()), removed.1.clone());
943            }
944            Ok(())
945        });
946        return match rollback {
947            Ok(()) => Err(command_error(error)),
948            Err(_) => Err("The account was removed, but its stored session couldn't be deleted. Can you restart Toolblox, then add and remove the account again?".into()),
949        };
950    }
951    runtime.set_session_expired(account_id, false);
952    if let Err(error) = runtime.storage.update_settings(|settings| {
953        for group in &mut settings.groups {
954            group.account_ids.retain(|id| *id != account_id);
955        }
956        for tag in &mut settings.tags {
957            tag.account_ids.retain(|id| *id != account_id);
958            for ids in tag.games.values_mut() {
959                ids.retain(|id| *id != account_id);
960            }
961        }
962        Ok(())
963    }) {
964        log::warn!(
965            "Removed account {account_id} couldn't be removed from its groups and tags: {error}"
966        );
967    }
968    log::info!("Removed account {account_id}");
969    Ok(())
970}
971
972/// Saves a manual account order. `account_ids` must list every account once.
973#[tauri::command]
974pub fn reorder_accounts(account_ids: Vec<u64>, runtime: State<'_, Runtime>) -> Result<(), String> {
975    runtime
976        .storage
977        .update_accounts(|accounts| {
978            if account_ids.len() != accounts.len() {
979                return Err(StorageError::Invalid(
980                    "The account order is incomplete. Can you refresh the list?".into(),
981                ));
982            }
983            let mut by_id: BTreeMap<_, _> = accounts
984                .drain(..)
985                .map(|account| (account.id, account))
986                .collect();
987            for id in &account_ids {
988                let account = by_id.remove(id).ok_or_else(|| {
989                    StorageError::Invalid(
990                        "The account order contains an unknown account. Can you refresh the list?"
991                            .into(),
992                    )
993                })?;
994                accounts.push(account);
995            }
996            if !by_id.is_empty() {
997                return Err(StorageError::Invalid(
998                    "The account order is incomplete. Can you refresh the list?".into(),
999                ));
1000            }
1001            Ok(())
1002        })
1003        .map_err(command_error)
1004}
1005
1006/// Pins an account to the dashboard, or unpins it.
1007#[tauri::command]
1008pub fn set_account_pinned(
1009    account_id: u64,
1010    pinned: bool,
1011    runtime: State<'_, Runtime>,
1012) -> Result<(), String> {
1013    runtime
1014        .storage
1015        .update_accounts(|accounts| {
1016            let account = accounts
1017                .iter_mut()
1018                .find(|account| account.id == account_id)
1019                .ok_or_else(|| {
1020                    StorageError::Invalid(
1021                        "The account wasn't found. Can you refresh the list?".into(),
1022                    )
1023                })?;
1024            account.pinned = pinned;
1025            Ok(())
1026        })
1027        .map_err(command_error)
1028}
1029
1030/// Finds players by username or display name.
1031#[tauri::command]
1032pub async fn search_players(
1033    query: String,
1034    runtime: State<'_, Runtime>,
1035) -> Result<Vec<crate::roblox::PlayerMatch>, String> {
1036    Ok(crate::roblox::search_players(&runtime.client, &query).await)
1037}
1038
1039/// Rejects a social lookup or change an account would make with itself.
1040fn other_player(account_id: u64, user_id: u64) -> Result<(), String> {
1041    if account_id == user_id || user_id == 0 {
1042        return Err("That's the same account. Can you choose a different player?".into());
1043    }
1044    Ok(())
1045}
1046
1047/// Returns an account's friend, follow, and block status with a player, read with that
1048/// account's session.
1049#[tauri::command]
1050pub async fn get_relationship(
1051    account_id: u64,
1052    user_id: u64,
1053    runtime: State<'_, Runtime>,
1054) -> Result<crate::roblox::Relationship, String> {
1055    other_player(account_id, user_id)?;
1056    let secret = runtime.session(account_id).map_err(command_error)?;
1057    let result =
1058        crate::roblox::fetch_relationship(&runtime.client, &secret, account_id, user_id).await;
1059    runtime.note_session(account_id, &result);
1060    result.map_err(command_error)
1061}
1062
1063/// Sends a friend request, follows, blocks, or undoes one of these, as an account.
1064#[tauri::command]
1065pub async fn change_relationship(
1066    account_id: u64,
1067    user_id: u64,
1068    action: crate::roblox::SocialAction,
1069    runtime: State<'_, Runtime>,
1070) -> Result<(), String> {
1071    other_player(account_id, user_id)?;
1072    let secret = runtime.session(account_id).map_err(command_error)?;
1073    let result =
1074        crate::roblox::change_relationship(&runtime.client, &secret, user_id, action).await;
1075    runtime.note_session(account_id, &result);
1076    match result {
1077        Ok(()) => {
1078            log::info!("Account {account_id} changed its relationship with {user_id}: {action:?}");
1079            Ok(())
1080        }
1081        Err(crate::roblox::RobloxError::Rejected(status @ (400 | 403 | 429))) => {
1082            log::warn!(
1083                "Relationship change {action:?} for account {account_id} was rejected with status {status}"
1084            );
1085            Err("Roblox didn't allow the change. Does it work on roblox.com?".into())
1086        }
1087        Err(error) => Err(command_error(error)),
1088    }
1089}
1090
1091/// Opens a player's Roblox profile in a window signed in as an account, for friend requests and
1092/// follows Roblox only allows after its own verification check.
1093#[tauri::command]
1094pub async fn open_roblox_profile(
1095    app: AppHandle,
1096    account_id: u64,
1097    user_id: u64,
1098    runtime: State<'_, Runtime>,
1099) -> Result<(), String> {
1100    other_player(account_id, user_id)?;
1101    let secret = runtime.session(account_id).map_err(command_error)?;
1102    crate::login::open_roblox_profile(&app, &secret, user_id)
1103        .map_err(|_| "The Roblox window couldn't open. Would trying again help?".into())
1104}
1105
1106/// Joins each account, at `place_id` when given, then minimizes the window if that setting is on.
1107/// `place_id` may also be `@` and a user ID, which follows that player into their game.
1108#[tauri::command]
1109pub async fn join_accounts(
1110    app: AppHandle,
1111    account_ids: Vec<u64>,
1112    place_id: Option<String>,
1113    runtime: State<'_, Runtime>,
1114) -> Result<(), String> {
1115    if account_ids.is_empty() {
1116        return Err("No accounts were selected. Can you select at least one?".into());
1117    }
1118    let place_id = place_id
1119        .as_deref()
1120        .map(crate::roblox::parse_join_target)
1121        .transpose()
1122        .map_err(command_error)?
1123        .map(|target| target.to_string());
1124    let progress = |done: usize, total: usize| {
1125        let _ = app.emit("join-progress", json!({ "done": done, "total": total }));
1126    };
1127    let finished = join_account_ids(
1128        &runtime,
1129        &account_ids,
1130        true,
1131        place_id.as_deref(),
1132        Some(&progress),
1133    )
1134    .await?;
1135    if !finished {
1136        return Ok(());
1137    }
1138    let minimize = runtime
1139        .storage
1140        .load_settings()
1141        .is_ok_and(|settings| settings.minimize_on_join);
1142    if minimize && let Some(window) = app.get_webview_window(crate::lifecycle::MAIN_WINDOW_LABEL) {
1143        let _ = window.minimize();
1144    }
1145    Ok(())
1146}
1147
1148/// Opens the Roblox sign-in window and waits for it, then adds or updates the signed-in account.
1149/// The previous session is restored if saving the account fails.
1150#[tauri::command]
1151pub async fn begin_roblox_login(
1152    app: AppHandle,
1153    expected_account_id: Option<u64>,
1154    runtime: State<'_, Runtime>,
1155) -> Result<AccountView, String> {
1156    let (sender, receiver) = std::sync::mpsc::sync_channel(1);
1157    let client = runtime.client.clone();
1158    let credentials = Arc::clone(&runtime.credentials);
1159    let credential_rollback: CredentialRollback = Arc::new(Mutex::new(None));
1160    let rollback_for_store = Arc::clone(&credential_rollback);
1161    crate::login::open_roblox_login(
1162        &app,
1163        move |cookie| {
1164            let profile = tauri::async_runtime::block_on(crate::roblox::authenticated_profile(
1165                &client,
1166                &crate::credentials::Secret::new(cookie.expose_secret().to_owned()),
1167            ))
1168            .map_err(|error| match error {
1169                crate::roblox::RobloxError::Network => LoginError::Network,
1170                _ => LoginError::InvalidSession,
1171            })?;
1172            if expected_account_id.is_some_and(|expected| expected != profile.id) {
1173                return Err(LoginError::WrongAccount);
1174            }
1175            Ok(AccountIdentity {
1176                id: profile.id,
1177                name: profile.name,
1178                display_name: profile.display_name,
1179                avatar_url: profile.avatar_url,
1180            })
1181        },
1182        move |identity, cookie| {
1183            let previous = credentials.get(identity.id).ok();
1184            credentials
1185                .set(identity.id, cookie.expose_secret())
1186                .map_err(|_| LoginError::CredentialStore)?;
1187            *rollback_for_store
1188                .lock()
1189                .map_err(|_| LoginError::CredentialStore)? = Some((identity.id, previous));
1190            Ok(())
1191        },
1192        move |notice| {
1193            let _ = sender.send(notice);
1194        },
1195    )
1196    .map_err(command_error)?;
1197    let notice = tauri::async_runtime::spawn_blocking(move || receiver.recv())
1198        .await
1199        .map_err(|_| "The Roblox sign-in stopped unexpectedly. Can you try again?".to_string())?
1200        .map_err(|_| "The Roblox sign-in stopped unexpectedly. Can you try again?".to_string())?;
1201    let identity = match notice {
1202        LoginNotice::Complete(identity) => identity,
1203        LoginNotice::Failed(error) => {
1204            log::warn!("Roblox sign-in failed: {error}");
1205            return Err(command_error(error));
1206        }
1207        LoginNotice::Cancelled => {
1208            log::info!("Roblox sign-in was cancelled");
1209            return Err("The Roblox sign-in was cancelled. Can you try again?".into());
1210        }
1211    };
1212    let account_result = runtime.storage.update_accounts(|accounts| {
1213        if let Some(account) = accounts
1214            .iter_mut()
1215            .find(|account| account.id == identity.id)
1216        {
1217            account.name = identity.name.clone();
1218            account.display_name = identity.display_name.clone();
1219            account.avatar_url = identity.avatar_url.clone();
1220            return Ok(account.clone());
1221        }
1222        let account = StoredAccount {
1223            id: identity.id,
1224            name: identity.name,
1225            display_name: identity.display_name,
1226            avatar_url: identity.avatar_url,
1227            notes: String::new(),
1228            game_notes: Default::default(),
1229            added_at: now_seconds(),
1230            last_played_at: None,
1231            play_count: 0,
1232            widget_data: BTreeMap::new(),
1233            place_id: None,
1234            last_place_id: None,
1235            pinned: false,
1236            extra: serde_json::Map::new(),
1237        };
1238        accounts.push(account.clone());
1239        Ok(account)
1240    });
1241    let account = match account_result {
1242        Ok(account) => {
1243            if let Ok(mut rollback) = credential_rollback.lock() {
1244                rollback.take();
1245            }
1246            log::info!("Signed in account {}", account.id);
1247            runtime.set_session_expired(account.id, false);
1248            account
1249        }
1250        Err(error) => {
1251            log::error!(
1252                "Signed-in account couldn't be saved, restoring its previous session: {error}"
1253            );
1254            if let Ok(mut rollback) = credential_rollback.lock()
1255                && let Some((account_id, previous)) = rollback.take()
1256            {
1257                if let Some(secret) = previous {
1258                    let _ = runtime.credentials.set(account_id, secret.expose());
1259                } else {
1260                    let _ = runtime.credentials.delete(account_id);
1261                }
1262            }
1263            return Err(command_error(error));
1264        }
1265    };
1266    Ok(AccountView {
1267        account: AccountDto::from(&account),
1268        presence: FrontendPresence::Warning,
1269        in_studio: false,
1270        game_name: None,
1271        game_place_id: None,
1272        session_expired: false,
1273    })
1274}
1275
1276/// Returns a widget's entry in the verified catalogue.
1277fn catalogue_entry(runtime: &Runtime, widget_id: &str) -> Result<CatalogueEntry, String> {
1278    runtime
1279        .catalogue
1280        .lock()
1281        .map_err(|_| "The widget catalogue is busy. Can you try again?".to_string())?
1282        .as_ref()
1283        .and_then(|catalogue| catalogue.entries.iter().find(|entry| entry.id == widget_id))
1284        .cloned()
1285        .ok_or_else(|| "The widget isn't in the verified catalogue. Can you refresh it?".into())
1286}
1287
1288/// Downloads a catalogue entry's package. Development builds package local catalogue folders
1289/// instead.
1290async fn download_package(entry: &CatalogueEntry, runtime: &Runtime) -> Result<Vec<u8>, String> {
1291    #[cfg(debug_assertions)]
1292    if let Ok(folder) = url::Url::parse(&entry.archive_url)
1293        .map_err(|_| ())
1294        .and_then(|url| url.to_file_path())
1295    {
1296        return crate::widgets::package_folder(&folder);
1297    }
1298    let response = runtime
1299        .client
1300        .get(&entry.archive_url)
1301        .send()
1302        .await
1303        .map_err(|_| {
1304            "The widget package couldn't be downloaded. Is the connection working?".to_string()
1305        })?;
1306    if !response.status().is_success() {
1307        return Err(format!(
1308            "The widget package download returned status {}. Can you try again?",
1309            response.status().as_u16()
1310        ));
1311    }
1312    read_response_limited(
1313        response,
1314        20 * 1024 * 1024,
1315        "The widget package is larger than 20 MB. Can you report this widget?",
1316        "The widget package couldn't be read. Can you try again?",
1317    )
1318    .await
1319}
1320
1321/// Downloads and installs a widget from the verified catalogue.
1322async fn install_catalogue_widget(widget_id: &str, runtime: &Runtime) -> Result<(), String> {
1323    let entry = catalogue_entry(runtime, widget_id)?;
1324    if let Some(minimum) = entry
1325        .min_app_version
1326        .as_deref()
1327        .filter(|minimum| !crate::widgets::app_supports(Some(minimum)))
1328    {
1329        return Err(crate::widgets::needs_newer_app(&entry.name, minimum));
1330    }
1331    let bytes = download_package(&entry, runtime).await?;
1332    crate::widgets::install_archive(
1333        &bytes,
1334        &entry.id,
1335        &entry.version,
1336        &entry.sha256,
1337        &entry.permissions,
1338        &runtime.widgets_root,
1339    )
1340    .inspect_err(|error| {
1341        log::warn!(
1342            "Widget {} {} wasn't installed: {error}",
1343            entry.id,
1344            entry.version
1345        );
1346    })?;
1347    log::info!("Installed widget {} {}", entry.id, entry.version);
1348    Ok(())
1349}
1350
1351/// Installs a catalogue widget that isn't installed yet.
1352#[tauri::command]
1353pub async fn install_widget(widget_id: String, runtime: State<'_, Runtime>) -> Result<(), String> {
1354    if find_installed_widget(&runtime, &widget_id).is_ok() {
1355        return Err("The widget is already installed. Can you update it instead?".into());
1356    }
1357    install_catalogue_widget(&widget_id, &runtime).await
1358}
1359
1360/// Stops a widget's processes and installs its newer catalogue version.
1361#[tauri::command]
1362pub async fn update_widget(
1363    app: AppHandle,
1364    widget_id: String,
1365    runtime: State<'_, Runtime>,
1366) -> Result<(), String> {
1367    let installed = find_installed_widget(&runtime, &widget_id)?;
1368    let entry = catalogue_entry(&runtime, &widget_id)?;
1369    let installed_version = semver::Version::parse(&installed.version).map_err(|_| {
1370        "The installed widget version isn't valid. Can you reinstall it?".to_string()
1371    })?;
1372    let available_version = semver::Version::parse(&entry.version)
1373        .map_err(|_| "The catalogue widget version isn't valid. Can you refresh it?".to_string())?;
1374    if available_version <= installed_version {
1375        return Err(
1376            "The catalogue doesn't contain a newer widget version. Can you refresh it?".into(),
1377        );
1378    }
1379    close_popout(&app, &widget_id);
1380    runtime
1381        .processes
1382        .lock()
1383        .map_err(|_| "The widget process manager is busy. Can you try again?".to_string())?
1384        .stop_widget(&widget_id);
1385    install_catalogue_widget(&widget_id, &runtime).await
1386}
1387
1388/// Stops a widget's processes, removes it, and clears its settings.
1389#[tauri::command]
1390pub fn uninstall_widget(
1391    app: AppHandle,
1392    widget_id: String,
1393    runtime: State<'_, Runtime>,
1394) -> Result<(), String> {
1395    close_popout(&app, &widget_id);
1396    runtime
1397        .processes
1398        .lock()
1399        .map_err(|_| "The widget process manager is busy. Can you try again?".to_string())?
1400        .stop_widget(&widget_id);
1401    crate::widgets::uninstall_widget(&widget_id, &runtime.widgets_root)?;
1402    log::info!("Uninstalled widget {widget_id}");
1403    let mut settings = runtime.storage.load_settings().map_err(command_error)?;
1404    settings.disabled_widgets.retain(|id| id != &widget_id);
1405    settings.widget_settings.remove(&widget_id);
1406    runtime
1407        .storage
1408        .save_settings(&settings)
1409        .map_err(command_error)
1410}
1411
1412/// Turns an installed widget on or off, stopping its processes when turned off.
1413#[tauri::command]
1414pub fn set_widget_enabled(
1415    app: AppHandle,
1416    widget_id: String,
1417    enabled: bool,
1418    runtime: State<'_, Runtime>,
1419) -> Result<(), String> {
1420    if !runtime.widgets_root.join(&widget_id).is_dir() {
1421        return Err("The widget isn't installed. Can you refresh the list?".into());
1422    }
1423    let mut settings = runtime.storage.load_settings().map_err(command_error)?;
1424    settings.disabled_widgets.retain(|id| id != &widget_id);
1425    log::info!(
1426        "{} widget {widget_id}",
1427        if enabled { "Enabled" } else { "Disabled" }
1428    );
1429    if !enabled {
1430        settings.disabled_widgets.push(widget_id.clone());
1431        close_popout(&app, &widget_id);
1432        runtime
1433            .processes
1434            .lock()
1435            .map_err(|_| "The widget process manager is busy. Can you try again?".to_string())?
1436            .stop_widget(&widget_id);
1437    }
1438    runtime
1439        .storage
1440        .save_settings(&settings)
1441        .map_err(command_error)
1442}
1443
1444/// Loads the widget catalogue again.
1445#[tauri::command]
1446pub async fn retry_catalogue(runtime: State<'_, Runtime>) -> Result<(), String> {
1447    refresh_catalogue_data(&runtime).await
1448}
1449
1450/// Base URL for installed widget assets. Windows WebView2 serves custom schemes over HTTP.
1451#[cfg(windows)]
1452const WIDGET_ORIGIN: &str = "http://widget.localhost";
1453/// Base URL for installed widget assets.
1454#[cfg(not(windows))]
1455const WIDGET_ORIGIN: &str = "widget://localhost";
1456
1457/// Returns the URL of a file in an installed widget.
1458fn widget_asset_url(widget_id: &str, path: &str) -> String {
1459    format!("{WIDGET_ORIGIN}/{widget_id}/{path}")
1460}
1461
1462/// A module's URL, tagged with the installed package's hash, or its version when no install record
1463/// exists. The page keeps each imported module by URL until it reloads, so a reinstall or update
1464/// needs a new URL to load the new code.
1465fn module_url(widget_id: &str, module: &str, sha256: &str, version: &str) -> String {
1466    let tag = sha256.get(..16).unwrap_or(version);
1467    format!("{}?v={tag}", widget_asset_url(widget_id, module))
1468}
1469
1470/// Downloads and verifies the signed widget catalogue, recording any error for the interface.
1471/// Debug builds without a catalogue URL use an empty catalogue.
1472async fn refresh_catalogue_data(runtime: &Runtime) -> Result<(), String> {
1473    let Some(url) = option_env!("TOOLBLOX_CATALOGUE_URL") else {
1474        #[cfg(debug_assertions)]
1475        {
1476            let catalogue = match crate::widgets::local_catalogue(
1477                &crate::widgets::LOCAL_CATALOGUE.map(std::path::Path::new),
1478            ) {
1479                Ok(catalogue) => catalogue,
1480                Err(error) => return set_catalogue_error(runtime, &error),
1481            };
1482            *runtime
1483                .catalogue
1484                .lock()
1485                .map_err(|_| "The widget catalogue is busy. Can you try again?".to_string())? =
1486                Some(catalogue);
1487            *runtime
1488                .catalogue_error
1489                .lock()
1490                .map_err(|_| "The widget catalogue is busy. Can you try again?".to_string())? =
1491                None;
1492            return Ok(());
1493        }
1494        #[cfg(not(debug_assertions))]
1495        return set_catalogue_error(
1496            runtime,
1497            "This build doesn't have a widget catalogue endpoint. Can you reinstall Toolblox?",
1498        );
1499    };
1500    let Some(public_key) = option_env!("TOOLBLOX_CATALOGUE_PUBLIC_KEY") else {
1501        return set_catalogue_error(
1502            runtime,
1503            "This build doesn't have a widget catalogue key. Can you reinstall Toolblox?",
1504        );
1505    };
1506    if !url.starts_with("https://") {
1507        return set_catalogue_error(
1508            runtime,
1509            "The widget catalogue endpoint isn't secure. Can you reinstall Toolblox?",
1510        );
1511    }
1512    let result = async {
1513        let response = runtime.client.get(url).send().await.map_err(|_| {
1514            "The widget catalogue couldn't be downloaded. Is the connection working?".to_string()
1515        })?;
1516        if !response.status().is_success() {
1517            return Err(format!(
1518                "The widget catalogue returned status {}. Can you try again?",
1519                response.status().as_u16()
1520            ));
1521        }
1522        let bytes = read_response_limited(
1523            response,
1524            1024 * 1024,
1525            "The widget catalogue is larger than 1 MB. Can you try again later?",
1526            "The widget catalogue couldn't be read. Can you try again?",
1527        )
1528        .await?;
1529        let signature = runtime
1530            .client
1531            .get(format!("{url}.sig"))
1532            .send()
1533            .await
1534            .map_err(|_| {
1535                "The widget catalogue signature couldn't be downloaded. Is the connection working?"
1536                    .to_string()
1537            })?;
1538        if !signature.status().is_success() {
1539            return Err(
1540                "The widget catalogue signature isn't available. Can you try again later?".into(),
1541            );
1542        }
1543        let signature = read_response_limited(
1544            signature,
1545            8 * 1024,
1546            "The widget catalogue signature is larger than expected. Can you try again later?",
1547            "The widget catalogue signature couldn't be read. Can you try again?",
1548        )
1549        .await?;
1550        let signature = String::from_utf8(signature).map_err(|_| {
1551            "The widget catalogue signature isn't valid text. Can you try again later?".to_string()
1552        })?;
1553        Catalogue::parse_verified(&bytes, &signature, public_key)
1554    }
1555    .await;
1556    match result {
1557        Ok(catalogue) => {
1558            *runtime
1559                .catalogue
1560                .lock()
1561                .map_err(|_| "The widget catalogue is busy. Can you try again?".to_string())? =
1562                Some(catalogue);
1563            *runtime
1564                .catalogue_error
1565                .lock()
1566                .map_err(|_| "The widget catalogue is busy. Can you try again?".to_string())? =
1567                None;
1568            Ok(())
1569        }
1570        Err(error) => set_catalogue_error(runtime, &error),
1571    }
1572}
1573
1574/// Records a catalogue error and returns it. A catalogue that already loaded stays in use, so a
1575/// failed recheck doesn't hide it.
1576fn set_catalogue_error(runtime: &Runtime, error: &str) -> Result<(), String> {
1577    log::warn!("Widget catalogue unavailable: {error}");
1578    if runtime
1579        .catalogue
1580        .lock()
1581        .is_ok_and(|catalogue| catalogue.is_some())
1582    {
1583        return Err(error.to_owned());
1584    }
1585    *runtime
1586        .catalogue_error
1587        .lock()
1588        .map_err(|_| "The widget catalogue is busy. Can you try again?".to_string())? =
1589        Some(error.to_owned());
1590    Err(error.to_owned())
1591}
1592
1593/// A widget surface to load and the session ID its requests must carry.
1594#[derive(Debug, Serialize)]
1595#[serde(rename_all = "camelCase")]
1596pub struct WidgetHostSession {
1597    session_id: String,
1598    url: String,
1599}
1600
1601/// Returns an installed widget by ID.
1602fn find_installed_widget(runtime: &Runtime, widget_id: &str) -> Result<InstalledWidget, String> {
1603    crate::widgets::discover_installed(&runtime.widgets_root)
1604        .into_iter()
1605        .filter_map(Result::ok)
1606        .find(|widget| widget.id == widget_id)
1607        .ok_or_else(|| "The widget isn't installed. Can you refresh the list?".into())
1608}
1609
1610/// Starts a session for a widget surface: `main`, `settings`, `dashboard`, or `module`.
1611///
1612/// Frame surfaces get the manifest's permissions. Module sessions get every permission because
1613/// modules run in the app window. Fails in safe mode and for disabled widgets.
1614#[tauri::command]
1615pub fn open_widget(
1616    widget_id: String,
1617    surface: Option<String>,
1618    runtime: State<'_, Runtime>,
1619) -> Result<WidgetHostSession, String> {
1620    let settings = runtime.storage.load_settings().map_err(command_error)?;
1621    if runtime.safe_mode {
1622        return Err("Widgets are off in safe mode. Can you restart Toolblox normally?".into());
1623    }
1624    if settings.disabled_widgets.contains(&widget_id) {
1625        return Err("The widget is disabled. Can you enable it first?".into());
1626    }
1627    let widget = find_installed_widget(&runtime, &widget_id)?;
1628    let permissions = widget.manifest.permissions.clone();
1629    let entry = match surface.as_deref().unwrap_or("main") {
1630        "main" => widget
1631            .manifest
1632            .entry
1633            .as_deref()
1634            .ok_or_else(|| "The widget doesn't provide a page.".to_string())?,
1635        "module" => {
1636            let module = widget
1637                .manifest
1638                .module
1639                .as_deref()
1640                .ok_or_else(|| "The widget doesn't provide a module.".to_string())?;
1641            return Ok(WidgetHostSession {
1642                session_id: insert_widget_session(
1643                    &runtime,
1644                    &widget_id,
1645                    crate::widgets::WidgetPermission::ALL.to_vec(),
1646                )?,
1647                url: widget_asset_url(&widget_id, module),
1648            });
1649        }
1650        "settings" => widget
1651            .manifest
1652            .settings_entry
1653            .as_deref()
1654            .ok_or_else(|| "The widget doesn't provide a settings view.".to_string())?,
1655        "dashboard" => widget
1656            .manifest
1657            .dashboard_entry
1658            .as_deref()
1659            .ok_or_else(|| "The widget doesn't provide a dashboard view.".to_string())?,
1660        _ => return Err("The widget surface isn't supported.".into()),
1661    };
1662    Ok(WidgetHostSession {
1663        session_id: insert_widget_session(&runtime, &widget_id, permissions)?,
1664        url: widget_asset_url(&widget_id, entry),
1665    })
1666}
1667
1668/// Registers a widget session with a random ID.
1669fn insert_widget_session(
1670    runtime: &Runtime,
1671    widget_id: &str,
1672    permissions: Vec<crate::widgets::WidgetPermission>,
1673) -> Result<String, String> {
1674    let session_id = uuid::Uuid::new_v4().to_string();
1675    runtime
1676        .widget_sessions
1677        .lock()
1678        .map_err(|_| "The widget session manager is busy. Can you try again?".to_string())?
1679        .insert(
1680            session_id.clone(),
1681            crate::widget_ipc::WidgetSession::new(widget_id.to_string(), permissions),
1682        );
1683    Ok(session_id)
1684}
1685
1686/// Largest value a widget can keep in its own store.
1687const MAX_WIDGET_STORE_BYTES: usize = 1024 * 1024;
1688
1689/// Reads the free-form JSON value a widget keeps for itself.
1690#[tauri::command]
1691pub fn get_widget_store(widget_id: String, runtime: State<'_, Runtime>) -> Result<Value, String> {
1692    find_installed_widget(&runtime, &widget_id)?;
1693    let settings = runtime.storage.load_settings().map_err(command_error)?;
1694    Ok(settings
1695        .widget_settings
1696        .get(&widget_id)
1697        .cloned()
1698        .unwrap_or(Value::Null))
1699}
1700
1701/// Replaces the free-form JSON value a widget keeps for itself.
1702#[tauri::command]
1703pub fn set_widget_store(
1704    widget_id: String,
1705    value: Value,
1706    runtime: State<'_, Runtime>,
1707) -> Result<(), String> {
1708    find_installed_widget(&runtime, &widget_id)?;
1709    let size = serde_json::to_vec(&value)
1710        .map_err(|_| "The widget data isn't valid JSON.".to_string())?
1711        .len();
1712    if size > MAX_WIDGET_STORE_BYTES {
1713        return Err("The widget data is larger than 1 MB. Can the widget store less?".into());
1714    }
1715    runtime
1716        .storage
1717        .update_settings(|settings| {
1718            if value.is_null() {
1719                settings.widget_settings.remove(&widget_id);
1720            } else {
1721                settings.widget_settings.insert(widget_id.clone(), value);
1722            }
1723            Ok(())
1724        })
1725        .map_err(command_error)
1726}
1727
1728/// Restarts Toolblox, optionally without loading any widgets for the next session.
1729#[tauri::command]
1730pub fn restart_app(app: AppHandle, safe_mode: bool, runtime: State<'_, Runtime>) {
1731    crate::set_safe_mode_marker(runtime.storage.root(), safe_mode);
1732    app.restart();
1733}
1734
1735/// The default window size in logical pixels, from `tauri.conf.json`. Snapping keeps its shape.
1736const DEFAULT_WINDOW: (f64, f64) = (900.0, 500.0);
1737/// The minimum window size in logical pixels, from `tauri.conf.json`.
1738const MIN_WINDOW: (f64, f64) = (720.0, 480.0);
1739const MIN_WINDOW_HEIGHT: f64 = MIN_WINDOW.1;
1740/// The mini window's width, and the range of heights it can grow to, in logical pixels.
1741const MINI_WINDOW_WIDTH: f64 = 280.0;
1742const MINI_WINDOW_HEIGHTS: (f64, f64) = (40.0, 420.0);
1743
1744/// The mini window's size for a requested `height`, kept within its range.
1745pub(crate) fn mini_window_size(height: f64) -> (f64, f64) {
1746    let height = if height.is_finite() {
1747        height
1748    } else {
1749        MINI_WINDOW_HEIGHTS.0
1750    };
1751    (
1752        MINI_WINDOW_WIDTH,
1753        height
1754            .clamp(MINI_WINDOW_HEIGHTS.0, MINI_WINDOW_HEIGHTS.1)
1755            .round(),
1756    )
1757}
1758
1759/// The size with the default aspect ratio for a window `width` wide, at least the minimum height,
1760/// and shrunk to fit `available`.
1761pub(crate) fn snapped_window_size(width: f64, available: (f64, f64)) -> (f64, f64) {
1762    let ratio = DEFAULT_WINDOW.0 / DEFAULT_WINDOW.1;
1763    let height = (width / ratio).max(MIN_WINDOW_HEIGHT);
1764    let width = height * ratio;
1765    let fit = (available.0 / width).min(available.1 / height).min(1.0);
1766    ((width * fit).round(), (height * fit).round())
1767}
1768
1769/// Leaves fullscreen or maximized and resizes the main window to the default aspect ratio,
1770/// keeping its width where it fits on the screen.
1771#[tauri::command]
1772pub fn snap_window(app: AppHandle) -> Result<(), String> {
1773    let window = app
1774        .get_webview_window(crate::lifecycle::MAIN_WINDOW_LABEL)
1775        .ok_or("The Toolblox window wasn't found. Does restarting Toolblox help?")?;
1776    if window.is_fullscreen().map_err(command_error)? {
1777        window.set_fullscreen(false).map_err(command_error)?;
1778    }
1779    if window.is_maximized().map_err(command_error)? {
1780        window.unmaximize().map_err(command_error)?;
1781    }
1782    let scale = window.scale_factor().map_err(command_error)?;
1783    let size = window
1784        .inner_size()
1785        .map_err(command_error)?
1786        .to_logical::<f64>(scale);
1787    let available = window
1788        .current_monitor()
1789        .map_err(command_error)?
1790        .map(|monitor| {
1791            let area = monitor
1792                .work_area()
1793                .size
1794                .to_logical::<f64>(monitor.scale_factor());
1795            (area.width * 0.9, area.height * 0.9)
1796        })
1797        .unwrap_or((f64::MAX, f64::MAX));
1798    let (width, height) = snapped_window_size(size.width, available);
1799    window
1800        .set_size(tauri::LogicalSize::new(width, height))
1801        .map_err(command_error)
1802}
1803
1804/// Turns the main window into the mini window, `height` logical pixels tall, or restores it when
1805/// `height` is `None`. The mini window is borderless, fixed in size, and always on top. Restoring
1806/// brings back the previous position and size and the Always on top setting.
1807#[tauri::command]
1808pub fn set_mini_window(
1809    app: AppHandle,
1810    height: Option<f64>,
1811    runtime: State<'_, Runtime>,
1812    lifecycle: State<'_, Arc<crate::lifecycle::LifecycleState>>,
1813) -> Result<(), String> {
1814    let window = app
1815        .get_webview_window(crate::lifecycle::MAIN_WINDOW_LABEL)
1816        .ok_or("The Toolblox window wasn't found. Does restarting Toolblox help?")?;
1817    let mut restore = lifecycle.mini_restore.lock().map_err(command_error)?;
1818    let Some(height) = height else {
1819        let Some((position, size)) = restore.take() else {
1820            return Ok(());
1821        };
1822        let always_on_top = runtime
1823            .storage
1824            .load_settings()
1825            .is_ok_and(|settings| settings.always_on_top);
1826        window.set_decorations(true).map_err(command_error)?;
1827        window.set_resizable(true).map_err(command_error)?;
1828        window
1829            .set_min_size(Some(tauri::LogicalSize::new(MIN_WINDOW.0, MIN_WINDOW.1)))
1830            .map_err(command_error)?;
1831        window.set_size(size).map_err(command_error)?;
1832        window.set_position(position).map_err(command_error)?;
1833        return window
1834            .set_always_on_top(always_on_top)
1835            .map_err(command_error);
1836    };
1837    if restore.is_none() {
1838        if window.is_fullscreen().map_err(command_error)? {
1839            window.set_fullscreen(false).map_err(command_error)?;
1840        }
1841        if window.is_maximized().map_err(command_error)? {
1842            window.unmaximize().map_err(command_error)?;
1843        }
1844        *restore = Some((
1845            window.outer_position().map_err(command_error)?,
1846            window.inner_size().map_err(command_error)?,
1847        ));
1848        window
1849            .set_min_size(None::<tauri::LogicalSize<f64>>)
1850            .map_err(command_error)?;
1851        window.set_decorations(false).map_err(command_error)?;
1852        window.set_resizable(false).map_err(command_error)?;
1853        window.set_always_on_top(true).map_err(command_error)?;
1854    }
1855    let (width, height) = mini_window_size(height);
1856    window
1857        .set_size(tauri::LogicalSize::new(width, height))
1858        .map_err(command_error)
1859}
1860
1861/// Moves the main window with the pointer, for the mini window, which has no title bar.
1862#[tauri::command]
1863pub fn start_window_drag(app: AppHandle) -> Result<(), String> {
1864    app.get_webview_window(crate::lifecycle::MAIN_WINDOW_LABEL)
1865        .ok_or("The Toolblox window wasn't found. Does restarting Toolblox help?")?
1866        .start_dragging()
1867        .map_err(command_error)
1868}
1869
1870/// Shows a system notification, used in place of in-app messages while the mini window is open.
1871/// The title and body are cut to 64 and 256 characters.
1872#[tauri::command]
1873pub fn show_notification(app: AppHandle, title: String, body: String) -> Result<(), String> {
1874    use tauri_plugin_notification::NotificationExt;
1875    let title: String = title.chars().take(64).collect();
1876    let body: String = body.chars().take(256).collect();
1877    app.notification()
1878        .builder()
1879        .title(title)
1880        .body(body)
1881        .show()
1882        .map_err(command_error)
1883}
1884
1885/// Event sent to every window when the widget catalogue reloads, or when development builds reinstall
1886/// widgets from the working tree.
1887pub const WIDGETS_CHANGED: &str = "widgets-changed";
1888
1889/// Reinstalls installed widgets whose folder under `widgets/` in the working tree changed since the
1890/// last call, stopping their processes first. `seen` keeps each folder's fingerprint between calls.
1891/// Returns whether any widget was reinstalled. Development builds only.
1892#[cfg(debug_assertions)]
1893pub fn sync_local_widgets(runtime: &Runtime, seen: &mut HashMap<String, u64>) -> bool {
1894    let Ok(entries) = std::fs::read_dir(crate::widgets::LOCAL_CATALOGUE[0]) else {
1895        return false;
1896    };
1897    let mut changed = false;
1898    for entry in entries.flatten() {
1899        let id = entry.file_name().to_string_lossy().into_owned();
1900        let folder = entry.path();
1901        if id.starts_with('.') || !folder.is_dir() {
1902            continue;
1903        }
1904        let fingerprint = crate::widgets::folder_fingerprint(&folder);
1905        if seen.insert(id.clone(), fingerprint) == Some(fingerprint) {
1906            continue;
1907        }
1908        let Ok(installed) = find_installed_widget(runtime, &id) else {
1909            continue;
1910        };
1911        let stop = || {
1912            if let Ok(mut processes) = runtime.processes.lock() {
1913                processes.stop_widget(&id);
1914            }
1915        };
1916        match crate::widgets::reinstall_from_folder(
1917            &folder,
1918            &installed.sha256,
1919            &runtime.widgets_root,
1920            stop,
1921        ) {
1922            Ok(true) => {
1923                log::info!("Reinstalled widget {id} from the working tree");
1924                changed = true;
1925            }
1926            Ok(false) => {}
1927            Err(error) => {
1928                log::warn!("Widget {id} wasn't reinstalled from the working tree: {error}")
1929            }
1930        }
1931    }
1932    changed
1933}
1934
1935/// Event sent to every window with the open popouts' widget IDs whenever one opens or closes.
1936const POPOUTS_CHANGED: &str = "widget-popouts-changed";
1937
1938/// IDs of widgets open in their own window, sorted, leaving out `closing`.
1939fn open_popouts(app: &AppHandle, closing: Option<&str>) -> Vec<String> {
1940    let mut ids: Vec<String> = app
1941        .webview_windows()
1942        .keys()
1943        .filter(|label| Some(label.as_str()) != closing)
1944        .filter_map(|label| crate::lifecycle::popout_widget_id(label))
1945        .map(str::to_owned)
1946        .collect();
1947    ids.sort();
1948    ids
1949}
1950
1951/// Closes a widget's popout window, if one is open.
1952fn close_popout(app: &AppHandle, widget_id: &str) {
1953    let label = format!("{}{widget_id}", crate::lifecycle::POPOUT_WINDOW_PREFIX);
1954    if let Some(window) = app.get_webview_window(&label) {
1955        let _ = window.destroy();
1956    }
1957}
1958
1959/// Opens an enabled module widget in its own window, or shows the window when it's already open.
1960///
1961/// The window loads the app's own interface, which then runs only that widget's module. Async,
1962/// because creating a window from a synchronous command can deadlock on Windows.
1963#[tauri::command]
1964pub async fn open_widget_popout(
1965    app: AppHandle,
1966    widget_id: String,
1967    runtime: State<'_, Runtime>,
1968) -> Result<(), String> {
1969    crate::widgets::validate_widget_id(&widget_id)?;
1970    if runtime.safe_mode {
1971        return Err("Widgets are off in safe mode. Can you restart Toolblox normally?".into());
1972    }
1973    let settings = runtime.storage.load_settings().map_err(command_error)?;
1974    if settings.disabled_widgets.contains(&widget_id) {
1975        return Err("The widget is disabled. Can you enable it first?".into());
1976    }
1977    let widget = find_installed_widget(&runtime, &widget_id)?;
1978    if widget.manifest.module.is_none() {
1979        return Err("The widget can't open in its own window. Does it have a module?".into());
1980    }
1981    let label = format!("{}{widget_id}", crate::lifecycle::POPOUT_WINDOW_PREFIX);
1982    if let Some(window) = app.get_webview_window(&label) {
1983        let _ = window.unminimize();
1984        let _ = window.show();
1985        return window
1986            .set_focus()
1987            .map_err(|_| "The widget window couldn't be shown. Is it still open?".to_string());
1988    }
1989    let ((width, height), (min_width, min_height)) = match widget.manifest.popout {
1990        crate::widgets::PopoutShape::Portrait => ((380.0, 520.0), (320.0, 400.0)),
1991        crate::widgets::PopoutShape::Landscape => ((600.0, 320.0), (520.0, 280.0)),
1992    };
1993    let window =
1994        tauri::WebviewWindowBuilder::new(&app, &label, tauri::WebviewUrl::App("index.html".into()))
1995            .title(&widget.manifest.name)
1996            .inner_size(width, height)
1997            .min_inner_size(min_width, min_height)
1998            .always_on_top(widget.manifest.popout_on_top)
1999            .build()
2000            .map_err(|_| "The widget window didn't open. Does retrying help?".to_string())?;
2001    let handle = app.clone();
2002    window.on_window_event(move |event| {
2003        if matches!(event, tauri::WindowEvent::Destroyed) {
2004            let _ = handle.emit(POPOUTS_CHANGED, open_popouts(&handle, Some(&label)));
2005        }
2006    });
2007    log::info!("Opened widget {widget_id} in its own window");
2008    let _ = app.emit(POPOUTS_CHANGED, open_popouts(&app, None));
2009    Ok(())
2010}
2011
2012/// Closes a widget's own window, returning the widget to the main window.
2013#[tauri::command]
2014pub fn close_widget_popout(app: AppHandle, widget_id: String) -> Result<(), String> {
2015    crate::widgets::validate_widget_id(&widget_id)?;
2016    close_popout(&app, &widget_id);
2017    Ok(())
2018}
2019
2020#[tauri::command]
2021pub fn close_widget_session(session_id: String, runtime: State<'_, Runtime>) {
2022    if let Ok(mut sessions) = runtime.widget_sessions.lock() {
2023        sessions.remove(&session_id);
2024    }
2025}
2026
2027/// Authorizes a widget message against its session and runs it. Method failures are returned
2028/// in the response rather than as a command error.
2029#[tauri::command]
2030pub async fn widget_request(
2031    session_id: String,
2032    widget_id: String,
2033    message: String,
2034    runtime: State<'_, Runtime>,
2035) -> Result<crate::widget_ipc::WidgetResponse, String> {
2036    let request = runtime
2037        .widget_sessions
2038        .lock()
2039        .map_err(|_| "The widget session manager is busy. Can you try again?".to_string())?
2040        .authorize(&session_id, &widget_id, message.as_bytes())?;
2041    let request_id = request.request_id.clone();
2042    match dispatch_widget_request(&runtime, &widget_id, &request.method, request.params)
2043        .await
2044        .and_then(without_session_cookie)
2045    {
2046        Ok(result) => Ok(crate::widget_ipc::success(request_id, result)),
2047        Err(error) => {
2048            log::warn!(
2049                target: &widget_target(&widget_id),
2050                "Request {} failed: {error}",
2051                request.method
2052            );
2053            Ok(crate::widget_ipc::failure(request_id, error))
2054        }
2055    }
2056}
2057
2058/// Refuses a widget response that contains a Roblox session cookie, whatever its source.
2059fn without_session_cookie(result: Value) -> Result<Value, String> {
2060    if crate::credentials::contains_session_cookie(&result.to_string()) {
2061        return Err(
2062            "The response was blocked because it contained a Roblox session. Can you report this widget?"
2063                .into(),
2064        );
2065    }
2066    Ok(result)
2067}
2068
2069/// Runs an authorized widget method.
2070async fn dispatch_widget_request(
2071    runtime: &Runtime,
2072    widget_id: &str,
2073    method: &str,
2074    params: Value,
2075) -> Result<Value, String> {
2076    match method {
2077        "accounts.list" => {
2078            let accounts = runtime.storage.load_accounts().map_err(command_error)?;
2079            Ok(Value::Array(
2080                accounts
2081                    .iter()
2082                    .map(|account| {
2083                        json!({
2084                            "id": account.id,
2085                            "name": account.name,
2086                            "displayName": account.display_name,
2087                            "avatarUrl": account.avatar_url,
2088                        })
2089                    })
2090                    .collect(),
2091            ))
2092        }
2093        "widgetData.get" => {
2094            let account_id = required_u64(&params, "accountId")?;
2095            let accounts = runtime.storage.load_accounts().map_err(command_error)?;
2096            let account = accounts
2097                .iter()
2098                .find(|account| account.id == account_id)
2099                .ok_or_else(|| {
2100                    "The account wasn't found. Can you refresh the widget?".to_string()
2101                })?;
2102            Ok(account
2103                .widget_data
2104                .get(widget_id)
2105                .cloned()
2106                .unwrap_or(Value::Null))
2107        }
2108        "widgetData.set" => {
2109            let account_id = required_u64(&params, "accountId")?;
2110            let value = params
2111                .get("value")
2112                .cloned()
2113                .ok_or_else(|| "The widget data value is missing.".to_string())?;
2114            if serde_json::to_vec(&value)
2115                .map_err(|_| "The widget data isn't valid JSON.".to_string())?
2116                .len()
2117                > 1024 * 1024
2118            {
2119                return Err("The widget data is larger than 1 MB.".into());
2120            }
2121            runtime
2122                .storage
2123                .update_accounts(|accounts| {
2124                    let account = accounts
2125                        .iter_mut()
2126                        .find(|account| account.id == account_id)
2127                        .ok_or_else(|| {
2128                            StorageError::Invalid(
2129                                "The account wasn't found. Can you refresh the widget?".into(),
2130                            )
2131                        })?;
2132                    account.widget_data.insert(widget_id.to_owned(), value);
2133                    Ok(())
2134                })
2135                .map_err(command_error)?;
2136            Ok(Value::Null)
2137        }
2138        "roblox.status" => {
2139            let accounts = runtime.storage.load_accounts().map_err(command_error)?;
2140            let ids: Vec<_> = accounts.iter().map(|account| account.id).collect();
2141            for account in &accounts {
2142                let Ok(secret) = runtime.credentials.get(account.id) else {
2143                    continue;
2144                };
2145                match crate::roblox::fetch_presence(&runtime.client, &secret, &ids).await {
2146                    Ok(states) => return Ok(json!(states)),
2147                    Err(crate::roblox::RobloxError::Rejected(_)) => continue,
2148                    Err(error) => return Err(command_error(error)),
2149                }
2150            }
2151            Err("No signed-in account could check Roblox status. Can you sign in again?".into())
2152        }
2153        "roblox.join" => {
2154            let account_ids = required_u64_array(&params, "accountIds")?;
2155            join_account_ids(runtime, &account_ids, true, None, None).await?;
2156            Ok(Value::Null)
2157        }
2158        "network.fetch" => widget_network_fetch(runtime, widget_id, &params).await,
2159        "log.write" => {
2160            let level = params
2161                .get("level")
2162                .cloned()
2163                .map_or(Ok(LogLevel::Info), serde_json::from_value)
2164                .map_err(|_| {
2165                    "The widget parameter level must be debug, info, warn, or error.".to_string()
2166                })?;
2167            write_record(
2168                level,
2169                &widget_target(widget_id),
2170                required_string(&params, "message")?,
2171            );
2172            Ok(Value::Null)
2173        }
2174        "process.spawn" => {
2175            let process_id = required_string(&params, "processId")?;
2176            let arguments = optional_string_array(&params, "arguments")?;
2177            let widget = find_installed_widget(runtime, widget_id)?;
2178            let declaration = widget
2179                .manifest
2180                .processes
2181                .iter()
2182                .find(|process| process.id == process_id)
2183                .ok_or_else(|| "The widget process isn't declared.".to_string())?;
2184            runtime
2185                .processes
2186                .lock()
2187                .map_err(|_| "The widget process manager is busy. Can you try again?".to_string())?
2188                .start(
2189                    widget_id,
2190                    &runtime.widgets_root.join(widget_id),
2191                    declaration,
2192                    &arguments,
2193                )?;
2194            Ok(Value::Null)
2195        }
2196        "process.send" => {
2197            let process_id = required_string(&params, "processId")?;
2198            let value = params
2199                .get("message")
2200                .cloned()
2201                .ok_or_else(|| "The process message is missing.".to_string())?;
2202            let message = serde_json::to_string(&value)
2203                .map_err(|_| "The process message isn't valid JSON.".to_string())?;
2204            let mut processes = runtime.processes.lock().map_err(|_| {
2205                "The widget process manager is busy. Can you try again?".to_string()
2206            })?;
2207            processes.send(widget_id, process_id, &message)?;
2208            Ok(json!({ "events": processes.drain_events(widget_id) }))
2209        }
2210        "process.poll" => {
2211            let mut processes = runtime.processes.lock().map_err(|_| {
2212                "The widget process manager is busy. Can you try again?".to_string()
2213            })?;
2214            Ok(json!({ "events": processes.drain_events(widget_id) }))
2215        }
2216        "process.stop" => {
2217            let process_id = required_string(&params, "processId")?;
2218            runtime
2219                .processes
2220                .lock()
2221                .map_err(|_| "The widget process manager is busy. Can you try again?".to_string())?
2222                .stop(widget_id, process_id)?;
2223            Ok(Value::Null)
2224        }
2225        _ => Err("The widget method isn't supported.".into()),
2226    }
2227}
2228
2229/// Joins each account at `place_id` when given, otherwise at its own place or the default place.
2230/// A player target follows that player, and fails for any account that can see they aren't in a
2231/// game.
2232///
2233/// `progress` is called with the number of the account being joined and the total. Returns
2234/// `false` when `cancel_join` stopped the join before every account was launched.
2235pub(crate) async fn join_account_ids(
2236    runtime: &Runtime,
2237    account_ids: &[u64],
2238    record_play: bool,
2239    place_id: Option<&str>,
2240    progress: Option<&(dyn Fn(usize, usize) + Sync)>,
2241) -> Result<bool, String> {
2242    let generation = runtime.join_generation.load(Ordering::SeqCst);
2243    let cancelled = || runtime.join_generation.load(Ordering::SeqCst) != generation;
2244    let cancelled_account = |id: u64, take: bool| {
2245        runtime.cancelled_joins.lock().is_ok_and(|mut set| {
2246            if take {
2247                set.remove(&id)
2248            } else {
2249                set.contains(&id)
2250            }
2251        })
2252    };
2253    if let Ok(mut set) = runtime.cancelled_joins.lock() {
2254        for id in account_ids {
2255            set.remove(id);
2256        }
2257    }
2258    let settings = runtime.storage.load_settings().map_err(command_error)?;
2259    let default_place = crate::roblox::parse_join_target(&settings.place_id).ok();
2260    let accounts = runtime.storage.load_accounts().map_err(command_error)?;
2261    let mut expired = Vec::new();
2262    let mut delay = std::time::Duration::ZERO;
2263    'accounts: for (index, id) in account_ids.iter().enumerate() {
2264        if cancelled() {
2265            log::info!(
2266                "Join stopped before account {} of {}",
2267                index + 1,
2268                account_ids.len()
2269            );
2270            return Ok(false);
2271        }
2272        if cancelled_account(*id, true) {
2273            log::info!("Join for account {id} was cancelled");
2274            continue;
2275        }
2276        if let Some(progress) = progress {
2277            progress(index + 1, account_ids.len());
2278        }
2279        let Some(account) = accounts.iter().find(|account| account.id == *id) else {
2280            return Err("An account wasn't found. Can you refresh the widget?".into());
2281        };
2282        if runtime.session_expired(*id) {
2283            expired.push(account.display_name.clone());
2284            continue;
2285        }
2286        let target = match place_id.or(account.place_id.as_deref()) {
2287            Some(place_id) => crate::roblox::parse_join_target(place_id).map_err(command_error)?,
2288            None => default_place.clone().ok_or_else(|| {
2289                "No place is set to join. Can you set one on the Accounts page?".to_string()
2290            })?,
2291        };
2292        let secret = match runtime.session(*id) {
2293            Ok(secret) => secret,
2294            Err(crate::credentials::CredentialError::Missing) => {
2295                expired.push(account.display_name.clone());
2296                continue;
2297            }
2298            Err(error) => {
2299                log::warn!("Session for account {id} couldn't be read: {error}");
2300                return Err(command_error(error));
2301            }
2302        };
2303        let place_id = match &target {
2304            crate::roblox::JoinTarget::Place(place_id) => Some(place_id.clone()),
2305            crate::roblox::JoinTarget::User(user_id) => {
2306                followed_place(runtime, &secret, *id, *user_id).await?
2307            }
2308        };
2309        match &target {
2310            crate::roblox::JoinTarget::Place(place_id) => {
2311                log::info!("Joining place {place_id} as account {id}")
2312            }
2313            crate::roblox::JoinTarget::User(user_id) => {
2314                log::info!("Following player {user_id} as account {id}")
2315            }
2316        }
2317        let mut attempt = 0;
2318        let uri = loop {
2319            match crate::roblox::build_join_uri(&runtime.client, &secret, &target).await {
2320                Ok(uri) => break uri,
2321                Err(error @ crate::roblox::RobloxError::InvalidPlace) => {
2322                    log::warn!("Target {target} isn't joinable: {error}");
2323                    return Err(command_error(error));
2324                }
2325                Err(error @ crate::roblox::RobloxError::Rejected(401)) => {
2326                    runtime.note_session(*id, &Err::<(), _>(error));
2327                    expired.push(account.display_name.clone());
2328                    continue 'accounts;
2329                }
2330                Err(error) => {
2331                    attempt += 1;
2332                    if attempt > LAUNCH_RETRIES {
2333                        log::warn!("Join ticket for account {id} failed after retries: {error}");
2334                        return Err(command_error(error));
2335                    }
2336                    log::info!("Join ticket for account {id} failed, retrying: {error}");
2337                    delay = next_launch_delay(delay);
2338                    tokio::time::sleep(delay).await;
2339                }
2340            }
2341        };
2342        if cancelled() {
2343            log::info!("Join stopped before account {id} opened Roblox");
2344            return Ok(false);
2345        }
2346        if cancelled_account(*id, true) {
2347            log::info!("Join for account {id} was cancelled before Roblox opened");
2348            continue;
2349        }
2350        if settings.multi_instance {
2351            let mut cleared = runtime
2352                .cleared_roblox_pids
2353                .lock()
2354                .map_err(|_| "The multi-instance state is busy. Can you try again?".to_string())?;
2355            crate::multi_instance::clear_new_roblox_instances(
2356                runtime.multi_instance_helper.as_deref(),
2357                &mut cleared,
2358            )
2359            .inspect_err(|error| log::warn!("Multiple instances couldn't be enabled: {error}"))?;
2360        } else {
2361            crate::multi_instance::release_roblox_singleton();
2362        }
2363        if settings.multi_instance && cfg!(target_os = "macos") {
2364            crate::multi_instance::open_new_roblox_instance(&uri).inspect_err(|error| {
2365                log::warn!("A separate Roblox client couldn't be started: {error}")
2366            })?;
2367        } else {
2368            opener::open(uri).map_err(|error| {
2369                log::error!("Roblox couldn't be opened: {error}");
2370                "Roblox couldn't be opened. Is Roblox installed?".to_string()
2371            })?;
2372        }
2373        if record_play {
2374            runtime
2375                .storage
2376                .update_accounts(|accounts| {
2377                    let account = accounts
2378                        .iter_mut()
2379                        .find(|account| account.id == *id)
2380                        .ok_or_else(|| {
2381                            StorageError::Invalid(
2382                                "The launched account wasn't found. Can you refresh the list?"
2383                                    .into(),
2384                            )
2385                        })?;
2386                    account
2387                        .record_play(now_seconds(), place_id.as_deref())
2388                        .map_err(StorageError::Invalid)
2389                })
2390                .map_err(command_error)?;
2391        }
2392        if index + 1 < account_ids.len() {
2393            let next = account_ids[index + 1];
2394            wait_until_in_game(runtime, &secret, *id, || {
2395                cancelled() || cancelled_account(next, false)
2396            })
2397            .await;
2398        }
2399    }
2400    match expired.as_slice() {
2401        [] => Ok(true),
2402        [name] => Err(format!(
2403            "{name} didn't join because its session expired. Can you sign in again from the Accounts page?"
2404        )),
2405        names => Err(format!(
2406            "{} didn't join because their sessions expired. Can you sign them in again from the Accounts page?",
2407            names.join(", ")
2408        )),
2409    }
2410}
2411
2412/// Returns a followed player's place when the joining account can see it. Only Roblox Studio stops
2413/// the join: privacy settings report a player in game as online or offline to accounts that can't
2414/// see their game, and the Roblox client reports a failed follow itself.
2415async fn followed_place(
2416    runtime: &Runtime,
2417    secret: &Secret,
2418    account_id: u64,
2419    user_id: u64,
2420) -> Result<Option<String>, String> {
2421    let result = crate::roblox::fetch_presence_details(&runtime.client, secret, &[user_id]).await;
2422    runtime.note_session(account_id, &result);
2423    let detail = match result {
2424        Ok(mut details) => details.remove(&user_id),
2425        Err(error) => {
2426            log::info!("Presence of player {user_id} couldn't be checked: {error}");
2427            None
2428        }
2429    };
2430    match detail.map(|detail| (detail.state, detail.place_id)) {
2431        Some((crate::models::PresenceState::InStudio, _)) => {
2432            Err("The player is in Roblox Studio. Can you try again once they're in a game?".into())
2433        }
2434        Some((_, place_id)) => Ok(place_id.map(|id| id.to_string())),
2435        None => Ok(None),
2436    }
2437}
2438
2439/// How often a join waiting between accounts checks whether it was stopped.
2440const CANCEL_POLL: std::time::Duration = std::time::Duration::from_millis(100);
2441
2442/// Cancels the joins in progress for `account_ids`, or every join in progress when it's `None`.
2443/// An account that already opened Roblox stays in game.
2444#[tauri::command]
2445pub fn cancel_join(account_ids: Option<Vec<u64>>, runtime: State<'_, Runtime>) {
2446    match account_ids {
2447        None => {
2448            runtime.join_generation.fetch_add(1, Ordering::SeqCst);
2449            log::info!("Joins in progress were stopped");
2450        }
2451        Some(ids) => {
2452            if let Ok(mut set) = runtime.cancelled_joins.lock() {
2453                set.extend(ids.iter().copied());
2454            }
2455            log::info!("Joins were cancelled for {} accounts", ids.len());
2456        }
2457    }
2458}
2459
2460/// First wait before a ticket request is retried.
2461const FIRST_LAUNCH_DELAY: std::time::Duration = std::time::Duration::from_secs(1);
2462/// Longest gap between launches after failures.
2463const MAX_LAUNCH_DELAY: std::time::Duration = std::time::Duration::from_secs(5);
2464/// Ticket requests retried per account before the join fails.
2465const LAUNCH_RETRIES: u32 = 3;
2466
2467/// Doubles a retry wait, from one second up to five.
2468fn next_launch_delay(current: std::time::Duration) -> std::time::Duration {
2469    (current * 2).clamp(FIRST_LAUNCH_DELAY, MAX_LAUNCH_DELAY)
2470}
2471
2472/// How often the queue checks whether the account it launched is in game.
2473const QUEUE_POLL: std::time::Duration = std::time::Duration::from_secs(2);
2474/// Longest the queue waits for one account before launching the next, for a client that crashed
2475/// or never finished loading.
2476const QUEUE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
2477
2478/// Waits until Roblox reports `account_id` in game, `stop` returns `true`, or [`QUEUE_TIMEOUT`]
2479/// passes. An account that was already in game counts as joined at once, because Roblox keeps
2480/// reporting its old server until the new client takes over.
2481async fn wait_until_in_game(
2482    runtime: &Runtime,
2483    secret: &Secret,
2484    account_id: u64,
2485    stop: impl Fn() -> bool,
2486) {
2487    let deadline = tokio::time::Instant::now() + QUEUE_TIMEOUT;
2488    let mut next_check = tokio::time::Instant::now() + QUEUE_POLL;
2489    while !stop() && tokio::time::Instant::now() < deadline {
2490        if tokio::time::Instant::now() >= next_check {
2491            next_check = tokio::time::Instant::now() + QUEUE_POLL;
2492            let result =
2493                crate::roblox::fetch_presence(&runtime.client, secret, &[account_id]).await;
2494            runtime.note_session(account_id, &result);
2495            if result.is_ok_and(|states| {
2496                states.get(&account_id) == Some(&crate::models::PresenceState::InGame)
2497            }) {
2498                return;
2499            }
2500        }
2501        tokio::time::sleep(CANCEL_POLL).await;
2502    }
2503    if !stop() {
2504        log::info!(
2505            "Account {account_id} wasn't in game after {} seconds; launching the next account",
2506            QUEUE_TIMEOUT.as_secs()
2507        );
2508    }
2509}
2510
2511/// Fetches an HTTPS URL for a widget and returns the status and a text body of up to 1 MB.
2512async fn widget_network_fetch(
2513    runtime: &Runtime,
2514    widget_id: &str,
2515    params: &Value,
2516) -> Result<Value, String> {
2517    let url = required_string(params, "url")?;
2518    let parsed = url::Url::parse(url).map_err(|_| "The widget URL isn't valid.".to_string())?;
2519    if parsed.scheme() != "https" || parsed.username() != "" || parsed.password().is_some() {
2520        return Err("Widgets can only fetch HTTPS URLs without embedded credentials.".into());
2521    }
2522    find_installed_widget(runtime, widget_id)?;
2523    let response =
2524        runtime.client.get(parsed).send().await.map_err(|_| {
2525            "The widget network request failed. Is the connection working?".to_string()
2526        })?;
2527    let status = response.status().as_u16();
2528    let bytes = read_response_limited(
2529        response,
2530        1024 * 1024,
2531        "The widget network response is larger than 1 MB.",
2532        "The widget network response couldn't be read.",
2533    )
2534    .await?;
2535    let body = String::from_utf8(bytes)
2536        .map_err(|_| "The widget network response isn't UTF-8 text.".to_string())?;
2537    Ok(json!({ "status": status, "body": body }))
2538}
2539
2540/// Reads a required non-negative integer parameter.
2541fn required_u64(params: &Value, field: &str) -> Result<u64, String> {
2542    params
2543        .get(field)
2544        .and_then(Value::as_u64)
2545        .ok_or_else(|| format!("The widget parameter {field} isn't a positive integer."))
2546}
2547
2548/// Reads a required non-empty string parameter.
2549fn required_string<'a>(params: &'a Value, field: &str) -> Result<&'a str, String> {
2550    params
2551        .get(field)
2552        .and_then(Value::as_str)
2553        .filter(|value| !value.is_empty())
2554        .ok_or_else(|| format!("The widget parameter {field} isn't a non-empty string."))
2555}
2556
2557/// Reads a required non-empty array of account IDs.
2558fn required_u64_array(params: &Value, field: &str) -> Result<Vec<u64>, String> {
2559    let values = params
2560        .get(field)
2561        .and_then(Value::as_array)
2562        .ok_or_else(|| format!("The widget parameter {field} isn't an array."))?;
2563    let result: Option<Vec<_>> = values.iter().map(Value::as_u64).collect();
2564    result
2565        .filter(|values| !values.is_empty())
2566        .ok_or_else(|| format!("The widget parameter {field} must contain account IDs."))
2567}
2568
2569/// Reads an optional array of strings, defaulting to empty.
2570fn optional_string_array(params: &Value, field: &str) -> Result<Vec<String>, String> {
2571    let Some(values) = params.get(field) else {
2572        return Ok(Vec::new());
2573    };
2574    let values = values
2575        .as_array()
2576        .ok_or_else(|| format!("The widget parameter {field} isn't an array."))?;
2577    values
2578        .iter()
2579        .map(|value| {
2580            value
2581                .as_str()
2582                .map(str::to_owned)
2583                .ok_or_else(|| format!("The widget parameter {field} contains a non-string value."))
2584        })
2585        .collect()
2586}
2587
2588/// Severity of a record written by the interface or a widget.
2589#[derive(Clone, Copy, Debug, Deserialize)]
2590#[serde(rename_all = "lowercase")]
2591pub enum LogLevel {
2592    Debug,
2593    Info,
2594    Warn,
2595    Error,
2596}
2597
2598impl From<LogLevel> for log::Level {
2599    fn from(level: LogLevel) -> Self {
2600        match level {
2601            LogLevel::Debug => log::Level::Debug,
2602            LogLevel::Info => log::Level::Info,
2603            LogLevel::Warn => log::Level::Warn,
2604            LogLevel::Error => log::Level::Error,
2605        }
2606    }
2607}
2608
2609/// Longest message accepted from the interface or a widget before it's cut.
2610const MAX_WRITTEN_LOG_BYTES: usize = 64 * 1024;
2611
2612/// Log target for a widget's records.
2613fn widget_target(widget_id: &str) -> String {
2614    format!("{}{widget_id}", crate::logs::WIDGET_TARGET_PREFIX)
2615}
2616
2617/// Writes a record for `target`, cutting overlong messages first.
2618fn write_record(level: LogLevel, target: &str, message: &str) {
2619    let mut end = message.len().min(MAX_WRITTEN_LOG_BYTES);
2620    while !message.is_char_boundary(end) {
2621        end -= 1;
2622    }
2623    log::log!(target: target, level.into(), "{}", &message[..end]);
2624}
2625
2626/// Returns up to `lines` of the most recent log lines, 300 by default, or the whole log when
2627/// `all` is set.
2628#[tauri::command]
2629pub fn read_log(lines: Option<usize>, all: Option<bool>) -> Result<String, String> {
2630    crate::logs::tail(match all {
2631        Some(true) => None,
2632        _ => Some(lines.unwrap_or(300)),
2633    })
2634}
2635
2636/// Opens the log folder in Explorer or Finder.
2637#[tauri::command]
2638pub fn open_log_folder() -> Result<(), String> {
2639    let directory = crate::logs::directory()
2640        .ok_or_else(|| "Logging couldn't start. Is the data folder writable?".to_string())?;
2641    opener::open(directory)
2642        .map_err(|_| "The log folder couldn't be opened. Does it still exist?".to_string())
2643}
2644
2645/// Closes every running Roblox client, force-closing any that don't close normally, and returns
2646/// how many were running.
2647#[tauri::command]
2648pub async fn close_all_clients() -> Result<usize, String> {
2649    crate::auto_rejoin::note_closed_all();
2650    let count = tauri::async_runtime::spawn_blocking(crate::roblox_process::close_all)
2651        .await
2652        .map_err(|_| {
2653            "Toolblox couldn't close the Roblox clients. Can you try again?".to_string()
2654        })??;
2655    log::info!("Closed {count} Roblox clients");
2656    Ok(count)
2657}
2658
2659/// Opens the app folder, which holds the `widgets` folder, in Explorer or Finder.
2660#[tauri::command]
2661pub fn open_data_folder(runtime: State<'_, Runtime>) -> Result<(), String> {
2662    opener::open(runtime.storage.root())
2663        .map_err(|_| "The app folder couldn't be opened. Does it still exist?".to_string())
2664}
2665
2666/// Writes a record from the interface, or from a widget when `widget_id` is set. Every line is
2667/// redacted and messages over 8 KB are cut.
2668#[tauri::command]
2669pub fn write_log(
2670    level: LogLevel,
2671    message: String,
2672    widget_id: Option<String>,
2673) -> Result<(), String> {
2674    let target = match widget_id {
2675        Some(widget_id) => {
2676            crate::widgets::validate_widget_id(&widget_id)?;
2677            widget_target(&widget_id)
2678        }
2679        None => "interface".into(),
2680    };
2681    write_record(level, &target, &message);
2682    Ok(())
2683}
2684
2685/// Returns the custom theme CSS.
2686#[tauri::command]
2687pub fn get_theme(runtime: State<'_, Runtime>) -> Result<String, String> {
2688    runtime.storage.load_theme().map_err(command_error)
2689}
2690
2691/// Validates and saves the custom theme CSS.
2692#[tauri::command]
2693pub fn save_theme(css: String, runtime: State<'_, Runtime>) -> Result<(), String> {
2694    runtime.storage.save_theme(&css).map_err(command_error)
2695}
2696
2697/// Inlines the local CSS files that theme CSS imports and embeds the files its `url()`s name.
2698#[tauri::command]
2699pub fn embed_theme_files(css: String) -> Result<String, String> {
2700    crate::theme::embed_files(&css)
2701}
2702
2703/// Writes the saved theme to a new CSS file in the Downloads folder, shows it in Explorer or
2704/// Finder, and returns its path.
2705#[tauri::command]
2706pub fn export_theme(app: AppHandle, runtime: State<'_, Runtime>) -> Result<String, String> {
2707    let css = runtime.storage.load_theme().map_err(command_error)?;
2708    let folder = app
2709        .path()
2710        .download_dir()
2711        .or_else(|_| app.path().home_dir())
2712        .map_err(|_| "The Downloads folder couldn't be found. Does it exist?".to_string())?;
2713    let written = (1..100).find_map(|copy| {
2714        let name = match copy {
2715            1 => "Toolblox theme.css".to_string(),
2716            _ => format!("Toolblox theme ({copy}).css"),
2717        };
2718        let path = folder.join(name);
2719        let mut file = std::fs::OpenOptions::new()
2720            .write(true)
2721            .create_new(true)
2722            .open(&path)
2723            .ok()?;
2724        std::io::Write::write_all(&mut file, css.as_bytes()).ok()?;
2725        Some(path)
2726    });
2727    let path = written.ok_or_else(|| {
2728        "The theme couldn't be saved to the Downloads folder. Is it writable?".to_string()
2729    })?;
2730    let _ = tauri_plugin_opener::reveal_item_in_dir(&path);
2731    Ok(path.display().to_string())
2732}
2733
2734#[cfg(test)]
2735mod tests {
2736
2737    #[test]
2738    fn catalogue_rechecks_when_stale_and_retries_failures_sooner() {
2739        let start = std::time::Instant::now();
2740        assert!(catalogue_due(None, false, start));
2741        assert!(!catalogue_due(Some(start), false, start + CATALOGUE_RETRY));
2742        assert!(catalogue_due(Some(start), false, start + CATALOGUE_FRESH));
2743        assert!(!catalogue_due(Some(start), true, start));
2744        assert!(catalogue_due(Some(start), true, start + CATALOGUE_RETRY));
2745    }
2746
2747    #[test]
2748    fn module_urls_change_with_the_installed_package() {
2749        let first = module_url("sample", "main.js", "0123456789abcdef0123", "1.0.0");
2750        let second = module_url("sample", "main.js", "fedcba98765432100123", "1.0.0");
2751        assert!(first.ends_with("/sample/main.js?v=0123456789abcdef"));
2752        assert_ne!(first, second);
2753        assert!(module_url("sample", "main.js", "", "1.0.0").ends_with("?v=1.0.0"));
2754    }
2755
2756    #[test]
2757    fn the_mini_window_stays_within_its_size_range() {
2758        assert_eq!(mini_window_size(120.0), (280.0, 120.0));
2759        assert_eq!(mini_window_size(10.0), (280.0, 40.0));
2760        assert_eq!(mini_window_size(5000.0), (280.0, 420.0));
2761        assert_eq!(mini_window_size(f64::NAN), (280.0, 40.0));
2762    }
2763
2764    #[test]
2765    fn snapping_keeps_the_default_aspect_ratio_within_the_screen() {
2766        let unlimited = (f64::MAX, f64::MAX);
2767        assert_eq!(snapped_window_size(900.0, unlimited), (900.0, 500.0));
2768        assert_eq!(snapped_window_size(1440.0, unlimited), (1440.0, 800.0));
2769        assert_eq!(snapped_window_size(720.0, unlimited), (864.0, 480.0));
2770        assert_eq!(
2771            snapped_window_size(2560.0, (1728.0, 1000.0)),
2772            (1728.0, 960.0)
2773        );
2774    }
2775
2776    use super::*;
2777
2778    #[test]
2779    fn written_records_need_a_valid_widget_id() {
2780        assert!(write_log(LogLevel::Info, "ok".into(), Some("sample_widget".into())).is_ok());
2781        assert!(write_log(LogLevel::Info, "ok".into(), Some("Bad ID".into())).is_err());
2782        assert!(write_log(LogLevel::Info, "é".repeat(MAX_WRITTEN_LOG_BYTES), None).is_ok());
2783    }
2784
2785    #[test]
2786    fn widget_responses_never_carry_a_session_cookie() {
2787        let cookie = "_|WARNING:-DO-NOT-SHARE-THIS.--Sharing|_ABCDEF";
2788        let nested = json!({ "events": [{ "line": format!("token {cookie}") }] });
2789        assert!(without_session_cookie(nested).is_err());
2790        assert!(without_session_cookie(json!({ "status": 200, "body": cookie })).is_err());
2791        let safe = json!([{ "id": 1, "name": "builderman" }]);
2792        assert_eq!(without_session_cookie(safe.clone()).unwrap(), safe);
2793    }
2794
2795    #[test]
2796    fn only_a_401_marks_a_session_expired() {
2797        use crate::roblox::RobloxError;
2798        assert_eq!(session_verdict(&Ok::<(), RobloxError>(())), Some(false));
2799        assert_eq!(
2800            session_verdict::<()>(&Err(RobloxError::Rejected(401))),
2801            Some(true)
2802        );
2803        for error in [
2804            RobloxError::Rejected(403),
2805            RobloxError::Rejected(429),
2806            RobloxError::Rejected(500),
2807            RobloxError::Network,
2808            RobloxError::InvalidResponse,
2809        ] {
2810            assert_eq!(session_verdict::<()>(&Err(error)), None);
2811        }
2812    }
2813
2814    #[test]
2815    fn launch_delay_backs_off_from_one_to_five_seconds() {
2816        let delays: Vec<_> = std::iter::successors(Some(FIRST_LAUNCH_DELAY), |delay| {
2817            Some(next_launch_delay(*delay))
2818        })
2819        .take(5)
2820        .map(|delay| delay.as_secs())
2821        .collect();
2822        assert_eq!(delays, [1, 2, 4, 5, 5]);
2823    }
2824}