mbr-markdown-browser 0.4.5

A fast, featureful markdown viewer, browser, and (optional) static site generator
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
use std::path::Path;
#[cfg(feature = "gui")]
use std::path::PathBuf;

use clap::Parser;
#[cfg(feature = "gui")]
use mbr::browser::{self, BrowserContext};
use mbr::{
    Config, ConfigError, MbrError, build::Builder, cli, link_transform::LinkTransformConfig,
    markdown, server, templates,
};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

/// Check if the given path requires a folder picker dialog.
/// This is true when launched as an app without a valid working directory.
#[cfg(feature = "gui")]
fn needs_folder_picker(path: &Path) -> bool {
    // Try to canonicalize, fall back to the path as-is
    let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());

    #[cfg(unix)]
    {
        // On Unix, check if path is root "/" or has only one component
        canonical.components().count() <= 1
    }

    #[cfg(windows)]
    {
        // On Windows, check for root drives or system directories
        canonical.parent().is_none()
            || canonical.starts_with(r"C:\Windows")
            || canonical.starts_with(r"C:\Program Files")
            || canonical.starts_with(r"C:\Program Files (x86)")
    }
}

/// Show a folder picker dialog and return the selected path.
/// Returns None if the user cancels.
#[cfg(feature = "gui")]
fn show_folder_picker() -> Option<PathBuf> {
    rfd::FileDialog::new()
        .set_title("Select Markdown Folder")
        .pick_folder()
}

