microsoft-webui-desktop 3.0.3

Configurable native desktop SDK for WebUI applications
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

use serde::Serialize;
use serde_json::Value;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use crate::error::{DesktopError, Result};
use crate::frame::DesktopFrame;
#[cfg(feature = "application-ipc")]
use crate::ipc::{IpcOptions, IpcRegistry};
#[cfg(feature = "source")]
use crate::runtime::DesktopSourceConfig;
use crate::runtime::{DesktopBundleConfig, DesktopRuntime};
use crate::{DesktopBundleManifest, DesktopShellConfig, WindowOptions};

enum AppInput {
    #[cfg(feature = "source")]
    Source(Box<SourceApp>),
    Bundle(Box<BundleApp>),
}

#[cfg(feature = "source")]
struct SourceApp {
    config: DesktopSourceConfig,
    shell: DesktopShellConfig,
    app_id: Option<String>,
}

struct BundleApp {
    config: DesktopBundleConfig,
    manifest: DesktopBundleManifest,
}

/// Builder for Rust-first WebUI desktop hosts.
///
/// Source and bundle inputs share registration and window configuration. No
/// startup rendering occurs until [`Self::build`], so route providers and Rust
/// state participate in the first render, not only subsequent requests.
pub struct DesktopAppBuilder {
    input: AppInput,
    #[cfg(feature = "application-ipc")]
    ipc_options: IpcOptions,
}

impl DesktopAppBuilder {
    /// Set the window options used by both rendering and the native frame.
    #[must_use]
    pub fn window(mut self, window: WindowOptions) -> Self {
        match &mut self.input {
            #[cfg(feature = "source")]
            AppInput::Source(app) => app.config.window = window,
            AppInput::Bundle(app) => app.manifest.window = window,
        }
        self
    }

    /// Set native shell configuration, overriding any bundled defaults.
    #[must_use]
    pub fn shell(mut self, shell: DesktopShellConfig) -> Self {
        match &mut self.input {
            #[cfg(feature = "source")]
            AppInput::Source(app) => app.shell = shell,
            AppInput::Bundle(app) => app.manifest.shell = shell,
        }
        self
    }

    /// Set the stable application identity used by the native frame.
    #[must_use]
    pub fn app_id(mut self, app_id: impl Into<String>) -> Self {
        let app_id = app_id.into();
        match &mut self.input {
            #[cfg(feature = "source")]
            AppInput::Source(app) => app.app_id = Some(app_id),
            AppInput::Bundle(app) => app.manifest.app_id = app_id,
        }
        self
    }

    /// Set the maximum asset bytes buffered in one protocol response.
    #[must_use]
    pub fn max_asset_bytes(mut self, max_asset_bytes: u64) -> Self {
        match &mut self.input {
            #[cfg(feature = "source")]
            AppInput::Source(app) => app.config.max_asset_bytes = max_asset_bytes,
            AppInput::Bundle(app) => app.config.max_asset_bytes = max_asset_bytes,
        }
        self
    }

    /// Set startup state from any serializable Rust value.
    ///
    /// # Errors
    ///
    /// Returns [`DesktopError`] if state serialization fails.
    pub fn state<T: Serialize>(self, state: &T) -> Result<Self> {
        let value = serde_json::to_value(state).map_err(|source| DesktopError::Serialization {
            context: "serializing desktop app state".to_string(),
            source,
        })?;
        Ok(self.state_value(value))
    }

    /// Set startup state from an existing JSON value.
    #[must_use]
    pub fn state_value(mut self, state: Value) -> Self {
        match &mut self.input {
            #[cfg(feature = "source")]
            AppInput::Source(app) => app.config.state = Some(state),
            AppInput::Bundle(app) => app.config.state = Some(state),
        }
        self
    }

    /// Set pre-resolved design token CSS.
    #[must_use]
    pub fn token_css(mut self, token_css: HashMap<String, String>) -> Self {
        match &mut self.input {
            #[cfg(feature = "source")]
            AppInput::Source(app) => app.config.token_css = Some(token_css),
            AppInput::Bundle(app) => app.config.token_css = Some(token_css),
        }
        self
    }

