victauri-plugin 0.2.0

Tauri plugin for Victauri — embedded MCP server with full-stack introspection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
#![deny(missing_docs)]
//! Victauri — full-stack introspection for Tauri apps via an embedded MCP server.
//!
//! Add this plugin to your Tauri app for AI-agent-driven testing and debugging:
//! DOM snapshots, IPC tracing, cross-boundary verification, and more tools —
//! all accessible over the Model Context Protocol.
//!
//! # Quick Start
//!
//! ```ignore
//! tauri::Builder::default()
//!     .plugin(victauri_plugin::init())
//!     .run(tauri::generate_context!())
//!     .unwrap();
//! ```
//!
//! In debug builds this starts an MCP server on port 7373. In release builds
//! the plugin is a no-op with zero overhead.
//!
//! # Configuration
//!
//! Authentication is enabled by default with an auto-generated token (printed to logs).
//! Use `.auth_disabled()` to opt out, or `.auth_token("...")` to set a specific token.
//!
//! ```ignore
//! tauri::Builder::default()
//!     .plugin(
//!         victauri_plugin::VictauriBuilder::new()
//!             .port(8080)
//!             .strict_privacy_mode()
//!             .build(),
//!     )
//!     .run(tauri::generate_context!())
//!     .unwrap();
//! ```

/// Runtime-erased webview bridge trait and its Tauri implementation.
pub mod bridge;
pub mod error;
/// JS bridge script generation for webview injection.
pub mod js_bridge;
/// MCP server, tool handler, and parameter types.
pub mod mcp;
mod memory;
/// Privacy controls: command allowlists, blocklists, and tool disabling.
pub mod privacy;
/// Output redaction for API keys, tokens, emails, and sensitive JSON keys.
pub mod redaction;
pub(crate) mod screenshot;
mod tools;

/// Bearer-token authentication, rate limiting, and security middlewares.
pub mod auth;

use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicU16, AtomicU64};
use tauri::plugin::{Builder, TauriPlugin};
use tauri::{Manager, RunEvent, Runtime};
use tokio::sync::{Mutex, oneshot, watch};
use victauri_core::{CommandRegistry, EventLog, EventRecorder};

pub use error::BuilderError;
pub use privacy::PrivacyProfile;

pub use victauri_core::CommandInfo;
pub use victauri_macros::inspectable;

/// Register command schemas with the Victauri plugin at app setup time.
///
/// Pass the `__schema()` function calls generated by `#[inspectable]`.
/// This populates the `CommandRegistry` so that `get_registry`, `resolve_command`,
/// and `detect_ghost_commands` return real results.
///
/// # Example
///
/// ```rust,ignore
/// use victauri_plugin::register_commands;
///
/// .setup(|app| {
///     register_commands!(app,
///         greet__schema(),
///         increment__schema(),
///         add_todo__schema(),
///     );
///     Ok(())
/// })
/// ```
#[macro_export]
macro_rules! register_commands {
    ($app:expr, $($schema_call:expr),+ $(,)?) => {{
        let state = $app.state::<std::sync::Arc<$crate::VictauriState>>();
        $(
            state.registry.register($schema_call);
        )+
    }};
}

const DEFAULT_PORT: u16 = 7373;
const DEFAULT_EVENT_CAPACITY: usize = 10_000;
const DEFAULT_RECORDER_CAPACITY: usize = 50_000;
const DEFAULT_EVAL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
const MAX_EVENT_CAPACITY: usize = 1_000_000;
const MAX_RECORDER_CAPACITY: usize = 1_000_000;
const MAX_EVAL_TIMEOUT_SECS: u64 = 300;

/// Map of pending JavaScript eval callbacks, keyed by request ID.
/// Each entry holds a oneshot sender that resolves when the webview returns a result.
pub type PendingCallbacks = Arc<Mutex<HashMap<String, oneshot::Sender<String>>>>;