#[tokio::main]
async fn main() -> Result<(), MbrError> {
    // Suppress ffmpeg warnings/info messages from the metadata crate
    // These would otherwise clutter stdout/stderr when processing video files
    #[cfg(feature = "media-metadata")]
    ffmpeg_next::log::set_level(ffmpeg_next::log::Level::Fatal);

    let args = cli::Args::parse();

    // Initialize tracing/logging based on verbosity flags
    // Use try_init to allow server to re-configure if needed (it uses tower_http logging)
    let log_filter = args.log_level_filter();
    let _ = tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| log_filter.into()),
        )
        .with(tracing_subscriber::fmt::layer())
        .try_init();

    // Determine if we're in GUI mode (no --server, --stdout, --build, --extract-video-metadata, --extract-pdf-cover flags)
    #[cfg(all(feature = "gui", feature = "media-metadata"))]
    let is_gui_mode = !args.server
        && !args.stdout
        && !args.build
        && !args.extract_video_metadata
        && !args.extract_pdf_cover;
    #[cfg(all(feature = "gui", not(feature = "media-metadata")))]
    let is_gui_mode = !args.server && !args.stdout && !args.build;
    #[cfg(not(feature = "gui"))]
    let _is_gui_mode = false;

    // Check if we need to show a folder picker (only in GUI mode when path is root/system dir)
    #[cfg(feature = "gui")]
    let input_path = if is_gui_mode && needs_folder_picker(&args.path) {
        match show_folder_picker() {
            Some(path) => path,
            None => {
                // User cancelled - exit gracefully
                std::process::exit(0);
            }
        }
    } else {
        args.path.clone()
    };
    #[cfg(not(feature = "gui"))]
    let input_path = args.path.clone();

    let input_path_ref = Path::new(&input_path);
    let absolute_path =
        input_path_ref
            .canonicalize()
            .map_err(|e| ConfigError::CanonicalizeFailed {
                path: input_path_ref.to_path_buf(),
                source: e,
            })?;

    let is_directory = absolute_path.is_dir();

    let mut config = Config::read(&absolute_path)?;

    // Apply CLI overrides
    if let Some(timeout) = args.oembed_timeout_ms {
        config.oembed_timeout_ms = timeout;
    }
    if let Some(cache_size) = args.oembed_cache_size {
        config.oembed_cache_size = cache_size;
    }
    if let Some(ref template_folder) = args.template_folder {
        // Canonicalize and validate the template folder path
        let template_path =
            template_folder
                .canonicalize()
                .map_err(|e| ConfigError::CanonicalizeFailed {
                    path: template_folder.clone(),
                    source: e,
                })?;
        if !template_path.is_dir() {
            return Err(ConfigError::TemplateFolderNotDirectory {
                path: template_path,
            }
            .into());
        }
        config.template_folder = Some(template_path);
    }
    if let Some(port) = args.port {
        config.port = port;
    }
    if let Some(ref host) = args.host {
        let ip: std::net::IpAddr = host
            .parse()
            .map_err(|_| ConfigError::InvalidHost { host: host.clone() })?;
        match ip {
            std::net::IpAddr::V4(v4) => {
                config.host = mbr::config::IpArray(v4.octets());
            }
            std::net::IpAddr::V6(_) => {
                return Err(ConfigError::InvalidHost { host: host.clone() }.into());
            }
        }
    }
    if let Some(ref theme) = args.theme {
        config.theme = theme.clone();
    }
    if let Some(concurrency) = args.build_concurrency {
        config.build_concurrency = Some(concurrency);
    }
    // Apply transcode options from CLI
    #[cfg(feature = "media-metadata")]
    if args.transcode {
        config.transcode = true;
    }
    // Apply skip_link_checks from CLI
    if args.skip_link_checks {
        config.skip_link_checks = true;
    }
    // Apply no_link_tracking from CLI
    if args.no_link_tracking {
        config.link_tracking = false;
    }
    // Apply title_prefix and title_suffix from CLI
    if let Some(ref prefix) = args.title_prefix {
        config.title_prefix = prefix.clone();
    }
    if let Some(ref suffix) = args.title_suffix {
        config.title_suffix = suffix.clone();
    }

    let path_relative_to_root =
        pathdiff::diff_paths(&absolute_path, &config.root_dir).ok_or_else(|| {
            ConfigError::RelativePathFailed {
                from: config.root_dir.clone(),
                to: absolute_path.clone(),
            }
        })?;

    tracing::info!(
        "Root dir: {}; File relative to root: {}",
        &config.root_dir.display(),
        &path_relative_to_root.display()
    );

    // Extract video metadata mode - extract cover/chapters/captions from video
    #[cfg(feature = "media-metadata")]
    if args.extract_video_metadata {
        if is_directory {
            eprintln!("Error: --extract-video-metadata requires a video file, not a directory.");
            eprintln!("Usage: mbr --extract-video-metadata /path/to/video.mp4");
            std::process::exit(1);
        }

        mbr::video_metadata::extract_and_save(&absolute_path)?;
        return Ok(());
    }

    // Extract PDF cover mode - extract cover images from PDFs
    #[cfg(feature = "media-metadata")]
    if args.extract_pdf_cover {
        use mbr::pdf_metadata::{extract_pdf_covers_recursive, save_cover};

        if is_directory {
            // Recursive directory mode
            let result = extract_pdf_covers_recursive(&absolute_path, |pdf_path, sidecar_path| {
                if let Some(sidecar) = sidecar_path {
                    println!(
                        "Extracting cover: {} -> {}",
                        pdf_path.display(),
                        sidecar.display()
                    );
                }
            });

            // Report failures to stderr
            for (path, error) in &result.failures {
                eprintln!("Error: {} - {}", path.display(), error);
            }

            // Print summary
            if result.failure_count > 0 && result.success_count > 0 {
                eprintln!(
                    "\u{26a0} {} PDFs failed, {} succeeded",
                    result.failure_count, result.success_count
                );
                std::process::exit(1); // Partial failure
            } else if result.failure_count > 0 && result.success_count == 0 {
                eprintln!(
                    "\u{26a0} {} PDFs failed, none succeeded",
                    result.failure_count
                );
                std::process::exit(2); // Total failure
            } else if result.success_count > 0 {
                println!("\u{2713} Created {} cover images", result.success_count);
                std::process::exit(0); // Success
            } else {
                println!("No PDF files found in directory.");
                std::process::exit(0);
            }
        } else {
            // Single file mode
            // Verify the file has a .pdf extension
            let extension = absolute_path
                .extension()
                .and_then(|e| e.to_str())
                .map(|e| e.to_ascii_lowercase());

            if extension.as_deref() != Some("pdf") {
                eprintln!(
                    "Error: {} is not a PDF file (expected .pdf extension)",
                    absolute_path.display()
                );
                std::process::exit(2);
            }

            match save_cover(&absolute_path) {
                Ok(sidecar_path) => {
                    println!(
                        "Extracting cover: {} -> {}",
                        absolute_path.display(),
                        sidecar_path.display()
                    );
                    println!("\u{2713} Created 1 cover image");
                    std::process::exit(0);
                }
                Err(e) => {
                    eprintln!("Error: {} - {}", absolute_path.display(), e);
                    std::process::exit(2);
                }
            }
        }
    }

    if args.build {
        // Build mode - generate static site
        // Default oembed timeout to 0 (disabled) for fastest builds unless explicitly set via CLI.
        // In tests on a 3,000 note repo, oembed=1000ms took 10 minutes vs 12 seconds with oembed=0.
        if args.oembed_timeout_ms.is_none() {
            config.oembed_timeout_ms = 0;
        }

        #[cfg(target_os = "windows")]
        {
            eprintln!("Error: Static site generation is not supported on Windows");
            std::process::exit(1);
        }

        #[cfg(not(target_os = "windows"))]
        {
            let output_dir = if args.output.is_absolute() {
                args.output.clone()
            } else {
                std::env::current_dir()
                    .map_err(ConfigError::CurrentDirFailed)?
                    .join(&args.output)
            };

            tracing::info!("Building static site to: {}", output_dir.display());

            let builder = Builder::new(config, output_dir)?;
            let stats = builder.build().await?;

            if stats.broken_links > 0 {
                println!(
                    "Build complete: {} markdown pages, {} section pages, {} assets linked, {} broken links in {:?}",
                    stats.markdown_pages,
                    stats.section_pages,
                    stats.assets_linked,
                    stats.broken_links,
                    stats.duration
                );
            } else {
                println!(
                    "Build complete: {} markdown pages, {} section pages, {} assets linked in {:?}",
                    stats.markdown_pages, stats.section_pages, stats.assets_linked, stats.duration
                );
            }
            return Ok(());
        }
    } else if args.stdout {
        // CLI mode - render markdown to stdout (explicit -o/--stdout flag)
        if is_directory {
            eprintln!(
                "Cannot render a directory to stdout. Use -s to start a server or omit -o for GUI mode."
            );
            eprintln!("  mbr -s {}  # Start server", input_path.display());
            eprintln!("  mbr {}     # Open in GUI (default)", input_path.display());
            std::process::exit(1);
        }

        // Determine if this is an index file (which doesn't need ../ prefix for links)
        let is_index_file = input_path
            .file_name()
            .and_then(|f| f.to_str())
            .is_some_and(|f| f == config.index_file);

        let link_transform_config = LinkTransformConfig {
            markdown_extensions: config.markdown_extensions.clone(),
            index_file: config.index_file.clone(),
            is_index_file,
            url_depth: None,
        };

        // CLI mode: server_mode=false, transcode disabled (transcode is server-only)
        let valid_tag_sources = mbr::config::tag_sources_to_set(&config.tag_sources);
        let render_result = markdown::render(
            input_path,
            config.root_dir.as_path(),
            config.oembed_timeout_ms,
            link_transform_config,
            false, // server_mode is false in CLI mode
            false, // transcode is disabled in CLI mode
            valid_tag_sources,
        )
        .await
        .inspect_err(|e| tracing::error!("Error rendering markdown: {:?}", e))?;
        let templates =
            templates::Templates::new(&config.root_dir, config.template_folder.as_deref())
                .inspect_err(|e| tracing::error!("Error parsing template: {e}"))?;
        let html_output = templates.render_markdown(
            &render_result.html,
            render_result.frontmatter,
            std::collections::HashMap::new(),
        )?;
        println!("{}", &html_output);
    } else if args.server {
        // Server mode - HTTP server only, no GUI
        let server_config = server::ServerConfig::from(&config).with_gui_mode(false);
        let server = server::Server::init(server_config)?;

        let url_path = build_url_path(
            &path_relative_to_root,
            is_directory,
            &config.markdown_extensions,
        );
        tracing::info!(
            "Server running at http://{}:{}/{}",
            config.host,
            config.port,
            url_path
        );

        server.start().await?;
    } else {
        // GUI mode - default when no flags specified (or explicit -g)
        #[cfg(feature = "gui")]
        {
            let config_copy = config.clone();
            let (ready_tx, ready_rx) = tokio::sync::oneshot::channel::<u16>();
            let handle = tokio::spawn(async move {
                let server_config = server::ServerConfig::from(&config_copy).with_gui_mode(true);
                let server = server::Server::init(server_config);
                match server {
                    Ok(mut s) => {
                        // Try up to 10 port increments if address is in use
                        if let Err(e) = s.start_with_port_retry(Some(ready_tx), 10).await {
                            tracing::error!("Server error: {e}");
                        }
                    }
                    Err(e) => {
                        tracing::error!(
                            "Couldn't initialize the server: {e}. Try with -s for more info"
                        );
                        // Drop the sender to signal failure
                        drop(ready_tx);
                    }
                }
            });

            // Wait for server to be ready before opening browser
            let actual_port = match ready_rx.await {
                Ok(port) => port,
                Err(_) => {
                    tracing::error!("Server failed to start");
                    return Ok(());
                }
            };

            let base_url =
                url::Url::parse(format!("http://{}:{}/", config.host, actual_port).as_str())?;

            // For media files, redirect to the appropriate viewer URL
            let url = if !is_directory {
                if let Some(media_type) = server::MediaViewerType::from_path(&path_relative_to_root)
                {
                    let file_url_path =
                        build_url_path(&path_relative_to_root, false, &config.markdown_extensions);
                    let viewer_url = build_media_viewer_url(media_type, &file_url_path);
                    base_url.join(&viewer_url)?
                } else {
                    let url_path = build_url_path(
                        &path_relative_to_root,
                        is_directory,
                        &config.markdown_extensions,
                    );
                    base_url.join(&url_path)?
                }
            } else {
                let url_path = build_url_path(
                    &path_relative_to_root,
                    is_directory,
                    &config.markdown_extensions,
                );
                base_url.join(&url_path)?
            };

            // Launch browser with full context for server management
            let ctx = BrowserContext {
                url: url.to_string(),
                server_handle: handle,
                config,
                tokio_runtime: tokio::runtime::Handle::current(),
            };

            browser::launch_browser(ctx)?;
            // Note: server handle is now managed by the browser context
            // It will be aborted when the browser window closes or when switching folders
        }
        #[cfg(not(feature = "gui"))]
        {
            // GUI mode not available - this shouldn't happen since is_gui_mode is always false
            // when the gui feature is disabled, but provide a clear error just in case
            tracing::error!(
                "GUI mode is not available in this build. Use -s for server mode or --stdout for stdout mode."
            );
            std::process::exit(1);
        }
    }
    Ok(())
}

