From 8a9a0abbd5b31a98be71c5293b4b6b59f2fe3726 Mon Sep 17 00:00:00 2001 From: ForeverInLaw <44206490+ForeverInLaw@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:53:46 +0000 Subject: [PATCH 001/180] settings: give ssh hosts a group and add the ssh.askpass switch --- crates/redshell-core/src/settings.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/redshell-core/src/settings.rs b/crates/redshell-core/src/settings.rs index 1998c87..6fcbf9f 100644 --- a/crates/redshell-core/src/settings.rs +++ b/crates/redshell-core/src/settings.rs @@ -460,6 +460,8 @@ pub struct SshHost { pub multiplexer: Option, /// Attach to (or create) this multiplexer session on connect. pub attach_session: Option, + /// Folder the host is listed under in the sidebar and pickers. + pub group: Option, pub tags: Vec, } @@ -471,6 +473,11 @@ pub struct SshSettings { pub ssh_config_path: Option, pub hosts: Vec, pub keep_alive_secs: u32, + /// Ask for passwords, passphrases and new host keys in a RedShell + /// dialog (and fill them in from the system keychain) instead of in the + /// terminal. Needs OpenSSH 8.4 or newer; older clients keep asking in + /// the terminal. + pub askpass: bool, } impl Default for SshSettings { @@ -481,6 +488,7 @@ impl Default for SshSettings { ssh_config_path: None, hosts: Vec::new(), keep_alive_secs: 30, + askpass: true, } } } From 3cac226cdb5a3c32e1a10fd2669f5f8aca764bfe Mon Sep 17 00:00:00 2001 From: ForeverInLaw <44206490+ForeverInLaw@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:53:46 +0000 Subject: [PATCH 002/180] ssh: connect to hosts named after a ~/.ssh/config alias through the alias A RedShell host whose name matches an alias from ~/.ssh/config now runs `ssh ` with the fields set in RedShell passed on top (-p, -l, -o HostName=), so the alias keeps its IdentityFile, ProxyJump and other options. Hosts only listed in ~/.ssh/config still pass nothing. --- crates/redshell-app/src/image_paste.rs | 9 +- crates/redshell-remote/src/lib.rs | 2 +- crates/redshell-remote/src/mux.rs | 6 +- crates/redshell-remote/src/ssh.rs | 118 ++++++++++++++++++------- crates/redshell-remote/src/upload.rs | 2 +- 5 files changed, 99 insertions(+), 38 deletions(-) diff --git a/crates/redshell-app/src/image_paste.rs b/crates/redshell-app/src/image_paste.rs index b70130c..40399b6 100644 --- a/crates/redshell-app/src/image_paste.rs +++ b/crates/redshell-app/src/image_paste.rs @@ -112,7 +112,7 @@ pub(super) fn start(profile: &LaunchProfile, cx: &mut Context) -> #[cfg(test)] mod tests { use redshell_core::settings::SshHost; - use redshell_remote::SshProfile; + use redshell_remote::{HostOrigin, SshProfile}; use super::*; @@ -126,7 +126,12 @@ mod tests { #[test] fn uploads_only_for_ssh_panes_while_enabled() { - let ssh = SshProfile { host: SshHost::default(), program: "ssh".into(), keep_alive_secs: 0, from_config: true }; + let ssh = SshProfile { + host: SshHost::default(), + program: "ssh".into(), + keep_alive_secs: 0, + origin: HostOrigin::Alias, + }; let remote = || Some(MuxTarget::Remote(Box::new(ssh.clone()))); let wsl = || Some(MuxTarget::Wsl { distribution: None }); assert!(upload_target(true, remote()).is_some()); diff --git a/crates/redshell-remote/src/lib.rs b/crates/redshell-remote/src/lib.rs index acca496..404f3e5 100644 --- a/crates/redshell-remote/src/lib.rs +++ b/crates/redshell-remote/src/lib.rs @@ -29,6 +29,6 @@ pub use mux::{ shell_join, }; pub use session_ref::{GENERATED_SESSION_PREFIX, MuxRef, NativeRef}; -pub use ssh::{SshProfile, SshProvider}; +pub use ssh::{HostOrigin, SshProfile, SshProvider}; pub use tmux_control::{AttachMode, ControlClient, ControlEvent, ControlPane, ControlWindow, Layout, LayoutContent}; pub use upload::{ImageType, PastedImage, upload_image}; diff --git a/crates/redshell-remote/src/mux.rs b/crates/redshell-remote/src/mux.rs index 138e863..45b0542 100644 --- a/crates/redshell-remote/src/mux.rs +++ b/crates/redshell-remote/src/mux.rs @@ -531,8 +531,7 @@ mod tests { fn hosts_are_polled_only_while_in_use_and_wsl_never() { assert_eq!(MuxTarget::Local.poll_interval(false), Some(Duration::from_secs(10))); assert_eq!(MuxTarget::Wsl { distribution: None }.poll_interval(true), None); - let ssh = - SshProfile { host: Default::default(), program: "ssh".into(), keep_alive_secs: 0, from_config: false }; + let ssh = SshProfile { program: "ssh".into(), ..Default::default() }; let remote = MuxTarget::Remote(Box::new(ssh)); assert_eq!(remote.poll_interval(true), Some(Duration::from_secs(60))); assert_eq!(remote.poll_interval(false), None); @@ -610,8 +609,7 @@ mod tests { #[test] fn a_snapshot_is_one_ssh_command() { - let ssh = - SshProfile { host: Default::default(), program: "ssh".into(), keep_alive_secs: 0, from_config: false }; + let ssh = SshProfile { program: "ssh".into(), ..Default::default() }; let spec = MuxTarget::Remote(Box::new(ssh)).batch(Tmux.list_all()); let remote = spec.args.last().unwrap(); assert!(remote.starts_with("tmux list-sessions -F 'S|:|#{session_id}"), "{remote}"); diff --git a/crates/redshell-remote/src/ssh.rs b/crates/redshell-remote/src/ssh.rs index 50ed8d0..7a8f038 100644 --- a/crates/redshell-remote/src/ssh.rs +++ b/crates/redshell-remote/src/ssh.rs @@ -11,27 +11,50 @@ use redshell_core::{CommandSpec, LaunchKind, LaunchProfile, LaunchProvider, Laun use crate::mux::{Multiplexer, mux_for}; use crate::ssh_config; +/// Where a host's settings come from, which decides how ssh is pointed at it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum HostOrigin { + /// A RedShell host with an address of its own: ssh gets every field. + #[default] + Settings, + /// A RedShell host named after a `~/.ssh/config` alias (or without an + /// address): ssh resolves the alias, and the fields set in RedShell are + /// passed on top of it (the command line wins over the config file). + Alias, + /// Only listed in `~/.ssh/config`: ssh resolves everything, the fields + /// read from the file are shown but not passed. + Imported, +} + /// One SSH destination. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Default)] pub struct SshProfile { pub host: SshHost, pub program: String, pub keep_alive_secs: u32, - /// Imported from `~/.ssh/config` (connect by alias, let ssh resolve it). - pub from_config: bool, + pub origin: HostOrigin, } impl SshProfile { + /// Whether ssh is given the host's name and resolves it from its config. + pub fn connects_by_alias(&self) -> bool { + self.origin != HostOrigin::Settings + } + /// `ssh` arguments up to and including the destination. pub fn base_args(&self, batch: bool) -> Vec { let h = &self.host; let mut args = Vec::new(); - if let Some(port) = h.port.filter(|_| !self.from_config) { + let explicit = self.origin != HostOrigin::Imported; + if let Some(port) = h.port.filter(|_| explicit) { args.extend(["-p".into(), port.to_string()]); } - if let Some(user) = h.user.as_ref().filter(|_| !self.from_config) { + if let Some(user) = h.user.as_ref().filter(|_| explicit) { args.extend(["-l".into(), user.clone()]); } + if self.origin == HostOrigin::Alias && !h.host.is_empty() { + args.extend(["-o".into(), format!("HostName={}", h.host)]); + } if let Some(id) = &h.identity_file { args.extend(["-i".into(), id.display().to_string()]); } @@ -45,7 +68,7 @@ impl SshProfile { args.extend(["-o".into(), "BatchMode=yes".into(), "-o".into(), "ConnectTimeout=6".into()]); } args.extend(h.extra_args.iter().cloned()); - args.push(if self.from_config { h.name.clone() } else { h.host.clone() }); + args.push(if self.connects_by_alias() { h.name.clone() } else { h.host.clone() }); args } @@ -108,35 +131,35 @@ pub struct SshProvider { impl SshProvider { pub fn new(settings: &SshSettings) -> Self { + let aliases = + if settings.import_ssh_config { ssh_config::load(settings.ssh_config_path.as_deref()) } else { Vec::new() }; + let profile = |host: SshHost, origin| SshProfile { + host, + program: settings.program.clone(), + keep_alive_secs: settings.keep_alive_secs, + origin, + }; let mut profiles: Vec = settings .hosts .iter() - .map(|h| SshProfile { - host: h.clone(), - program: settings.program.clone(), - keep_alive_secs: settings.keep_alive_secs, - from_config: h.host.is_empty(), + .map(|h| { + let alias = h.host.is_empty() || aliases.iter().any(|a| a.alias == h.name); + profile(h.clone(), if alias { HostOrigin::Alias } else { HostOrigin::Settings }) }) .collect(); - if settings.import_ssh_config { - for entry in ssh_config::load(settings.ssh_config_path.as_deref()) { - if profiles.iter().any(|p| p.host.name == entry.alias) { - continue; - } - profiles.push(SshProfile { - host: SshHost { - name: entry.alias.clone(), - host: entry.hostname.unwrap_or_default(), - user: entry.user, - port: entry.port, - tags: vec!["ssh_config".into()], - ..Default::default() - }, - program: settings.program.clone(), - keep_alive_secs: settings.keep_alive_secs, - from_config: true, - }); + for entry in aliases { + if profiles.iter().any(|p| p.host.name == entry.alias) { + continue; } + let host = SshHost { + name: entry.alias, + host: entry.hostname.unwrap_or_default(), + user: entry.user, + port: entry.port, + tags: vec!["ssh_config".into()], + ..Default::default() + }; + profiles.push(profile(host, HostOrigin::Imported)); } Self { profiles } } @@ -177,10 +200,45 @@ mod tests { }, program: "ssh".into(), keep_alive_secs: 0, - from_config: false, + origin: HostOrigin::Settings, }; let cmd = p.command(); assert_eq!(cmd.args, ["-t", "-p", "2222", "-l", "deploy", "prod.example.com", "tmux new-session -A -s main"]); assert_eq!(p.description(), "deploy@prod.example.com"); } + + fn args(host: SshHost, origin: HostOrigin) -> Vec { + SshProfile { host, program: "ssh".into(), keep_alive_secs: 0, origin }.base_args(false) + } + + #[test] + fn an_alias_keeps_the_config_and_layers_what_redshell_sets() { + let host = SshHost { + name: "box".into(), + host: "10.0.0.5".into(), + user: Some("me".into()), + port: Some(2200), + ..Default::default() + }; + assert_eq!(args(host.clone(), HostOrigin::Settings), ["-p", "2200", "-l", "me", "10.0.0.5"]); + assert_eq!(args(host.clone(), HostOrigin::Alias), ["-p", "2200", "-l", "me", "-o", "HostName=10.0.0.5", "box"]); + assert_eq!(args(host, HostOrigin::Imported), ["box"]); + } + + #[test] + fn a_host_named_after_a_config_alias_connects_through_it() { + let dir = tempfile::tempdir().unwrap(); + let config = dir.path().join("config"); + std::fs::write(&config, "Host box\n HostName 10.0.0.5\n User me\n\nHost other\n HostName o.example\n") + .unwrap(); + let mut settings = SshSettings { ssh_config_path: Some(config), ..Default::default() }; + settings.hosts.push(SshHost { name: "box".into(), port: Some(2200), ..Default::default() }); + settings.hosts.push(SshHost { name: "web".into(), host: "w.example".into(), ..Default::default() }); + let provider = SshProvider::new(&settings); + let origin = |name| provider.find(name).unwrap().origin; + assert_eq!(origin("box"), HostOrigin::Alias); + assert_eq!(origin("web"), HostOrigin::Settings); + assert_eq!(origin("other"), HostOrigin::Imported); + assert_eq!(provider.hosts().len(), 3); + } } diff --git a/crates/redshell-remote/src/upload.rs b/crates/redshell-remote/src/upload.rs index 32a797c..61bb9c3 100644 --- a/crates/redshell-remote/src/upload.rs +++ b/crates/redshell-remote/src/upload.rs @@ -225,7 +225,7 @@ mod tests { fn ssh_upload_runs_a_fixed_script_in_batch_mode() { let host = SshHost { name: "box".into(), host: "box.example.com".into(), port: Some(2222), ..Default::default() }; - let ssh = SshProfile { host, program: "ssh".into(), keep_alive_secs: 0, from_config: false }; + let ssh = SshProfile { host, program: "ssh".into(), ..Default::default() }; let spec = upload_command(&MuxTarget::Remote(Box::new(ssh)), "20261201-093012-1a2b3c4d.png"); assert_eq!(spec.program, "ssh"); let (remote, options) = spec.args.split_last().unwrap(); From e64b42deb0ad9b2620391b61c6539cf603085928 Mon Sep 17 00:00:00 2001 From: ForeverInLaw <44206490+ForeverInLaw@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:16:57 +0000 Subject: [PATCH 003/180] docs: design the headless server and the remote PWA --- docs/design/remote-server.md | 122 +++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 docs/design/remote-server.md diff --git a/docs/design/remote-server.md b/docs/design/remote-server.md new file mode 100644 index 0000000..fcc09ff --- /dev/null +++ b/docs/design/remote-server.md @@ -0,0 +1,122 @@ +# RedShell Server and RedShell Remote (PWA): design + +Status: accepted for 0.0.3. + +## Why + +The owner runs coding agents (Claude Code, Codex, OpenCode) in RedShell and wants to keep driving them while away from the desk. Today an agent lives in a desktop tab and dies with the desktop. The goal is a small always-on box (a Raspberry Pi) that runs the sessions. The desktop RedShell attaches to them like to any tab, and a phone installs a PWA that is at least as convenient as Claude Code's Remote Control (`/rc`) and OpenCode's web/mobile access. It has to be light (a Pi), properly secured (password and passkey-only sign-in) and beautiful. + +## Goals + +- `redshell-server`: a headless binary (Linux x86_64/aarch64, also macOS/Windows) that owns PTY sessions (shells, agents, SSH hosts). Sessions survive every client disconnect. +- The desktop RedShell connects to one or more servers: their sessions show in the sidebar and open as normal tabs. New sessions start on the server. SSH hosts can be sent from the desktop to the server. +- RedShell Remote, a PWA served by the server: a session inbox with live agent state, a mobile terminal with a composer and key bar, approvals of agent actions, push notifications, new sessions, SSH hosts, account and device management. +- Sign-in with username and password (Argon2id), passkeys (WebAuthn, discoverable credentials: iPhone, Android, Windows Hello, security keys), and an optional passkey-only mode per user that turns password sign-in off. +- Idle footprint on a Pi: one process, no runtime besides the binary, a few MB of RAM per idle session. + +## Non-goals (0.0.3) + +- A hosted relay. Reachability comes from the owner's network: Tailscale Serve (recommended), a Cloudflare named tunnel, or a reverse proxy with a real certificate. +- Multi-tenant isolation between users on one server. Every user of a server is trusted with its sessions; there is no per-user sandbox. +- A structured chat transcript built from agent log files (their schemas are undocumented and move every release). The terminal stays the source of truth; structure comes from hooks (approvals, finished, needs input). +- Native mobile apps. + +## Anti-goals + +- Exposing a shell to the internet with weak auth: no default password, no unauthenticated endpoints besides sign-in, the PWA shell and the manifest. +- A heavy server (Node, Python, Docker required). +- A PWA that is a desktop terminal squeezed into a phone. + +## Approaches considered + +1. **Terminal-first server with hook-based agent awareness (chosen).** The server owns PTYs, exactly like desktop tabs, and multiplexes them to any number of clients. Agents get structure through their own extension points: Claude Code HTTP hooks (PermissionRequest is held open until a client answers, Notification, Stop, UserPromptSubmit) passed with `claude --settings ''` so the user's config is untouched. Codex gets its `notify` program, and any program gets OSC 9 / OSC 777 notifications and BEL. Works for every agent and TUI, and the desktop and phone see the same session. +2. **Structured agents over ACP / app-server protocols.** Best chat UI, but the sessions would no longer be the TUIs the desktop shows, Claude and Codex need extra adapters (Node), and arbitrary programs are left out. +3. **Tail agent transcript files for a chat view.** Undocumented, version-fragile formats. Rejected for 0.0.3; it can come later as an optional lens on top of approach 1. + +## Architecture + +``` +crates/redshell-protocol serde types shared by server, desktop and (via ts-rs) the PWA +crates/redshell-server lib + bin: axum/tokio HTTP + WebSocket, SQLite store +crates/redshell-app desktop: src/remote/ (server list, auth, attach, host push) +web/ PWA: Vite + React + TypeScript, xterm.js, TanStack Query, Zustand +``` + +### Server + +- **Config.** The server reads the same `config.toml` format as the desktop, through `redshell-core::Settings` and `SettingsFile`, from its own config dir (`--config`). It adds a `[server]` section: + - `listen` (default `127.0.0.1:4747`); + - `public_url` (the HTTPS origin; required for passkeys and push); + - `tls_cert` / `tls_key` (optional built-in TLS); + - `trusted_proxies`. + SSH hosts, agent and terminal settings mean the same thing as on the desktop. +- **Store.** SQLite (`rusqlite`, already used): users, password hashes, passkeys, browser sessions and device tokens (stored as SHA-256 of 256-bit random tokens), WebAuthn ceremonies in flight, push subscriptions, VAPID keys, audit log, sessions metadata. +- **Sessions.** Each session is a `redshell-terminal` engine (alacritty VT + portable-pty) on the server. + - A late client gets a snapshot and then the live stream. The snapshot is the screen and recent scrollback serialized as ANSI, plus the terminal modes a client needs to send the right input and draw the right screen: alt screen, application cursor and keypad, bracketed paste, mouse reporting and its encoding, focus reporting, cursor visibility and shape, and the title. + - Size follows the client that last typed (like tmux `window-size latest`). + - Sessions are listed with title, cwd, kind (shell, agent, ssh), exit state and agent state (`working`, `needs_approval`, `needs_input`, `idle`, `finished`), plus the last line of output. +- **API.** REST under `/api/*` (JSON) for auth, sessions, hosts, profiles, devices, passkeys, push, and server info. One WebSocket per client (`/api/ws`): JSON control messages plus binary frames for PTY data, per attached session. +- **Agent hooks.** + - Hooks have their own listener, bound to loopback on a random port and never served on the public listener. A reverse proxy (Tailscale Serve, cloudflared) makes every request look like it came from loopback, so a loopback peer is never trusted by itself; every hook URL carries a per-session random token. + - Claude Code agents are started with `--settings `, a 0600 file in the server's runtime dir (inline JSON would show the token in `ps`). The file adds `http` hooks to `http://127.0.0.1:/claude//`. + - PermissionRequest is held open, shown to every client of that session and to push, and answered by the first client that decides (allow, deny, or "answer in terminal", which returns no decision so Claude shows its own dialog). + - The hook times out after `server.approval_timeout_secs` (default 600) with no decision. + - The desktop shows the same approval as a banner over the tab, so a user at the desk is never left watching a held prompt. + - Codex gets `-c notify=[...]` pointing at `redshell-server hook codex`. + - OSC 9 / 777 / BEL from any session raise a notification event. +- **Push.** Web Push with VAPID (keys generated at first start), RFC 8291 encryption in pure Rust (no OpenSSL, so it cross-compiles for the Pi). Sent for approval needed, input needed, finished and failed exit, but not while a client is actively typing in that session. +- **Plain HTTP.** It is allowed only on a loopback listener (behind Tailscale Serve or another TLS proxy). A non-loopback `listen` without `tls_cert`/`tls_key` is refused at start. The desktop client refuses `http://` server URLs that are not loopback, because a bearer token would cross the network in clear. +- **Static PWA.** Built assets are embedded in the binary. Strict CSP, no inline script, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`. + +### Auth + +- **First start.** It prints a one-time setup link (`/setup?code=…`, valid 30 minutes) to the log, and the first account is created there. CLI subcommands are `redshell-server user add|passwd|remove|reset-passkeys` and `redshell-server serve`. +- **Passwords.** Argon2id. Sign-in is rate-limited per IP and per user (exponential backoff), with the same error for an unknown user and a wrong password, and the attempt is logged. +- **Passkeys.** `webauthn-rs`: discoverable credentials, so "Sign in with a passkey" works without typing a name. Several passkeys per user, each with a name and a last-used time, and each can be revoked. Passkey-only mode refuses password sign-in for that user; it can be switched on only while the user has a passkey. +- **Browser sessions.** A `__Host-` cookie, HttpOnly, Secure, SameSite=Strict, with a 30-day sliding expiry. Every state-changing request needs a matching Origin, and the WebSocket upgrade is checked against `public_url`. +- **Desktop devices.** Bearer device tokens. The desktop gets one either by username and password in its dialog, or by browser pairing: + 1. the desktop asks for a pairing request and shows its short code (for example `KX7-4MP`), then opens `/pair`; + 2. the user signs in there, including by passkey, and types the code shown on the desktop. The page then shows the device name and asks to approve it. A link that pre-fills the code is never offered, so a pairing request someone else started cannot be approved by clicking a link; + 3. the desktop polls and receives the token. A request expires after 10 minutes. + Devices are listed and can be revoked from the PWA and the desktop. + +### Desktop client + +- Settings has a Servers page: add a server (URL), sign in (password or browser pairing), sign out, and remove. +- The sidebar gets a `servers` section listing each server's sessions with their agent state, plus a "+" for a new session on that server. +- A remote session opens as a tab through `Terminal::external` over the WebSocket. Tabs of remote sessions are restored on start. +- On an SSH host's context menu, "Send to server…" copies the host. Secrets never leave the machine. + +### PWA + +The visual direction is set with references (Muse) and checked by a design review on real mobile screenshots before release. + +**Screens:** +- sign-in (passkey first, password second), plus first-run setup; +- session inbox (cards with live state; those needing attention first); +- session view: full-bleed xterm.js; a key bar with Esc, Tab, Ctrl, arrows, ↑↓ history and paste; a composer that sends a line; an approval bottom sheet with the tool, command or diff and the actions Allow, Always allow, Deny, and Answer in terminal; +- new session (agent, shell or SSH host; folder from recent folders); +- SSH hosts; +- settings: passkeys, devices, notifications, password, passkey-only. + +**Behaviour:** +- installable (manifest and icons), with a service worker for the app shell and push; +- reconnects transparently; +- works on iPhone Safari, Android Chrome and desktop browsers. + +## Security notes + +- The server never stores a secret in plain text that a client gave it, except the PTY data it must show. +- Hooks run on loopback with a per-session random token. +- Every endpoint except `/`, static assets, the manifest, `/api/auth/*` and `/api/setup` requires a valid session or device token. +- Responses never include password hashes, token hashes or WebAuthn private material. + +## Packaging + +- The release gets `redshell-server` for linux-x86_64 and linux-aarch64 (Raspberry Pi OS 64-bit) as a tarball and a `.deb` with a systemd unit (`redshell-server.service`, a dedicated user, state in `/var/lib/redshell-server`). +- The PWA is built in CI (`npm ci && npm run build`) before cargo. +- Without a built PWA, `cargo build` embeds a small page that says how to build it. + +## Left to the builders + +Exact endpoint paths and message names are left to the builders and documented in `docs/REMOTE.md`. So are the internal module split, the snapshot format details, the backoff constants and the component structure of the PWA. From 8b14a51fc11b44c9fcda07a0dde66bc3c348a5d2 Mon Sep 17 00:00:00 2001 From: ForeverInLaw <44206490+ForeverInLaw@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:59:47 +0000 Subject: [PATCH 004/180] state: rebuild ssh hosts when their settings change --- crates/redshell-app/src/state.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/redshell-app/src/state.rs b/crates/redshell-app/src/state.rs index 7b1feb2..d775624 100644 --- a/crates/redshell-app/src/state.rs +++ b/crates/redshell-app/src/state.rs @@ -300,8 +300,12 @@ impl AppState { if self.settings != old { self.save(&old); } - // Only the shell settings change the profiles (searching PATH for shells). - if self.settings.terminal != old.terminal { + // Only the shell and SSH settings change the profiles (searching PATH + // for shells, reading ~/.ssh/config). + if self.settings.ssh != old.ssh { + self.ssh = SshProvider::new(&self.settings.ssh); + } + if self.settings.terminal != old.terminal || self.settings.ssh != old.ssh { self.refresh_profiles(); } old From 565e02f4ff8011de477e1b9af592940f3f81c488 Mon Sep 17 00:00:00 2001 From: ForeverInLaw <44206490+ForeverInLaw@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:06:34 +0000 Subject: [PATCH 005/180] text input: masked mode that shows bullets and keeps the text off the clipboard --- .../redshell-ui/src/components/text_input.rs | 70 +++++++++++++++++-- 1 file changed, 63 insertions(+), 7 deletions(-) diff --git a/crates/redshell-ui/src/components/text_input.rs b/crates/redshell-ui/src/components/text_input.rs index 5c1cd09..54915e8 100644 --- a/crates/redshell-ui/src/components/text_input.rs +++ b/crates/redshell-ui/src/components/text_input.rs @@ -4,6 +4,9 @@ //! the platform input handler (typing, IME composition) onto it and paints //! the text, selection and caret. Emits [`InputEvent`]s so owners (pickers, //! search, settings) react without knowing about key handling. +//! +//! A [masked](TextInput::masked) input (passwords) paints a bullet per +//! character and keeps its text off the clipboard. use std::ops::Range; @@ -23,6 +26,8 @@ actions!(text_input, [SelectAll, Copy, Cut, Paste]); const CONTEXT: &str = "TextInput"; const CARET_WIDTH: Pixels = px(1.5); +/// What a masked input shows for each character. +const BULLET: char = '•'; #[derive(Debug, Clone, PartialEq, Eq)] pub enum InputEvent { @@ -41,6 +46,7 @@ pub struct TextInput { editor: LineEditor, placeholder: SharedString, prefix: Option, + masked: bool, /// The shaped text and where it was painted, for mouse hit-testing and /// placing the IME candidate window. last_layout: Option<(ShapedLine, Bounds)>, @@ -65,6 +71,7 @@ impl TextInput { editor: LineEditor::default(), placeholder: "".into(), prefix: None, + masked: false, last_layout: None, scroll_x: px(0.), selecting: false, @@ -106,6 +113,12 @@ impl TextInput { self } + /// Shows bullets instead of the text and turns off copy and cut. + pub fn masked(mut self, masked: bool) -> Self { + self.masked = masked; + self + } + pub fn value(&self) -> &str { self.editor.text() } @@ -185,6 +198,9 @@ impl TextInput { } fn copy(&mut self, _: &Copy, _w: &mut Window, cx: &mut Context) { + if self.masked { + return; + } let selected = self.editor.selected_text(); if !selected.is_empty() { cx.write_to_clipboard(ClipboardItem::new_string(selected.to_owned())); @@ -192,7 +208,7 @@ impl TextInput { } fn cut(&mut self, _: &Cut, _w: &mut Window, cx: &mut Context) { - if !self.editor.selection().is_empty() { + if !self.masked && !self.editor.selection().is_empty() { let mut taken = String::new(); self.edit(cx, |e| taken = e.take_selection()); cx.write_to_clipboard(ClipboardItem::new_string(taken)); @@ -205,11 +221,21 @@ impl TextInput { } } + /// Where text offset `offset` falls in what is painted. + fn shown_offset(&self, offset: usize) -> usize { + if self.masked { mask_offset(self.editor.text(), offset) } else { offset } + } + + /// The text offset of `shown`, an offset in what is painted. + fn unmasked_offset(&self, shown: usize) -> usize { + if self.masked { unmask_offset(self.editor.text(), shown) } else { shown } + } + /// Text offset under a window position (the placeholder counts as empty). fn offset_at(&self, position: Point) -> usize { match &self.last_layout { Some((line, bounds)) if !self.editor.text().is_empty() => { - line.closest_index_for_x(position.x - bounds.left() + self.scroll_x) + self.unmasked_offset(line.closest_index_for_x(position.x - bounds.left() + self.scroll_x)) } _ => 0, } @@ -219,9 +245,11 @@ impl TextInput { self.focus.focus(window); let offset = self.offset_at(ev.position); self.selecting = ev.click_count == 1; + let masked = self.masked; self.edit(cx, |e| match ev.click_count { 1 => e.move_to(offset, ev.modifiers.shift), - 2 => e.select_word_at(offset), + // Words would give away where a masked text has spaces. + 2 if !masked => e.select_word_at(offset), _ => e.select_all(), }); } @@ -238,6 +266,16 @@ impl TextInput { } } +/// Byte offset in a masked text's bullets of byte `offset` in `text`. +fn mask_offset(text: &str, offset: usize) -> usize { + text[..offset].chars().count() * BULLET.len_utf8() +} + +/// Byte offset in `text` of byte `shown` in its bullets. +fn unmask_offset(text: &str, shown: usize) -> usize { + text.char_indices().nth(shown / BULLET.len_utf8()).map_or(text.len(), |(i, _)| i) +} + /// Typing, IME commits and pre-edit text from the platform. impl EntityInputHandler for TextInput { fn text_for_range( @@ -315,7 +353,7 @@ impl EntityInputHandler for TextInput { ) -> Option> { let (line, _) = self.last_layout.as_ref()?; let range = self.editor.range_from_utf16(&range_utf16); - let x = |i| bounds.left() + line.x_for_index(i) - self.scroll_x; + let x = |i| bounds.left() + line.x_for_index(self.shown_offset(i)) - self.scroll_x; Some(Bounds::from_corners(point(x(range.start), bounds.top()), point(x(range.end), bounds.bottom()))) } @@ -392,6 +430,8 @@ impl Element for TextLine { let style = window.text_style(); let (text, color) = if editor.text().is_empty() { (input.placeholder.clone(), ui.muted_foreground.into()) + } else if input.masked { + (SharedString::from(BULLET.to_string().repeat(editor.text().chars().count())), style.color) } else { (SharedString::from(editor.text().to_owned()), style.color) }; @@ -403,7 +443,7 @@ impl Element for TextLine { underline: None, strikethrough: None, }; - let runs = match editor.marked() { + let runs = match editor.marked().map(|r| input.shown_offset(r.start)..input.shown_offset(r.end)) { Some(marked) => { let underline = UnderlineStyle { color: Some(color), thickness: px(1.), wavy: false }; [ @@ -421,14 +461,14 @@ impl Element for TextLine { let line = window.text_system().shape_line(text, font_size, &runs, None); let width = bounds.size.width; - let caret_x = line.x_for_index(editor.caret()); + let caret_x = line.x_for_index(input.shown_offset(editor.caret())); let mut scroll_x = input.scroll_x; if caret_x - scroll_x > width - CARET_WIDTH { scroll_x = caret_x - width + CARET_WIDTH; } scroll_x = scroll_x.min(caret_x).min((line.width - width + CARET_WIDTH).max(px(0.))).max(px(0.)); let sel = editor.selection(); - let selection = line.x_for_index(sel.start)..line.x_for_index(sel.end); + let selection = line.x_for_index(input.shown_offset(sel.start))..line.x_for_index(input.shown_offset(sel.end)); TextLinePaint { line, scroll_x, selection, caret_x } } @@ -506,3 +546,19 @@ impl Render for TextInput { .child(TextLine { input: cx.entity() }) } } + +#[cfg(test)] +mod tests { + use super::{mask_offset, unmask_offset}; + + #[test] + fn masked_offsets_map_characters_to_bullets_and_back() { + let text = "aé€😀b"; + let bullets = "•".repeat(text.chars().count()); + for (n, (offset, _)) in text.char_indices().chain([(text.len(), ' ')]).enumerate() { + let shown = mask_offset(text, offset); + assert_eq!(shown, bullets.char_indices().nth(n).map_or(bullets.len(), |(i, _)| i)); + assert_eq!(unmask_offset(text, shown), offset); + } + } +} From 0bbd071c38530eca594da6345de0d6b0d9d2ac69 Mon Sep 17 00:00:00 2001 From: ForeverInLaw <44206490+ForeverInLaw@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:06:34 +0000 Subject: [PATCH 006/180] text input: shift+tab moves back, as tab moves on --- crates/redshell-app/src/find_bar.rs | 2 +- crates/redshell-app/src/picker.rs | 2 +- crates/redshell-app/src/search.rs | 2 +- crates/redshell-ui/src/components/text_input.rs | 3 +++ 4 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/redshell-app/src/find_bar.rs b/crates/redshell-app/src/find_bar.rs index d91535e..d22b0bf 100644 --- a/crates/redshell-app/src/find_bar.rs +++ b/crates/redshell-app/src/find_bar.rs @@ -52,7 +52,7 @@ impl FindBar { InputEvent::Submit | InputEvent::Up => cx.emit(FindEvent::Step(SearchDirection::Older)), InputEvent::Down => cx.emit(FindEvent::Step(SearchDirection::Newer)), InputEvent::Cancel => cx.emit(FindEvent::Close), - InputEvent::SubmitStrong | InputEvent::Tab => {} + InputEvent::SubmitStrong | InputEvent::Tab | InputEvent::BackTab => {} }); input.read(cx).focus(window); Self { input, case_sensitive: false, regex: false, status: FindStatus::Idle, _sub: sub } diff --git a/crates/redshell-app/src/picker.rs b/crates/redshell-app/src/picker.rs index 58ff3b1..4e9acd7 100644 --- a/crates/redshell-app/src/picker.rs +++ b/crates/redshell-app/src/picker.rs @@ -268,7 +268,7 @@ impl Picker { } cx.notify(); } - InputEvent::Up => self.move_by(-1, cx), + InputEvent::Up | InputEvent::BackTab => self.move_by(-1, cx), InputEvent::Down | InputEvent::Tab => self.move_by(1, cx), InputEvent::Submit => self.confirm(false, cx), InputEvent::SubmitStrong => self.confirm(true, cx), diff --git a/crates/redshell-app/src/search.rs b/crates/redshell-app/src/search.rs index fdba6a1..b391af5 100644 --- a/crates/redshell-app/src/search.rs +++ b/crates/redshell-app/src/search.rs @@ -170,7 +170,7 @@ impl SessionSearch { let q = q.clone(); self.run_query(&q); } - InputEvent::Up => self.selected = self.selected.saturating_sub(1), + InputEvent::Up | InputEvent::BackTab => self.selected = self.selected.saturating_sub(1), InputEvent::Down | InputEvent::Tab => { self.selected = (self.selected + 1).min(self.rows.len().saturating_sub(1)) } diff --git a/crates/redshell-ui/src/components/text_input.rs b/crates/redshell-ui/src/components/text_input.rs index 54915e8..b9a8b61 100644 --- a/crates/redshell-ui/src/components/text_input.rs +++ b/crates/redshell-ui/src/components/text_input.rs @@ -39,6 +39,8 @@ pub enum InputEvent { Up, Down, Tab, + /// Shift+Tab. + BackTab, } pub struct TextInput { @@ -173,6 +175,7 @@ impl TextInput { "escape" => cx.emit(InputEvent::Cancel), "up" => cx.emit(InputEvent::Up), "down" => cx.emit(InputEvent::Down), + "tab" if m.shift => cx.emit(InputEvent::BackTab), "tab" => cx.emit(InputEvent::Tab), "n" if m.control => cx.emit(InputEvent::Down), "p" if m.control => cx.emit(InputEvent::Up), From a6d07a5b69a803beecc1f49591503700e4df6eda Mon Sep 17 00:00:00 2001 From: ForeverInLaw <44206490+ForeverInLaw@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:08:53 +0000 Subject: [PATCH 007/180] settings: leave empty ssh host fields out of config.toml --- crates/redshell-core/src/settings.rs | 7 +++++++ crates/redshell-core/src/settings/edit.rs | 9 +++++++++ 2 files changed, 16 insertions(+) diff --git a/crates/redshell-core/src/settings.rs b/crates/redshell-core/src/settings.rs index 6fcbf9f..d3e3a68 100644 --- a/crates/redshell-core/src/settings.rs +++ b/crates/redshell-core/src/settings.rs @@ -446,15 +446,21 @@ pub struct MultiplexerSettings { pub auto_attach_local: bool, } +/// One `[[ssh.hosts]]` entry. Empty fields stay out of config.toml, so an +/// entry that only overrides a few fields of a `~/.ssh/config` alias reads +/// as just those fields. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] #[serde(default)] pub struct SshHost { pub name: String, + /// Empty: the name is a `~/.ssh/config` alias, which ssh resolves. + #[serde(skip_serializing_if = "String::is_empty")] pub host: String, pub user: Option, pub port: Option, pub identity_file: Option, pub jump_host: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] pub extra_args: Vec, /// Remote multiplexer to manage on this host (overrides the global one). pub multiplexer: Option, @@ -462,6 +468,7 @@ pub struct SshHost { pub attach_session: Option, /// Folder the host is listed under in the sidebar and pickers. pub group: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] pub tags: Vec, } diff --git a/crates/redshell-core/src/settings/edit.rs b/crates/redshell-core/src/settings/edit.rs index c85b47d..01df414 100644 --- a/crates/redshell-core/src/settings/edit.rs +++ b/crates/redshell-core/src/settings/edit.rs @@ -364,6 +364,15 @@ mod tests { assert_eq!(out, text.replace("\"b\"", "\"c\"")); } + #[test] + fn a_new_ssh_host_is_written_without_empty_fields() { + let out = + edited("", |s| s.ssh.hosts.push(SshHost { name: "box".into(), port: Some(2200), ..Default::default() })); + assert_eq!(out, "[[ssh.hosts]]\nname = \"box\"\nport = 2200\n"); + let out = edited(&out.replace("port", "host = \"10.0.0.5\"\nport"), |s| s.ssh.hosts[0].host.clear()); + assert_eq!(out, "[[ssh.hosts]]\nname = \"box\"\nport = 2200\n"); + } + #[test] fn list_names_unknown_to_this_version_survive_a_change() { let text = "[appearance]\nsidebar_sections = [\"sessions\", \"widgets\", \"hosts\"]\n"; From c734abb87fc0d1b24ddfc13f62d73c7323ff7fec Mon Sep 17 00:00:00 2001 From: ForeverInLaw <44206490+ForeverInLaw@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:10:39 +0000 Subject: [PATCH 008/180] list item: a right-click handler for context menus --- crates/redshell-ui/src/components/list_item.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/redshell-ui/src/components/list_item.rs b/crates/redshell-ui/src/components/list_item.rs index 1b2040a..e5be808 100644 --- a/crates/redshell-ui/src/components/list_item.rs +++ b/crates/redshell-ui/src/components/list_item.rs @@ -4,8 +4,8 @@ use gpui::prelude::*; use std::ops::Range; use gpui::{ - AnyElement, App, ClickEvent, ElementId, FontWeight, HighlightStyle, Pixels, SharedString, StyledText, Window, div, - px, + AnyElement, App, ClickEvent, ElementId, FontWeight, HighlightStyle, MouseButton, MouseDownEvent, Pixels, + SharedString, StyledText, Window, div, px, }; use crate::components::icon::{Icon, IconName}; @@ -13,6 +13,7 @@ use crate::styled::StyledExt; use crate::theme::{ThemeExt, alpha, space}; type ClickHandler = Box; +type RightClickHandler = Box; #[derive(IntoElement)] pub struct ListItem { @@ -25,6 +26,7 @@ pub struct ListItem { accent_icon: bool, end: Vec, on_click: Option, + on_right_click: Option, dense: bool, highlights: Vec>, } @@ -41,6 +43,7 @@ impl ListItem { accent_icon: false, end: Vec::new(), on_click: None, + on_right_click: None, dense: false, highlights: Vec::new(), } @@ -86,6 +89,11 @@ impl ListItem { self.on_click = Some(Box::new(f)); self } + /// Runs on a right mouse button press, e.g. to open a context menu. + pub fn on_right_click(mut self, f: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static) -> Self { + self.on_right_click = Some(Box::new(f)); + self + } /// Fixed row height, so scrolling lists can be sized to whole rows. pub fn height(has_subtitle: bool, dense: bool) -> Pixels { @@ -147,6 +155,9 @@ impl RenderOnce for ListItem { if let Some(handler) = self.on_click { row = row.on_click(handler); } + if let Some(handler) = self.on_right_click { + row = row.on_mouse_down(MouseButton::Right, handler); + } let icon_color = if self.accent_icon || self.selected { ui.primary } else { ui.muted_foreground }; let mark = HighlightStyle { color: Some(ui.primary.into()), From b8f39550e461142c5ac0c678fa3ff338e4830e2d Mon Sep 17 00:00:00 2001 From: ForeverInLaw <44206490+ForeverInLaw@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:23:14 +0000 Subject: [PATCH 009/180] ssh: add and edit hosts in a dialog instead of config.toml The sidebar's "+" and empty-state hint, and the new Add SSH Host and Edit SSH Host commands, open a host editor with every [[ssh.hosts]] field, inline errors, Delete, Save and Save & Connect. ssh_hosts is the one place hosts are checked, saved, renamed and deleted. A host only in ~/.ssh/config is saved as an entry of the same name holding just the fields the user changed; one that overrides an alias can be reset to the file. --- Cargo.lock | 1 + crates/redshell-app/Cargo.toml | 2 + crates/redshell-app/src/commands.rs | 2 + crates/redshell-app/src/confirm.rs | 6 + crates/redshell-app/src/host_editor.rs | 392 ++++++++++++++++++++++++ crates/redshell-app/src/main.rs | 2 + crates/redshell-app/src/overlays.rs | 63 ++++ crates/redshell-app/src/picker.rs | 2 + crates/redshell-app/src/sidebar.rs | 6 +- crates/redshell-app/src/ssh_hosts.rs | 404 +++++++++++++++++++++++++ crates/redshell-app/src/workspace.rs | 24 +- 11 files changed, 896 insertions(+), 8 deletions(-) create mode 100644 crates/redshell-app/src/host_editor.rs create mode 100644 crates/redshell-app/src/ssh_hosts.rs diff --git a/Cargo.lock b/Cargo.lock index ccc924a..22c11b7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4635,6 +4635,7 @@ dependencies = [ "semver", "serde", "serde_json", + "shlex 1.3.0", "tempfile", "tokio", "uuid", diff --git a/crates/redshell-app/Cargo.toml b/crates/redshell-app/Cargo.toml index f8e3012..485416d 100644 --- a/crates/redshell-app/Cargo.toml +++ b/crates/redshell-app/Cargo.toml @@ -35,6 +35,8 @@ image = "0.25" which.workspace = true dirs.workspace = true semver.workspace = true +# Splits and quotes the extra ssh arguments of a host the way a shell would. +shlex = "1.3" # The HTTP client gpui already builds (through gpui_http_client), with features it already # enables, so the update check compiles nothing new. Keep the version in step with gpui's. reqwest = { package = "zed-reqwest", version = "0.12.15-zed", default-features = false, features = ["rustls-tls-native-roots"] } diff --git a/crates/redshell-app/src/commands.rs b/crates/redshell-app/src/commands.rs index c583aab..d6731f6 100644 --- a/crates/redshell-app/src/commands.rs +++ b/crates/redshell-app/src/commands.rs @@ -126,6 +126,8 @@ commands! { LaunchPalette => "palette.launch", "Launch", "Open Profile…", &["cmd-o"], &["ctrl-shift-o"]; LaunchAgent => "agent.launch", "Launch", "Launch AI Agent…", &["cmd-shift-i"], &["ctrl-shift-i"]; ConnectSsh => "ssh.connect", "Launch", "Connect to SSH Host…", &["cmd-shift-s"], &["ctrl-shift-s"]; + AddSshHost => "ssh.add_host", "Launch", "Add SSH Host…", &[], &[]; + EditSshHost => "ssh.edit_host", "Launch", "Edit SSH Host…", &[], &[]; SelectTheme => "theme.select", "Appearance", "Select Theme…", &[], &[]; ImportTheme => "theme.import_clipboard", "Appearance", "Import tweakcn Theme from Clipboard", &[], &[]; InsertSnippet => "snippet.insert", "Terminal", "Insert Snippet…", &["cmd-shift-e"], &["ctrl-shift-e"]; diff --git a/crates/redshell-app/src/confirm.rs b/crates/redshell-app/src/confirm.rs index 4720300..c77d89e 100644 --- a/crates/redshell-app/src/confirm.rs +++ b/crates/redshell-app/src/confirm.rs @@ -33,6 +33,12 @@ pub enum ConfirmAction { DetachNative(usize), /// Close a native tmux tab and kill its tmux window. KillNative(usize), + /// Delete the saved SSH host `name`; `from_editor` when asked from its + /// editor, which is reopened on cancel. + DeleteHost { + name: String, + from_editor: bool, + }, /// Delete a recorded session; `reopen` is the list to return to. DeleteSession { session: redshell_core::SessionId, diff --git a/crates/redshell-app/src/host_editor.rs b/crates/redshell-app/src/host_editor.rs new file mode 100644 index 0000000..e0193a4 --- /dev/null +++ b/crates/redshell-app/src/host_editor.rs @@ -0,0 +1,392 @@ +//! The dialog that adds or edits an SSH host. It only collects the form: +//! checking and saving go through [`ssh_hosts`](crate::ssh_hosts). + +use gpui::prelude::*; +use gpui::{ + AnyElement, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, KeyDownEvent, + PathPromptOptions, SharedString, Subscription, Window, div, point, px, +}; +use redshell_core::settings::{MultiplexerKind, SshHost}; +use redshell_ui::{ + Button, ButtonSize, ButtonVariant, IconName, InputEvent, Menu, MenuEntry, Modal, Select, SelectOption, TextInput, + ThemeExt, key_hints, modal_footer, modal_header, section_label, setting_row, space, +}; + +use crate::ssh_hosts::{self, Field, HostBook, HostError, HostForm, Source}; + +#[derive(Debug, Clone, PartialEq)] +pub enum HostEditorEvent { + Close, + /// The host was saved under `name`; `connect` asks to open it too. + Saved { + name: String, + connect: bool, + }, + /// Asks to delete the saved host `name`; `reset` when that hands it + /// back to its `~/.ssh/config` entry. + Remove { + name: String, + reset: bool, + }, +} + +pub struct HostEditor { + book: HostBook, + source: Source, + /// One input per text field, in [`Field::ALL`] order. + inputs: Vec<(Field, Entity)>, + multiplexer: Option, + errors: Vec, + /// Set by the first save attempt; the errors then follow every edit. + checked: bool, + focus: FocusHandle, + group_menu: Option<(Entity, Subscription)>, + _subs: Vec, +} + +impl EventEmitter for HostEditor {} + +impl Focusable for HostEditor { + fn focus_handle(&self, cx: &App) -> FocusHandle { + self.input(Field::Name).focus_handle(cx) + } +} + +/// Width of the column of inputs. +const CONTROL_WIDTH: f32 = 300.; + +impl HostEditor { + pub fn new(book: HostBook, source: Source, window: &mut Window, cx: &mut Context) -> Self { + let host = book.host(&source); + let form = HostForm::from_host(&host); + let alias = book.alias(&host.name).cloned().unwrap_or_default(); + let mut subs = Vec::new(); + let inputs: Vec<_> = Field::ALL + .into_iter() + .map(|field| { + let input = cx.new(|cx| { + let mut input = TextInput::new(cx).placeholder(placeholder(field, &alias)); + input.set_value(form.get(field), cx); + input + }); + subs.push(cx.subscribe_in(&input, window, Self::on_input)); + (field, input) + }) + .collect(); + inputs[0].1.read(cx).focus(window); + Self { + book, + source, + inputs, + multiplexer: form.multiplexer, + errors: Vec::new(), + checked: false, + focus: cx.focus_handle(), + group_menu: None, + _subs: subs, + } + } + + fn input(&self, field: Field) -> &Entity { + &self.inputs[field as usize].1 + } + + fn form(&self, cx: &App) -> HostForm { + let mut form = HostForm::default(); + form.multiplexer = self.multiplexer; + for (field, input) in &self.inputs { + form.set(*field, input.read(cx).value()); + } + form + } + + fn on_input(&mut self, input: &Entity, ev: &InputEvent, window: &mut Window, cx: &mut Context) { + match ev { + InputEvent::Submit => self.save(false, window, cx), + InputEvent::SubmitStrong => self.save(true, window, cx), + InputEvent::Cancel => cx.emit(HostEditorEvent::Close), + InputEvent::Tab | InputEvent::BackTab => { + let at = self.inputs.iter().position(|(_, i)| i == input).unwrap_or_default(); + let len = self.inputs.len(); + let next = if *ev == InputEvent::Tab { (at + 1) % len } else { (at + len - 1) % len }; + self.inputs[next].1.read(cx).focus(window); + } + InputEvent::Changed(_) if self.checked => { + self.errors = self.book.check(&self.source, &self.form(cx)).err().unwrap_or_default(); + cx.notify(); + } + InputEvent::Changed(_) | InputEvent::Up | InputEvent::Down => {} + } + } + + /// Escape and Enter when no input has the keyboard. + fn on_key(&mut self, ev: &KeyDownEvent, window: &mut Window, cx: &mut Context) { + match ev.keystroke.key.as_str() { + "escape" => cx.emit(HostEditorEvent::Close), + "enter" => self.save(false, window, cx), + _ => return, + } + cx.stop_propagation(); + } + + /// Saves the host, or shows what is wrong and focuses the first such field. + fn save(&mut self, connect: bool, window: &mut Window, cx: &mut Context) { + let form = self.form(cx); + match ssh_hosts::save(cx, &self.book, &self.source, &form) { + Ok(name) => cx.emit(HostEditorEvent::Saved { name, connect }), + Err(errors) => { + if let Some(first) = errors.first() { + self.input(first.field()).read(cx).focus(window); + } + self.errors = errors; + self.checked = true; + cx.notify(); + } + } + } + + fn browse_key_file(&mut self, cx: &mut Context) { + let rx = cx.prompt_for_paths(PathPromptOptions { + files: true, + directories: false, + multiple: false, + prompt: Some("Use key".into()), + }); + let input = self.input(Field::KeyFile).clone(); + cx.spawn(async move |_, cx| { + if let Ok(Ok(Some(paths))) = rx.await + && let Some(path) = paths.into_iter().next() + { + input.update(cx, |input, cx| input.set_value(path.display().to_string(), cx)).ok(); + } + }) + .detach(); + } + + /// The menu of the groups other hosts are in, below the group input. + fn open_group_menu(&mut self, window: &mut Window, cx: &mut Context) { + let input = self.input(Field::Group).clone(); + let current = input.read(cx).value().trim().to_owned(); + let groups = self.book.groups(); + let menu = Menu::build(window, cx, |menu| { + groups.into_iter().fold(menu.offset(point(px(0.), px(40.))), |menu, group| { + let (input, checked) = (input.clone(), group == current); + menu.entry( + MenuEntry::new(group.clone(), move |window, cx| { + input.update(cx, |input, cx| input.set_value(group.clone(), cx)); + input.read(cx).focus(window); + }) + .checked(checked), + ) + }) + }); + let sub = cx.subscribe(&menu, |this, _, _: &DismissEvent, cx| { + this.group_menu = None; + cx.notify(); + }); + self.group_menu = Some((menu, sub)); + cx.notify(); + } + + /// A labelled input with its error (if any) underneath, and the group + /// menu below the group input while it is open. + fn field_row(&self, field: Field, trailing: Option, cx: &mut Context) -> AnyElement { + let t = cx.theme(); + let error = self.errors.iter().find(|e| e.field() == field).map(|e| e.message()); + let menu = self.group_menu.as_ref().filter(|_| field == Field::Group).map(|(menu, _)| menu.clone()); + let input = div() + .flex() + .gap(space::S1_5) + .children(menu) + .child(div().flex_1().min_w_0().child(self.input(field).clone())); + let control = div() + .flex() + .flex_col() + .gap(space::S1) + .w(px(CONTROL_WIDTH)) + .child(input.children(trailing)) + .children(error.map(|e| div().text_size(t.text_xs()).text_color(t.ui().destructive).child(e))); + let (label, description) = label(field); + setting_row(label, description, control, cx) + } + + fn multiplexer_row(&self, cx: &mut Context) -> AnyElement { + let options = vec![ + SelectOption::new("default", "Default"), + SelectOption::new("tmux", "tmux"), + SelectOption::new("screen", "GNU screen"), + ]; + let selected = match self.multiplexer { + None => "default", + Some(MultiplexerKind::Tmux) => "tmux", + Some(MultiplexerKind::Screen) => "screen", + }; + let this = cx.entity().downgrade(); + let select = Select::new("host-mux", options, selected).on_select(move |value, _, cx| { + let kind = match value.as_ref() { + "tmux" => Some(MultiplexerKind::Tmux), + "screen" => Some(MultiplexerKind::Screen), + _ => None, + }; + this.update(cx, |this, cx| { + this.multiplexer = kind; + cx.notify(); + }) + .ok(); + }); + setting_row("Multiplexer", Some("Whose sessions the session manager lists here"), select, cx) + } + + /// What the dialog is about, under its title. + fn description(&self) -> Option { + match &self.source { + Source::Imported(_) => { + Some("From ~/.ssh/config. Your changes are kept in RedShell, the file stays as it is.".into()) + } + Source::Saved(name) if self.book.alias(name).is_some() => { + Some("Named after a ~/.ssh/config alias: empty fields come from the file.".into()) + } + Source::Saved(_) | Source::New => None, + } + } + + /// Delete…, or Reset for a host that overrides a `~/.ssh/config` alias; + /// nothing for a new host or one only in the file. + fn remove_button(&self, cx: &mut Context) -> Option + ); +} diff --git a/web/src/components/Dialog.tsx b/web/src/components/Dialog.tsx new file mode 100644 index 0000000..679279f --- /dev/null +++ b/web/src/components/Dialog.tsx @@ -0,0 +1,74 @@ +import { type ReactNode, useId } from "react"; +import { cx } from "../lib/platform"; +import { Button } from "./Button"; +import type { ButtonVariant } from "./styles"; + +const showModal = (dialog: HTMLDialogElement | null) => { + if (dialog && !dialog.open) dialog.showModal(); +}; + +interface DialogProps { + title: string; + children?: ReactNode; + onClose: () => void; + className?: string; +} + +/** A centred dialog on the native ``: focus trap, Esc and the top layer come free. */ +export function Dialog({ title, children, onClose, className }: DialogProps) { + const titleId = useId(); + return ( + { + event.preventDefault(); + onClose(); + }} + onClick={(event) => { + if (event.target === event.currentTarget) onClose(); + }} + className={cx( + "m-auto w-[calc(100%-2rem)] max-w-[22rem] animate-[dialog-in_var(--dur-base)_var(--ease-out)_both] rounded-xl border border-border bg-popover p-0 text-foreground shadow-menu", + "backdrop:bg-(--scrim-dialog)", + className, + )} + > +
+

+ {title} +

+ {children} +
+
+ ); +} + +interface ConfirmProps { + title: string; + body?: ReactNode; + confirmLabel: string; + confirmVariant?: Extract; + pending?: boolean; + error?: string | null; + onConfirm: () => void; + onCancel: () => void; +} + +/** "Sign out of pi?" with Cancel and the action. */ +export function Confirm({ title, body, confirmLabel, confirmVariant = "destructive", pending, error, onConfirm, onCancel }: ConfirmProps) { + return ( + + {body &&

{body}

} + {error &&

{error}

} +
+ + +
+
+ ); +} diff --git a/web/src/components/Field.tsx b/web/src/components/Field.tsx new file mode 100644 index 0000000..9dbd2c1 --- /dev/null +++ b/web/src/components/Field.tsx @@ -0,0 +1,69 @@ +import { CircleAlert, Eye, EyeOff } from "lucide-react"; +import { type ComponentProps, type ReactNode, useId, useState } from "react"; +import { cx } from "../lib/platform"; +import { inputClass } from "./styles"; + +type FieldProps = ComponentProps<"input"> & { + label: string; + helper?: ReactNode; + error?: ReactNode; + /** Hostnames and paths: mono, still 16px so iOS never zooms. */ + mono?: boolean; + trailing?: ReactNode; +}; + +/** A labelled input (§3.2): label above, helper or error below, linked by aria-describedby. */ +export function Field({ label, helper, error, mono = false, trailing, className, id, ...props }: FieldProps) { + const fallbackId = useId(); + const inputId = id ?? fallbackId; + const noteId = `${inputId}-note`; + const note = error ?? helper; + return ( +
+ +
+ + {trailing &&
{trailing}
} +
+ {note && ( +

+ {error && } + {note} +

+ )} +
+ ); +} + +/** A password field with the 44px eye toggle inside it. */ +export function PasswordField(props: Omit) { + const [visible, setVisible] = useState(false); + return ( + setVisible((v) => !v)} + > + {visible ? : } + + } + /> + ); +} diff --git a/web/src/components/List.tsx b/web/src/components/List.tsx new file mode 100644 index 0000000..31f39b9 --- /dev/null +++ b/web/src/components/List.tsx @@ -0,0 +1,118 @@ +import { ChevronRight } from "lucide-react"; +import type { ComponentProps, ReactNode } from "react"; +import { Link } from "react-router"; +import { cx } from "../lib/platform"; + +/** A section header: sentence case, footnote 500, muted, with an optional count. */ +export function SectionHeader({ children, count, id }: { children: ReactNode; count?: number; id?: string }) { + return ( +

+ {children} + {count !== undefined && {count}} +

+ ); +} + +/** Explanations live under groups, not in rows. */ +export function Footnote({ children, className }: { children: ReactNode; className?: string }) { + return

{children}

; +} + +/** A list group (§3.4): card, hairline, 14px radius, inset 16px; rows separated by inset hairlines. */ +export function Group({ children, className, ...props }: ComponentProps<"div">) { + return ( +
*+*]:relative [&>*+*]:before:absolute [&>*+*]:before:top-0 [&>*+*]:before:right-0 [&>*+*]:before:left-(--row-inset,1rem) [&>*+*]:before:h-px [&>*+*]:before:bg-border", + className, + )} + {...props} + > + {children} +
+ ); +} + +/** A labelled block of the settings screens: header, group, footnote; groups are 24px apart. */ +export function Section({ title, footnote, children, className }: { title?: ReactNode; footnote?: ReactNode; children: ReactNode; className?: string }) { + return ( +
+ {title && {title}} + {children} + {footnote && {footnote}} +
+ ); +} + +interface RowContent { + icon?: ReactNode; + label: ReactNode; + subtitle?: ReactNode; + /** Mono subtitle for hosts and paths. */ + monoSubtitle?: boolean; + value?: ReactNode; + /** Detail rows end in a chevron; action rows don't. */ + chevron?: boolean; + trailing?: ReactNode; + tone?: "default" | "destructive"; +} + +const rowClass = (interactive: boolean, twoLine: boolean) => + cx( + "flex w-full items-center gap-3 px-4 text-left", + twoLine ? "min-h-15 py-2.5" : "min-h-12 py-2", + interactive && "transition-colors duration-(--dur-press) pressed:bg-accent hover:bg-accent", + ); + +function RowBody({ icon, label, subtitle, monoSubtitle, value, chevron, trailing, tone = "default" }: RowContent) { + return ( + <> + {icon && {icon}} + + {label} + {subtitle && ( + {subtitle} + )} + + {value !== undefined && {value}} + {trailing} + {chevron && } + + ); +} + +/** A row that navigates. */ +export function LinkRow({ to, ...content }: RowContent & { to: string }) { + return ( +
+ + + +
+ ); +} + +/** A row that does something on tap. */ +export function ButtonRow({ onClick, disabled, ...content }: RowContent & { onClick: () => void; disabled?: boolean }) { + return ( +
+ +
+ ); +} + +/** A row that only shows a value, or holds a control (a whole-row `