/// Runtime state shared between the MCP server and all tool handlers.
pub struct VictauriState {
    /// Ring-buffer event log for IPC calls, state changes, and DOM mutations.
    pub event_log: EventLog,
    /// Registry of all discovered Tauri commands with metadata.
    pub registry: CommandRegistry,
    /// TCP port the MCP server listens on (may differ from configured port if fallback was used).
    pub port: AtomicU16,
    /// Pending JavaScript eval callbacks awaiting webview responses.
    pub pending_evals: PendingCallbacks,
    /// Session recorder for time-travel debugging.
    pub recorder: EventRecorder,
    /// Privacy configuration (tool disabling, command filtering, output redaction).
    pub privacy: privacy::PrivacyConfig,
    /// Timeout for JavaScript eval operations.
    pub eval_timeout: std::time::Duration,
    /// Sends `true` to signal graceful MCP server shutdown.
    pub shutdown_tx: watch::Sender<bool>,
    /// Instant the plugin was initialized, for uptime tracking.
    pub started_at: std::time::Instant,
    /// Total number of MCP tool invocations since startup.
    pub tool_invocations: AtomicU64,
    /// Whether `file:` URLs are allowed in the `navigate` tool's `go_to` action.
    /// Defaults to `false` — only `http` and `https` are permitted unless opted in
    /// via [`VictauriBuilder::allow_file_navigation`].
    pub allow_file_navigation: bool,
}

/// Builder for configuring the Victauri plugin before adding it to a Tauri app.
///
/// Supports port selection, authentication, privacy controls, output redaction,
/// and capacity tuning. All settings have sensible defaults and can be overridden
/// via environment variables.
///
/// **Authentication is enabled by default.** If no explicit token is set and no
/// `VICTAURI_AUTH_TOKEN` env var exists, a random `UUID` token is auto-generated
/// and printed to the log. Call [`auth_disabled()`](VictauriBuilder::auth_disabled)
/// to explicitly opt out of authentication.
pub struct VictauriBuilder {
    port: Option<u16>,
    event_capacity: usize,
    recorder_capacity: usize,
    eval_timeout: std::time::Duration,
    auth_token: Option<String>,
    auth_explicitly_disabled: bool,
    disabled_tools: Vec<String>,
    command_allowlist: Option<Vec<String>>,
    command_blocklist: Vec<String>,
    redaction_patterns: Vec<String>,
    redaction_enabled: bool,
    strict_privacy: bool,
    privacy_profile: Option<privacy::PrivacyProfile>,
    bridge_capacities: js_bridge::BridgeCapacities,
    on_ready: Option<Box<dyn FnOnce(u16) + Send + 'static>>,
    commands: Vec<victauri_core::CommandInfo>,
    allow_file_navigation: bool,
}

impl Default for VictauriBuilder {
    fn default() -> Self {
        Self {
            port: None,
            event_capacity: DEFAULT_EVENT_CAPACITY,
            recorder_capacity: DEFAULT_RECORDER_CAPACITY,
            eval_timeout: DEFAULT_EVAL_TIMEOUT,
            auth_token: None,
            auth_explicitly_disabled: false,
            disabled_tools: Vec::new(),
            command_allowlist: None,
            command_blocklist: Vec::new(),
            redaction_patterns: Vec::new(),
            redaction_enabled: false,
            strict_privacy: false,
            privacy_profile: None,
            bridge_capacities: js_bridge::BridgeCapacities::default(),
            on_ready: None,
            commands: Vec::new(),
            allow_file_navigation: false,
        }
    }
}

impl VictauriBuilder {
    /// Create a new builder with default settings.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the TCP port for the MCP server (default: 7373, env: `VICTAURI_PORT`).
    #[must_use]
    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    /// Set the maximum number of events in the ring-buffer log (default: 10,000).
    #[must_use]
    pub fn event_capacity(mut self, capacity: usize) -> Self {
        self.event_capacity = capacity;
        self
    }

    /// Set the maximum events kept during session recording (default: 50,000).
    #[must_use]
    pub fn recorder_capacity(mut self, capacity: usize) -> Self {
        self.recorder_capacity = capacity;
        self
    }