/// Builds a URL path from a relative filesystem path.
///
/// - For directories: returns the path with a trailing slash
/// - For markdown files: replaces the extension with a trailing slash
/// - For other files: returns the path as-is
pub fn build_url_path(
    relative_path: &std::path::Path,
    is_directory: bool,
    markdown_extensions: &[String],
) -> String {
    let relative_str = relative_path.to_str().unwrap_or_default();

    if is_directory {
        if relative_str.is_empty() {
            String::new()
        } else {
            format!("{}/", relative_str)
        }
    } else {
        replace_markdown_extension_with_slash(relative_str, markdown_extensions)
    }
}

fn replace_markdown_extension_with_slash(s: &str, extensions: &[String]) -> String {
    if let Some((base, extension)) = s.rsplit_once('.') {
        match extensions
            .iter()
            .find(|cur_ext| extension == cur_ext.as_str())
        {
            Some(_) => format!("{}/", base), // one of the sought extensions is there, replace with a "/"
            None => s.to_string(), // no sought extensions found, just return input as provided
        }
    } else {
        s.to_string() // no extension, so return input as provided
    }
}

/// Builds a media viewer URL for the given media type and file path.
///
/// The returned path is relative to the server root, e.g.,
/// `/.mbr/videos/?path=%2Fvideos%2Fexample.mp4`.
///
/// The `file_url_path` should be the URL path to the file (as returned by `build_url_path`),
/// without a leading slash (e.g., `videos/example.mp4`).
fn build_media_viewer_url(media_type: server::MediaViewerType, file_url_path: &str) -> String {
    use percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode};

    // Encode the path for use as a query parameter value.
    // We need to encode everything except unreserved characters.
    const QUERY_ENCODE_SET: &AsciiSet = &CONTROLS
        .add(b' ')
        .add(b'"')
        .add(b'#')
        .add(b'%')
        .add(b'&')
        .add(b'+')
        .add(b'=')
        .add(b'?');

    // Ensure the file path has a leading slash for the query param
    let full_path = if file_url_path.starts_with('/') {
        file_url_path.to_string()
    } else {
        format!("/{file_url_path}")
    };

    let encoded_path = utf8_percent_encode(&full_path, QUERY_ENCODE_SET).to_string();
    format!("{}?path={}", media_type.route_path(), encoded_path)
}

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

    #[test]
    fn test_build_url_path_root_directory() {
        let path = Path::new("");
        let extensions = vec!["md".to_string()];
        assert_eq!(build_url_path(path, true, &extensions), "");
    }

    #[test]
    fn test_build_url_path_subdirectory() {
        let path = Path::new("docs/api");
        let extensions = vec!["md".to_string()];
        assert_eq!(build_url_path(path, true, &extensions), "docs/api/");
    }

    #[test]
    fn test_build_url_path_markdown_file() {
        let path = Path::new("readme.md");
        let extensions = vec!["md".to_string()];
        assert_eq!(build_url_path(path, false, &extensions), "readme/");
    }

    #[test]
    fn test_build_url_path_markdown_file_in_subdir() {
        let path = Path::new("docs/guide.md");
        let extensions = vec!["md".to_string()];
        assert_eq!(build_url_path(path, false, &extensions), "docs/guide/");
    }

    #[test]
    fn test_build_url_path_alternate_extension() {
        let path = Path::new("notes.markdown");
        let extensions = vec!["md".to_string(), "markdown".to_string()];
        assert_eq!(build_url_path(path, false, &extensions), "notes/");
    }

    #[test]
    fn test_build_url_path_non_markdown_file() {
        let path = Path::new("image.png");
        let extensions = vec!["md".to_string()];
        assert_eq!(build_url_path(path, false, &extensions), "image.png");
    }

    #[test]
    fn test_replace_markdown_extension_with_slash() {
        let extensions = ["md".to_string()];
        assert_eq!(
            replace_markdown_extension_with_slash("test.md", &extensions),
            "test/"
        );
        assert_eq!(
            replace_markdown_extension_with_slash("test.txt", &extensions),
            "test.txt"
        );
        assert_eq!(
            replace_markdown_extension_with_slash("noext", &extensions),
            "noext"
        );
    }

    #[test]
    fn test_build_media_viewer_url_video() {
        let url = build_media_viewer_url(server::MediaViewerType::Video, "videos/example.mp4");
        assert_eq!(url, "/.mbr/videos/?path=/videos/example.mp4");
    }

    #[test]
    fn test_build_media_viewer_url_audio() {
        let url = build_media_viewer_url(server::MediaViewerType::Audio, "music/song.mp3");
        assert_eq!(url, "/.mbr/audio/?path=/music/song.mp3");
    }

    #[test]
    fn test_build_media_viewer_url_image() {
        let url = build_media_viewer_url(server::MediaViewerType::Image, "images/photo.jpg");
        assert_eq!(url, "/.mbr/images/?path=/images/photo.jpg");
    }

    #[test]
    fn test_build_media_viewer_url_pdf() {
        let url = build_media_viewer_url(server::MediaViewerType::Pdf, "docs/paper.pdf");
        assert_eq!(url, "/.mbr/pdfs/?path=/docs/paper.pdf");
    }

    #[test]
    fn test_build_media_viewer_url_with_leading_slash() {
        let url = build_media_viewer_url(server::MediaViewerType::Video, "/videos/example.mp4");
        assert_eq!(url, "/.mbr/videos/?path=/videos/example.mp4");
    }

    #[test]
    fn test_build_media_viewer_url_encodes_spaces() {
        let url = build_media_viewer_url(server::MediaViewerType::Video, "videos/my video.mp4");
        assert!(url.contains("path=/videos/my%20video.mp4"));
    }

    #[test]
    fn test_build_media_viewer_url_encodes_special_chars() {
        let url = build_media_viewer_url(server::MediaViewerType::Video, "videos/file#1&2=3.mp4");
        // Hash, ampersand, and equals should be encoded
        assert!(url.contains("path=/videos/file%231%262%3D3.mp4"));
    }

    #[test]
    #[cfg(feature = "gui")]
    fn test_needs_folder_picker_root() {
        assert!(needs_folder_picker(Path::new("/")));
    }

    #[test]
    #[cfg(feature = "gui")]
    fn test_needs_folder_picker_normal_path() {
        // A normal path like /Users/foo should not need folder picker
        assert!(!needs_folder_picker(Path::new("/Users/foo")));
    }

    #[test]
    #[cfg(feature = "gui")]
    fn test_needs_folder_picker_current_dir() {
        // Current directory "." should not need folder picker when it resolves to a real path
        // This test depends on where it's run from
        let cwd = std::env::current_dir().unwrap();
        if cwd.components().count() > 1 {
            assert!(!needs_folder_picker(&cwd));
        }
    }
}