Skip to main content

trusty_code/fs_browse/
mod.rs

1//! Daemon-side directory inspection for the UI's project picker (UI Phase-1).
2//!
3//! Why: the UI is a THIN CLIENT — "the UI communicates with the daemon; all UI
4//! services talk to the daemon, the daemon provides all functionality". No UI
5//! target touches the local filesystem directly, **including Tauri** (which
6//! technically could, but must not: doing so would make the Tauri build capable
7//! of something the web build isn't, forking the UI into two behaviours). So
8//! "browse my disk to pick a project" has to be a daemon API, and this module
9//! is it. One call serves both jobs the picker needs: rendering the folder list
10//! (screen 7a — breadcrumb + a `git` badge per entry) AND feeding tcode's
11//! three-state project binding model (projectless → non-git dir → git repo),
12//! because [`DirEntryInfo::is_git_repo`] is exactly the discriminator that model
13//! keys on. A non-git directory is a FIRST-CLASS, supported state here, never an
14//! error — #2728 removed the git-repo short-circuit precisely so tcode indexes
15//! non-git working dirs, and #2747 extended that to temp dirs.
16//!
17//! What: [`list_dir`] resolves a (possibly `~`-relative) path, then returns a
18//! [`DirListing`] — the resolved path, a tilde-collapsed `display_path` for the
19//! breadcrumb, the `parent` for up-navigation, and the sorted `entries`, each
20//! carrying `name`/`path`/`is_dir`/`is_git_repo`. Failures are the typed
21//! [`ListDirError`], distinguishable rather than stringly.
22//!
23//! ## No path guard here, deliberately — do not "fix" this
24//!
25//! There is no denylist, allowlist, sandbox root, or permission layer on the
26//! path argument, and that is a decision, not an oversight. tcode is a LOCAL
27//! app: the daemon runs as the user, with the user's own OS entitlements, so a
28//! directory listing discloses nothing the user could not already get from `ls`
29//! in their own shell. Decisively: the same API already exposes `task.run`,
30//! which executes ARBITRARY CODE as the user. `list_dir` is strictly less
31//! powerful than a capability sitting right beside it — guarding browse while
32//! `task.run` is one method away is ceremony, not security. There is likewise no
33//! macOS TCC permission-state machine: the app inherits whatever entitlements it
34//! is granted, and an OS-level refusal surfaces as an ordinary typed error
35//! ([`ListDirError::PermissionDenied`]) rather than a bespoke permission model.
36//!
37//! Note for anyone reaching for a precedent: trusty-search's
38//! `allow_sensitive_path` (#2747) is NOT one. That guards INDEXING — file
39//! CONTENT leaving the machine for an embedder — which is a categorically
40//! different act from listing path names locally.
41//!
42//! Test: `fs_browse::tests::*` (resolution, git-ness incl. the linked-worktree
43//! `.git`-as-file shape, error distinguishability, 7a response shape).
44//!
45//! [`DirEntryInfo::is_git_repo`]: crate::fs_browse::DirEntryInfo::is_git_repo
46//! [`list_dir`]: crate::fs_browse::list_dir
47//! [`DirListing`]: crate::fs_browse::DirListing
48//! [`ListDirError`]: crate::fs_browse::ListDirError
49//! [`ListDirError::PermissionDenied`]: crate::fs_browse::ListDirError::PermissionDenied
50
51pub mod mpm_registry;
52pub mod protocol;
53pub mod roster;
54
55use std::io::Read as _;
56use std::path::{Path, PathBuf};
57
58use serde::Serialize;
59
60/// A single entry in a [`DirListing`] — one row of screen 7a's picker.
61///
62/// Why: carries exactly the four fields 7a renders and the binding model
63/// consumes: the label (`name`), the value to navigate/bind to (`path`),
64/// whether it can be descended into (`is_dir`), and whether it draws the `git`
65/// badge vs. the `—` placeholder (`is_git_repo`).
66/// What: `path` is absolute and already resolved; `is_git_repo` is always
67/// `false` for a non-directory (a file cannot be a repo).
68/// Test: `tests::lists_entries_with_names_and_paths`,
69/// `tests::non_git_dir_is_reported_as_non_git`.
70#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
71pub struct DirEntryInfo {
72    /// The entry's file name — 7a's row label (e.g. `acme-api`).
73    pub name: String,
74    /// Absolute path to the entry; what the client passes back to navigate
75    /// into it or to bind it as the project root.
76    pub path: String,
77    /// Whether the entry is a directory (symlinks are followed).
78    pub is_dir: bool,
79    /// Whether the entry is a git repository — 7a's `git` badge, and the
80    /// non-git → git discriminator of the three-state binding model. See
81    /// [`is_git_repo`] for how this is determined.
82    pub is_git_repo: bool,
83}
84
85/// The result of a successful [`list_dir`] — everything screen 7a needs to
86/// render one view of the picker.
87///
88/// Why: a bare `Vec<DirEntryInfo>` would force the client to re-derive
89/// navigation state it cannot compute without filesystem access it does not
90/// have. The listed directory has to describe itself: where it resolved to
91/// (`path` — `~`/`..` are resolved server-side), how to caption it (`display_path`),
92/// and where "up" goes (`parent`).
93/// What: `path` is the canonical absolute directory; `display_path` is `path`
94/// with the home prefix collapsed back to `~` for the breadcrumb (7a shows
95/// `~/code / acme-api /`, which the client renders by splitting this on `/`);
96/// `parent` is `None` only at the filesystem root, which is precisely when the
97/// client must disable its up-affordance.
98/// Test: `tests::listing_shape_supports_breadcrumb_and_badges`,
99/// `tests::parent_is_none_at_filesystem_root`.
100#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
101pub struct DirListing {
102    /// Canonical absolute path of the directory that was listed.
103    pub path: String,
104    /// `path` with the user's home collapsed to `~` — the breadcrumb caption.
105    pub display_path: String,
106    /// Absolute path of the parent, or `None` at the filesystem root.
107    pub parent: Option<String>,
108    /// Entries, directories first, then case-insensitively by name.
109    pub entries: Vec<DirEntryInfo>,
110}
111
112/// Why a [`list_dir`] call failed, in distinguishable variants.
113///
114/// Why: the picker reacts differently per cause — a typo'd path is a
115/// recoverable inline message, a permission refusal is an OS-level prompt, an
116/// unexpected IO fault is a bug report. A stringly error would force the client
117/// to substring-match to tell those apart. Each variant maps to a distinct
118/// JSON-RPC code in `protocol::to_rpc_error`.
119/// What: `NotFound`/`NotADirectory`/`PermissionDenied` are the three
120/// caller-actionable cases; `Io` is the residual OS fault; `NoHome` covers a
121/// `~` path on a system with no resolvable home directory.
122/// Test: `tests::nonexistent_path_is_not_found`,
123/// `tests::file_path_is_not_a_directory`,
124/// `tests::unreadable_dir_is_permission_denied`.
125#[derive(Debug, thiserror::Error)]
126pub enum ListDirError {
127    /// The path does not exist.
128    #[error("path not found: {0}")]
129    NotFound(String),
130    /// The path exists but is a file, not a directory.
131    #[error("not a directory: {0}")]
132    NotADirectory(String),
133    /// The OS refused access. tcode inherits the user's entitlements — this is
134    /// reported, never worked around (see module docs).
135    #[error("permission denied: {0}")]
136    PermissionDenied(String),
137    /// Any other OS-level IO failure.
138    #[error("io error reading {path}: {source}")]
139    Io {
140        path: String,
141        #[source]
142        source: std::io::Error,
143    },
144    /// A `~`-relative path was given but no home directory could be resolved.
145    #[error("cannot expand `~` — no home directory for this user: {0}")]
146    NoHome(String),
147}
148
149/// Expand a leading `~` against the user's home directory.
150///
151/// Why: the picker's breadcrumb speaks in `~/code`, and an operator typing a
152/// path into it expects shell semantics. This mirrors the expansion the rest of
153/// the workspace already does (`trusty-mpm`'s `managed_root::expand_tilde`,
154/// `trusty-agents`' `repl::commands::connect::expand_tilde`) so tcode is
155/// consistent with its siblings rather than inventing a third convention.
156/// What: `~` and `~/...` expand against `dirs::home_dir`; `~user` is NOT
157/// supported (no workspace precedent does it either) and is left verbatim, as
158/// is every non-`~` path. Returns `NoHome` only when expansion was actually
159/// required and home is unresolvable.
160/// Test: `tests::tilde_expands_to_home`, `tests::tilde_bare_expands_to_home`,
161/// `tests::absolute_path_is_left_alone`.
162fn expand_tilde(raw: &str) -> Result<PathBuf, ListDirError> {
163    if raw != "~" && !raw.starts_with("~/") {
164        return Ok(PathBuf::from(raw));
165    }
166    let home = dirs::home_dir().ok_or_else(|| ListDirError::NoHome(raw.to_string()))?;
167    Ok(match raw.strip_prefix("~/") {
168        Some(rest) => home.join(rest),
169        None => home,
170    })
171}
172
173/// Collapse a leading home-directory prefix back to `~` for display.
174///
175/// Why: the inverse of [`expand_tilde`], so the breadcrumb reads `~/code`
176/// rather than `/Users/masa/code` — screen 7a's caption. Purely cosmetic: the
177/// client always navigates with the absolute `path`, never with this string.
178/// What: returns `~` / `~/rest` when `path` is under home, else `path`
179/// unchanged (including when home cannot be resolved at all).
180/// Test: `tests::display_path_collapses_home_to_tilde`.
181fn collapse_home(path: &Path) -> String {
182    let Some(home) = dirs::home_dir() else {
183        return path.display().to_string();
184    };
185    if path == home {
186        return "~".to_string();
187    }
188    match path.strip_prefix(&home) {
189        Ok(rest) => format!("~/{}", rest.display()),
190        Err(_) => path.display().to_string(),
191    }
192}
193
194/// Whether `dir` is a git repository.
195///
196/// Why: this is 7a's `git` badge and the binding model's non-git → git
197/// discriminator, so it has to be right on the shapes this repo actually
198/// contains — and this workspace lives in linked worktrees. `pub(crate)` (not
199/// private) since [`roster::list_projects`] (issue #3365's project-picker
200/// roster) reuses the exact same discriminator to filter candidate
201/// directories down to git repos — one implementation, not a second copy.
202///
203/// **The subtlety:** in a linked git worktree (and in a submodule), `.git` is a
204/// FILE containing a `gitdir: <path>` pointer, NOT a directory. Testing
205/// `.git.is_dir()` therefore reports every worktree as non-git — exactly the bug
206/// PR #2839 hit in `build.rs`, and the same latent bug still sitting in
207/// `trusty_common::project_discovery::inspect_project_dir`. This function
208/// handles BOTH shapes.
209///
210/// What: `.git` as a directory → repo. `.git` as a file → repo only if it
211/// actually carries git's documented `gitdir:` pointer, so a coincidental file
212/// named `.git` does not earn a badge. The pointer check reads only the first
213/// 64 bytes of the file rather than the whole thing — `gitdir: <path>\n` is
214/// always well under that, and this runs on the picker's hot path across every
215/// entry, so an unbounded `read_to_string` on a `.git` that happens to be a
216/// large coincidental file (not a real pointer) would be an avoidable stall.
217/// Anything else (including a metadata error, e.g. a permission refusal on the
218/// probe) → `false`.
219///
220/// **Why not shell out to `git rev-parse`** (as `run_task::diff::is_git_repo`
221/// does): that costs one subprocess PER ENTRY, and this runs across every entry
222/// of a directory on an interactive picker's hot path — a 200-entry `~/code` at
223/// ~5ms a spawn is a second of latency for a badge. Two `stat`s and, only for
224/// the rare `.git`-as-file, one small bounded read gets the same answer.
225/// `rev-parse` stays the right tool in `diff.rs`, which asks once per run about
226/// one root.
227///
228/// Note this deliberately answers "is `dir` a repo ROOT", not "is `dir` inside a
229/// work tree" — the picker badges repos, and a plain subdirectory of a repo is
230/// not itself one to bind to.
231/// Test: `tests::git_dir_is_detected`, `tests::linked_worktree_gitfile_is_detected`,
232/// `tests::bogus_dot_git_file_is_not_a_repo`, `tests::non_git_dir_is_reported_as_non_git`,
233/// `tests::large_dot_git_file_is_not_a_repo`, `tests::gitdir_pointer_at_exactly_the_read_bound`.
234pub(crate) fn is_git_repo(dir: &Path) -> bool {
235    let dot_git = dir.join(".git");
236    // `metadata` follows symlinks, matching how git itself resolves `.git`.
237    match std::fs::metadata(&dot_git) {
238        Ok(m) if m.is_dir() => true,
239        // Bounded read: `gitdir: <path>` is always well under 64 bytes, and this
240        // runs per-entry on the picker's hot path — never read a coincidental
241        // large file in full just to check its first few bytes.
242        Ok(m) if m.is_file() => std::fs::File::open(&dot_git)
243            .and_then(|mut f| {
244                let mut buf = [0u8; 64];
245                let n = f.read(&mut buf)?;
246                Ok(String::from_utf8_lossy(&buf[..n])
247                    .trim_start()
248                    .starts_with("gitdir:"))
249            })
250            .unwrap_or(false),
251        _ => false,
252    }
253}
254
255/// Map an OS IO error onto the typed [`ListDirError`] for `path`.
256///
257/// Why: keeps the `NotFound`/`PermissionDenied`/`Io` triage in one place so
258/// `list_dir`'s two fallible syscalls classify failures identically.
259/// What: matches `ErrorKind::NotFound`/`PermissionDenied`, else `Io`.
260/// Test: exercised via `tests::nonexistent_path_is_not_found` and
261/// `tests::unreadable_dir_is_permission_denied`.
262fn classify_io(err: std::io::Error, path: &str) -> ListDirError {
263    match err.kind() {
264        std::io::ErrorKind::NotFound => ListDirError::NotFound(path.to_string()),
265        std::io::ErrorKind::PermissionDenied => ListDirError::PermissionDenied(path.to_string()),
266        _ => ListDirError::Io {
267            path: path.to_string(),
268            source: err,
269        },
270    }
271}
272
273/// List `path`, returning everything the picker needs to render it.
274///
275/// Why: the single daemon-side primitive behind screen 7a — see module docs for
276/// why this is an API at all rather than UI-local filesystem access, and for why
277/// it carries no path guard.
278/// What: expands `~`, canonicalizes (resolving `..`, symlinks, and relative
279/// segments — so a client can navigate up by passing `parent`, or by passing
280/// `<path>/..`), rejects a non-directory, then reads the entries. `include_hidden`
281/// gates dot-entries: `false` (the picker default) hides them, since 7a lists
282/// project folders and a user's home is otherwise mostly dotfile noise; `true`
283/// is the escape hatch for reaching a genuinely hidden project directory.
284/// Entries are sorted directories-first then case-insensitively by name, so the
285/// picker's order is stable and does not depend on the OS's readdir order.
286/// An entry whose metadata cannot be read is included with `is_dir: false`
287/// rather than dropped — a listing that silently omits rows is worse than one
288/// that shows an unbadged entry. Likewise, an entry that `read_dir`'s iterator
289/// itself fails to produce (a per-entry OS fault mid-enumeration) is skipped
290/// with a `tracing::warn!` rather than failing the whole listing — the same
291/// best-effort philosophy, just one layer up. This skip path has no dedicated
292/// test: triggering a per-entry `read_dir` iteration error deterministically
293/// requires a TOCTOU race (e.g. another process removing an entry between
294/// `readdir` returning its name and the kernel stat'ing it) that cannot be
295/// reproduced portably in a unit test without faking the OS boundary; the
296/// existing coverage for `list_dir`'s other per-entry fallback (metadata read
297/// failure → `is_dir: false`, see `tests::*` above) exercises the same
298/// best-effort code shape.
299/// Test: `tests::*`.
300pub fn list_dir(path: &str, include_hidden: bool) -> Result<DirListing, ListDirError> {
301    let expanded = expand_tilde(path)?;
302    let resolved = std::fs::canonicalize(&expanded)
303        .map_err(|e| classify_io(e, &expanded.display().to_string()))?;
304    let resolved_str = resolved.display().to_string();
305
306    if !resolved.is_dir() {
307        return Err(ListDirError::NotADirectory(resolved_str));
308    }
309
310    let read = std::fs::read_dir(&resolved).map_err(|e| classify_io(e, &resolved_str))?;
311
312    let mut entries = Vec::new();
313    for entry in read {
314        let entry = match entry {
315            Ok(entry) => entry,
316            Err(e) => {
317                // A per-entry enumeration fault (e.g. a file vanishing mid-scan) is
318                // best-effort: skip that row rather than failing the whole listing,
319                // matching the "an unbadged entry beats a missing one" philosophy
320                // above.
321                tracing::warn!(
322                    dir = %resolved_str,
323                    error = %e,
324                    "skipping unreadable directory entry"
325                );
326                continue;
327            }
328        };
329        let name = entry.file_name().to_string_lossy().into_owned();
330        if !include_hidden && name.starts_with('.') {
331            continue;
332        }
333        let entry_path = entry.path();
334        // `metadata` (not `file_type`) so a symlink to a directory lists as a
335        // directory — the picker cares about the target, as `cd` would.
336        let is_dir = std::fs::metadata(&entry_path)
337            .map(|m| m.is_dir())
338            .unwrap_or(false);
339        entries.push(DirEntryInfo {
340            name,
341            path: entry_path.display().to_string(),
342            is_dir,
343            is_git_repo: is_dir && is_git_repo(&entry_path),
344        });
345    }
346
347    entries.sort_by(|a, b| {
348        b.is_dir
349            .cmp(&a.is_dir)
350            .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
351    });
352
353    Ok(DirListing {
354        display_path: collapse_home(&resolved),
355        parent: resolved.parent().map(|p| p.display().to_string()),
356        path: resolved_str,
357        entries,
358    })
359}
360
361#[cfg(test)]
362mod tests;