    /// Set the timeout for JavaScript eval operations (default: 30s, env: `VICTAURI_EVAL_TIMEOUT`).
    #[must_use]
    pub fn eval_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.eval_timeout = timeout;
        self
    }

    /// Set an explicit auth token for the MCP server (env: `VICTAURI_AUTH_TOKEN`).
    #[must_use]
    pub fn auth_token(mut self, token: impl Into<String>) -> Self {
        self.auth_token = Some(token.into());
        self
    }

    /// Generate a random `UUID` v4 auth token.
    #[must_use]
    pub fn generate_auth_token(mut self) -> Self {
        self.auth_token = Some(auth::generate_token());
        self
    }

    /// Explicitly disable authentication. By default, Victauri auto-generates a
    /// token if none is provided. Call this method to opt out of auth entirely.
    ///
    /// **Warning:** Without authentication, any process on localhost can access
    /// the MCP server. Only use this in trusted environments.
    #[must_use]
    pub fn auth_disabled(mut self) -> Self {
        self.auth_explicitly_disabled = true;
        self.auth_token = None;
        self
    }

    /// Disable specific MCP tools by name (e.g., `["eval_js", "screenshot"]`).
    #[must_use]
    pub fn disable_tools(mut self, tools: &[&str]) -> Self {
        self.disabled_tools = tools.iter().map(std::string::ToString::to_string).collect();
        self
    }

    /// Only allow these Tauri commands to be invoked via MCP (positive allowlist).
    #[must_use]
    pub fn command_allowlist(mut self, commands: &[&str]) -> Self {
        self.command_allowlist = Some(
            commands
                .iter()
                .map(std::string::ToString::to_string)
                .collect(),
        );
        self
    }

    /// Block specific Tauri commands from being invoked via MCP.
    #[must_use]
    pub fn command_blocklist(mut self, commands: &[&str]) -> Self {
        self.command_blocklist = commands
            .iter()
            .map(std::string::ToString::to_string)
            .collect();
        self
    }

    /// Add a regex pattern for output redaction (e.g., `r"SECRET_\w+"`).
    #[must_use]
    pub fn add_redaction_pattern(mut self, pattern: impl Into<String>) -> Self {
        self.redaction_patterns.push(pattern.into());
        self
    }

    /// Enable output redaction with built-in patterns (API keys, emails, tokens).
    #[must_use]
    pub fn enable_redaction(mut self) -> Self {
        self.redaction_enabled = true;
        self
    }

    /// Enable strict privacy mode (equivalent to [`PrivacyProfile::Observe`]).
    ///
    /// Disables all mutation tools (`eval_js`, screenshot, interactions, input,
    /// storage writes, navigation, CSS injection) and enables output redaction.
    ///
    /// Prefer [`privacy_profile()`](Self::privacy_profile) for finer control.
    #[must_use]
    pub fn strict_privacy_mode(mut self) -> Self {
        self.strict_privacy = true;
        self.privacy_profile = Some(privacy::PrivacyProfile::Observe);
        self
    }

    /// Set the privacy profile tier.
    ///
    /// - [`Observe`](privacy::PrivacyProfile::Observe) — read-only (snapshots, logs, registry)
    /// - [`Test`](privacy::PrivacyProfile::Test) — observe + interactions + input + storage writes + recording
    /// - [`FullControl`](privacy::PrivacyProfile::FullControl) — everything (default)
    ///
    /// Profiles automatically enable redaction for `Observe` and `Test`.
    /// Use [`disable_tools()`](Self::disable_tools) to apply overrides on top of a profile.
    #[must_use]
    pub fn privacy_profile(mut self, profile: privacy::PrivacyProfile) -> Self {
        self.privacy_profile = Some(profile);
        if matches!(
            profile,
            privacy::PrivacyProfile::Observe | privacy::PrivacyProfile::Test
        ) {
            self.redaction_enabled = true;
        }
        self
    }

    /// Set the maximum console log entries kept in the JS bridge (default: 1000).
    #[must_use]
    pub fn console_log_capacity(mut self, capacity: usize) -> Self {
        self.bridge_capacities.console_logs = capacity;
        self
    }

    /// Set the maximum network log entries kept in the JS bridge (default: 1000).
    #[must_use]
    pub fn network_log_capacity(mut self, capacity: usize) -> Self {
        self.bridge_capacities.network_log = capacity;
        self
    }

    /// Set the maximum navigation log entries kept in the JS bridge (default: 200).
    #[must_use]
    pub fn navigation_log_capacity(mut self, capacity: usize) -> Self {
        self.bridge_capacities.navigation_log = capacity;
        self
    }

    /// Pre-register command schemas so `get_registry`, `resolve_command`, and
    /// `detect_ghost_commands` return real results from the moment the server starts.
    ///
    /// Pass the `__schema()` functions generated by `#[inspectable]`.
    ///
    /// ```rust,ignore
    /// VictauriBuilder::new()
    ///     .commands(&[
    ///         greet__schema(),
    ///         increment__schema(),
    ///         add_todo__schema(),
    ///     ])
    ///     .build()
    /// ```
    #[must_use]
    pub fn commands(mut self, schemas: &[victauri_core::CommandInfo]) -> Self {
        self.commands = schemas.to_vec();
        self
    }

    /// Auto-discover all `#[inspectable]` commands in the binary.
    ///
    /// Uses `inventory` to collect every command marked with `#[inspectable]`
    /// at link time — no manual listing required. This replaces both
    /// `.commands(&[...])` and `register_commands!()`.
    ///
    /// ```rust,ignore
    /// tauri::Builder::default()
    ///     .plugin(
    ///         VictauriBuilder::new()
    ///             .auto_discover()
    ///             .build()
    ///             .unwrap(),
    ///     )
    /// ```
    #[must_use]
    pub fn auto_discover(mut self) -> Self {
        self.commands
            .extend(victauri_core::auto_discovered_commands());
        self
    }

    /// Allow `file:` URLs in the `navigate` tool's `go_to` action.
    ///
    /// By default, only `http` and `https` schemes are permitted. Calling this
    /// method opts in to `file:` navigation, which grants the MCP client access
    /// to local filesystem paths via the webview.
    ///
    /// **Warning:** Enabling this in untrusted environments exposes local files
    /// to any process that can reach the MCP server.
    #[must_use]
    pub fn allow_file_navigation(mut self) -> Self {
        self.allow_file_navigation = true;
        self
    }

    /// Register a callback invoked once the MCP server is listening.
    /// The callback receives the port number.
    #[must_use]
    pub fn on_ready(mut self, f: impl FnOnce(u16) + Send + 'static) -> Self {
        self.on_ready = Some(Box::new(f));
        self
    }

    fn resolve_port(&self) -> u16 {
        self.port
            .or_else(|| std::env::var("VICTAURI_PORT").ok()?.parse().ok())
            .unwrap_or(DEFAULT_PORT)
    }

    fn resolve_auth_token(&self) -> Option<String> {
        if self.auth_explicitly_disabled {
            return None;
        }
        self.auth_token
            .clone()
            .or_else(|| std::env::var("VICTAURI_AUTH_TOKEN").ok())
            .or_else(|| Some(auth::generate_token()))
    }

    fn resolve_eval_timeout(&self) -> std::time::Duration {
        std::env::var("VICTAURI_EVAL_TIMEOUT")
            .ok()
            .and_then(|s| s.parse::<u64>().ok())
            .map_or(self.eval_timeout, std::time::Duration::from_secs)
    }

    fn build_privacy_config(&self) -> privacy::PrivacyConfig {
        let profile = self
            .privacy_profile
            .unwrap_or(privacy::PrivacyProfile::FullControl);

        let redaction_enabled = self.redaction_enabled
            || self.strict_privacy
            || matches!(
                profile,
                privacy::PrivacyProfile::Observe | privacy::PrivacyProfile::Test
            );

        privacy::PrivacyConfig {
            profile,
            command_allowlist: self
                .command_allowlist
                .as_ref()
                .map(|v| v.iter().cloned().collect::<HashSet<String>>()),
            command_blocklist: self.command_blocklist.iter().cloned().collect(),
            disabled_tools: self.disabled_tools.iter().cloned().collect(),
            redactor: redaction::Redactor::new(&self.redaction_patterns),
            redaction_enabled,
        }
    }

    fn validate(&self) -> Result<(), BuilderError> {
        let port = self.resolve_port();
        if port == 0 {
            return Err(BuilderError::InvalidPort {
                port,
                reason: "port 0 is reserved".to_string(),
            });
        }

        if self.event_capacity == 0 || self.event_capacity > MAX_EVENT_CAPACITY {
            return Err(BuilderError::InvalidEventCapacity {
                capacity: self.event_capacity,
                reason: format!("must be between 1 and {MAX_EVENT_CAPACITY}"),
            });
        }

        if self.recorder_capacity == 0 || self.recorder_capacity > MAX_RECORDER_CAPACITY {
            return Err(BuilderError::InvalidRecorderCapacity {
                capacity: self.recorder_capacity,
                reason: format!("must be between 1 and {MAX_RECORDER_CAPACITY}"),
            });
        }

        let timeout = self.resolve_eval_timeout();
        if timeout.as_secs() == 0 || timeout.as_secs() > MAX_EVAL_TIMEOUT_SECS {
            return Err(BuilderError::InvalidEvalTimeout {
                timeout_secs: timeout.as_secs(),
                reason: format!("must be between 1 and {MAX_EVAL_TIMEOUT_SECS} seconds"),
            });
        }

        Ok(())
    }

    /// Consume the builder and produce a Tauri plugin.
    ///
    /// In release builds this always succeeds. In debug builds the builder configuration is
    /// validated first.
    ///
    /// # Errors
    ///
    /// Returns [`BuilderError`] if the port, event capacity, recorder capacity, or eval
    /// timeout are outside their valid ranges (debug builds only).
    pub fn build<R: Runtime>(self) -> Result<TauriPlugin<R>, BuilderError> {
        #[cfg(not(debug_assertions))]
        {
            Ok(Builder::new("victauri").build())
        }

        #[cfg(debug_assertions)]
        {
            self.validate()?;

            let port = self.resolve_port();
            let event_capacity = self.event_capacity;
            let recorder_capacity = self.recorder_capacity;
            let eval_timeout = self.resolve_eval_timeout();
            let auth_token = self.resolve_auth_token();
            let privacy_config = self.build_privacy_config();
            let allow_file_navigation = self.allow_file_navigation;
            let on_ready = self.on_ready;
            let commands = self.commands;
            let js_init = js_bridge::init_script(&self.bridge_capacities);

            Ok(Builder::new("victauri")
                .setup(move |app, _api| {
                    let event_log = EventLog::new(event_capacity);
                    let registry = CommandRegistry::new();
                    let (shutdown_tx, shutdown_rx) = watch::channel(false);

                    let state = Arc::new(VictauriState {
                        event_log,
                        registry,
                        port: AtomicU16::new(port),
                        pending_evals: Arc::new(Mutex::new(HashMap::new())),
                        recorder: EventRecorder::new(recorder_capacity),
                        privacy: privacy_config,
                        eval_timeout,
                        shutdown_tx,
                        started_at: std::time::Instant::now(),
                        tool_invocations: AtomicU64::new(0),
                        allow_file_navigation,
                    });

                    app.manage(state.clone());

                    for cmd in commands {
                        state.registry.register(cmd);
                    }

                    if let Some(ref token) = auth_token {
                        tracing::info!(
                            "Victauri MCP server auth enabled — token: {token}"
                        );
                    } else {
                        tracing::warn!(
                            "Victauri MCP server auth DISABLED — any localhost process can access the MCP server"
                        );
                    }

                    let app_handle = app.clone();
                    let ready_state = state.clone();
                    tauri::async_runtime::spawn(async move {
                        match mcp::start_server_with_options(
                            app_handle, state, port, auth_token, shutdown_rx,
                        )
                        .await
                        {
                            Ok(()) => {
                                tracing::info!("Victauri MCP server stopped");
                            }
                            Err(e) => {
                                tracing::error!("Victauri MCP server failed: {e}");
                            }
                        }
                    });

                    if let Some(cb) = on_ready {
                        tauri::async_runtime::spawn(async move {
                            for _ in 0..50 {
                                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
                                let actual_port = ready_state.port.load(std::sync::atomic::Ordering::Relaxed);
                                if tokio::net::TcpStream::connect(format!(
                                    "127.0.0.1:{actual_port}"
                                ))
                                .await
                                .is_ok()
                                {
                                    cb(actual_port);
                                    return;
                                }
                            }
                            let actual_port = ready_state.port.load(std::sync::atomic::Ordering::Relaxed);
                            tracing::warn!("Victauri on_ready: server did not become ready within 5s");
                            cb(actual_port);
                        });
                    }

                    tracing::info!("Victauri plugin initialized — MCP server on port {port}");
                    Ok(())
                })
                .on_event(|app, event| {
                    if let RunEvent::Exit = event
                        && let Some(state) = app.try_state::<Arc<VictauriState>>()
                    {
                        let _ = state.shutdown_tx.send(true);
                        tracing::info!("Victauri shutdown signal sent");
                    }
                })
                .js_init_script(js_init)
                .invoke_handler(tauri::generate_handler![
                    tools::victauri_eval_js,
                    tools::victauri_eval_callback,
                    tools::victauri_get_window_state,
                    tools::victauri_list_windows,
                    tools::victauri_get_ipc_log,
                    tools::victauri_get_registry,
                    tools::victauri_get_memory_stats,
                    tools::victauri_dom_snapshot,
                    tools::victauri_verify_state,
                    tools::victauri_detect_ghost_commands,
                    tools::victauri_check_ipc_integrity,
                ])
                .build())
        }
    }
}

