Skip to main content

hyprstream_core/tui/
vfs.rs

1//! VFS namespace construction for TUI-spawned ChatApps.
2//!
3//! Builds the same VFS namespace layout as [`crate::cli::shell_handlers`] so that
4//! remotely-spawned ChatApps (via TuiService RPC) have full `/bin/`, `/env/`,
5//! `/srv/model`, and `/lang/tcl` access.
6
7use std::sync::Arc;
8
9use hyprstream_rpc::Subject;
10use hyprstream_vfs::Namespace;
11
12/// Build a VFS namespace suitable for ChatApp usage.
13///
14/// Returns `(namespace, subject)`. The namespace contains:
15/// - `/bin/` — cat, ls, help, mount, echo commands (static entries for listing)
16/// - `/env/` — session variable store
17/// - `/srv/model` — remote model service mount (if model service is reachable)
18/// - `/lang/tcl` — Tcl interpreter state
19///
20/// Note: Actual VFS command execution goes through TclShell builtins via the
21/// VFS proxy channel, not through /bin/ ctl files. The /bin/ entries exist
22/// for directory listing so `ls /bin` shows available commands.
23///
24/// Spawn a VFS proxy on a **dedicated thread** with its own tokio runtime.
25///
26/// The TUI service's `RequestLoop` runs on a `current_thread` runtime inside
27/// a `LocalSet`. Tasks spawned via `tokio::spawn` on that runtime may not be
28/// polled promptly because the LocalSet's event loop dominates. By running
29/// the proxy on its own thread, we guarantee responsiveness regardless of
30/// the service's runtime state.
31pub fn spawn_dedicated_vfs_proxy(
32    ns: Arc<Namespace>,
33    subject: Subject,
34) -> tokio::sync::mpsc::Sender<hyprstream_vfs::proxy::VfsRequest> {
35    let (tx, rx) = tokio::sync::mpsc::channel::<hyprstream_vfs::proxy::VfsRequest>(64);
36    #[allow(clippy::expect_used)] // Thread/runtime creation failure is unrecoverable
37    std::thread::Builder::new()
38        .name("vfs-proxy".into())
39        .spawn(move || {
40            let rt = tokio::runtime::Builder::new_current_thread()
41                .enable_all()
42                .build()
43                .expect("vfs-proxy runtime");
44            rt.block_on(vfs_proxy_loop(ns, subject, rx));
45        })
46        .expect("vfs-proxy thread");
47    tx
48}
49
50async fn vfs_proxy_loop(
51    ns: Arc<Namespace>,
52    subject: Subject,
53    mut rx: tokio::sync::mpsc::Receiver<hyprstream_vfs::proxy::VfsRequest>,
54) {
55    use hyprstream_vfs::proxy::VfsOp;
56
57    while let Some(req) = rx.recv().await {
58        let result = match req.op {
59            VfsOp::Cat { ref path } => ns.cat(path, &subject).await.map_err(|e| e.to_string()),
60            VfsOp::Ls { ref path } => ns
61                .ls(path, &subject)
62                .await
63                .map(|entries| {
64                    entries
65                        .iter()
66                        .map(|e| {
67                            if e.is_dir {
68                                format!("{}/", e.name)
69                            } else {
70                                e.name.clone()
71                            }
72                        })
73                        .collect::<Vec<_>>()
74                        .join("\n")
75                        .into_bytes()
76                })
77                .map_err(|e| e.to_string()),
78            VfsOp::Echo { ref path, ref data } => ns
79                .echo(path, data, &subject)
80                .await
81                .map(|_| Vec::new())
82                .map_err(|e| e.to_string()),
83            VfsOp::Ctl { ref path, ref cmd } => {
84                ns.ctl(path, cmd, &subject).await.map_err(|e| e.to_string())
85            }
86            VfsOp::MountPrefixes => Ok(ns.mount_prefixes().join("\n").into_bytes()),
87        };
88        let _ = req.reply.send(result);
89    }
90}
91
92pub fn build_chat_vfs_namespace(
93    signing_key: &ed25519_dalek::SigningKey,
94    pep: Arc<hyprstream_vfs::NamespacePep>,
95) -> anyhow::Result<(Arc<Namespace>, Subject)> {
96    let subject = {
97        let vk = signing_key.verifying_key();
98        let pubkey_hex = hex::encode(vk.as_bytes());
99        Subject::new(pubkey_hex)
100    };
101
102    let model_client = crate::tui::service::production_model_client(signing_key.clone())?;
103
104    // Compose the standard namespace shared with the CLI shell (see
105    // `crate::services::namespace_builder`). This builder does not currently
106    // obtain a registry client, so `/srv/registry` and its `/worktree` alias
107    // are omitted here (unchanged from pre-#634 behavior).
108    let ns = crate::services::build_standard_namespace(crate::services::StandardNamespaceConfig {
109        subject: subject.clone(),
110        model_client,
111        registry: None,
112        pep: Some(pep),
113        model_path: "/srv/model".to_owned(),
114        registry_path: "/srv/registry".to_owned(),
115        worktree_path: "/worktree".to_owned(),
116        bin_path: "/bin".to_owned(),
117        env_path: "/env".to_owned(),
118        tcl_path: "/lang/tcl".to_owned(),
119    });
120
121    Ok((Arc::new(ns), subject))
122}