    /// Set the protobuf IPC registry.
    #[must_use]
    #[cfg(feature = "application-ipc")]
    pub fn ipc_registry(mut self, registry: IpcRegistry) -> Self {
        match &mut self.input {
            #[cfg(feature = "source")]
            AppInput::Source(app) => app.config.ipc_registry = registry,
            AppInput::Bundle(app) => app.config.ipc_registry = registry,
        }
        self
    }

    /// Configure application IPC permissions and bounded resource limits.
    ///
    /// The default denies all application methods. Use
    /// [`IpcOptions::for_schema`] to explicitly grant a generated contract.
    #[must_use]
    #[cfg(feature = "application-ipc")]
    pub fn ipc_options(mut self, options: IpcOptions) -> Self {
        self.ipc_options = options;
        self
    }

    /// Register a Rust route state provider.
    ///
    /// Patterns support literal segments and `:param` captures, e.g.
    /// `/contacts/:id`.
    ///
    /// # Errors
    ///
    /// Returns [`DesktopError`] if the pattern is invalid.
    pub fn route<F>(mut self, pattern: impl AsRef<str>, handler: F) -> Result<Self>
    where
        F: Fn(crate::RouteContext<'_>) -> Result<Value> + Send + Sync + 'static,
    {
        match &mut self.input {
            #[cfg(feature = "source")]
            AppInput::Source(app) => app.config.route_state.route(pattern, handler)?,
            AppInput::Bundle(app) => app.config.route_state.route(pattern, handler)?,
        }
        Ok(self)
    }

    /// Register a Rust custom-protocol API handler.
    ///
    /// Patterns support literal segments and `:param` captures, e.g.
    /// `/api/contacts/:id`.
    ///
    /// # Errors
    ///
    /// Returns [`DesktopError`] if the pattern is invalid.
    pub fn api_route<F>(mut self, pattern: impl AsRef<str>, handler: F) -> Result<Self>
    where
        F: Fn(crate::ApiContext<'_>) -> Result<crate::DesktopProtocolResponse>
            + Send
            + Sync
            + 'static,
    {
        match &mut self.input {
            #[cfg(feature = "source")]
            AppInput::Source(app) => app.config.api_routes.route(pattern, handler)?,
            AppInput::Bundle(app) => app.config.api_routes.route(pattern, handler)?,
        }
        Ok(self)
    }

    /// Render startup content and construct the owning desktop frame.
    ///
    /// # Errors
    ///
    /// Returns [`DesktopError`] if source compilation, bundle loading, a route
    /// provider, or startup rendering fails.
    pub fn build(self) -> Result<DesktopFrame> {
        match self.input {
            #[cfg(feature = "source")]
            AppInput::Source(app) => {
                let SourceApp {
                    config,
                    shell,
                    app_id,
                } = *app;
                let window = config.window.clone();
                let runtime = DesktopRuntime::from_source(config)?;
                #[cfg(feature = "application-ipc")]
                let frame =
                    DesktopFrame::with_ipc_options(Arc::new(runtime), window, self.ipc_options)?;
                #[cfg(not(feature = "application-ipc"))]
                let frame = DesktopFrame::new(Arc::new(runtime), window)?;
                let mut frame = frame.with_shell(shell);
                frame.app_id = app_id;
                Ok(frame)
            }
            AppInput::Bundle(app) => {
                let BundleApp { config, manifest } = *app;
                let window = manifest.window.clone();
                let shell = manifest.shell.clone();
                let app_id = manifest.app_id.clone();
                let runtime = DesktopRuntime::from_bundle_config_and_manifest(config, manifest)?;
                #[cfg(feature = "application-ipc")]
                let frame =
                    DesktopFrame::with_ipc_options(Arc::new(runtime), window, self.ipc_options)?;
                #[cfg(not(feature = "application-ipc"))]
                let frame = DesktopFrame::new(Arc::new(runtime), window)?;
                Ok(frame.with_shell(shell).with_app_id(app_id))
            }
        }
    }
}

/// Entry point for constructing Rust-first desktop apps.
pub struct DesktopApp;

impl DesktopApp {
    /// Create an opt-in native frame for an already-running loopback HTTP app.
    ///
    /// This does not start a server, compile sources, load a bundle, or grant IPC.
    #[cfg(feature = "local-server")]
    #[must_use]
    pub fn from_local_server(options: crate::LocalServerOptions) -> crate::LocalServerAppBuilder {
        crate::LocalServerAppBuilder::new(options)
    }
    /// Construct a source-backed app without compiling or rendering it yet.
    ///
    /// Source-only asset and theme settings belong on `config`. Register shared
    /// state and handlers on the returned builder before calling `build`.
    #[cfg(feature = "source")]
    #[must_use]
    pub fn from_source(config: DesktopSourceConfig) -> DesktopAppBuilder {
        DesktopAppBuilder {
            #[cfg(feature = "application-ipc")]
            ipc_options: IpcOptions::default(),
            input: AppInput::Source(Box::new(SourceApp {
                config,
                shell: DesktopShellConfig::default(),
                app_id: None,
            })),
        }
    }

    /// Load bundle metadata and prepare an app for shared handler registration.
    ///
    /// # Errors
    ///
    /// Returns [`DesktopError`] when the bundle manifest cannot be read or parsed.
    pub fn from_bundle(bundle_dir: impl Into<PathBuf>) -> Result<DesktopAppBuilder> {
        Self::from_bundle_config(DesktopBundleConfig::new(bundle_dir.into()))
    }

    /// Prepare a bundle-backed app with existing Rust state and registrations.
    ///
    /// # Errors
    ///
    /// Returns [`DesktopError`] when the bundle manifest cannot be read or parsed.
    pub fn from_bundle_config(config: DesktopBundleConfig) -> Result<DesktopAppBuilder> {
        let manifest =
            DesktopBundleManifest::load(&config.bundle_dir.join("manifest.webui-desktop.json"))?;
        Ok(Self::from_bundle_config_and_manifest(config, manifest))
    }

    /// Prepare a bundle-backed app using an already-loaded manifest.
    ///
    /// This avoids reading metadata twice when the host also needs it to
    /// initialize application storage or other shared services.
    #[must_use]
    pub fn from_bundle_config_and_manifest(
        config: DesktopBundleConfig,
        manifest: DesktopBundleManifest,
    ) -> DesktopAppBuilder {
        DesktopAppBuilder {
            #[cfg(feature = "application-ipc")]
            ipc_options: IpcOptions::default(),
            input: AppInput::Bundle(Box::new(BundleApp { config, manifest })),
        }
    }
}

/// Run a packaged app with bundled seed state and default Rust registrations.
///
/// Hosts needing route or IPC handlers should configure [`DesktopApp`] and
/// launch the resulting frame instead.
///
/// # Errors
///
/// Returns [`DesktopError`] when resources are missing, bundle loading fails,
/// or the native backend fails to initialize or run.
#[cfg(feature = "native")]
pub fn run_packaged_app() -> Result<()> {
    let resources = crate::frame::find_packaged_resources_dir()
        .ok_or(DesktopError::PackagedResourcesNotFound)?;
    crate::frame::run_frame(DesktopApp::from_bundle(resources)?.build()?)
}

#[cfg(test)]
#[allow(clippy::disallowed_methods)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use crate::frame::test_support;
    use crate::{BundleAsset, DesktopProtocolRequest, DesktopProtocolResponse, TitlebarStyle};

    #[derive(Serialize)]
    struct Seed {
        label: &'static str,
    }

    fn configure(builder: DesktopAppBuilder, calls: Arc<AtomicUsize>) -> Result<DesktopAppBuilder> {
        #[cfg(feature = "application-ipc")]
        let builder = builder
            .ipc_registry(crate::ipc_test_support::registry())
            .ipc_options(crate::ipc_test_support::options());
        builder
            .state(&Seed { label: "seed" })?
            .token_css(HashMap::from([(
                "default".to_string(),
                "--accent:red".to_string(),
            )]))
            .max_asset_bytes(1024)
            .app_id("com.example.configured")
            .window(WindowOptions {
                title: "Configured".to_string(),
                titlebar: TitlebarStyle::Overlay { height: 48 },
                background: Some("#123456".parse().unwrap()),
                ..WindowOptions::default()
            })
            .shell(DesktopShellConfig {
                icon_path: Some(PathBuf::from("assets/icon.png")),
                ..DesktopShellConfig::default()
            })
            .route("/", move |ctx| {
                calls.fetch_add(1, Ordering::SeqCst);
                assert_eq!(ctx.base_state["label"], "seed");
                Ok(ctx.base_state.clone())
            })?
            .api_route("/api/:id", |ctx| {
                Ok(DesktopProtocolResponse::text(200, ctx.param("id").unwrap()))
            })
    }

    fn assert_configured_frame(frame: &DesktopFrame, calls: &AtomicUsize) {
        assert_eq!(calls.load(Ordering::SeqCst), 1);
        assert_eq!(frame.app_id.as_deref(), Some("com.example.configured"));
        assert_eq!(frame.window.title, "Configured");
        assert_eq!(
            frame.shell.icon_path.as_deref(),
            Some(std::path::Path::new("assets/icon.png"))
        );
        assert!(frame
            .runtime
            .startup_html()
            .contains("--webui-titlebar-height:48px"));
        assert!(frame
            .runtime
            .startup_html()
            .contains("--webui-window-background:#123456"));
        let response = frame
            .runtime
            .handle_request(&DesktopProtocolRequest::get("/api/registered"))
            .unwrap();
        assert_eq!(response.body, b"registered");

        #[cfg(feature = "application-ipc")]
        crate::ipc_test_support::assert_echo(frame, b"registered");
    }

    #[test]
    fn bundle_preserves_manifest_identity_window_and_shell_without_reloading_it() {
        let (dir, mut manifest) = test_support::bundle();
        manifest.window.title = "Bundled".to_string();
        manifest.window.background = Some("#abcdef".parse().unwrap());
        manifest.shell.icon_path = Some(PathBuf::from("assets/bundled.png"));
        std::fs::remove_file(dir.path().join("manifest.webui-desktop.json")).unwrap();

        let frame = DesktopApp::from_bundle_config_and_manifest(
            DesktopBundleConfig::new(dir.path().to_path_buf()),
            manifest,
        )
        .build()
        .unwrap();

        assert_eq!(
            frame.app_id.as_deref(),
            Some("com.example.webui.frame-test")
        );
        assert_eq!(frame.window.title, "Bundled");
        assert_eq!(
            frame.shell.icon_path.as_deref(),
            Some(std::path::Path::new("assets/bundled.png"))
        );
        assert!(frame
            .runtime
            .startup_html()
            .contains("--webui-window-background:#abcdef"));
    }

    #[test]
    fn bundle_shared_handlers_and_overrides_are_installed_before_startup_render() {
        let (dir, _) = test_support::bundle();
        let calls = Arc::new(AtomicUsize::new(0));
        let builder = configure(
            DesktopApp::from_bundle(dir.path()).unwrap(),
            Arc::clone(&calls),
        )
        .unwrap();
        assert_eq!(calls.load(Ordering::SeqCst), 0);
        // Construction already loaded metadata; build must not reload it.
        std::fs::remove_file(dir.path().join("manifest.webui-desktop.json")).unwrap();

        let frame = builder.build().unwrap();

        assert_configured_frame(&frame, &calls);
    }

    #[test]
    fn bundle_config_keeps_existing_registrations_and_accepts_json_state_override() {
        let (dir, _) = test_support::bundle();
        let mut config = DesktopBundleConfig::new(dir.path().to_path_buf());
        config
            .api_routes
            .route("/api/preset", |_| {
                Ok(DesktopProtocolResponse::text(200, "preset"))
            })
            .unwrap();
        let builder = DesktopApp::from_bundle_config(config)
            .unwrap()
            .state_value(serde_json::to_value(Seed { label: "override" }).unwrap())
            .route("/", |ctx| {
                assert_eq!(ctx.base_state["label"], "override");
                Ok(Value::Null)
            })
            .unwrap();

        let frame = builder.build().unwrap();

        assert_eq!(
            frame
                .runtime
                .handle_request(&DesktopProtocolRequest::get("/api/preset"))
                .unwrap()
                .body,
            b"preset"
        );
    }

    #[test]
    fn bundle_asset_limit_override_reaches_runtime_validation() {
        let (dir, mut manifest) = test_support::bundle();
        std::fs::write(dir.path().join("assets/large.txt"), b"large").unwrap();
        manifest.integrity.assets.push(BundleAsset {
            path: "assets/large.txt".to_string(),
            sha256: String::new(),
            size_bytes: 5,
        });
        let result = DesktopApp::from_bundle_config_and_manifest(
            DesktopBundleConfig::new(dir.path().to_path_buf()),
            manifest,
        )
        .max_asset_bytes(4)
        .build();

        assert!(matches!(result, Err(DesktopError::AssetTooLarge { .. })));
    }

    #[test]
    fn invalid_registrations_and_provider_failures_are_explicit() {
        let (dir, _) = test_support::bundle();
        assert!(matches!(
            DesktopApp::from_bundle(dir.path())
                .unwrap()
                .route("invalid", |_| Ok(Value::Null)),
            Err(DesktopError::InvalidRoutePattern { .. })
        ));
        assert!(matches!(
            DesktopApp::from_bundle(dir.path())
                .unwrap()
                .api_route("invalid", |_| Ok(DesktopProtocolResponse::text(200, ""))),
            Err(DesktopError::InvalidRoutePattern { .. })
        ));
        let result = DesktopApp::from_bundle(dir.path())
            .unwrap()
            .route("/", |_| {
                Err(DesktopError::UnsupportedRuntime {
                    message: "fixture provider failure".to_string(),
                    help: "return route state".to_string(),
                })
            })
            .unwrap()
            .build();
        assert!(matches!(result, Err(DesktopError::RouteProvider { .. })));
    }

    #[test]
    fn state_serialization_failure_is_returned() {
        struct InvalidState;
        impl Serialize for InvalidState {
            fn serialize<S: serde::Serializer>(
                &self,
                _serializer: S,
            ) -> std::result::Result<S::Ok, S::Error> {
                Err(serde::ser::Error::custom("fixture serialization failure"))
            }
        }

        let (dir, _) = test_support::bundle();
        assert!(matches!(
            DesktopApp::from_bundle(dir.path())
                .unwrap()
                .state(&InvalidState),
            Err(DesktopError::Serialization { .. })
        ));
    }

    #[cfg(feature = "source")]
    #[test]
    fn source_uses_the_same_handler_and_render_configuration() {
        let dir = tempfile::TempDir::new().unwrap();
        let config = DesktopSourceConfig::new(crate::BuildOptions {
            app_dir: dir.path().to_path_buf(),
            ..Default::default()
        });
        let calls = Arc::new(AtomicUsize::new(0));
        let builder = configure(DesktopApp::from_source(config), Arc::clone(&calls)).unwrap();
        // A source builder also defers compilation until build.
        std::fs::write(dir.path().join("index.html"), "<main>Hello</main>").unwrap();
        assert_eq!(calls.load(Ordering::SeqCst), 0);

        let frame = builder.build().unwrap();

        assert_configured_frame(&frame, &calls);
    }
}