/// Initialize the Victauri plugin with default settings (port 7373 or `VICTAURI_PORT` env var).
///
/// In debug builds: starts the embedded MCP server, injects the JS bridge, and
/// registers all Tauri command handlers.
///
/// In release builds: returns a no-op plugin. The MCP server, JS bridge, and
/// all introspection tools are completely stripped — zero overhead, zero attack surface.
///
/// For custom configuration, use `VictauriBuilder::new().port(8080).build()`.
///
/// # Panics
///
/// Panics if the default builder configuration is invalid (this is a bug).
#[must_use]
pub fn init<R: Runtime>() -> TauriPlugin<R> {
    VictauriBuilder::new()
        .build()
        .expect("default Victauri configuration is always valid")
}

/// Initialize the Victauri plugin with auto-discovery of all `#[inspectable]` commands.
///
/// Equivalent to `VictauriBuilder::new().auto_discover().build()` — all commands
/// marked with `#[inspectable]` are registered automatically without manual listing.
///
/// # Panics
///
/// Panics if the default builder configuration is invalid (this is a bug).
#[must_use]
pub fn init_auto_discover<R: Runtime>() -> TauriPlugin<R> {
    VictauriBuilder::new()
        .auto_discover()
        .build()
        .expect("default Victauri configuration is always valid")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn builder_default_values() {
        let builder = VictauriBuilder::new();
        assert_eq!(builder.event_capacity, DEFAULT_EVENT_CAPACITY);
        assert_eq!(builder.recorder_capacity, DEFAULT_RECORDER_CAPACITY);
        // Raw field is None, but resolve_auth_token() auto-generates a token
        assert!(builder.auth_token.is_none());
        assert!(!builder.auth_explicitly_disabled);
        let resolved = builder.resolve_auth_token();
        assert!(resolved.is_some(), "auth should be enabled by default");
        assert_eq!(
            resolved.unwrap().len(),
            36,
            "auto-generated token should be a UUID"
        );
        assert!(builder.disabled_tools.is_empty());
        assert!(builder.command_allowlist.is_none());
        assert!(builder.command_blocklist.is_empty());
        assert!(!builder.redaction_enabled);
        assert!(!builder.strict_privacy);
    }

    #[test]
    fn builder_port_override() {
        let builder = VictauriBuilder::new().port(9090);
        assert_eq!(builder.resolve_port(), 9090);
    }

    #[test]
    #[allow(unsafe_code)]
    fn builder_default_port() {
        let builder = VictauriBuilder::new();
        // SAFETY: test-only — no concurrent env reads in this test binary.
        unsafe { std::env::remove_var("VICTAURI_PORT") };
        assert_eq!(builder.resolve_port(), DEFAULT_PORT);
    }

    #[test]
    fn builder_auth_token_explicit() {
        let builder = VictauriBuilder::new().auth_token("my-secret");
        assert_eq!(builder.resolve_auth_token(), Some("my-secret".to_string()));
    }

    #[test]
    fn builder_auth_token_generated() {
        let builder = VictauriBuilder::new().generate_auth_token();
        let token = builder.resolve_auth_token().unwrap();
        assert_eq!(token.len(), 36);
    }

    #[test]
    fn builder_auth_disabled() {
        let builder = VictauriBuilder::new().auth_disabled();
        assert!(builder.auth_explicitly_disabled);
        assert!(
            builder.resolve_auth_token().is_none(),
            "auth_disabled should opt out of auto-generated token"
        );
    }

    #[test]
    fn builder_auth_disabled_overrides_explicit_token() {
        let builder = VictauriBuilder::new()
            .auth_token("my-secret")
            .auth_disabled();
        assert!(
            builder.resolve_auth_token().is_none(),
            "auth_disabled should override explicit token"
        );
    }

    #[test]
    fn builder_capacities() {
        let builder = VictauriBuilder::new()
            .event_capacity(500)
            .recorder_capacity(2000);
        assert_eq!(builder.event_capacity, 500);
        assert_eq!(builder.recorder_capacity, 2000);
    }

    #[test]
    fn builder_disable_tools() {
        let builder = VictauriBuilder::new().disable_tools(&["eval_js", "screenshot"]);
        assert_eq!(builder.disabled_tools.len(), 2);
        assert!(builder.disabled_tools.contains(&"eval_js".to_string()));
    }

    #[test]
    fn builder_command_allowlist() {
        let builder = VictauriBuilder::new().command_allowlist(&["greet", "increment"]);
        assert!(builder.command_allowlist.is_some());
        assert_eq!(builder.command_allowlist.as_ref().unwrap().len(), 2);
    }

    #[test]
    fn builder_command_blocklist() {
        let builder = VictauriBuilder::new().command_blocklist(&["dangerous_cmd"]);
        assert_eq!(builder.command_blocklist.len(), 1);
    }

    #[test]
    fn builder_redaction() {
        let builder = VictauriBuilder::new()
            .add_redaction_pattern(r"SECRET_\w+")
            .enable_redaction();
        assert!(builder.redaction_enabled);
        assert_eq!(builder.redaction_patterns.len(), 1);
    }

    #[test]
    fn builder_strict_privacy_config() {
        let builder = VictauriBuilder::new().strict_privacy_mode();
        let config = builder.build_privacy_config();
        assert!(config.redaction_enabled);
        assert_eq!(config.profile, crate::privacy::PrivacyProfile::Observe);
        assert!(!config.is_tool_enabled("eval_js"));
        assert!(!config.is_tool_enabled("screenshot"));
        assert!(!config.is_tool_enabled("interact"));
        assert!(config.is_tool_enabled("dom_snapshot"));
    }

    #[test]
    fn builder_normal_privacy_config() {
        let builder = VictauriBuilder::new()
            .command_blocklist(&["secret_cmd"])
            .disable_tools(&["eval_js"]);
        let config = builder.build_privacy_config();
        assert!(config.command_blocklist.contains("secret_cmd"));
        assert!(!config.is_tool_enabled("eval_js"));
        assert!(!config.redaction_enabled);
    }

    #[test]
    fn builder_strict_with_extra_blocklist() {
        let builder = VictauriBuilder::new()
            .strict_privacy_mode()
            .command_blocklist(&["extra_dangerous"]);
        let config = builder.build_privacy_config();
        assert!(config.command_blocklist.contains("extra_dangerous"));
        assert!(!config.is_tool_enabled("eval_js"));
    }

    #[test]
    fn builder_test_profile() {
        let builder = VictauriBuilder::new().privacy_profile(crate::privacy::PrivacyProfile::Test);
        let config = builder.build_privacy_config();
        assert_eq!(config.profile, crate::privacy::PrivacyProfile::Test);
        assert!(config.redaction_enabled);
        assert!(config.is_tool_enabled("interact"));
        assert!(config.is_tool_enabled("fill"));
        assert!(config.is_tool_enabled("recording"));
        assert!(!config.is_tool_enabled("eval_js"));
        assert!(!config.is_tool_enabled("screenshot"));
        assert!(!config.is_tool_enabled("navigate"));
    }

    #[test]
    fn builder_profile_with_extra_disables() {
        let builder = VictauriBuilder::new()
            .privacy_profile(crate::privacy::PrivacyProfile::Test)
            .disable_tools(&["interact"]);
        let config = builder.build_privacy_config();
        assert!(!config.is_tool_enabled("interact"));
        assert!(config.is_tool_enabled("fill"));
    }

    #[test]
    fn builder_bridge_capacities() {
        let builder = VictauriBuilder::new()
            .console_log_capacity(5000)
            .network_log_capacity(2000)
            .navigation_log_capacity(500);
        assert_eq!(builder.bridge_capacities.console_logs, 5000);
        assert_eq!(builder.bridge_capacities.network_log, 2000);
        assert_eq!(builder.bridge_capacities.navigation_log, 500);
        assert_eq!(builder.bridge_capacities.mutation_log, 500);
        assert_eq!(builder.bridge_capacities.dialog_log, 100);
    }

    #[test]
    fn builder_on_ready_sets_callback() {
        let builder = VictauriBuilder::new().on_ready(|_port| {});
        assert!(builder.on_ready.is_some());
    }

    #[test]
    fn builder_file_navigation_disabled_by_default() {
        let builder = VictauriBuilder::new();
        assert!(
            !builder.allow_file_navigation,
            "file navigation should be disabled by default"
        );
    }

    #[test]
    fn builder_allow_file_navigation() {
        let builder = VictauriBuilder::new().allow_file_navigation();
        assert!(builder.allow_file_navigation);
    }

    #[test]
    fn init_script_contains_custom_capacities() {
        let caps = js_bridge::BridgeCapacities {
            console_logs: 3000,
            mutation_log: 750,
            network_log: 5000,
            navigation_log: 400,
            dialog_log: 250,
            long_tasks: 200,
        };
        let script = js_bridge::init_script(&caps);
        assert!(script.contains("CAP_CONSOLE = 3000"));
        assert!(script.contains("CAP_MUTATION = 750"));
        assert!(script.contains("CAP_NETWORK = 5000"));
        assert!(script.contains("CAP_NAVIGATION = 400"));
        assert!(script.contains("CAP_DIALOG = 250"));
        assert!(script.contains("CAP_LONG_TASKS = 200"));
    }

    #[test]
    fn init_script_default_contains_standard_capacities() {
        let caps = js_bridge::BridgeCapacities::default();
        let script = js_bridge::init_script(&caps);
        assert!(script.contains("CAP_CONSOLE = 1000"));
        assert!(script.contains("CAP_NETWORK = 1000"));
        assert!(script.contains("window.__VICTAURI__"));
    }

    #[test]
    fn builder_validates_defaults() {
        let builder = VictauriBuilder::new();
        assert!(builder.validate().is_ok());
    }

    #[test]
    fn builder_rejects_zero_port() {
        let builder = VictauriBuilder::new().port(0);
        let err = builder.validate().unwrap_err();
        assert!(matches!(err, BuilderError::InvalidPort { port: 0, .. }));
    }

    #[test]
    fn builder_rejects_zero_event_capacity() {
        let builder = VictauriBuilder::new().event_capacity(0);
        let err = builder.validate().unwrap_err();
        assert!(matches!(
            err,
            BuilderError::InvalidEventCapacity { capacity: 0, .. }
        ));
    }

    #[test]
    fn builder_rejects_excessive_event_capacity() {
        let builder = VictauriBuilder::new().event_capacity(2_000_000);
        assert!(builder.validate().is_err());
    }

    #[test]
    fn builder_rejects_zero_recorder_capacity() {
        let builder = VictauriBuilder::new().recorder_capacity(0);
        assert!(builder.validate().is_err());
    }

    #[test]
    fn builder_rejects_zero_eval_timeout() {
        let builder = VictauriBuilder::new().eval_timeout(std::time::Duration::from_secs(0));
        assert!(builder.validate().is_err());
    }

    #[test]
    fn builder_rejects_excessive_eval_timeout() {
        let builder = VictauriBuilder::new().eval_timeout(std::time::Duration::from_secs(600));
        assert!(builder.validate().is_err());
    }

    #[test]
    fn builder_accepts_edge_values() {
        let builder = VictauriBuilder::new()
            .port(1)
            .event_capacity(1)
            .recorder_capacity(1)
            .eval_timeout(std::time::Duration::from_secs(1));
        assert!(builder.validate().is_ok());

        let builder = VictauriBuilder::new()
            .port(65535)
            .event_capacity(MAX_EVENT_CAPACITY)
            .recorder_capacity(MAX_RECORDER_CAPACITY)
            .eval_timeout(std::time::Duration::from_secs(MAX_EVAL_TIMEOUT_SECS));
        assert!(builder.validate().is_ok());
    }
}