fresh-editor 0.1.96

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
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
use super::node::{NodeId, NodeState, TreeNode};
use crate::model::filesystem::DirEntry;
use crate::services::fs::FsManager;
use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;

/// File tree with lazy loading support
///
/// The tree starts with just the root node. Directories are only read
/// when explicitly expanded via `expand_node()`. This makes the tree
/// efficient even for very large directory structures.
#[derive(Debug)]
pub struct FileTree {
    /// Root directory path
    root_path: PathBuf,
    /// All nodes indexed by ID
    nodes: HashMap<NodeId, TreeNode>,
    /// Path to node ID mapping for quick lookups
    path_to_node: HashMap<PathBuf, NodeId>,
    /// Root node ID
    root_id: NodeId,
    /// Next node ID to assign
    next_id: usize,
    /// Filesystem manager for async operations
    fs_manager: Arc<FsManager>,
}

impl FileTree {
    /// Create a new file tree rooted at the given path
    ///
    /// # Errors
    ///
    /// Returns an error if the root path doesn't exist or isn't a directory.
    pub async fn new(root_path: PathBuf, fs_manager: Arc<FsManager>) -> io::Result<Self> {
        // Verify root path exists and is a directory
        if !fs_manager.exists(&root_path).await {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("Path does not exist: {:?}", root_path),
            ));
        }

        if !fs_manager.is_dir(&root_path).await? {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("Path is not a directory: {:?}", root_path),
            ));
        }

        // Get root entry
        let root_entry = fs_manager.get_entry(&root_path).await?;

        // Create root node
        let root_id = NodeId(0);
        let root_node = TreeNode::new(root_id, root_entry.clone(), None);

        let mut nodes = HashMap::new();
        nodes.insert(root_id, root_node);

        let mut path_to_node = HashMap::new();
        path_to_node.insert(root_path.clone(), root_id);

        Ok(Self {
            root_path,
            nodes,
            path_to_node,
            root_id,
            next_id: 1,
            fs_manager,
        })
    }

    /// Get the root node ID
    pub fn root_id(&self) -> NodeId {
        self.root_id
    }

    /// Get the root path
    pub fn root_path(&self) -> &Path {
        &self.root_path
    }

    /// Get a node by ID
    pub fn get_node(&self, id: NodeId) -> Option<&TreeNode> {
        self.nodes.get(&id)
    }

    /// Get a mutable reference to a node by ID
    fn get_node_mut(&mut self, id: NodeId) -> Option<&mut TreeNode> {
        self.nodes.get_mut(&id)
    }

    /// Get a node by path
    pub fn get_node_by_path(&self, path: &Path) -> Option<&TreeNode> {
        self.path_to_node
            .get(path)
            .and_then(|id| self.get_node(*id))
    }

    /// Get all nodes
    pub fn all_nodes(&self) -> impl Iterator<Item = &TreeNode> {
        self.nodes.values()
    }

    /// Expand a directory node (load its children)
    ///
    /// This is an async operation that reads the directory contents and creates
    /// child nodes. If the directory is already expanded, this does nothing.
    ///
    /// # Errors
    ///
    /// Returns an error if the directory cannot be read.
    pub async fn expand_node(&mut self, id: NodeId) -> io::Result<()> {
        // Check if node exists and is a directory
        let node = self
            .get_node(id)
            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Node not found"))?;

        if !node.is_dir() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "Cannot expand a file node",
            ));
        }

        // If already expanded, do nothing
        if node.is_expanded() {
            return Ok(());
        }

        // Set state to loading
        if let Some(node) = self.get_node_mut(id) {
            node.state = NodeState::Loading;
        }

        // Read directory contents with metadata (for file sizes)
        let path = self.get_node(id).unwrap().entry.path.clone();
        let result = self.fs_manager.list_dir_with_metadata(path.clone()).await;

        match result {
            Ok(entries) => {
                // Sort entries: directories first, then by name
                let mut sorted_entries = entries;
                sorted_entries.sort_by(|a, b| match (a.is_dir(), b.is_dir()) {
                    (true, false) => std::cmp::Ordering::Less,
                    (false, true) => std::cmp::Ordering::Greater,
                    _ => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
                });

                // Create child nodes
                let mut child_ids = Vec::new();
                for entry in sorted_entries {
                    let child_id = self.add_node(entry, Some(id));
                    child_ids.push(child_id);
                }

                // Update parent node
                if let Some(node) = self.get_node_mut(id) {
                    node.children = child_ids;
                    node.state = NodeState::Expanded;
                }

                Ok(())
            }
            Err(e) => {
                // Set error state
                if let Some(node) = self.get_node_mut(id) {
                    node.state = NodeState::Error(e.to_string());
                }
                Err(e)
            }
        }
    }

    /// Collapse a directory node
    ///
    /// This removes all child nodes from memory to save space.
    /// They will be reloaded if the directory is expanded again.
    pub fn collapse_node(&mut self, id: NodeId) {
        if let Some(node) = self.get_node(id) {
            if !node.is_dir() {
                return;
            }

            // Collect child IDs to remove
            let children_to_remove: Vec<NodeId> = node.children.clone();

            // Remove all descendants recursively
            for child_id in children_to_remove {
                self.remove_node_recursive(child_id);
            }
        }

        // Update parent node state
        if let Some(node) = self.get_node_mut(id) {
            node.children.clear();
            node.state = NodeState::Collapsed;
        }
    }

    /// Toggle node expansion (expand if collapsed, collapse if expanded)
    pub async fn toggle_node(&mut self, id: NodeId) -> io::Result<()> {
        let node = self
            .get_node(id)
            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Node not found"))?;

        if !node.is_dir() {
            return Ok(());
        }

        if node.is_expanded() {
            self.collapse_node(id);
            Ok(())
        } else {
            self.expand_node(id).await
        }
    }

    /// Refresh a node (re-read directory contents)
    ///
    /// This is useful when filesystem contents have changed.
    pub async fn refresh_node(&mut self, id: NodeId) -> io::Result<()> {
        // Collapse and re-expand
        self.collapse_node(id);
        self.expand_node(id).await
    }

    /// Get all visible nodes in tree order
    ///
    /// Returns a flat list of nodes that should be visible, respecting
    /// the expansion state of parent directories.
    pub fn get_visible_nodes(&self) -> Vec<NodeId> {
        let mut visible = Vec::new();
        self.collect_visible_recursive(self.root_id, &mut visible);
        visible
    }

    /// Recursively collect visible nodes
    fn collect_visible_recursive(&self, id: NodeId, visible: &mut Vec<NodeId>) {
        visible.push(id);

        if let Some(node) = self.get_node(id) {
            if node.is_expanded() {
                for &child_id in &node.children {
                    self.collect_visible_recursive(child_id, visible);
                }
            }
        }
    }

    /// Get the parent chain for a node (from root to node)
    pub fn get_ancestors(&self, id: NodeId) -> Vec<NodeId> {
        let mut ancestors = Vec::new();
        let mut current = Some(id);

        while let Some(node_id) = current {
            ancestors.push(node_id);
            current = self.get_node(node_id).and_then(|n| n.parent);
        }

        ancestors.reverse();
        ancestors
    }

    /// Get the depth of a node (root is 0)
    pub fn get_depth(&self, id: NodeId) -> usize {
        self.get_ancestors(id).len() - 1
    }

    /// Find node by relative path from root
    pub fn find_by_relative_path(&self, relative_path: &Path) -> Option<NodeId> {
        let full_path = self.root_path.join(relative_path);
        self.path_to_node.get(&full_path).copied()
    }

    /// Add a new node to the tree
    fn add_node(&mut self, entry: DirEntry, parent: Option<NodeId>) -> NodeId {
        let id = NodeId(self.next_id);
        self.next_id += 1;

        let node = TreeNode::new(id, entry.clone(), parent);
        self.path_to_node.insert(entry.path.clone(), id);
        self.nodes.insert(id, node);

        id
    }

    /// Remove a node and all its descendants
    fn remove_node_recursive(&mut self, id: NodeId) {
        if let Some(node) = self.get_node(id) {
            let children = node.children.clone();
            let path = node.entry.path.clone();

            // Remove all children first
            for child_id in children {
                self.remove_node_recursive(child_id);
            }

            // Remove from path mapping
            self.path_to_node.remove(&path);

            // Remove node itself
            self.nodes.remove(&id);
        }
    }

    /// Get number of nodes currently in memory
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    /// Expand all directories along a path and return the final node ID
    ///
    /// This is useful for revealing a specific file in the tree, even if its
    /// parent directories are collapsed. All parent directories will be expanded
    /// as needed.
    ///
    /// # Arguments
    ///
    /// * `path` - The full path to the target file or directory
    ///
    /// # Returns
    ///
    /// Returns the NodeId of the target if found, or None if:
    /// - The path is not under the root directory
    /// - The path doesn't exist
    /// - There was an error expanding intermediate directories
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Expand to src/components/App.js
    /// if let Some(node_id) = tree.expand_to_path(&project_root.join("src/components/App.js")).await {
    ///     // All parent directories (src, src/components) are now expanded
    ///     // node_id points to App.js
    /// }
    /// ```
    pub async fn expand_to_path(&mut self, path: &Path) -> Option<NodeId> {
        // Check if path is under root
        let relative_path = path.strip_prefix(&self.root_path).ok()?;

        // Start from root
        let mut current_id = self.root_id;

        // Walk through each component of the path
        for component in relative_path.components() {
            let component_str = component.as_os_str().to_str()?;

            // Expand current directory if it's not already expanded
            let node = self.get_node(current_id)?;
            if node.is_dir() && !node.is_expanded() {
                // Expand this directory
                if let Err(e) = self.expand_node(current_id).await {
                    tracing::warn!("Failed to expand node during path traversal: {}", e);
                    return None;
                }
            }

            // Find the child with the matching name
            let node = self.get_node(current_id)?;
            let child_id = node
                .children
                .iter()
                .find(|&&child_id| {
                    if let Some(child_node) = self.get_node(child_id) {
                        child_node.entry.name == component_str
                    } else {
                        false
                    }
                })
                .copied();

            match child_id {
                Some(id) => current_id = id,
                None => {
                    // Child not found - path doesn't exist
                    tracing::warn!("Component '{}' not found in tree", component_str);
                    return None;
                }
            }
        }

        Some(current_id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::filesystem::StdFileSystem;
    use std::fs as std_fs;
    use tempfile::TempDir;

    async fn create_test_tree() -> (TempDir, FileTree) {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        // Create test structure:
        // /
        // ├── dir1/
        // │   ├── file1.txt
        // │   └── file2.txt
        // ├── dir2/
        // │   └── subdir/
        // │       └── file3.txt
        // └── file4.txt

        std_fs::create_dir(temp_path.join("dir1")).unwrap();
        std_fs::write(temp_path.join("dir1/file1.txt"), "content1").unwrap();
        std_fs::write(temp_path.join("dir1/file2.txt"), "content2").unwrap();

        std_fs::create_dir(temp_path.join("dir2")).unwrap();
        std_fs::create_dir(temp_path.join("dir2/subdir")).unwrap();
        std_fs::write(temp_path.join("dir2/subdir/file3.txt"), "content3").unwrap();

        std_fs::write(temp_path.join("file4.txt"), "content4").unwrap();

        let backend = Arc::new(StdFileSystem);
        let manager = Arc::new(FsManager::new(backend));
        let tree = FileTree::new(temp_path.to_path_buf(), manager)
            .await
            .unwrap();

        (temp_dir, tree)
    }

    #[tokio::test]
    async fn test_tree_creation() {
        let (_temp_dir, tree) = create_test_tree().await;

        assert_eq!(tree.node_count(), 1); // Only root initially
        let root = tree.get_node(tree.root_id()).unwrap();
        assert!(root.is_collapsed());
        assert_eq!(root.children.len(), 0);
    }

    #[tokio::test]
    async fn test_expand_root() {
        let (_temp_dir, mut tree) = create_test_tree().await;

        tree.expand_node(tree.root_id()).await.unwrap();

        let root = tree.get_node(tree.root_id()).unwrap();
        assert!(root.is_expanded());
        assert_eq!(root.children.len(), 3); // dir1, dir2, file4.txt

        // Should be 4 nodes: root + 3 children
        assert_eq!(tree.node_count(), 4);
    }

    #[tokio::test]
    async fn test_expand_nested() {
        let (_temp_dir, mut tree) = create_test_tree().await;

        // Expand root
        tree.expand_node(tree.root_id()).await.unwrap();

        // Find dir1 and expand it
        let root = tree.get_node(tree.root_id()).unwrap();
        let dir1_id = root.children[0]; // dir1 (directories come first)

        tree.expand_node(dir1_id).await.unwrap();

        let dir1 = tree.get_node(dir1_id).unwrap();
        assert!(dir1.is_expanded());
        assert_eq!(dir1.children.len(), 2); // file1.txt, file2.txt

        // Total nodes: root + 3 children + 2 grandchildren = 6
        assert_eq!(tree.node_count(), 6);
    }

    #[tokio::test]
    async fn test_collapse_node() {
        let (_temp_dir, mut tree) = create_test_tree().await;

        // Expand root and dir1
        tree.expand_node(tree.root_id()).await.unwrap();
        let root = tree.get_node(tree.root_id()).unwrap();
        let dir1_id = root.children[0];
        tree.expand_node(dir1_id).await.unwrap();

        assert_eq!(tree.node_count(), 6);

        // Collapse dir1
        tree.collapse_node(dir1_id);

        let dir1 = tree.get_node(dir1_id).unwrap();
        assert!(dir1.is_collapsed());
        assert_eq!(dir1.children.len(), 0);

        // Should remove the 2 child nodes
        assert_eq!(tree.node_count(), 4);
    }

    #[tokio::test]
    async fn test_toggle_node() {
        let (_temp_dir, mut tree) = create_test_tree().await;

        tree.expand_node(tree.root_id()).await.unwrap();
        let root = tree.get_node(tree.root_id()).unwrap();
        let dir1_id = root.children[0];

        // Toggle to expand
        tree.toggle_node(dir1_id).await.unwrap();
        assert!(tree.get_node(dir1_id).unwrap().is_expanded());

        // Toggle to collapse
        tree.toggle_node(dir1_id).await.unwrap();
        assert!(tree.get_node(dir1_id).unwrap().is_collapsed());
    }

    #[tokio::test]
    async fn test_get_visible_nodes() {
        let (_temp_dir, mut tree) = create_test_tree().await;

        // Initially only root is visible
        let visible = tree.get_visible_nodes();
        assert_eq!(visible.len(), 1);

        // Expand root
        tree.expand_node(tree.root_id()).await.unwrap();
        let visible = tree.get_visible_nodes();
        assert_eq!(visible.len(), 4); // root + 3 children

        // Expand dir1
        let root = tree.get_node(tree.root_id()).unwrap();
        let dir1_id = root.children[0];
        tree.expand_node(dir1_id).await.unwrap();

        let visible = tree.get_visible_nodes();
        assert_eq!(visible.len(), 6); // root + 3 children + 2 grandchildren
    }

    #[tokio::test]
    async fn test_get_ancestors() {
        let (_temp_dir, mut tree) = create_test_tree().await;

        tree.expand_node(tree.root_id()).await.unwrap();
        let root = tree.get_node(tree.root_id()).unwrap();
        let dir1_id = root.children[0];
        tree.expand_node(dir1_id).await.unwrap();

        let dir1 = tree.get_node(dir1_id).unwrap();
        let file1_id = dir1.children[0];

        let ancestors = tree.get_ancestors(file1_id);
        assert_eq!(ancestors.len(), 3); // root -> dir1 -> file1
        assert_eq!(ancestors[0], tree.root_id());
        assert_eq!(ancestors[1], dir1_id);
        assert_eq!(ancestors[2], file1_id);
    }

    #[tokio::test]
    async fn test_get_depth() {
        let (_temp_dir, mut tree) = create_test_tree().await;

        tree.expand_node(tree.root_id()).await.unwrap();
        let root = tree.get_node(tree.root_id()).unwrap();
        let dir1_id = root.children[0];
        tree.expand_node(dir1_id).await.unwrap();

        assert_eq!(tree.get_depth(tree.root_id()), 0);
        assert_eq!(tree.get_depth(dir1_id), 1);

        let dir1 = tree.get_node(dir1_id).unwrap();
        let file1_id = dir1.children[0];
        assert_eq!(tree.get_depth(file1_id), 2);
    }

    #[tokio::test]
    async fn test_sorted_entries() {
        let (_temp_dir, mut tree) = create_test_tree().await;

        tree.expand_node(tree.root_id()).await.unwrap();

        let root = tree.get_node(tree.root_id()).unwrap();
        let children: Vec<_> = root
            .children
            .iter()
            .map(|&id| tree.get_node(id).unwrap())
            .collect();

        // Directories should come first
        assert!(children[0].is_dir());
        assert!(children[1].is_dir());
        assert!(children[2].is_file());

        // Directories should be sorted by name
        assert_eq!(children[0].entry.name, "dir1");
        assert_eq!(children[1].entry.name, "dir2");
    }

    #[tokio::test]
    async fn test_refresh_node() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        std_fs::create_dir(temp_path.join("dir1")).unwrap();
        std_fs::write(temp_path.join("dir1/file1.txt"), "content").unwrap();

        let backend = Arc::new(StdFileSystem);
        let manager = Arc::new(FsManager::new(backend));
        let mut tree = FileTree::new(temp_path.to_path_buf(), manager)
            .await
            .unwrap();

        // Expand root and dir1
        tree.expand_node(tree.root_id()).await.unwrap();
        let root = tree.get_node(tree.root_id()).unwrap();
        let dir1_id = root.children[0];
        tree.expand_node(dir1_id).await.unwrap();

        // Initially 1 file in dir1
        let dir1 = tree.get_node(dir1_id).unwrap();
        assert_eq!(dir1.children.len(), 1);

        // Add another file
        std_fs::write(temp_path.join("dir1/file2.txt"), "content2").unwrap();

        // Refresh dir1
        tree.refresh_node(dir1_id).await.unwrap();

        // Should now have 2 files
        let dir1 = tree.get_node(dir1_id).unwrap();
        assert_eq!(dir1.children.len(), 2);
    }

    #[tokio::test]
    async fn test_find_by_relative_path() {
        let (_temp_dir, mut tree) = create_test_tree().await;

        tree.expand_node(tree.root_id()).await.unwrap();
        let root = tree.get_node(tree.root_id()).unwrap();
        let dir1_id = root.children[0];

        let found_id = tree.find_by_relative_path(Path::new("dir1"));
        assert_eq!(found_id, Some(dir1_id));

        let not_found = tree.find_by_relative_path(Path::new("nonexistent"));
        assert_eq!(not_found, None);
    }

    #[tokio::test]
    async fn test_expand_to_path() {
        let (_temp_dir, mut tree) = create_test_tree().await;
        let root_path = tree.root_path().to_path_buf();

        // Initially tree is collapsed
        assert_eq!(tree.node_count(), 1);

        // Expand to a deeply nested file
        let target_path = root_path.join("dir2/subdir/file3.txt");
        let node_id = tree.expand_to_path(&target_path).await;

        assert!(node_id.is_some(), "Should find the nested file");

        // All parent directories should now be expanded
        let root = tree.get_node(tree.root_id()).unwrap();
        assert!(root.is_expanded(), "Root should be expanded");

        // Find dir2
        let dir2_node = root
            .children
            .iter()
            .find_map(|&id| {
                let node = tree.get_node(id)?;
                if node.entry.name == "dir2" {
                    Some(node)
                } else {
                    None
                }
            })
            .expect("dir2 should exist");

        assert!(dir2_node.is_expanded(), "dir2 should be expanded");

        // Find subdir
        let subdir_node = dir2_node
            .children
            .iter()
            .find_map(|&id| {
                let node = tree.get_node(id)?;
                if node.entry.name == "subdir" {
                    Some(node)
                } else {
                    None
                }
            })
            .expect("subdir should exist");

        assert!(subdir_node.is_expanded(), "subdir should be expanded");

        // Verify the target file is found
        let target_node = tree.get_node(node_id.unwrap()).unwrap();
        assert_eq!(target_node.entry.name, "file3.txt");
        assert!(target_node.is_file());
    }

    #[tokio::test]
    async fn test_expand_to_path_not_under_root() {
        let (_temp_dir, mut tree) = create_test_tree().await;

        // Try to expand to a path not under root
        let outside_path = PathBuf::from("/tmp/somefile.txt");
        let result = tree.expand_to_path(&outside_path).await;

        assert!(
            result.is_none(),
            "Should return None for paths outside root"
        );
    }

    #[tokio::test]
    async fn test_expand_to_path_nonexistent() {
        let (_temp_dir, mut tree) = create_test_tree().await;
        let root_path = tree.root_path().to_path_buf();

        // Try to expand to a nonexistent file
        let nonexistent_path = root_path.join("dir1/nonexistent.txt");
        let result = tree.expand_to_path(&nonexistent_path).await;

        assert!(result.is_none(), "Should return None for nonexistent paths");
    }
}