From 9695b375e689605478acb0982e850ff0d403afaa Mon Sep 17 00:00:00 2001 From: yansfil Date: Tue, 6 Oct 2026 16:42:55 +0900 Subject: [PATCH 1/7] Ask the account's login shell for the PATH its startup files set up hide_platform::host::login_shell_path runs $SHELL -ilc with the login variables and the given home, reads the PATH it prints between two marks past anything the startup files print, and ends the shell and its tree at the deadline or on stop. Windows says Unsupported. login_path's comment no longer claims to be the login shell's PATH: it is the process's own. --- docs/ARCHITECTURE.md | 2 +- hide-platform/src/host.rs | 83 ++++++++++++++++++++++++++++++++--- hide-platform/tests/host.rs | 86 +++++++++++++++++++++++++++++++++++++ 3 files changed, 165 insertions(+), 6 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 22122daf48..f096a4ebec 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -568,7 +568,7 @@ macOS and Linux are watched through `notify`; Windows is watched with `ReadDirec The Git watch in `herdr-core/src/worktrees.rs` is the caller: it keeps only Git's facts (`HEAD`, `index`, `packed-refs`, `FETCH_HEAD`, `refs/`), drains the queue on the coordinator's tick outside the runtime lock, and turns an overflow into a `git_watch.overflow` diagnostic and a re-read of every watched project, where an inotify overflow used to be dropped without a word. No watch event wakes the core: the coordinator's tick reads the queue, as it read the callback's map before, so the notifier's fan-out is unchanged. -`host` is the fifth module and answers where the account's things live and what the machine is called: `home_dir` (`HOME`, `USERPROFILE` on Windows), `state_dir` (`~/Library/Application Support`, `$XDG_STATE_HOME` or `~/.local/state`, `%LOCALAPPDATA%`) and `state_dir_under` for a caller whose state follows a home it was handed, `herdr_socket_default` (Herdr's own order for the pinned release: `$XDG_CONFIG_HOME/herdr`, then `%APPDATA%\herdr` on Windows, then `~/.config/herdr`, each with `herdr.sock`, which `real_herdr.rs` checks against what the pinned Herdr reports), `login_path` and `find_program` (an execute bit on Unix, `PATHEXT` on Windows), `default_shell`, `trash` (`NSFileManager` on macOS, the Recycle Bin, the freedesktop trash), `tailscale_cli` (the app's CLI on macOS and Windows; `Unsupported` on Linux, which has no fixed place), `name` and `machine_id` (`IOPlatformUUID`, `/etc/machine-id`, the `MachineGuid` the Windows registry keeps). +`host` is the fifth module and answers where the account's things live and what the machine is called: `home_dir` (`HOME`, `USERPROFILE` on Windows), `state_dir` (`~/Library/Application Support`, `$XDG_STATE_HOME` or `~/.local/state`, `%LOCALAPPDATA%`) and `state_dir_under` for a caller whose state follows a home it was handed, `herdr_socket_default` (Herdr's own order for the pinned release: `$XDG_CONFIG_HOME/herdr`, then `%APPDATA%\herdr` on Windows, then `~/.config/herdr`, each with `herdr.sock`, which `real_herdr.rs` checks against what the pinned Herdr reports), `login_path` (this process's `PATH`, which starts no shell) and `find_program` (an execute bit on Unix, `PATHEXT` on Windows), `login_shell_path` (the `PATH` the account's login shell sets up: `$SHELL -ilc` prints it between two marks, past whatever the startup files print, under a deadline and a stop flag; `Unsupported` on Windows, whose processes already get the account's `Path`), `default_shell`, `trash` (`NSFileManager` on macOS, the Recycle Bin, the freedesktop trash), `tailscale_cli` (the app's CLI on macOS and Windows; `Unsupported` on Linux, which has no fixed place), `name` and `machine_id` (`IOPlatformUUID`, `/etc/machine-id`, the `MachineGuid` the Windows registry keeps). Each refuses with `NotFound`, `InvalidInput` or `Unsupported` rather than guessing; hided's environment registry hands its own values to the `_from` forms, so the variables it depends on stay listed in `hided/src/env.rs`. The Windows check builds the whole workspace, tests included. `listeners` observes Windows TCP owners through the native IPv4 and IPv6 listener tables and reads each owner's cwd from bounded process-parameter memory, while the core's Unix reader retains `lsof`. diff --git a/hide-platform/src/host.rs b/hide-platform/src/host.rs index 67feae9d29..a1627773f8 100644 --- a/hide-platform/src/host.rs +++ b/hide-platform/src/host.rs @@ -1,8 +1,8 @@ //! What this machine and the account running on it are called, and where //! their things live: the home folder, the folder an application keeps its //! state in, the socket the pinned Herdr listens on by default, the programs -//! on the search path, the default shell, the Trash, the Tailscale CLI, and -//! the machine's name and identity. +//! on the search path, the `PATH` the login shell sets up, the default +//! shell, the Trash, the Tailscale CLI, and the machine's name and identity. //! //! Every function answers for the machine this process runs on, from the //! variables and tables that system defines, and refuses (`NotFound`, or @@ -136,15 +136,88 @@ pub fn herdr_config_dir_from(variables: Variables) -> io::Result { Ok(home_dir_from(variables)?.join(".config").join("herdr")) } -/// The search path this process finds programs on (`PATH`). The desktop app -/// adds the folders installers put programs in before it starts `hide`, so -/// this is the login shell's path even when the app was opened from the Dock. +/// The search path this process finds programs on (`PATH`), as whoever +/// started it set it. It starts no shell, so a folder the account's startup +/// files add (`~/.zshrc`, `~/.bashrc`) is on it only when the process was +/// started from a terminal: the desktop app opened from the Dock adds the +/// system folders and the usual install folders, and an SSH exec channel has +/// the system folders alone. [`login_shell_path`] asks the shell. pub fn login_path() -> io::Result { std::env::var_os("PATH") .filter(|path| !path.is_empty()) .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "PATH is not set")) } +/// The mark the login shell prints its `PATH` between, so nothing its startup +/// files print before or after can be read as part of it. +const SHELL_PATH_MARK: &str = "__HIDE_LOGIN_PATH__"; + +/// The `PATH` the account's login shell sets up, which is what the operator's +/// terminal searches: `shell -ilc` runs the startup files an installer edits +/// (`-i` reads `~/.zshrc` and `~/.bashrc`, `-l` the login files) and prints +/// the result between two marks, past anything those files print. +/// +/// The shell gets the account's login variables only +/// ([`crate::process::LOGIN_CHILD_VARIABLES`]), with `HOME` set to `home`, +/// plus the variables that keep Oh My Zsh's update prompt and its tmux +/// autostart from holding an interactive shell open, the ones the desktop +/// host sets when it asks the same question (`desktop/src/main/cli.ts`). The +/// shell and everything it started end when `deadline` passes (`TimedOut`) +/// or `stop` is raised (`Interrupted`); a shell that ends without printing +/// the marks says `InvalidData`. Windows has no login shell: a process there +/// is given the account's own `Path`, so it says `Unsupported`. +pub fn login_shell_path( + shell: &Path, + home: &Path, + deadline: std::time::Duration, + stop: &std::sync::atomic::AtomicBool, +) -> io::Result { + use crate::process::{RunFailure, restrict_to_login_environment, run_to_end}; + if cfg!(windows) { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "Windows has no login shell; a process already has the account's Path", + )); + } + let mut command = std::process::Command::new(shell); + command.arg("-ilc").arg(format!( + "printf '\\n{SHELL_PATH_MARK}%s{SHELL_PATH_MARK}\\n' \"$PATH\"" + )); + restrict_to_login_environment(&mut command); + command + .env(HOME_VARIABLE, home) + .env("DISABLE_AUTO_UPDATE", "true") + .env("ZSH_TMUX_AUTOSTARTED", "true") + .env("ZSH_TMUX_AUTOSTART", "false"); + let finished = run_to_end(&mut command, deadline, stop).map_err(|failure| match failure { + RunFailure::Start(error) | RunFailure::Wait(error) => error, + RunFailure::TimedOut => io::Error::new( + io::ErrorKind::TimedOut, + format!("{} did not answer in time", shell.display()), + ), + RunFailure::Stopped => io::Error::new(io::ErrorKind::Interrupted, "stopped"), + })?; + marked_path(&finished.stdout) + .map(OsString::from) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + format!( + "{} printed no PATH (exit {:?})", + shell.display(), + finished.code + ), + ) + }) +} + +/// The non-empty text between the first two marks. +fn marked_path(output: &str) -> Option<&str> { + let (_, after) = output.split_once(SHELL_PATH_MARK)?; + let (path, _) = after.split_once(SHELL_PATH_MARK)?; + (!path.is_empty()).then_some(path) +} + /// The program `name` as this system's shell would find it on `path`: the /// first folder holding it, where a file without an execute bit is not a /// program on Unix, and on Windows a name without an extension is tried with diff --git a/hide-platform/tests/host.rs b/hide-platform/tests/host.rs index 080bcee5d3..ed9191c48c 100644 --- a/hide-platform/tests/host.rs +++ b/hide-platform/tests/host.rs @@ -117,6 +117,92 @@ fn the_default_shell_when_there_is_one_is_a_file_that_exists() { } } +/// A stand-in login shell: `body` runs first, as startup files do, then the +/// command the caller passed with `-ilc`. +#[cfg(unix)] +fn fake_shell(folder: &Path, body: &str) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + let shell = folder.join("shell"); + fs::write( + &shell, + format!("#!/bin/sh\n{body}\n[ \"$1\" = -ilc ] || exit 64\neval \"$2\"\n"), + ) + .unwrap(); + fs::set_permissions(&shell, fs::Permissions::from_mode(0o755)).unwrap(); + shell +} + +#[cfg(unix)] +#[test] +fn the_login_shell_path_is_what_its_startup_files_set_past_what_they_print() { + use std::sync::atomic::AtomicBool; + use std::time::Duration; + let folder = tempfile::tempdir().unwrap(); + let home = folder.path().join("home"); + let shell = fake_shell( + folder.path(), + "echo 'Last login: today'\necho 'nvm: warning' >&2\nPATH=\"$HOME/.grok/bin:$PATH\"\nexport PATH", + ); + + let path = host::login_shell_path( + &shell, + &home, + Duration::from_secs(10), + &AtomicBool::new(false), + ) + .unwrap(); + + let folders: Vec = std::env::split_paths(&path).collect(); + // The shell ran with the home it was given, not this process's. + assert_eq!(folders[0], home.join(".grok/bin"), "{path:?}"); + assert!(folders.len() > 1, "the inherited folders follow: {path:?}"); +} + +#[cfg(unix)] +#[test] +fn a_login_shell_that_prints_no_path_or_never_answers_is_refused_in_time() { + use std::sync::atomic::AtomicBool; + use std::time::{Duration, Instant}; + let folder = tempfile::tempdir().unwrap(); + let silent = fake_shell(folder.path(), "exit 0"); + let error = host::login_shell_path( + &silent, + folder.path(), + Duration::from_secs(10), + &AtomicBool::new(false), + ) + .unwrap_err(); + assert_eq!(error.kind(), ErrorKind::InvalidData, "{error}"); + + let hanging = folder.path().join("hanging"); + fs::create_dir(&hanging).unwrap(); + let hanging = fake_shell(&hanging, "sleep 30"); + let started = Instant::now(); + let error = host::login_shell_path( + &hanging, + folder.path(), + Duration::from_millis(500), + &AtomicBool::new(false), + ) + .unwrap_err(); + assert_eq!(error.kind(), ErrorKind::TimedOut, "{error}"); + assert!(started.elapsed() < Duration::from_secs(10)); +} + +#[cfg(windows)] +#[test] +fn windows_has_no_login_shell_to_ask() { + use std::sync::atomic::AtomicBool; + let error = host::login_shell_path( + &host::default_shell().unwrap(), + &host::home_dir().unwrap(), + std::time::Duration::from_secs(1), + &AtomicBool::new(false), + ) + .unwrap_err(); + assert_eq!(error.kind(), ErrorKind::Unsupported, "{error}"); +} + #[test] fn the_tailscale_location_is_absolute_where_the_system_has_one() { match host::tailscale_cli() { From da1775f145363f66d39d61ebee920dc9e4cf7226 Mon Sep 17 00:00:00 2001 From: yansfil Date: Tue, 6 Oct 2026 16:43:01 +0900 Subject: [PATCH 2/7] Count an agent as installed only when its program is found An agent is installed when one of its programs is found on the login shell's PATH, the daemon's own PATH or the usual install folders; a folder the agent creates no longer counts (~/.cursor without cursor-agent, ~/.pi/agent without pi). home_markers and AgentAdapter::detected/executable are gone. The nine adapters found by folder alone now name their program, confirmed against each vendor's install script and docs: copilot, amp, droid, goose, kilo, pi, grok, kimi, vibe. The kit's search asks the login shell (cached until a startup file changes, retried a minute after a failure, logged as kit.login_shell_unread), so CLIs whose installers add their own folder in ~/.zshrc (~/.grok/bin, ~/.kilo/bin, ~/.opencode/bin, ~/.kimi-code/bin, ~/.pi/agent/bin) are found from a Dock launch and on an SSH device helper. Only the kit asks; cli_path keeps its shell-free search for the hook diagnosis, Memory and Codex CLI per pane. An agent that is on and whose program is gone keeps its record, stub and hook, reads Not on this machine with the reason, and keeps its switch to take them out. --- docs/ARCHITECTURE.md | 5 +- docs/INSTALL.md | 5 +- docs/PERFORMANCE_TESTING.md | 2 +- docs/UI_BEHAVIOR.md | 14 +- docs/agent-hooks.md | 40 +++- hide-agent-hooks/src/codex_daemon.rs | 2 +- hide-agent-hooks/src/diagnosis.rs | 54 +++-- hide-agent-hooks/src/lib.rs | 2 +- hide-kit/src/agent_kit.rs | 85 ++++--- hide-kit/src/agents.rs | 335 ++++++++++++++++++--------- hide-kit/src/device.rs | 1 + hide-kit/src/lib.rs | 5 + hide-kit/src/local.rs | 1 + hide-kit/src/tests.rs | 9 +- hide-kit/src/tests/agent_cases.rs | 185 ++++++++++++--- 15 files changed, 524 insertions(+), 221 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f096a4ebec..94fd6458e2 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1323,7 +1323,7 @@ Another tool's hook entries, a `hide` that is not Hide's link, and Herdr's per-p Every apply also retires the agent labels Herdr plugin `hide.agent-context-labels`, which the core's label worker replaced (PRD labels-in-hided D-12; `hide-kit/src/labels.rs`), before it installs any part: its Herdr link is taken out (a GitHub install with the machine's `herdr plugin uninstall`, any other link with `plugin.unlink`), a watcher found by the lock it holds under `/.local/state/hide.agent-context-labels/watcher.lock` is sent `SIGTERM` and, after five seconds, `SIGKILL` for it and its descendants, and the kit's copy `~/.hide/kit/plugins/agent-context-labels` and the plugin's state folder are removed once the link is gone, so a pass that could not unlink (Herdr down) keeps them and tries again on the next. What was removed and what stayed is `KitReport.labels_retirement`, which the core logs as `plugin.retired` or `plugin.retire_incomplete`; it is not a kit part, so Settings shows no row for it. On this Mac the core imports the plugin's state before the kit first runs. -Every child the kit starts (`herdr plugin uninstall`, `codex features`) runs with a cleared environment, as an owned child that leads its own tree, under a deadline, and ends when the kit's owner raises its stop flag (`hide-kit/src/process.rs`, `hide-agent-hooks/src/codex_daemon.rs`, both over `hide_platform::process::run_to_end`). +Every child the kit starts (`herdr plugin uninstall`, `codex features`, the login shell asked for its `PATH`) runs with a cleared environment, as an owned child that leads its own tree, under a deadline, and ends when the kit's owner raises its stop flag (`hide-kit/src/process.rs`, `hide-agent-hooks/src/codex_daemon.rs`, both over `hide_platform::process::run_to_end`). The one-release retirement stage first performs bounded, read-only checks of the former coordinator and Hide ledgers, sasu registry and registered checkout run state. An active run, open request, active watch, unreadable record or capacity failure leaves every installation and folder unchanged and reports why. For a device, `remote::retirement` reads that account's state and its registered checkout roots through the existing SSH/SFTP connection before any helper upload, folder creation or current-link update, with the existing 15-second operation deadline. @@ -1348,7 +1348,8 @@ It is the one part with a switch (`ComponentId::can_turn_off`, the `kit_componen Every other agent is a row of `hide_kit::agents::ADAPTERS`, and a per-agent layer (`hide-kit/src/agent_kit.rs`) sits beside the parts: `Scope` carries `agent_on` and `agent_off`, `KitReport.agents` answers one `AgentReport` per adapter, the record keeps the operator's choice and the pieces installed, and the core's `kit_agent_set` event, `KitSnapshot.agents` and the host protocol's `reinstall` (`agents_on`, `agents_off`, both defaulted so a helper that predates them ignores them) carry the same choice to a device. Claude Code's and Codex's hook parts stay kit parts, because Memory, the pane diagnosis and `device_hook_status` read them, and their agent switch gates the part: off, the part is neither installed nor replaced, and switched off now it is taken out. The other agents' hooks are `hide_agent_hooks::guidance`, a smaller module with its own marker and per-agent file shape, so the five-event runtime code and its counters never take a meaningless arm for an agent that does not feed them. -Detection runs only on the kit worker and the helper, never on the render path, and under test it searches only the fixture's `~/.local/bin`, so a developer's own agents cannot decide a result. +An agent is installed when one of its programs is found on the login shell's `PATH`, the daemon's own or the usual install folders; a folder it creates does not count, and an agent that is on and whose program is gone keeps its pieces and its switch until the operator switches it off ([agent-hooks.md: Installed means the program is found](agent-hooks.md#installed-means-the-program-is-found)). +Detection, and the login shell it asks (once, then again only when a startup file changed), run only on the kit worker and the helper, never on the render path, and under test the search is the fixture's `~/.local/bin` and a stand-in shell's answer, so a developer's own agents cannot decide a result. `hide_kit::Scope` carries both choices, `restore` and `turn_off`, and two queued requests for one machine merge with the later choice winning for a part both name; the device helper receives them in `kit` `reinstall` (helper protocol 14). Removing a machine leaves the setting as it is, since Hide cannot tell its own switch from the operator's choice. Every Codex start Hide makes passes `--no-daemon` first when that machine's kit read a Codex that has the setting, whichever way the switch stands: `wire::agent_start_params` takes the machine's `codex_launch::CodexDaemon`, which every start path (a task's agent, a reopen, a fork, a wake) carries from the runtime, so no path can leave it out; a missing, failed, outdated or pending capability refuses the start with an instruction to recheck the target machine’s kit in Settings. diff --git a/docs/INSTALL.md b/docs/INSTALL.md index e7663aab4e..b42726d9d6 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -206,7 +206,7 @@ Every launch of the installed app installs Hide's kit on this Mac without asking The one exception is a Mac the kit has never run on: it holds Claude Code's and Codex's hook entries and skills, and Codex's per-pane daemon setting, until the operator answers the first-run agent choice (UI_BEHAVIOR.md, Settings > Agents); both agents are recorded off in the hold, installed or not, so an agent installed later also starts off, and the rest below is installed as usual: - `~/.local/bin/hide`, a link to the app's `hide` command, unless a `hide` that is not Hide's is already there; -- Hide's entries in `~/.claude/settings.json` and `~/.codex/hooks.json`, for each of Claude Code and Codex that is set up on this Mac, next to whatever other tools put there; +- Hide's entries in `~/.claude/settings.json` and `~/.codex/hooks.json`, for each of Claude Code and Codex whose folder (`~/.claude`, `~/.codex`) is on this Mac, next to whatever other tools put there; - A one-release retirement stage removes the former coordination installation after its read-only preflight succeeds; see Coordination retirement below; - `Codex를 pane마다 실행`: when this Mac's Codex has the shared app-server daemon turned on, `codex features disable daemon_auto_start`, so each Codex runs in its own pane and Hide can read it. A daemon already running keeps running, and the setting reaches each Codex started after it. Settings > Devices turns it back on (`codex features enable daemon_auto_start`), and Hide then leaves it on. @@ -266,7 +266,8 @@ The first launch of a newer app moves them once: Settings > Devices shows each of these on This Mac's row, with where it is or why it is not. A part you remove by hand stays removed; Reinstall on that row puts it back. Each agent Hide knows also has a switch on that row, and Claude Code and Codex are on until you turn them off. -An agent that is on gets a `hide-browser` skill stub in the folder it reads skills from, and, where its documentation supports one, a `SessionStart` hook entry; every other agent is off until you switch it on, and an agent that is not set up on the machine has no switch there. +An agent that is on gets a `hide-browser` skill stub in the folder it reads skills from, and, where its documentation supports one, a `SessionStart` hook entry; every other agent is off until you switch it on, and an agent that is not installed on the machine has no switch there. +An agent is installed when Hide finds its program where your terminal would: on your login shell's `PATH` and in the usual install folders; a folder the agent creates does not count. Switching an agent off takes out only the entries and stubs Hide wrote, and [agent-hooks.md](agent-hooks.md#other-agents-skill-and-guidance-hook) lists every agent, its skill folder, and why a hook is or is not written for it. A `hided` run outside the installed app, such as a development build, installs nothing on this Mac and says so there. Agent labels are made by hide's own daemon, so there is no labels part to install. diff --git a/docs/PERFORMANCE_TESTING.md b/docs/PERFORMANCE_TESTING.md index 02d1494691..ce716f9119 100644 --- a/docs/PERFORMANCE_TESTING.md +++ b/docs/PERFORMANCE_TESTING.md @@ -54,7 +54,7 @@ The missing bounds and shutdown gaps below describe the current implementation; | Capability readers: `session_sync/coordinator.rs`, `ports.rs`, `usage.rs`, `ai.rs` | UI-attached gate; Ports 5 s after completion; Usage initial 1 s, visible-window refresh 5 min or popover opening after 60 s; Background AI probes 30 s with 2 s changed-request spacing; hook diagnosis 1 s while Settings is observed. | Run due `lsof`, credential/network/transcript reads, provider probes or hook diagnosis outside Runtime; ingest changed answers. | Ports are synchronous on the coordinator, with a 10 s subprocess deadline; Claude usage and AI probes each use one `BackgroundRead`; no general aggregate response-byte cap covers this group. | Coordinator ends polling; Usage Drop cancels Claude; generic `BackgroundRead` Drop does not cancel or join an in-flight read. | | Git facts watcher: `worktrees.rs`, `hide-platform/src/watch.rs` | OS changes, drained on coordinator wakes; 300 ms quiet period. | Filter Git facts before queuing, mark affected projects and request one off-lock worktree read; overflow invalidates watched projects. | First 64 requested projects are watched; 4,096 queued paths become an explicit overflow; one background read; this watch cap does not cap the full project request vector. | Reconciliation unwatches removed roots; dropping the reader drops its OS watcher; a generic in-flight read may finish after the driver ends. | | Changes pump: `changes.rs` | Pump 250 ms; read on changed input or 2 s after settlement while Explorer, Changes or an active diff needs it. | Take the front checkout request, start one off-lock host read and ingest its scoped result. | One active `BackgroundRead`, current request coalesces changes; host-call deadline 30 s; no additional pump queue of requests. | Pump Drop sends Stop and joins the pump; its generic in-flight host read is not joined by `BackgroundRead`. | -| Kit pump: `kit.rs`, `runtime/kit.rs` | Pump 250 ms; launch/apply intent, or 5 s status refresh while Settings is observed. | Take one local kit job under the lock, run installation/status outside it and ingest the result; devices use their own workers. | One local job at a time and one worker per device; device call deadline 180 s; no fixed global device-worker count cap in this pump. | Local pump Drop sets the child stop flag, sends Stop and joins; a device worker exits when work/connection/weak owner ends, without a retained join handle. | +| Kit pump: `kit.rs`, `runtime/kit.rs` | Pump 250 ms; launch/apply intent, or 5 s status refresh while Settings is observed. | Take one local kit job under the lock, run installation/status outside it and ingest the result; devices use their own workers. The agent search stats about 25 shell startup files per pass and starts the login shell (`$SHELL -ilc`, 10 s deadline) only on its first pass, after one of those files changed, or a minute after a failed ask; this Mac's shell answered in 1.2 to 1.9 s, and a re-read with nothing changed starts no process. | One local job at a time and one worker per device; device call deadline 180 s; no fixed global device-worker count cap in this pump. | Local pump Drop sets the child stop flag, sends Stop and joins; a device worker exits when work/connection/weak owner ends, without a retained join handle. | | Terminal recovery: `terminal_recovery.rs` | 1 s clock; retry delays 5, 10, 20 and 30 s. | Try the Runtime lock, skip a busy lock and advance pending terminal recovery only. | One maintenance worker; at most 4 automatic retries per recovery; retries are not an additional unbounded command queue. | Maintenance Drop sends Stop and joins. | | Project Memory due poll: `runtime/memory.rs`, `runtime/operations.rs` | 5 s due poll on operation ticks; a session must be unchanged for 60 s before analysis. | Check eligibility under the lock, then discover sessions/read SQLite/analyze off-lock and apply a scoped result. | One poll and one Memory operation at a time; input/storage limits belong to the [Memory cost contract](#project-memory-cost-contract). | Runtime Drop cancels the provider; poll and operation threads have no retained join handle, so cancellation is not a join guarantee. | | Session search worker: `runtime/session_search.rs`, `hide-session/src/search.rs` | Condvar wake; 5 s wait with no indexing queue or 40 ms while indexing; refresh/retention due at 30 s. | Process control/query requests and bounded transcript indexing chunks outside Runtime. | One latest pending query, 8 queued controls, 2,000 session files per current-project indexing request; at most 8 chunks of 1 MiB per indexing turn, yielding after 20 ms between chunks. | Worker Drop marks stop, wakes and joins after draining already accepted controls. | diff --git a/docs/UI_BEHAVIOR.md b/docs/UI_BEHAVIOR.md index 4aeeee73d6..47301d226a 100644 --- a/docs/UI_BEHAVIOR.md +++ b/docs/UI_BEHAVIOR.md @@ -1311,18 +1311,20 @@ The add form has one Add button and lists, once, what the kit puts on the device Removing a device asks once, names in one line what comes off that device (with its helper folder, `~/.hide/host-helper` by default) and that the records in `~/.hide` stay, or, when its helper is not connected, that the kit stays there; no button is focused when the confirmation opens (B22). When another registered device reaches the same account on that machine, such as a second Herdr server there, the line says the kit stays for it instead. -Settings > Agents lists, for every machine, This Mac first and then each device in the Devices order, one row per agent that is set up there or is on: its name, one line saying what its switch puts there (a skill and a session hook, or the skill only), its state, and the switch. +Settings > Agents lists, for every machine, This Mac first and then each device in the Devices order, one row per agent that is installed there or is on: its name, one line saying what its switch puts there (a skill and a session hook, or the skill only), its state, and the switch. An agent that is off reads `Off` with nothing else, an agent that is on reads the state of its worst piece with that piece's reason when it is not installed, and Reinstall sits on an agent's row only while that agent is on and one of its pieces needs it. -An agent set up on the machine keeps its switch whatever the system, as long as one of its pieces (the skill, the hook) works there, so one switched off can be switched on again; a hook that cannot be written (Kiro below 3.0, a version Hide cannot read) shows its reason beside the skill's `Installed`. -The agents Hide knows that are not set up on the machine are one muted line, with no switch and no row each, so a machine with two agents shows two rows and not twenty. +An agent is installed on a machine when its program is found there ([agent-hooks.md: Installed means the program is found](agent-hooks.md#installed-means-the-program-is-found)); a folder it creates does not count. +An agent installed on the machine keeps its switch whatever the system, as long as one of its pieces (the skill, the hook) works there, so one switched off can be switched on again; a hook that cannot be written (Kiro below 3.0, a version Hide cannot read) shows its reason beside the skill's `Installed`. +An agent that is on and whose program is no longer found keeps its row and its switch, reads `Not on this machine` with the reason that its program is not found, and offers no Reinstall; what Hide put down for it stays until the operator switches it off, and it is whole again once the program is back. +The agents Hide knows that are not installed on the machine are one muted line, with no switch and no row each, so a machine with two agents shows two rows and not twenty. Settings > Devices shows the same agents on a machine's kit rows, each with its switch. The first-run agent choice is a dialog over the shell, PRD agent-adapters-onboarding, shown when this Mac's kit has never run and stays until it is answered. -It lists all twenty agents Hide knows as tiles in a grid, each with the agent's own mark (or a two-letter monogram where no official mark is bundled, `docs/BRAND.md`) and its state: the agents set up here are on and show a check, an agent not installed is dimmed and has no switch, and a tile is a switch (`role="switch"`) pressed with Space or Enter. -Claude Code and Codex are on when they are set up; every other set-up agent is on too, since the operator chose the full set, and `Apply` installs what is left on. +It lists all twenty agents Hide knows as tiles in a grid, each with the agent's own mark (or a two-letter monogram where no official mark is bundled, `docs/BRAND.md`) and its state: the agents installed here are on and show a check, an agent not installed is dimmed and has no switch, and a tile is a switch (`role="switch"`) pressed with Space or Enter. +Claude Code and Codex are on when they are installed; every other installed agent is on too, since the operator chose the full set, and `Apply` installs what is left on. `Apply` is the only button and the only way out: Escape, a click outside and a close button do nothing, so a stray key cannot finish a choice that leaves Claude Code and Codex off with no hooks; with every tile off, Apply installs nothing and ends the question. The question belongs to the kit record (`awaiting_choice` in `~/.hide/kit/installed.json`), not to the window: closing the app, reloading the page or a failed save leaves it asked, and the next launch asks again until Apply has saved. -The tiles are drawn from the live availability plus the operator's own flips, so an agent that becomes set up while the dialog is open appears on, and Apply sends exactly what is shown. +The tiles are drawn from the live availability plus the operator's own flips, so an agent that becomes installed while the dialog is open appears on, and Apply sends exactly what is shown. A Mac whose kit has already run (an existing install) never sees it, and nothing is held back from it. Until the choice is made the kit puts nothing for Claude Code or Codex on a fresh Mac either, so the hooks wait for Apply or for Settings, Agents. A device whose own record waits gets the saved choice once per run, by what is installed there, as soon as it reports (also after it was not connected when Apply was pressed); with nothing chosen it is told that, so its record stops waiting, and nothing is installed for agents. diff --git a/docs/agent-hooks.md b/docs/agent-hooks.md index 84f8d0e7fa..f86832a5ab 100644 --- a/docs/agent-hooks.md +++ b/docs/agent-hooks.md @@ -131,21 +131,19 @@ The core follows it (`ui_state.agent_onboarding`), applies the answer to this Ma Claude Code and Codex are the agents the kit has always had a hook for. Every other agent Hide knows is one row of `hide-kit/src/agents.rs` (`ADAPTERS`), and one switch per agent per machine turns its pieces on and off, in Settings, Agents and in each device's row. -A row carries the agent's detection (a program on the login `PATH` or the usual install folders, or a folder it creates under the home; the names `goose`, `amp`, `droid`, `copilot` and `kilo` are other programs too, so those agents are detected by their folder alone), the folder it reads skills from and the systems the documentation confirms that folder on, whether Hide writes a hook for it, the oldest version whose documentation has that hook, and the official page the row's answers come from (`doc_url`). -The usual install folders are `~/.local/bin`, pnpm's global folder (`~/Library/pnpm` on macOS and `~/.local/share/pnpm` on Linux, and the `bin` folder inside it from pnpm 11), `~/.npm-global/bin`, `/opt/homebrew/bin` and `/usr/local/bin` (`cli_path` in `hide-agent-hooks/src/diagnosis.rs`). -A program found there is also run with that `PATH`, because a CLI installed as a script starts its interpreter by name (pnpm's `codex` runs `node`) and a device helper started over SSH has only the system folders. -A test fails a row with no `https` `doc_url`, so a claim in the table below always has a page behind it. +A row carries the agent's program names (`executables`), the folder it reads skills from and the systems the documentation confirms that folder on, whether Hide writes a hook for it, the oldest version whose documentation has that hook, and the official page the row's answers come from (`doc_url`). +A test fails a row with no `https` `doc_url`, and a row with no program, so a claim in the table below always has a page behind it and every agent can be found. Two pieces are written per agent, and nothing else: - The skill stub `hide-browser/SKILL.md` in the folder the agent reads. It is a few lines that point at `hide browser help`, so it stays right as the CLI's guide changes. Its folder is `~/.agents/skills` for the agents that read it, `~/.claude/skills` for Claude Code (which documents that it does not read the shared folder), and the agent's own folder for Kiro, Qwen Code and Cline. - A shared folder is written while any agent that reads it is on and set up, and it is removed only when none is. + A shared folder is written while any agent that reads it is on and installed, and it is removed only when none is. A file is Hide's only when its marker line, ``, is the first line after the front matter; a file that merely mentions `hide-skill@` is never replaced or removed, and the agent's row says a skill that Hide did not write is already there. A stub with Hide's marker over text that is not Hide's was edited by the operator: no pass rewrites it and a switch-off leaves it, the row reads Outdated with that reason, and only Reinstall puts Hide's text back. A stub of an older marker version is Hide's own and is replaced by the next pass. - An agent's own folder (`~/.claude`, `~/.kiro`, `~/.qwen`, `~/.cline`) is never created for the stub: its presence is how the kit judges the agent, so a pass that made it would change what the next pass finds. + An agent's own folder (`~/.claude`, `~/.kiro`, `~/.qwen`, `~/.cline`) is never created for the stub: the hook code reads that folder as the agent's settings being there, so a pass that made it would write a hook on the next pass that it did not write on this one, and a second apply would not be a no-op; the row says the agent has not created its folder yet, and the stub goes in on the pass after it has. - The guidance hook, for the agents below marked as done. It is one `SessionStart` entry, in the agent's own format, whose command is `hide-agent-hooks hook --runtime --event SessionStart`. `hide-agent-hooks` writes it (`src/guidance.rs`) and nothing else does, under the marker `hide-guidance@1` that proves an entry is Hide's and separates a current one from an older one. @@ -180,7 +178,31 @@ Non-Copilot guidance hooks are not written on Windows, because their commands ar The record `~/.hide/kit/installed.json` keeps the operator's choice per agent (`agents`) and the pieces Hide installed (`hook:`, `skill:`), and an older build ignores both. With no choice on record Claude Code and Codex are on, as they have been since their hooks became part of the kit, and every other agent is off. A piece that was installed and is gone stays gone until Reinstall, and an agent switched off keeps nothing of Hide's and gets nothing back from a later pass. -Detection only decides whether a switch can work: an agent that is not set up on a machine has no switch there, and the choice for it is not recorded. +Whether the agent is installed only decides whether a switch can work: an agent that is not installed on a machine has no switch there, and switching it on is not recorded. +A guidance hook also needs the agent's own settings folder, which Hide does not create: an installed agent that has not made it yet reads that, and its hook goes in on the pass after it has. + +### Installed means the program is found + +An agent is installed on a machine when one of its programs is found there, the way the operator's terminal would find it; a folder the agent creates does not count, because an editor makes `~/.cursor` without the `cursor-agent` CLI and a CLI that was removed leaves its folder behind (`~/.pi/agent` without `pi`). +The program names are the ones each vendor's install documentation and install script give the command: `claude`, `codex`, `opencode`, `gemini`, `cursor-agent`, `copilot`, `amp`, `droid`, `kiro-cli`, `qwen`, `goose`, `cline`, `kilo`, `crush`, `junie`, `auggie`, `pi`, `grok`, `kimi` and `vibe`. +Cursor's installer now calls its command `agent` and keeps `cursor-agent` as a second name; Hide looks for `cursor-agent` only, because Grok's installer also puts an `agent` on the `PATH`. +Some of these names belong to other programs too (`goose`, `amp` and `kilo` are also a database migration tool and two text editors); such a program reads as the agent, as it does in other tools that list agents by `PATH`, and the only cost is a switch for an agent that is not there. + +The search is, in order, the folders the account's login shell puts on its `PATH`, the daemon's own `PATH`, and the usual install folders: `~/.local/bin`, pnpm's global folder (`~/Library/pnpm` on macOS and `~/.local/share/pnpm` on Linux, and the `bin` folder inside it from pnpm 11), `~/.npm-global/bin`, `/opt/homebrew/bin` and `/usr/local/bin` (`cli_path_with` in `hide-agent-hooks/src/diagnosis.rs`). +The login shell is asked because many installers put their own folder on the `PATH` by editing a startup file rather than using one of those folders: Grok's `~/.grok/bin`, Kilo Code's `~/.kilo/bin`, OpenCode's `~/.opencode/bin`, Kimi Code's `~/.kimi-code/bin` and Pi's `~/.pi/agent/bin` are written into `~/.zshrc`, `~/.bashrc` or `config.fish`, and a Node CLI installed under nvm lives in nvm's folder. +No daemon sees those folders on its own: an app opened from the Dock gets the system folders and the usual install folders from the desktop host, and a device helper started over an SSH exec channel gets the system folders alone (a non-interactive zsh reads only `~/.zshenv`). +`hide_platform::host::login_shell_path` runs `$SHELL -ilc` with the account's login variables and the home being searched, and reads the `PATH` it prints between two marks, past anything the startup files print; it gives the shell ten seconds, the same as the desktop host's own ask, and ends it and everything it started after that or when Hide quits. +Only the kit asks, on the kit worker on this Mac and in the helper on a device; the hook diagnosis, Memory's version probe and Codex's per-pane part keep the search without the shell, so nothing that reads `cli_path` outside the kit starts a shell. +The answer is kept until one of the shell's startup files changes (zsh's, bash's and sh's in the home and in `~/.config/zsh`, fish's, and the system's in `/etc`), which is how an installer adds a folder, so Settings re-reading the kit every few seconds starts no shell; a file those files read in turn is not watched, and is read again when `hided` or a device's helper next starts. +A shell that does not answer is logged as `kit.login_shell_unread` with its error kind, asked again after a minute, and the search goes on without its folders meanwhile; Windows has no login shell, and its search is the account's own `Path` plus the usual folders. +A program found by the search is also run with it, because a CLI installed as a script starts its interpreter by name (pnpm's `codex` runs `node`). + +### When the program is gone + +An agent that is on and whose program is no longer found (uninstalled, or moved where the search does not reach) keeps everything: the operator's choice stays on record, the stub and the hook Hide wrote stay where they are, and no pass installs, replaces or removes anything for it. +Taking them out on a guess would remove what the operator may want back, and an unused stub or a guarded hook does nothing; this is the kit's rule that only the operator takes a piece away (D-20, D-26). +Its row stays in Settings with its switch, reads `Not on this machine` with the reason that its program is not found, and offers no Reinstall, since Reinstall cannot bring a CLI back; switching it off takes out Hide's pieces as for any agent, and once the program is found again the agent is whole with nothing asked. +Claude Code's and Codex's hook parts follow the kit-part rule instead: they are written while the agent is on and its folder (`~/.claude`, `~/.codex`) is there, found or not, because a CLI the search misses still runs the hook. ### Support table @@ -210,7 +232,7 @@ Every row gets the skill stub where the system column says so. | Kimi Code | `~/.agents/skills` (macOS, Linux) | none: `SessionStart` is fire-and-forget; injection is documented for `UserPromptSubmit` only | [skills](https://github.com/MoonshotAI/kimi-code/blob/main/docs/en/customization/skills.md) | | Mistral Vibe | `~/.agents/skills` (macOS, Linux) | none: no `SessionStart` event | [README](https://github.com/mistralai/mistral-vibe/blob/main/README.md) | -An agent is a row only when its documentation confirms where it reads skills and how it is detected. +An agent is a row only when its documentation confirms where it reads skills and the name of the program it installs. Roo Code is not a row because it was shut down in May 2026, and Aider is not a row because it reads no skills. Hide does not write an agent's `AGENTS.md` or `CLAUDE.md`, its MCP configuration, its model settings, or its Codex hook trust review, and it runs no installer for an agent. @@ -275,7 +297,7 @@ Reinstall, the `kit_reinstall` event, is offered only where a part is outdated, Project Memory's "update hooks" sends the same Reinstall for this Mac's hook parts. Reinstall repairs what is on: the hook part of an agent that is switched off reads Off whatever its file says, the machine row does not offer Reinstall for it, and a pane of that agent says its hook is switched off in Settings, Agents (`hooks_switched_off`), not that it was never installed. A switch pressed while an earlier press for the same agent is still queued replaces it, so the latest press is what the machine ends up with. -The kit looks for the agents once per pass, and asks a CLI for its version once per version of its file, so Settings re-reading the kit every few seconds runs no subprocess. +The kit looks for the agents once per pass, asks the login shell for its `PATH` only when a startup file changed, and asks a CLI for its version once per version of its file, so Settings re-reading the kit every few seconds runs no subprocess. Removal does not need the helper, and must not: it reads the configuration file and takes out the entries carrying Hide's marker, and nothing else. Removing a device from Hide does that on the device while its helper is connected (D-16); the operator removes a hook on their own machine by editing the file, and the kit then leaves it removed. diff --git a/hide-agent-hooks/src/codex_daemon.rs b/hide-agent-hooks/src/codex_daemon.rs index 36c5a803ed..5b0a6bc773 100644 --- a/hide-agent-hooks/src/codex_daemon.rs +++ b/hide-agent-hooks/src/codex_daemon.rs @@ -240,7 +240,7 @@ mod tests { Ok(DaemonSetting::Off) ); assert_eq!( - crate::program_version(&shim, home.path()).as_deref(), + crate::program_version(&shim, &crate::cli_path(home.path()).unwrap()).as_deref(), Some("0.160.0") ); } diff --git a/hide-agent-hooks/src/diagnosis.rs b/hide-agent-hooks/src/diagnosis.rs index 34b0e7ca93..3e36b21de0 100644 --- a/hide-agent-hooks/src/diagnosis.rs +++ b/hide-agent-hooks/src/diagnosis.rs @@ -6,7 +6,7 @@ //! that matches is the one shown; nothing falls through to an empty value or //! an invented cause (PRD B21, B32, D-64). -use std::ffi::OsString; +use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::atomic::AtomicBool; @@ -341,7 +341,9 @@ pub fn runtime_compatibility(runtime: AgentRuntime, home: &Path) -> MemoryCompat minimum_version: minimum.to_owned(), }; }; - let Some(output) = version_output(&binary, home, RUNTIME_VERSION_PROBE_TIMEOUT) else { + let Some(output) = cli_path(home) + .and_then(|path| version_output(&binary, &path, RUNTIME_VERSION_PROBE_TIMEOUT)) + else { return MemoryCompatibility::UpdateRequired { installed_version: None, minimum_version: minimum.to_owned(), @@ -374,8 +376,8 @@ pub(crate) fn runtime_binary(runtime: AgentRuntime, home: &Path) -> Option Option { hide_platform::host::find_program(&cli_path(home)?, name) } @@ -387,8 +389,32 @@ pub fn find_binary(name: &str, home: &Path) -> Option { /// (pnpm's `codex` is a shell script that runs `node`), so a CLI found here /// is run with this value, never with the daemon's `PATH` alone. pub fn cli_path(home: &Path) -> Option { + cli_path_with(home, None) +} + +/// [`cli_path`] with the folders the account's login shell puts on its +/// `PATH` in front, in the shell's order, which is the order the operator's +/// terminal searches: an installer that adds its own folder in `~/.zshrc` +/// (`~/.grok/bin`, `~/.kilo/bin`, `~/.opencode/bin`) reaches no other place +/// this search looks. Asking the shell is a subprocess with a deadline, so +/// only the install kit asks (`hide_platform::host::login_shell_path`) and +/// hands the answer in here; a folder named twice is searched once. +pub fn cli_path_with(home: &Path, shell_path: Option<&OsStr>) -> Option { let inherited = hide_platform::host::login_path().unwrap_or_else(|_| "/usr/bin:/bin".into()); - std::env::join_paths(std::env::split_paths(&inherited).chain([ + let mut seen = std::collections::HashSet::new(); + let shell = shell_path.map(std::env::split_paths).into_iter().flatten(); + std::env::join_paths( + shell + .chain(std::env::split_paths(&inherited)) + .chain(usual_install_folders(home)) + .filter(|folder| seen.insert(folder.clone())), + ) + .ok() +} + +/// The folders installers put a CLI in that a daemon's `PATH` may not reach. +fn usual_install_folders(home: &Path) -> [PathBuf; 8] { + [ home.join(".local/bin"), // pnpm's global bin folder: `$PNPM_HOME` up to pnpm 10 and // `$PNPM_HOME/bin` from pnpm 11, with `$PNPM_HOME` defaulting to @@ -400,21 +426,21 @@ pub fn cli_path(home: &Path) -> Option { home.join(".npm-global/bin"), PathBuf::from("/opt/homebrew/bin"), PathBuf::from("/usr/local/bin"), - ])) - .ok() + ] } -/// The version a program reports for `--version`, within the same short -/// bound the runtime probe uses; `None` when it does not answer in time, -/// exits non-zero or prints no `x.y.z`. -pub fn program_version(binary: &Path, home: &Path) -> Option { - version_output(binary, home, RUNTIME_VERSION_PROBE_TIMEOUT) +/// The version a program reports for `--version`, run with `path` (the +/// search it was found on), within the same short bound the runtime probe +/// uses; `None` when it does not answer in time, exits non-zero or prints no +/// `x.y.z`. +pub fn program_version(binary: &Path, path: &OsStr) -> Option { + version_output(binary, path, RUNTIME_VERSION_PROBE_TIMEOUT) .and_then(|output| parse_version(&output)) } -fn version_output(binary: &Path, home: &Path, timeout: Duration) -> Option { +fn version_output(binary: &Path, path: &OsStr, timeout: Duration) -> Option { let mut command = Command::new(binary); - command.arg("--version").env("PATH", cli_path(home)?); + command.arg("--version").env("PATH", path); let finished = run_to_end(&mut command, timeout, &AtomicBool::new(false)).ok()?; let output = if finished.stdout.trim().is_empty() { finished.stderr diff --git a/hide-agent-hooks/src/lib.rs b/hide-agent-hooks/src/lib.rs index cd776242a7..716bc9a6b0 100644 --- a/hide-agent-hooks/src/lib.rs +++ b/hide-agent-hooks/src/lib.rs @@ -31,7 +31,7 @@ pub mod runtime; pub use counters::PaneCounters; pub use diagnosis::{ Diagnosis, MemoryCompatibility, PaneInstrumentation, RuntimeDiagnosis, UninstrumentedReason, - find_binary, program_version, runtime_compatibility, version_at_least, + cli_path, cli_path_with, find_binary, program_version, runtime_compatibility, version_at_least, }; pub use install::{ HookStatus, InstallFailure, InstallOutcome, RemoveOutcome, install, installed_helper_path, diff --git a/hide-kit/src/agent_kit.rs b/hide-kit/src/agent_kit.rs index 631d919e51..6ad088cad9 100644 --- a/hide-kit/src/agent_kit.rs +++ b/hide-kit/src/agent_kit.rs @@ -20,8 +20,8 @@ use hide_agent_hooks::{HookStatus, InstallFailure}; use crate::agents::{ ADAPTERS, AgentAdapter, AgentReport, Detection, HookSupport, PieceReport, SkillDir, - SkillObserved, adapter_of_part, availability, install_skill, observe_skill, program_version, - remove_skill, skill_location, + SkillObserved, adapter_of_part, availability, install_skill, observe_skill, remove_skill, + skill_location, }; use crate::record::Record; use crate::{ComponentId, ComponentState, KitTarget, Observed, RemoveOutcome, Scope}; @@ -135,8 +135,14 @@ fn observe_guidance( )); } let observed = match guidance::status(agent, &target.home) { + // Installed, but the agent has not made its settings folder yet; the + // hook goes in on the pass after it has. HookStatus::RuntimeAbsent => { - return Observed::Absent(format!("{} is not set up on this machine", adapter.label)); + return Observed::Absent(format!( + "{} has not created {} yet; the hook is put in once it has", + adapter.label, + agent.home_directory(&target.home).display() + )); } // Reading a file never says Off: the kit's record does (`HookStatus::Off`). HookStatus::NotInstalled | HookStatus::Off => Observed::Missing, @@ -169,7 +175,7 @@ fn observe_guidance( helper(target).display() )); } - match version_gate(adapter, detection, &target.home) { + match version_gate(adapter, detection) { Ok(()) => observed, // Nothing a Reinstall can change: the agent is too old, or its // version cannot be read, so the row says why and is not repairable. @@ -179,13 +185,13 @@ fn observe_guidance( /// An agent with a documented minimum version gets the hook only when its /// CLI answers a version at or above it; one with none has no gate. -fn version_gate(adapter: &AgentAdapter, detection: &Detection, home: &Path) -> Result<(), String> { +fn version_gate(adapter: &AgentAdapter, detection: &Detection) -> Result<(), String> { let Some(minimum) = adapter.min_version else { return Ok(()); }; let version = detection .executable(adapter) - .and_then(|binary| program_version(binary, home)); + .and_then(|binary| detection.version(binary)); match version { Some(version) if hide_agent_hooks::version_at_least(&version, minimum) => Ok(()), Some(version) => Err(format!( @@ -217,6 +223,17 @@ fn remove_guidance(target: &KitTarget, agent: GuidanceAgent) -> RemoveOutcome { // --- One pass ------------------------------------------------------------------ +/// Why an agent that is on has nothing put in place: none of its programs is +/// found here. +fn not_found(adapter: &AgentAdapter) -> String { + let programs: Vec = adapter + .executables + .iter() + .map(|name| format!("`{name}`")) + .collect(); + format!("{} is not found on this machine", programs.join(" or ")) +} + fn dir_state( observed: &SkillObserved, recorded: bool, @@ -263,7 +280,7 @@ pub(crate) fn status( let empty = Record::default(); let scope = Scope::default(); let readable = record.as_ref().unwrap_or(&empty); - let detection = Detection::probe(&target.home); + let detection = Detection::probe(target); let dirs = observe_dirs(target, readable, &scope, &detection); ADAPTERS .iter() @@ -285,7 +302,7 @@ pub(crate) fn status( } /// The skill folders' states, with a folder wanted only while an agent that -/// reads it is on and set up here. +/// reads it is on and installed here. fn observe_dirs( target: &KitTarget, record: &Record, @@ -299,7 +316,7 @@ fn observe_dirs( adapter.skill_dir == dir && adapter.skill_supported() && enabled(record, scope, adapter) - && detection.detected(adapter) + && detection.installed(adapter) && dir.writable(&target.home) }); (dir, observe_skill(dir, &target.home), wanted) @@ -319,11 +336,11 @@ fn report_agent( record_readable: bool, parts: &[PartView], ) -> AgentReport { - let detected = detection.detected(adapter); + let installed = detection.installed(adapter); // The switch works while either piece can be put here: Codex on a system // with no documented skill folder still has its hook to switch off. let availability = availability( - detected, + installed, adapter.skill_supported(), adapter.hook_supported(), ); @@ -346,17 +363,21 @@ fn report_agent( location: Some(location), }, } - } else if !detected || !adapter.skill_supported() { + } else if !installed { + // On, and its program is gone or was never here: a pass leaves what + // Hide put down in place, and the switch still takes it out. PieceReport { state: ComponentState::Absent, - reason: Some(if detected { - format!( - "{}'s documentation gives no skill folder for this system", - adapter.label - ) - } else { - format!("{} is not set up on this machine", adapter.label) - }), + reason: Some(not_found(adapter)), + location: None, + } + } else if !adapter.skill_supported() { + PieceReport { + state: ComponentState::Absent, + reason: Some(format!( + "{}'s documentation gives no skill folder for this system", + adapter.label + )), location: None, } } else { @@ -428,7 +449,7 @@ fn report_agent( } /// Hide's skill stub is still in the folder of an agent the operator switched -/// off, with no agent that is on and set up reading it: the removal failed +/// off, with no agent that is on and installed reading it: the removal failed /// or never ran, and the row must not read Off over it. fn left_behind( record: &Record, @@ -485,10 +506,10 @@ fn guidance_piece( }, }; } - if !detection.detected(adapter) { + if !detection.installed(adapter) { return PieceReport { state: ComponentState::Absent, - reason: Some(format!("{} is not set up on this machine", adapter.label)), + reason: Some(not_found(adapter)), location: None, }; } @@ -537,18 +558,17 @@ pub(crate) fn apply( let mut failures = AgentFailures::default(); let record_readable = record_failure.is_none(); // Looked for once: every decision below reads this, not the PATH. - let detection = Detection::probe(&target.home); + let detection = Detection::probe(target); // What the operator chose now is the record's, whatever else this pass - // can or cannot do for the agent. A switch for an agent that is not set - // up here has nothing to switch. + // can or cannot do for the agent. A switch on for an agent that is not + // installed here has nothing to switch. if record_readable && answers_choice(scope) { changed |= record.answer_choice(); } for adapter in ADAPTERS { - let detected = detection.detected(adapter); if record_readable { - if scope.agent_on.contains(adapter.id) && detected { + if scope.agent_on.contains(adapter.id) && detection.installed(adapter) { changed |= record.set_agent_choice(adapter.id, true); } else if scope.agent_off.contains(adapter.id) { changed |= record.set_agent_choice(adapter.id, false); @@ -562,7 +582,6 @@ pub(crate) fn apply( continue; }; let on = enabled(record, scope, adapter); - let detected = detection.detected(adapter); let code = hook_code(adapter); if !on { if scope.agent_off.contains(adapter.id) { @@ -575,7 +594,9 @@ pub(crate) fn apply( } continue; } - if !detected { + // An agent whose program is gone keeps the hook Hide wrote: only the + // operator's switch takes it out (D-20, D-26). + if !detection.installed(adapter) { continue; } let observed = observe_guidance(target, adapter, agent, &detection); @@ -610,12 +631,12 @@ pub(crate) fn apply( let wanted = readers().any(|adapter| { adapter.skill_supported() && enabled(record, scope, adapter) - && detection.detected(adapter) + && detection.installed(adapter) && dir.writable(&target.home) }); let switched_off = readers().any(|adapter| scope.agent_off.contains(adapter.id)); let switched_on = readers() - .any(|adapter| scope.agent_on.contains(adapter.id) && detection.detected(adapter)); + .any(|adapter| scope.agent_on.contains(adapter.id) && detection.installed(adapter)); let code = skill_code(dir); if wanted { let observed = observe_skill(dir, &target.home); diff --git a/hide-kit/src/agents.rs b/hide-kit/src/agents.rs index b97cb32bf1..f795641edb 100644 --- a/hide-kit/src/agents.rs +++ b/hide-kit/src/agents.rs @@ -1,11 +1,11 @@ //! The agent adapters: which coding agents Hide knows how to reach, and what //! it puts where each one reads it (issue #517). //! -//! One data row per agent declares how it is detected, where its skills -//! live, whether it has hooks, the oldest version the hook needs and the -//! official page every one of those answers comes from. The content an agent -//! reads is the same for all of them and is read from the `hide` binary at -//! run time (`hide browser help`), so a new agent is a row here and a +//! One data row per agent declares the programs it is found by, where its +//! skills live, whether it has hooks, the oldest version the hook needs and +//! the official page every one of those answers comes from. The content an +//! agent reads is the same for all of them and is read from the `hide` binary +//! at run time (`hide browser help`), so a new agent is a row here and a //! fixture, never a new text (engineering rule 2, 7). //! //! Three things a row can turn on for an agent the operator switched on: @@ -18,12 +18,15 @@ //! get the SessionStart guidance hook ([`HookSupport::Guidance`]); //! - nothing else. What Hide never writes is listed in `docs/agent-hooks.md`. +use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; +use std::sync::{LazyLock, Mutex}; +use std::time::{Duration, Instant, SystemTime}; use hide_agent_hooks::guidance::GuidanceAgent; use serde::{Deserialize, Serialize}; -use crate::{ComponentId, ComponentState}; +use crate::{ComponentId, ComponentState, KitTarget}; /// The operating systems a skill folder is documented for. #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -98,8 +101,10 @@ impl SkillDir { /// Whether the folder can be written without creating the agent's own /// folder: the shared folder is Hide's to create, an agent's own is not, - /// because its presence is how other parts of the kit see the agent - /// (a pass that made it would change what the next pass finds). + /// because its presence is how the hook code tells that the agent's + /// settings are there (`hide_agent_hooks`' runtime-absent answer), so a + /// pass that made it would let the next pass write a hook this one did + /// not, and a second apply would not be a no-op. pub(crate) fn writable(self, home: &Path) -> bool { let [folder, _] = self.relative(); self == Self::Shared || home.join(folder).is_dir() @@ -135,14 +140,12 @@ pub struct AgentAdapter { pub id: &'static str, /// The name the operator reads (a product name, never translated). pub label: &'static str, - /// Program names looked for on the login `PATH` and the usual install - /// folders; empty when the name is too generic to mean this agent - /// (`goose`, `amp`, `droid`, `copilot` and `kilo` are also other - /// programs), which is then detected by its home folder alone. + /// The program names the vendor's install documentation gives the CLI; + /// the agent is installed on a machine when one of them is found + /// ([`Detection`]). A folder the agent creates does not count: an editor + /// makes `~/.cursor` without the `cursor-agent` CLI, and a CLI that was + /// removed leaves its folder behind. pub executables: &'static [&'static str], - /// Folders under the home the agent creates; any one present means it is - /// set up here. - pub home_markers: &'static [&'static str], /// The folder the agent reads skills from. pub skill_dir: SkillDir, /// The systems the agent's documentation confirms that folder on. @@ -167,7 +170,6 @@ pub const ADAPTERS: &[AgentAdapter] = &[ id: "claude-code", label: "Claude Code", executables: &["claude"], - home_markers: &[".claude"], skill_dir: SkillDir::Claude, skill_os: ALL_OS, hook: HookSupport::Part(ComponentId::ClaudeCodeHook), @@ -179,7 +181,6 @@ pub const ADAPTERS: &[AgentAdapter] = &[ id: "codex", label: "Codex", executables: &["codex"], - home_markers: &[".codex"], skill_dir: SkillDir::Shared, skill_os: UNIX_OS, hook: HookSupport::Part(ComponentId::CodexHook), @@ -191,7 +192,6 @@ pub const ADAPTERS: &[AgentAdapter] = &[ id: "opencode", label: "OpenCode", executables: &["opencode"], - home_markers: &[".config/opencode"], skill_dir: SkillDir::Shared, skill_os: UNIX_OS, hook: HookSupport::None, @@ -203,7 +203,6 @@ pub const ADAPTERS: &[AgentAdapter] = &[ id: "gemini-cli", label: "Gemini CLI", executables: &["gemini"], - home_markers: &[".gemini"], skill_dir: SkillDir::Shared, skill_os: UNIX_OS, hook: HookSupport::Guidance(GuidanceAgent::Gemini), @@ -215,7 +214,6 @@ pub const ADAPTERS: &[AgentAdapter] = &[ id: "cursor", label: "Cursor", executables: &["cursor-agent"], - home_markers: &[".cursor"], skill_dir: SkillDir::Shared, skill_os: UNIX_OS, hook: HookSupport::Guidance(GuidanceAgent::Cursor), @@ -226,8 +224,7 @@ pub const ADAPTERS: &[AgentAdapter] = &[ AgentAdapter { id: "copilot-cli", label: "GitHub Copilot CLI", - executables: &[], - home_markers: &[".copilot"], + executables: &["copilot"], skill_dir: SkillDir::Shared, skill_os: ALL_OS, hook: HookSupport::Guidance(GuidanceAgent::Copilot), @@ -238,8 +235,7 @@ pub const ADAPTERS: &[AgentAdapter] = &[ AgentAdapter { id: "amp", label: "Amp", - executables: &[], - home_markers: &[".config/amp"], + executables: &["amp"], skill_dir: SkillDir::Shared, skill_os: UNIX_OS, hook: HookSupport::None, @@ -250,8 +246,7 @@ pub const ADAPTERS: &[AgentAdapter] = &[ AgentAdapter { id: "factory-droid", label: "Factory Droid", - executables: &[], - home_markers: &[".factory"], + executables: &["droid"], skill_dir: SkillDir::Shared, skill_os: UNIX_OS, hook: HookSupport::Guidance(GuidanceAgent::Droid), @@ -263,7 +258,6 @@ pub const ADAPTERS: &[AgentAdapter] = &[ id: "kiro", label: "Kiro", executables: &["kiro-cli"], - home_markers: &[".kiro"], skill_dir: SkillDir::Kiro, skill_os: UNIX_OS, hook: HookSupport::Guidance(GuidanceAgent::Kiro), @@ -275,7 +269,6 @@ pub const ADAPTERS: &[AgentAdapter] = &[ id: "qwen-code", label: "Qwen Code", executables: &["qwen"], - home_markers: &[".qwen"], skill_dir: SkillDir::Qwen, skill_os: UNIX_OS, hook: HookSupport::Guidance(GuidanceAgent::Qwen), @@ -286,8 +279,7 @@ pub const ADAPTERS: &[AgentAdapter] = &[ AgentAdapter { id: "goose", label: "Goose", - executables: &[], - home_markers: &[".config/goose"], + executables: &["goose"], skill_dir: SkillDir::Shared, skill_os: UNIX_OS, hook: HookSupport::None, @@ -299,7 +291,6 @@ pub const ADAPTERS: &[AgentAdapter] = &[ id: "cline", label: "Cline", executables: &["cline"], - home_markers: &[".cline"], skill_dir: SkillDir::Cline, skill_os: ALL_OS, hook: HookSupport::None, @@ -310,8 +301,7 @@ pub const ADAPTERS: &[AgentAdapter] = &[ AgentAdapter { id: "kilo-code", label: "Kilo Code", - executables: &[], - home_markers: &[".config/kilo"], + executables: &["kilo"], skill_dir: SkillDir::Shared, skill_os: ALL_OS, hook: HookSupport::None, @@ -323,7 +313,6 @@ pub const ADAPTERS: &[AgentAdapter] = &[ id: "crush", label: "Crush", executables: &["crush"], - home_markers: &[".config/crush"], skill_dir: SkillDir::Shared, skill_os: ALL_OS, hook: HookSupport::None, @@ -335,7 +324,6 @@ pub const ADAPTERS: &[AgentAdapter] = &[ id: "junie", label: "Junie", executables: &["junie"], - home_markers: &[".junie"], skill_dir: SkillDir::Shared, skill_os: ALL_OS, hook: HookSupport::Guidance(GuidanceAgent::Junie), @@ -347,7 +335,6 @@ pub const ADAPTERS: &[AgentAdapter] = &[ id: "augment", label: "Augment", executables: &["auggie"], - home_markers: &[".augment"], skill_dir: SkillDir::Shared, skill_os: UNIX_OS, hook: HookSupport::Guidance(GuidanceAgent::Augment), @@ -358,8 +345,7 @@ pub const ADAPTERS: &[AgentAdapter] = &[ AgentAdapter { id: "pi", label: "Pi", - executables: &[], - home_markers: &[".pi/agent"], + executables: &["pi"], skill_dir: SkillDir::Shared, skill_os: ALL_OS, hook: HookSupport::None, @@ -370,8 +356,7 @@ pub const ADAPTERS: &[AgentAdapter] = &[ AgentAdapter { id: "grok", label: "Grok", - executables: &[], - home_markers: &[".grok"], + executables: &["grok"], skill_dir: SkillDir::Shared, skill_os: UNIX_OS, hook: HookSupport::None, @@ -382,8 +367,7 @@ pub const ADAPTERS: &[AgentAdapter] = &[ AgentAdapter { id: "kimi-code", label: "Kimi Code", - executables: &[], - home_markers: &[".kimi-code"], + executables: &["kimi"], skill_dir: SkillDir::Shared, skill_os: UNIX_OS, hook: HookSupport::None, @@ -394,8 +378,7 @@ pub const ADAPTERS: &[AgentAdapter] = &[ AgentAdapter { id: "mistral-vibe", label: "Mistral Vibe", - executables: &[], - home_markers: &[".vibe"], + executables: &["vibe"], skill_dir: SkillDir::Shared, skill_os: UNIX_OS, hook: HookSupport::None, @@ -445,92 +428,218 @@ impl AgentAdapter { HookSupport::None => false, } } - - /// The agent's program, when it is on this machine. - pub fn executable(&self, home: &Path) -> Option { - // A test machine's own agents must not decide what a fixture home - // finds, so under test only the fixture's `~/.local/bin` is searched. - #[cfg(test)] - { - let folder = home.join(".local/bin").into_os_string(); - self.executables - .iter() - .find_map(|name| hide_platform::host::find_program(&folder, name)) - } - #[cfg(not(test))] - { - self.executables - .iter() - .find_map(|name| hide_agent_hooks::find_binary(name, home)) - } - } - - /// Whether the agent is set up on this machine: its program is found, or - /// a folder it creates is there. - pub fn detected(&self, home: &Path) -> bool { - self.executable(home).is_some() - || self - .home_markers - .iter() - .any(|marker| home.join(marker).is_dir()) - } } /// What one pass found out about the agents on a machine: each adapter's -/// program and home folder, looked for once. Every decision of the pass reads -/// this instead of searching the `PATH` again. +/// program, looked for once on one search. Every decision of the pass reads +/// this instead of searching again. pub(crate) struct Detection { - rows: Vec<(&'static str, Option, bool)>, + /// The search the programs were looked for on; a program found there is + /// run with it too, since a CLI installed as a script starts its + /// interpreter by name (`hide_agent_hooks::cli_path`). + path: OsString, + rows: Vec<(&'static str, Option)>, } impl Detection { - pub(crate) fn probe(home: &Path) -> Self { + pub(crate) fn probe(target: &KitTarget) -> Self { + let path = search_path(target); let rows = ADAPTERS .iter() .map(|adapter| { - let executable = adapter.executable(home); - let present = executable.is_some() - || adapter - .home_markers - .iter() - .any(|marker| home.join(marker).is_dir()); - (adapter.id, executable, present) + let program = adapter + .executables + .iter() + .find_map(|name| hide_platform::host::find_program(&path, name)); + (adapter.id, program) }) .collect(); - Self { rows } + Self { path, rows } } - pub(crate) fn detected(&self, adapter: &AgentAdapter) -> bool { - self.rows - .iter() - .any(|(id, _, present)| *id == adapter.id && *present) + /// Whether the agent is installed here: one of its programs is found. + pub(crate) fn installed(&self, adapter: &AgentAdapter) -> bool { + self.executable(adapter).is_some() } pub(crate) fn executable(&self, adapter: &AgentAdapter) -> Option<&Path> { self.rows .iter() - .find(|(id, ..)| *id == adapter.id) - .and_then(|(_, executable, _)| executable.as_deref()) + .find(|(id, _)| *id == adapter.id) + .and_then(|(_, program)| program.as_deref()) + } + + /// `program --version`, run with the search it was found on. + pub(crate) fn version(&self, program: &Path) -> Option { + program_version(program, &self.path) } } -/// How long a version that could not be read is not asked for again. A -/// version that was read stays until the program's file changes. -const UNREAD_VERSION_RETRY: std::time::Duration = std::time::Duration::from_secs(60); +/// Where the agents' programs are looked for: the folders the account's +/// login shell puts on its `PATH`, then the daemon's own `PATH` and the +/// usual install folders (`hide_agent_hooks::cli_path_with`). A join fails +/// only for a folder whose name holds the separator, which no search can +/// hold, so then nothing is found. +fn search_path(target: &KitTarget) -> OsString { + let shell = login_shell_path(target); + // A test machine's own agents must not decide what a fixture home finds, + // so under test the search is the fixture's `~/.local/bin` and what the + // fixture's stand-in shell answers, never this process's `PATH`. + #[cfg(test)] + { + let folders = shell + .iter() + .flat_map(std::env::split_paths) + .chain([target.home.join(".local/bin")]); + std::env::join_paths(folders).unwrap_or_default() + } + #[cfg(not(test))] + { + hide_agent_hooks::cli_path_with(&target.home, shell.as_deref()).unwrap_or_default() + } +} -type VersionKey = (PathBuf, Option, u64); +/// The account's login shell: `$SHELL` on macOS and Linux, which launchd +/// gives an app and sshd gives an exec channel. Windows has none to ask; a +/// process there is given the account's own `Path`. A Unix process started +/// without `SHELL` asks none, and the log says so. +pub(crate) fn login_shell() -> Option { + if cfg!(windows) { + return None; + } + hide_platform::host::default_shell() + .inspect_err(|error| eprintln!("kit.login_shell_missing kind={:?}", error.kind())) + .ok() +} -/// What was answered for a program's version, and when it was asked. -type VersionAnswers = std::collections::HashMap, std::time::Instant)>; +/// How long the login shell has to answer, as long as the desktop host gives +/// it when it asks the same question. +const LOGIN_SHELL_DEADLINE: Duration = Duration::from_secs(10); + +/// The startup files a login shell reads that installers edit to put their +/// folder on the `PATH`: zsh's (in the home, and in `~/.config/zsh` for a +/// `ZDOTDIR` there), bash's and sh's, fish's, and the system's own. +const STARTUP_FILES_IN_HOME: &[&str] = &[ + ".zshenv", + ".zprofile", + ".zshrc", + ".zlogin", + ".config/zsh/.zshenv", + ".config/zsh/.zprofile", + ".config/zsh/.zshrc", + ".config/zsh/.zlogin", + ".bash_profile", + ".bash_login", + ".profile", + ".bashrc", + ".config/fish/config.fish", + ".config/fish/conf.d", + ".config/fish/fish_variables", +]; +const SYSTEM_STARTUP_FILES: &[&str] = &[ + "/etc/paths", + "/etc/paths.d", + "/etc/zshenv", + "/etc/zprofile", + "/etc/zshrc", + "/etc/zlogin", + "/etc/profile", + "/etc/profile.d", + "/etc/bashrc", + "/etc/bash.bashrc", +]; -/// `binary --version`, asked at most once per version of the file: Settings -/// re-reads the kit every few seconds, and a subprocess per read would put a -/// slow or hanging program on the kit worker for as long as Settings is open. -/// The probe itself is bounded (`hide_agent_hooks::program_version`). -pub(crate) fn program_version(binary: &Path, home: &Path) -> Option { - use std::sync::{LazyLock, Mutex}; - use std::time::Instant; +/// Each startup file's write time and length, `None` where there is none. +type StartupStamps = Vec, u64)>>; +fn startup_stamps(home: &Path) -> StartupStamps { + STARTUP_FILES_IN_HOME + .iter() + .map(|name| home.join(name)) + .chain(SYSTEM_STARTUP_FILES.iter().map(PathBuf::from)) + .map(|file| { + std::fs::metadata(file) + .ok() + .map(|meta| (meta.modified().ok(), meta.len())) + }) + .collect() +} + +/// What the login shell last answered, for which shell, home and startup +/// files, and when it was asked. +struct ShellAnswer { + shell: PathBuf, + home: PathBuf, + stamps: StartupStamps, + path: Option, + asked: Instant, +} + +/// The `PATH` the account's login shell sets up, asked again only when one +/// of its startup files changed: an installer puts its folder on the `PATH` +/// by editing one, and Settings re-reads the kit every few seconds, which +/// must not start a shell each time. A file those files read in turn is not +/// watched; the next launch or connection asks afresh. A shell that did not +/// answer is asked again after [`UNREAD_RETRY`], and the search goes on +/// without its folders meanwhile; the failure is logged, since there is +/// nothing on screen the operator could do about it (design rule 13). +fn login_shell_path(target: &KitTarget) -> Option { + static ANSWER: LazyLock>> = LazyLock::new(Mutex::default); + let shell = target.login_shell.as_deref()?; + let stamps = startup_stamps(&target.home); + if let Ok(answer) = ANSWER.lock() + && let Some(answer) = answer.as_ref() + && answer.shell == shell + && answer.home == target.home + && answer.stamps == stamps + && (answer.path.is_some() || answer.asked.elapsed() < UNREAD_RETRY) + { + return answer.path.clone(); + } + let asked = Instant::now(); + let path = hide_platform::host::login_shell_path( + shell, + &target.home, + LOGIN_SHELL_DEADLINE, + &target.stop, + ) + .inspect_err(|error| { + eprintln!( + "kit.login_shell_unread shell={} kind={:?} elapsed_ms={}", + shell.display(), + error.kind(), + asked.elapsed().as_millis() + ); + }) + .ok(); + if let Ok(mut answer) = ANSWER.lock() { + *answer = Some(ShellAnswer { + shell: shell.to_path_buf(), + home: target.home.clone(), + stamps, + path: path.clone(), + asked, + }); + } + path +} + +/// How long an answer that could not be read (a version, the login shell's +/// `PATH`) is not asked for again. One that was read stays until what it +/// came from changes. +const UNREAD_RETRY: Duration = Duration::from_secs(60); + +type VersionKey = (PathBuf, Option, u64); + +/// What was answered for a program's version, and when it was asked. +type VersionAnswers = std::collections::HashMap, Instant)>; + +/// `binary --version`, run with `path`, asked at most once per version of the +/// file: Settings re-reads the kit every few seconds, and a subprocess per +/// read would put a slow or hanging program on the kit worker for as long as +/// Settings is open. The probe itself is bounded +/// (`hide_agent_hooks::program_version`). +fn program_version(binary: &Path, path: &OsStr) -> Option { static ANSWERS: LazyLock> = LazyLock::new(Mutex::default); let key = std::fs::metadata(binary) .map(|meta| (binary.to_path_buf(), meta.modified().ok(), meta.len())) @@ -538,11 +647,11 @@ pub(crate) fn program_version(binary: &Path, home: &Path) -> Option { if let Some(key) = &key && let Ok(answers) = ANSWERS.lock() && let Some((version, asked)) = answers.get(key) - && (version.is_some() || asked.elapsed() < UNREAD_VERSION_RETRY) + && (version.is_some() || asked.elapsed() < UNREAD_RETRY) { return version.clone(); } - let version = hide_agent_hooks::program_version(binary, home); + let version = hide_agent_hooks::program_version(binary, path); if let Some(key) = key && let Ok(mut answers) = ANSWERS.lock() { @@ -658,20 +767,20 @@ pub struct PieceReport { #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Availability { - /// Detected, and at least one of its pieces (the skill, the hook) works + /// Installed, and at least one of its pieces (the skill, the hook) works /// on this system: the switch works. Available, - /// Not found on this machine. + /// None of its programs is found on this machine. NotInstalled, - /// Found, but neither the skill folder nor the hook is documented for + /// Installed, but neither the skill folder nor the hook is documented for /// this system, so there is nothing for the switch to do. UnsupportedSystem, } -/// What the switch can do for an agent: it needs the agent on the machine and -/// at least one piece that works on this system. -pub(crate) fn availability(detected: bool, skill_here: bool, hook_here: bool) -> Availability { - if !detected { +/// What the switch can do for an agent: it needs the agent installed and at +/// least one piece that works on this system. +pub(crate) fn availability(installed: bool, skill_here: bool, hook_here: bool) -> Availability { + if !installed { Availability::NotInstalled } else if !skill_here && !hook_here { Availability::UnsupportedSystem diff --git a/hide-kit/src/device.rs b/hide-kit/src/device.rs index d91dd40dba..fc3f35efde 100644 --- a/hide-kit/src/device.rs +++ b/hide-kit/src/device.rs @@ -38,6 +38,7 @@ pub fn device_target( herdr_socket: herdr_socket.to_path_buf(), herdr_bin, codex: hide_agent_hooks::codex_daemon::find_codex(home), + login_shell: crate::agents::login_shell(), legacy_coordination_home: relocated, user_agents: hide_platform::user_agents::UserAgents::current(), retirement_projects: Vec::new(), diff --git a/hide-kit/src/lib.rs b/hide-kit/src/lib.rs index e7a83b7c9d..4e676965ee 100644 --- a/hide-kit/src/lib.rs +++ b/hide-kit/src/lib.rs @@ -242,6 +242,11 @@ pub struct KitTarget { pub herdr_bin: Option, /// The machine's `codex`, `None` when Hide finds none. pub codex: Option, + /// The account's login shell, asked for the `PATH` its startup files set + /// up, so an agent's CLI is found where the operator's terminal finds it + /// (`agents::Detection`). `None` asks nothing: Windows has no login + /// shell, and a test searches only its fixture. + pub login_shell: Option, /// Legacy relocation, inspected only by the one-release retirement. pub legacy_coordination_home: Option, /// Account login-agent boundary. Fixtures inject a stand-in command. diff --git a/hide-kit/src/local.rs b/hide-kit/src/local.rs index 4332625388..c12074bada 100644 --- a/hide-kit/src/local.rs +++ b/hide-kit/src/local.rs @@ -65,6 +65,7 @@ pub fn local_target( herdr_socket: herdr_socket.to_path_buf(), herdr_bin: herdr.is_file().then(|| herdr.clone()), codex: hide_agent_hooks::codex_daemon::find_codex(home), + login_shell: crate::agents::login_shell(), legacy_coordination_home: relocated, user_agents: hide_platform::user_agents::UserAgents::current(), retirement_projects: Vec::new(), diff --git a/hide-kit/src/tests.rs b/hide-kit/src/tests.rs index b19c5a5475..5fcbdde148 100644 --- a/hide-kit/src/tests.rs +++ b/hide-kit/src/tests.rs @@ -180,6 +180,8 @@ impl Fixture { let kit = root.join("kit"); std::fs::create_dir_all(home.join(".claude")).unwrap(); std::fs::write(home.join(".claude/settings.json"), OTHER_TOOL).unwrap(); + // Claude Code is installed: its program is what says so. + executable(&home.join(".local/bin/claude"), "#!/bin/sh\n"); executable(&kit.join("hide"), "#!/bin/sh\n"); executable(&kit.join("hide-agent-hooks"), "#!/bin/sh\n"); executable(&root.join("launchctl"), "#!/bin/sh\nexit 113\n"); @@ -196,6 +198,7 @@ impl Fixture { herdr_socket: herdr.socket.clone(), herdr_bin: Some(root.join("bin/herdr")), codex: None, + login_shell: None, legacy_coordination_home: None, user_agents: hide_platform::user_agents::UserAgents::fixture( root.join("launchctl"), @@ -301,15 +304,13 @@ fn a_first_apply_installs_every_part_and_keeps_other_tools_entries() { &std::fs::read_to_string(fixture.home().join(".hide/kit/installed.json")).unwrap(), ) .unwrap(); - // Skill stubs depend on which agents the machine running the test has, so - // only the parts and the Claude Code stub (its folder is in the fixture) - // are pinned. + // The fixture machine has Claude Code installed and no other agent, so + // its stub is the only one. let installed: Vec<&str> = record["installed"] .as_array() .unwrap() .iter() .map(|code| code.as_str().unwrap()) - .filter(|code| *code == "skill:claude" || !code.starts_with("skill:")) .collect(); assert_eq!( installed, diff --git a/hide-kit/src/tests/agent_cases.rs b/hide-kit/src/tests/agent_cases.rs index 2b35620123..5da804f526 100644 --- a/hide-kit/src/tests/agent_cases.rs +++ b/hide-kit/src/tests/agent_cases.rs @@ -24,10 +24,22 @@ fn gemini_settings(fixture: &Fixture) -> PathBuf { fixture.home().join(".gemini/settings.json") } +/// A folder the agent makes under the home, such as its settings folder. fn set_up(fixture: &Fixture, folder: &str) { std::fs::create_dir_all(fixture.home().join(folder)).unwrap(); } +/// An agent installed the way its installer leaves it: its program in the +/// fixture's `~/.local/bin` (the only folder a test searches) and its own +/// folder under the home. +fn install(fixture: &Fixture, program: &str, folder: &str) { + executable( + &fixture.home().join(".local/bin").join(program), + "#!/bin/sh\n", + ); + set_up(fixture, folder); +} + /// A program the kit will run for its version. A script written a moment ago /// cannot be executed while another test thread's fork still holds the file /// open for writing (ETXTBSY), so this waits until it can be. @@ -68,8 +80,8 @@ fn every_adapter_names_an_official_page_and_a_unique_id() { ); assert!(!adapter.label.is_empty()); assert!( - !adapter.executables.is_empty() || !adapter.home_markers.is_empty(), - "{} could never be detected", + !adapter.executables.is_empty(), + "{} names no program, so it could never be installed", adapter.id ); if let HookSupport::Guidance(guidance) = adapter.hook { @@ -87,7 +99,7 @@ fn every_adapter_names_an_official_page_and_a_unique_id() { #[test] fn an_agent_that_is_not_on_gets_nothing_until_the_operator_switches_it_on() { let fixture = Fixture::new(); - set_up(&fixture, ".gemini"); + install(&fixture, "gemini", ".gemini"); let report = apply(&fixture.target, &Scope::automatic()); @@ -118,7 +130,7 @@ fn an_agent_that_is_not_on_gets_nothing_until_the_operator_switches_it_on() { } #[test] -fn switching_on_an_agent_that_is_not_set_up_here_records_nothing() { +fn switching_on_an_agent_that_is_not_installed_here_records_nothing() { let fixture = Fixture::new(); let report = apply(&fixture.target, &Scope::agents(["gemini-cli"], [])); @@ -134,7 +146,7 @@ fn switching_on_an_agent_that_is_not_set_up_here_records_nothing() { } #[test] -fn a_program_on_the_home_bin_folder_counts_as_the_agent_being_set_up() { +fn a_program_on_the_home_bin_folder_is_the_agent_being_installed() { let fixture = Fixture::new(); executable(&fixture.home().join(".local/bin/gemini"), "#!/bin/sh\n"); @@ -153,7 +165,7 @@ fn a_program_on_the_home_bin_folder_counts_as_the_agent_being_set_up() { #[test] fn a_second_apply_of_an_agent_that_is_on_changes_nothing() { let fixture = Fixture::new(); - set_up(&fixture, ".gemini"); + install(&fixture, "gemini", ".gemini"); apply(&fixture.target, &Scope::agents(["gemini-cli"], [])); let tree = home_tree(fixture.home()); @@ -166,7 +178,7 @@ fn a_second_apply_of_an_agent_that_is_on_changes_nothing() { #[test] fn removed_by_hand_stays_removed_until_the_operator_reinstalls() { let fixture = Fixture::new(); - set_up(&fixture, ".gemini"); + install(&fixture, "gemini", ".gemini"); apply(&fixture.target, &Scope::agents(["gemini-cli"], [])); std::fs::remove_file(gemini_settings(&fixture)).unwrap(); std::fs::remove_dir_all(fixture.home().join(".agents")).unwrap(); @@ -192,7 +204,7 @@ fn removed_by_hand_stays_removed_until_the_operator_reinstalls() { #[test] fn an_older_stub_is_replaced_without_the_operator_asking() { let fixture = Fixture::new(); - set_up(&fixture, ".gemini"); + install(&fixture, "gemini", ".gemini"); apply(&fixture.target, &Scope::agents(["gemini-cli"], [])); let path = shared_skill(&fixture); let current = std::fs::read_to_string(&path).unwrap(); @@ -215,8 +227,8 @@ fn an_older_stub_is_replaced_without_the_operator_asking() { #[test] fn switching_an_agent_off_takes_only_hides_pieces_and_keeps_a_folder_another_agent_reads() { let fixture = Fixture::new(); - set_up(&fixture, ".gemini"); - set_up(&fixture, ".codex"); + install(&fixture, "gemini", ".gemini"); + install(&fixture, "codex", ".codex"); let settings = r#"{"theme":"dark","hooks":{"SessionStart":[{"matcher":"*","hooks":[{"name":"other","type":"command","command":"/opt/other/start.sh"}]}]}}"#; std::fs::write(gemini_settings(&fixture), settings).unwrap(); apply(&fixture.target, &Scope::agents(["gemini-cli"], [])); @@ -252,7 +264,7 @@ fn switching_an_agent_off_takes_only_hides_pieces_and_keeps_a_folder_another_age #[test] fn a_skill_that_hide_did_not_write_is_left_alone_and_reported() { let fixture = Fixture::new(); - set_up(&fixture, ".gemini"); + install(&fixture, "gemini", ".gemini"); let own = shared_skill(&fixture); std::fs::create_dir_all(own.parent().unwrap()).unwrap(); std::fs::write(&own, "---\nname: hide-browser\n---\nmine\n").unwrap(); @@ -387,7 +399,7 @@ fn an_agent_with_a_documented_minimum_gets_the_hook_only_from_that_version() { #[test] fn removing_a_machine_takes_every_marked_piece_and_nothing_else() { let fixture = Fixture::new(); - set_up(&fixture, ".gemini"); + install(&fixture, "gemini", ".gemini"); apply(&fixture.target, &Scope::agents(["gemini-cli"], [])); let removed = remove(&fixture.target); @@ -407,14 +419,14 @@ fn removing_a_machine_takes_every_marked_piece_and_nothing_else() { } #[test] -fn the_shared_stub_goes_when_the_last_agent_reading_it_is_switched_off_even_with_codex_not_set_up() -{ +fn the_shared_stub_goes_when_the_last_agent_reading_it_is_switched_off_even_with_codex_not_installed() + { let fixture = Fixture::new(); - set_up(&fixture, ".gemini"); + install(&fixture, "gemini", ".gemini"); apply(&fixture.target, &Scope::agents(["gemini-cli"], [])); assert!(shared_skill(&fixture).is_file()); - // Codex is on by default but not set up here, so it reads nothing. + // Codex is on by default but not installed here, so it reads nothing. apply(&fixture.target, &Scope::agents([], ["gemini-cli"])); assert!(!shared_skill(&fixture).exists()); @@ -423,7 +435,7 @@ fn the_shared_stub_goes_when_the_last_agent_reading_it_is_switched_off_even_with #[test] fn a_switch_off_that_left_hides_stub_behind_does_not_read_as_off() { let fixture = Fixture::new(); - set_up(&fixture, ".gemini"); + install(&fixture, "gemini", ".gemini"); apply(&fixture.target, &Scope::agents(["gemini-cli"], [])); // The choice is off and Hide's stub is still there, as a removal that // failed would leave it. @@ -465,7 +477,7 @@ fn an_agent_found_only_by_its_program_reports_its_folder_as_not_made_yet() { #[test] fn switching_factory_droid_off_finds_its_entry_in_either_file() { let fixture = Fixture::new(); - set_up(&fixture, ".factory"); + install(&fixture, "droid", ".factory"); std::fs::write( fixture.home().join(".factory/settings.json"), r#"{"hooks":{"SessionStart":[]}}"#, @@ -491,7 +503,7 @@ fn switching_factory_droid_off_finds_its_entry_in_either_file() { #[test] fn a_file_that_only_mentions_the_marker_is_not_hides_stub() { let fixture = Fixture::new(); - set_up(&fixture, ".gemini"); + install(&fixture, "gemini", ".gemini"); let own = shared_skill(&fixture); std::fs::create_dir_all(own.parent().unwrap()).unwrap(); // The marker's words sit in the body, not in the line Hide writes. @@ -511,7 +523,7 @@ fn a_file_that_only_mentions_the_marker_is_not_hides_stub() { #[test] fn an_edited_stub_is_reported_and_only_reinstall_puts_hides_text_back() { let fixture = Fixture::new(); - set_up(&fixture, ".gemini"); + install(&fixture, "gemini", ".gemini"); apply(&fixture.target, &Scope::agents(["gemini-cli"], [])); let path = shared_skill(&fixture); let hide_text = std::fs::read_to_string(&path).unwrap(); @@ -541,27 +553,33 @@ fn an_edited_stub_is_reported_and_only_reinstall_puts_hides_text_back() { } #[test] -fn a_program_with_a_common_name_does_not_count_as_the_agent() { - // `goose`, `amp`, `droid`, `copilot` and `kilo` are other programs too. +fn a_folder_the_agent_makes_is_not_the_agent_being_installed() { + // Each agent's folder alone: an editor makes `~/.cursor` without the + // `cursor-agent` CLI, and Pi's installer keeps `~/.pi/agent` around. for (program, id, folder) in [ + ("pi", "pi", ".pi/agent"), + ("cursor-agent", "cursor", ".cursor"), + ("grok", "grok", ".grok"), ("goose", "goose", ".config/goose"), ("amp", "amp", ".config/amp"), ("droid", "factory-droid", ".factory"), ("copilot", "copilot-cli", ".copilot"), ("kilo", "kilo-code", ".config/kilo"), + ("kimi", "kimi-code", ".kimi-code"), + ("vibe", "mistral-vibe", ".vibe"), ] { let fixture = Fixture::new(); + set_up(&fixture, folder); + let report = apply(&fixture.target, &Scope::agents([id], [])); + let row = agent(&report, id); + assert_eq!(row.availability, Availability::NotInstalled, "{id}"); + assert!(record(&fixture).get("agents").is_none(), "{id}"); + + // Its program is what makes it installed. executable( &fixture.home().join(".local/bin").join(program), "#!/bin/sh\n", ); - assert_eq!( - agent(&status(&fixture.target), id).availability, - Availability::NotInstalled, - "{program} alone is not {id}" - ); - // The agent's own folder is the signal. - set_up(&fixture, folder); assert_eq!( agent(&status(&fixture.target), id).availability, Availability::Available, @@ -570,6 +588,101 @@ fn a_program_with_a_common_name_does_not_count_as_the_agent() { } } +#[test] +fn an_agent_whose_program_is_gone_keeps_what_hide_put_down_until_it_is_switched_off() { + let fixture = Fixture::new(); + install(&fixture, "gemini", ".gemini"); + apply(&fixture.target, &Scope::agents(["gemini-cli"], [])); + assert!(shared_skill(&fixture).is_file()); + std::fs::remove_file(fixture.home().join(".local/bin/gemini")).unwrap(); + let tree = home_tree(fixture.home()); + + let report = apply(&fixture.target, &Scope::automatic()); + + // Nothing is taken out or written: the operator's choice and Hide's + // pieces stay as they were, so the agent is whole again once its + // program is back. + assert_eq!(home_tree(fixture.home()), tree); + assert_eq!(record(&fixture)["agents"]["gemini-cli"], true); + let gemini = agent(&report, "gemini-cli"); + assert_eq!(gemini.availability, Availability::NotInstalled); + assert!(gemini.enabled, "the switch stays so it can be turned off"); + assert!(!gemini.needs_attention(), "nothing for Reinstall to do"); + for piece in [&gemini.skill, gemini.hook.as_ref().unwrap()] { + assert_eq!(piece.state, ComponentState::Absent, "{gemini:?}"); + assert!( + piece + .reason + .as_deref() + .unwrap() + .contains("`gemini` is not found"), + "{piece:?}" + ); + } + + // The switch still takes Hide's pieces out. + let report = apply(&fixture.target, &Scope::agents([], ["gemini-cli"])); + + assert!(!agent(&report, "gemini-cli").enabled); + assert!(!shared_skill(&fixture).exists()); + assert!( + !std::fs::read_to_string(gemini_settings(&fixture)) + .map(|text| text.contains("hide-guidance")) + .unwrap_or(false) + ); +} + +/// A stand-in login shell that puts `~/.grok/bin` on its `PATH`, as Grok's +/// installer does in `~/.zshrc`, and counts how often it is asked. Its `PATH` +/// is that folder alone, so this process's own `PATH` stays out of the +/// search as in every other test. +fn grok_login_shell(fixture: &Fixture) -> PathBuf { + let shell = fixture.root.join("bin/login-shell"); + version_program( + &shell, + &format!( + "#!/bin/sh\n[ \"$1\" = -ilc ] || exit 64\necho x >> '{}'\necho 'Last login: today'\nPATH=\"$HOME/.grok/bin\"\nexport PATH\neval \"$2\"\n", + fixture.root.join("shell-asked").display() + ), + ); + shell +} + +#[test] +fn a_program_on_the_login_shells_path_is_installed_and_the_shell_is_asked_again_only_after_its_files_change() + { + let mut fixture = Fixture::new(); + executable(&fixture.home().join(".grok/bin/grok"), "#!/bin/sh\n"); + assert_eq!( + agent(&status(&fixture.target), "grok").availability, + Availability::NotInstalled, + "no other folder this test searches holds it" + ); + fixture.target.login_shell = Some(grok_login_shell(&fixture)); + let asked = || { + std::fs::read_to_string(fixture.root.join("shell-asked")) + .map(|text| text.lines().count()) + .unwrap_or(0) + }; + + for _ in 0..3 { + assert_eq!( + agent(&status(&fixture.target), "grok").availability, + Availability::Available + ); + } + assert_eq!(asked(), 1, "Settings re-reads the kit every few seconds"); + + // An installer that adds its folder edits a startup file. + std::fs::write( + fixture.home().join(".zshrc"), + "export PATH=\"$HOME/.kilo/bin:$PATH\"\n", + ) + .unwrap(); + status(&fixture.target); + assert_eq!(asked(), 2); +} + #[test] fn a_cli_version_is_asked_once_however_often_the_kit_is_read() { let fixture = Fixture::new(); @@ -608,7 +721,7 @@ fn the_switch_works_while_either_the_skill_or_the_hook_does_here() { #[test] fn a_machine_the_kit_has_never_touched_waits_for_the_first_choice_before_any_agent_gets_anything() { let fixture = Fixture::fresh(); - set_up(&fixture, ".codex"); + install(&fixture, "codex", ".codex"); let report = apply(&fixture.target, &Scope::automatic()); @@ -657,7 +770,7 @@ fn a_machine_the_kit_has_never_touched_waits_for_the_first_choice_before_any_age #[test] fn answering_with_nothing_chosen_is_still_an_answer() { let fixture = Fixture::fresh(); - set_up(&fixture, ".codex"); + install(&fixture, "codex", ".codex"); assert!(apply(&fixture.target, &Scope::automatic()).held_for_onboarding); let answered = apply(&fixture.target, &Scope::first_run([])); @@ -702,13 +815,13 @@ fn a_machine_with_a_record_keeps_what_it_had_when_this_build_arrives() { #[cfg(unix)] #[test] fn cursor_augment_and_junie_get_the_guidance_hook_with_the_switch_and_lose_it_with_it() { - for (id, folder, file) in [ - ("cursor", ".cursor", ".cursor/hooks.json"), - ("augment", ".augment", ".augment/settings.json"), - ("junie", ".junie", ".junie/config.json"), + for (id, program, folder, file) in [ + ("cursor", "cursor-agent", ".cursor", ".cursor/hooks.json"), + ("augment", "auggie", ".augment", ".augment/settings.json"), + ("junie", "junie", ".junie", ".junie/config.json"), ] { let fixture = Fixture::new(); - set_up(&fixture, folder); + install(&fixture, program, folder); let report = apply(&fixture.target, &Scope::agents([id], [])); From 5560fde2151a564fff4add5abecfde07552e29cc Mon Sep 17 00:00:00 2001 From: yansfil Date: Tue, 6 Oct 2026 16:43:05 +0900 Subject: [PATCH 3/7] Say Not installed for agents whose program is not found The Settings line for agents with no switch read "Not set up on this machine"; it now reads "Not installed on this machine" under the key settings.agentsNotInstalled, matching the onboarding tile and the other languages. Comments that defined a tile's or row's switch by "set up" now say installed. --- web/src/AgentOnboarding.tsx | 2 +- web/src/SettingsSheet.tsx | 6 +++--- web/src/agentOnboardingRules.test.ts | 2 +- web/src/agentOnboardingRules.ts | 4 ++-- web/src/i18n/resources/settings.ts | 8 ++++---- web/src/settings.test.ts | 10 +++++----- web/src/settings.ts | 8 ++++---- 7 files changed, 20 insertions(+), 20 deletions(-) diff --git a/web/src/AgentOnboarding.tsx b/web/src/AgentOnboarding.tsx index 09c52ba495..e1519156eb 100644 --- a/web/src/AgentOnboarding.tsx +++ b/web/src/AgentOnboarding.tsx @@ -67,7 +67,7 @@ function AgentOnboarding({ actions, agents }: { actions: Actions; agents: KitAge /** * One square tile: the agent's logo (or a monogram when no official mark may * be bundled) and its name. On or off is a mark and a word as well as a - * colour; a tile for an agent that is not set up here is dimmed and has no + * colour; a tile for an agent that is not installed here is dimmed and has no * switch. */ function AgentTile({ agent, on, onToggle }: { agent: KitAgent; on: boolean; onToggle: () => void }) { diff --git a/web/src/SettingsSheet.tsx b/web/src/SettingsSheet.tsx index f35fbb5c3a..61abac9f82 100644 --- a/web/src/SettingsSheet.tsx +++ b/web/src/SettingsSheet.tsx @@ -573,13 +573,13 @@ function AgentsTab({ actions }: { actions: Actions }) { note={t("settings.agentHooksDescription")} data-agent-hooks="true" > - {machines.map(({ device, setUp, others, unavailable }) => ( + {machines.map(({ device, listed, others, unavailable }) => (
{device.id === "local" ? t("common.thisMac") : device.label}} detail={unavailable ? {unavailable} : device.kit?.components.length === 0 ? {t("settings.notChecked")} : null} /> - {setUp.map((agent) => { + {listed.map((agent) => { const line = kitAgentLine(agent, t); const switched = kitAgentSwitch(agent); return ( @@ -625,7 +625,7 @@ function AgentsTab({ actions }: { actions: Actions }) { ); })} {others.length > 0 ? ( - {t("settings.agentsNotSetUp", { agents: others.join(", ") })}} /> + {t("settings.agentsNotInstalled", { agents: others.join(", ") })}} /> ) : null}
))} diff --git a/web/src/agentOnboardingRules.test.ts b/web/src/agentOnboardingRules.test.ts index f6d398bfaf..61924e4686 100644 --- a/web/src/agentOnboardingRules.test.ts +++ b/web/src/agentOnboardingRules.test.ts @@ -16,7 +16,7 @@ const agent = (id: string, availability: KitAgent["availability"]): KitAgent => describe("the first-run agent choice", () => { const agents = [agent("claude-code", "available"), agent("cursor", "not_installed"), agent("codex", "available"), agent("amp", "unsupported_system")]; - it("starts with the agents that are set up on, and never switches on one that is not", () => { + it("starts with the agents that are installed on, and never switches on one that is not", () => { expect([...selection(agents, new Set())]).toEqual(["claude-code", "codex"]); // The operator's flip turns one off; a flip of a tile with no switch changes nothing. expect([...selection(agents, new Set(["codex", "cursor"]))]).toEqual(["claude-code"]); diff --git a/web/src/agentOnboardingRules.ts b/web/src/agentOnboardingRules.ts index 93b69e591a..82fe9e8f8a 100644 --- a/web/src/agentOnboardingRules.ts +++ b/web/src/agentOnboardingRules.ts @@ -3,7 +3,7 @@ import type { KitAgent } from "./snapshot"; /** - * What the tiles show: an agent set up on the machine starts on, and the + * What the tiles show: an agent installed on the machine starts on, and the * operator's flips (the ids they toggled) turn it off. Read from the live * availability each time, so an agent that becomes available while the dialog * is open shows on, and Apply sends exactly what is drawn. The operator turns @@ -13,7 +13,7 @@ export function selection(agents: readonly KitAgent[], flipped: ReadonlySet tileSwitchable(agent) && !flipped.has(agent.id)).map((agent) => agent.id)); } -/** A tile has a switch only where the agent is set up here. */ +/** A tile has a switch only where the agent is installed here. */ export function tileSwitchable(agent: KitAgent): boolean { return agent.availability === "available"; } diff --git a/web/src/i18n/resources/settings.ts b/web/src/i18n/resources/settings.ts index 284ecf9896..cb7c9a6f16 100644 --- a/web/src/i18n/resources/settings.ts +++ b/web/src/i18n/resources/settings.ts @@ -92,7 +92,7 @@ export const settingsEnglish = { "settings.agentHooksDescription": "Hide gives each agent set up on a machine, This Mac and each device, a skill that points at `hide browser help` and, where the agent documents one, a session hook. Switching an agent off takes out only Hide's own entries and never touches another tool's. Something you removed stays removed until you press Reinstall.", "settings.agentGetsSkillHook": "Skill and session hook", "settings.agentGetsSkill": "Skill only", - "settings.agentsNotSetUp": "Not set up on this machine: {{agents}}", + "settings.agentsNotInstalled": "Not installed on this machine: {{agents}}", "onboarding.title": "Choose the agents Hide works with", "onboarding.description": "Each agent you leave on gets a skill for driving Hide's browser and, where the agent supports one, a session hook. Hide edits only its own entries, and you can change this any time in Settings, Agents.", "onboarding.devices": "Connected devices get the same choice, each by what is installed there.", @@ -232,7 +232,7 @@ const ko = { "settings.agentHooksDescription": "Hide는 이 Mac과 각 기기에 설치된 에이전트마다 `hide browser help`를 가리키는 스킬을 넣고, 에이전트가 훅을 문서화했다면 세션 훅도 넣습니다. 에이전트를 끄면 Hide가 넣은 항목만 빠지고 다른 도구의 설정은 건드리지 않습니다. 직접 제거한 항목은 다시 설치를 누를 때까지 그대로 둡니다.", "settings.agentGetsSkillHook": "스킬과 세션 훅", "settings.agentGetsSkill": "스킬만", - "settings.agentsNotSetUp": "이 기기에 설치되지 않음: {{agents}}", + "settings.agentsNotInstalled": "이 기기에 설치되지 않음: {{agents}}", "onboarding.title": "Hide와 함께 쓸 에이전트를 고르세요", "onboarding.description": "켜 둔 에이전트에는 Hide 브라우저를 다루는 스킬과, 에이전트가 지원하면 세션 훅이 들어갑니다. Hide는 자기 항목만 수정하며, 선택은 언제든 설정의 에이전트에서 바꿀 수 있습니다.", "onboarding.devices": "연결된 기기에도 같은 선택이 적용되며, 각 기기에 설치된 에이전트 기준입니다.", @@ -372,7 +372,7 @@ const ja = { "settings.agentHooksDescription": "Hideは、このMacと各デバイスにあるエージェントごとに、`hide browser help` を指すスキルと、エージェントがフックを文書化している場合はセッションフックを入れます。エージェントをオフにすると Hide が入れた項目だけが外れ、ほかのツールの設定は変更しません。自分で削除したものは「再インストール」を押すまで削除されたままです。", "settings.agentGetsSkillHook": "スキルとセッションフック", "settings.agentGetsSkill": "スキルのみ", - "settings.agentsNotSetUp": "このデバイスにはありません: {{agents}}", + "settings.agentsNotInstalled": "このデバイスにはありません: {{agents}}", "onboarding.title": "Hideで使うエージェントを選びます", "onboarding.description": "オンのままにしたエージェントには、Hideのブラウザを操作するスキルと、対応していればセッションフックが入ります。Hideは自分の項目だけを編集し、設定のエージェントでいつでも変更できます。", "onboarding.devices": "接続中のデバイスにも同じ選択が適用され、各デバイスにインストールされているものだけが対象です。", @@ -512,7 +512,7 @@ const zhCN = { "settings.agentHooksDescription": "Hide 会为此 Mac 和各设备上已安装的每个智能体放入一个指向 `hide browser help` 的技能,并在智能体文档说明支持时放入会话钩子。关闭智能体只会移除 Hide 自己的条目,不会更改其他工具的条目。你自己移除的内容只会在点击“重新安装”后恢复。", "settings.agentGetsSkillHook": "技能和会话钩子", "settings.agentGetsSkill": "仅技能", - "settings.agentsNotSetUp": "此设备上未安装:{{agents}}", + "settings.agentsNotInstalled": "此设备上未安装:{{agents}}", "onboarding.title": "选择与 Hide 配合的智能体", "onboarding.description": "保持开启的智能体会获得操作 Hide 浏览器的技能,并在智能体支持时获得会话钩子。Hide 只修改自己的条目,你可以随时在设置的智能体中更改。", "onboarding.devices": "已连接的设备也会得到同样的选择,以各设备上已安装的为准。", diff --git a/web/src/settings.test.ts b/web/src/settings.test.ts index e0fc0e219a..779034f6c7 100644 --- a/web/src/settings.test.ts +++ b/web/src/settings.test.ts @@ -274,17 +274,17 @@ describe("the install kit rows (PRD device-parity B7, B8, B27)", () => { expect(kitPartLine(part("codex_per_pane", "off"))).toEqual({ text: "Off", tone: "muted" }); }); - it("lists This Mac first and then each device, with the agents that are set up and the labels of the rest", () => { + it("lists This Mac first and then each device, with the agents that are installed and the labels of the rest", () => { const set = [agent("codex", { hook: piece("installed") }), agent("gemini-cli", { enabled: false, skill: piece("off") }), agent("cursor", { availability: "not_installed", enabled: false, skill: piece("off") })]; const local = device({ id: "local", label: "mini", kind: "local", state: "ready", ssh_alias: null, kit: kit([part("cli", "installed")], null, set) }); const studio = device({ kit: kit([], "Allow the helper to install Hide on Studio") }); const unchecked = device({ id: "box", label: "Box" }); const machines = kitAgentMachines([local, studio, unchecked]); expect(machines.map((machine) => machine.device.id)).toEqual(["local", "studio", "box"]); - expect(machines[0]?.setUp.map((row) => row.id)).toEqual(["codex", "gemini-cli"]); + expect(machines[0]?.listed.map((row) => row.id)).toEqual(["codex", "gemini-cli"]); expect(machines[0]?.others).toEqual(["cursor"]); - expect(machines[1]).toMatchObject({ setUp: [], others: [], unavailable: "Allow the helper to install Hide on Studio" }); - expect(machines[2]).toMatchObject({ setUp: [], unavailable: null }); + expect(machines[1]).toMatchObject({ listed: [], others: [], unavailable: "Allow the helper to install Hide on Studio" }); + expect(machines[2]).toMatchObject({ listed: [], unavailable: null }); }); it("words an agent by its switch and its worst piece, and switches only what can be switched (issue #517)", () => { @@ -299,7 +299,7 @@ describe("the install kit rows (PRD device-parity B7, B8, B27)", () => { expect(kitAgentSwitch(agent("a"))).toEqual({ on: true }); expect(kitAgentSwitch(agent("a", { enabled: false }))).toEqual({ on: false }); expect(kitAgentSwitch(agent("a", { availability: "not_installed", enabled: false }))).toBeNull(); - // An agent that is on keeps its switch even where it can no longer be set up. + // An agent that is on keeps its switch even where its program is no longer found. expect(kitAgentSwitch(agent("a", { availability: "not_installed" }))).toEqual({ on: true }); expect(kitAgentNeedsReinstall(agent("a", { hook: piece("removed") }))).toBe(true); expect(kitAgentNeedsReinstall(agent("a", { enabled: false, skill: piece("removed") }))).toBe(false); diff --git a/web/src/settings.ts b/web/src/settings.ts index 49470dea52..3dac3207cb 100644 --- a/web/src/settings.ts +++ b/web/src/settings.ts @@ -340,7 +340,7 @@ export function kitAgentLine(agent: KitAgent, t: Translate): { text: string; ton } /** - * The agent's switch: an agent set up on the machine can be switched; one + * The agent's switch: an agent installed on the machine can be switched; one * that is not has nothing to switch, and one that is on keeps a switch so it * can be turned off. */ @@ -361,19 +361,19 @@ export function kitAgentGets(agent: KitAgent, t: Translate): string { /** * Every machine's agents for the Agents tab (B27): This Mac first, then each - * device in the Devices tab's order. `setUp` are the agents on the machine + * device in the Devices tab's order. `listed` are the agents installed there * (or on, which the operator can still turn off); `others` are the labels of * the rest, which have nothing to switch. A machine whose kit does not run * carries its reason instead of rows; one not checked yet carries neither. */ -export function kitAgentMachines(devices: readonly Device[]): { device: Device; setUp: KitAgent[]; others: string[]; unavailable: string | null }[] { +export function kitAgentMachines(devices: readonly Device[]): { device: Device; listed: KitAgent[]; others: string[]; unavailable: string | null }[] { return devices .filter((device) => device.kind === "remote" || device.id === "local") .map((device) => { const agents = device.kit?.agents ?? []; return { device, - setUp: agents.filter((agent) => kitAgentSwitch(agent) !== null), + listed: agents.filter((agent) => kitAgentSwitch(agent) !== null), others: agents.filter((agent) => kitAgentSwitch(agent) === null).map((agent) => agent.label), unavailable: device.kit?.unavailable ?? null, }; From 9ca08f027f9f4e31c4847a1176c6ebd4a3c2f2a8 Mon Sep 17 00:00:00 2001 From: yansfil Date: Tue, 6 Oct 2026 16:51:31 +0900 Subject: [PATCH 4/7] Leave a stopped login shell read unlogged and unremembered When the kit's owner goes away (Hide quitting, a device connection closing) the shell read is cut short on purpose; that is not a failure to log or a PATH to remember for the next pass. --- hide-kit/src/agents.rs | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/hide-kit/src/agents.rs b/hide-kit/src/agents.rs index f795641edb..4a3c0adcbb 100644 --- a/hide-kit/src/agents.rs +++ b/hide-kit/src/agents.rs @@ -597,21 +597,26 @@ fn login_shell_path(target: &KitTarget) -> Option { return answer.path.clone(); } let asked = Instant::now(); - let path = hide_platform::host::login_shell_path( + let path = match hide_platform::host::login_shell_path( shell, &target.home, LOGIN_SHELL_DEADLINE, &target.stop, - ) - .inspect_err(|error| { - eprintln!( - "kit.login_shell_unread shell={} kind={:?} elapsed_ms={}", - shell.display(), - error.kind(), - asked.elapsed().as_millis() - ); - }) - .ok(); + ) { + Ok(path) => Some(path), + // The kit's owner is going away (Hide quitting, a device's + // connection closed): nothing failed, and nothing is remembered. + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => return None, + Err(error) => { + eprintln!( + "kit.login_shell_unread shell={} kind={:?} elapsed_ms={}", + shell.display(), + error.kind(), + asked.elapsed().as_millis() + ); + None + } + }; if let Ok(mut answer) = ANSWER.lock() { *answer = Some(ShellAnswer { shell: shell.to_path_buf(), From 95f0751a5f1340675947370cac9aa40049b4d144 Mon Sep 17 00:00:00 2001 From: yansfil Date: Tue, 6 Oct 2026 16:51:31 +0900 Subject: [PATCH 5/7] Put the agents' programs in the first-run e2e home An agent now counts as installed only when its program is found, so the fixture home carries `claude` and `gemini` in ~/.local/bin. --- web/e2e/agent-onboarding.spec.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/web/e2e/agent-onboarding.spec.ts b/web/e2e/agent-onboarding.spec.ts index b1b106f093..421cf8f66d 100644 --- a/web/e2e/agent-onboarding.spec.ts +++ b/web/e2e/agent-onboarding.spec.ts @@ -13,11 +13,16 @@ const modal = (page: Page) => page.locator("[data-agent-onboarding]"); const tile = (page: Page, id: string, state: string) => page.locator(`[data-onboarding-tile="${id}:${state}"]`); const read = (file: string) => (fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""); -/** A private HOME with two agents set up, a kit record only when `record`, and a daemon that runs the kit. */ +/** + * A private HOME with two agents installed (a program in `~/.local/bin`, which the kit searches, and the + * folder each agent makes), a kit record only when `record`, and a daemon that runs the kit. + */ async function start(record: boolean) { const herdr = await startHerdr(); const home = path.join(fs.mkdtempSync(path.join(herdr.root, "ob-")), "home"); for (const folder of [".claude", ".gemini"]) fs.mkdirSync(path.join(home, folder), { recursive: true }); + fs.mkdirSync(path.join(home, ".local", "bin"), { recursive: true }); + for (const program of ["claude", "gemini"]) fs.writeFileSync(path.join(home, ".local", "bin", program), "#!/bin/sh\n", { mode: 0o755 }); if (record) { fs.mkdirSync(path.join(home, ".hide", "kit"), { recursive: true }); fs.writeFileSync(path.join(home, ".hide", "kit", "installed.json"), JSON.stringify({ format: 1, installed: [] })); @@ -30,7 +35,7 @@ async function open(page: Page, daemon: Daemon) { await page.goto(`${daemon.origin}/#token=${daemon.token}`); } -test("a Mac with no kit record is asked once, the set-up agents are on, and Apply writes only what is left on", async ({ page }) => { +test("a Mac with no kit record is asked once, the installed agents are on, and Apply writes only what is left on", async ({ page }) => { const { daemon, home } = await start(false); try { await open(page, daemon); From 9d8289063f96fe6fd2cccb36ab670d0678193a32 Mon Sep 17 00:00:00 2001 From: yansfil Date: Tue, 6 Oct 2026 16:55:38 +0900 Subject: [PATCH 6/7] Say installed in the Agents settings note in English and Japanese Korean and Chinese already describe the agents Hide equips as the ones installed on a machine; the English and Japanese note now say the same. --- web/src/i18n/resources/settings.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/web/src/i18n/resources/settings.ts b/web/src/i18n/resources/settings.ts index cb7c9a6f16..fbd7067526 100644 --- a/web/src/i18n/resources/settings.ts +++ b/web/src/i18n/resources/settings.ts @@ -89,7 +89,7 @@ export const settingsEnglish = { "settings.modelsUnavailable": "Models could not be listed ({{reason}}); only the configured one is offered.", "settings.backgroundDegraded": "{{agent}}: {{status}}. Background requests go to the other agent until {{agent}} can answer.", "settings.agentHooks": "Agent skills and hooks", - "settings.agentHooksDescription": "Hide gives each agent set up on a machine, This Mac and each device, a skill that points at `hide browser help` and, where the agent documents one, a session hook. Switching an agent off takes out only Hide's own entries and never touches another tool's. Something you removed stays removed until you press Reinstall.", + "settings.agentHooksDescription": "Hide gives each agent installed on a machine, This Mac and each device, a skill that points at `hide browser help` and, where the agent documents one, a session hook. Switching an agent off takes out only Hide's own entries and never touches another tool's. Something you removed stays removed until you press Reinstall.", "settings.agentGetsSkillHook": "Skill and session hook", "settings.agentGetsSkill": "Skill only", "settings.agentsNotInstalled": "Not installed on this machine: {{agents}}", @@ -369,7 +369,7 @@ const ja = { "settings.modelsUnavailable": "モデル一覧を取得できませんでした({{reason}})。設定済みのモデルのみ表示します。", "settings.backgroundDegraded": "{{agent}}:{{status}}。{{agent}}が応答できるようになるまで、バックグラウンド要求はもう一方のエージェントが処理します。", "settings.agentHooks": "エージェントのスキルとフック", - "settings.agentHooksDescription": "Hideは、このMacと各デバイスにあるエージェントごとに、`hide browser help` を指すスキルと、エージェントがフックを文書化している場合はセッションフックを入れます。エージェントをオフにすると Hide が入れた項目だけが外れ、ほかのツールの設定は変更しません。自分で削除したものは「再インストール」を押すまで削除されたままです。", + "settings.agentHooksDescription": "Hideは、このMacと各デバイスにインストールされているエージェントごとに、`hide browser help` を指すスキルと、エージェントがフックを文書化している場合はセッションフックを入れます。エージェントをオフにすると Hide が入れた項目だけが外れ、ほかのツールの設定は変更しません。自分で削除したものは「再インストール」を押すまで削除されたままです。", "settings.agentGetsSkillHook": "スキルとセッションフック", "settings.agentGetsSkill": "スキルのみ", "settings.agentsNotInstalled": "このデバイスにはありません: {{agents}}", From 56b090a8da221fd3d3595b9d1c81b1b4f0888b21 Mon Sep 17 00:00:00 2001 From: yansfil Date: Tue, 6 Oct 2026 17:29:24 +0900 Subject: [PATCH 7/7] Give the package smoke's home the agents' programs An agent counts as installed only when its program is found, so the smoke's private home now carries stand-in `claude` and `codex` programs in ~/.local/bin, which the kit searches on Linux and Windows. Without them the first-run answer installs the hooks but is not recorded, and the upgraded package's pass reads both hooks off. --- desktop/scripts/smoke-package.mjs | 11 ++++++++++- docs/BUILD.md | 2 +- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/desktop/scripts/smoke-package.mjs b/desktop/scripts/smoke-package.mjs index 2ee3fa94dd..060e913465 100644 --- a/desktop/scripts/smoke-package.mjs +++ b/desktop/scripts/smoke-package.mjs @@ -10,7 +10,7 @@ // folder: Herdr reports the pinned version, the device helper and the hook // helper start, and the bundled // `hide connect` starts the bundled daemon, which serves the web shell it -// embeds, installs the CLI and holds both agents for the first-run choice +// embeds, installs the CLI and holds both installed agents for the first-run choice // (their files untouched), installs both hooks once that choice is answered // over the daemon's socket, and is replaced by a second // package fixture with a changed daemon hash, before `hide stop` ends it. Every process runs with a private home @@ -135,6 +135,15 @@ try { }); delete isolated.XDG_STATE_HOME; + // Both runtimes are installed: an agent counts only when its program is + // found, and the kit searches `~/.local/bin` on every system. The stand-ins + // answer nothing, and a version Hide cannot read does not hold a hook back. + const programs = path.join(home, ".local", "bin"); + fs.mkdirSync(programs, { recursive: true }); + for (const name of ["claude", "codex"]) { + if (process.platform === "win32") fs.writeFileSync(path.join(programs, `${name}.cmd`), "@exit /b 0\r\n"); + else fs.writeFileSync(path.join(programs, name), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + } // Both runtimes are configured, with an unrelated hook we must preserve. for (const [folder, file] of [[".claude", "settings.json"], [".codex", "hooks.json"]]) { fs.mkdirSync(path.join(home, folder)); diff --git a/docs/BUILD.md b/docs/BUILD.md index 1eea0395b6..d8ed16f4da 100644 --- a/docs/BUILD.md +++ b/docs/BUILD.md @@ -94,7 +94,7 @@ An acquisition failure blocks the suite at that prerequisite and retains the ups | `pnpm --dir desktop typecheck`, `lint`, `test` | The desktop CI lane | | `pnpm --dir desktop e2e` | Playwright `_electron` against a private hided and pinned Herdr; needs `web/dist`, `target/debug/hide` and `hided`, and the pinned `herdr` as the web e2e does | | `pnpm --dir desktop package` | `desktop/scripts/package.mjs`: builds the release binaries and fetches the pinned Herdr, bundles `hided`, `hide`, `hide-agent-hooks`, `hide-host-helper-macos-` and `herdr` into `Contents/Resources`, ad-hoc signs `desktop/out/hide-darwin-/hide.app` (bundle id `me.grab.hide.desktop`), and archives it to `desktop/out/hide-v-macos-.zip` beside a `.sha256` checksum; nothing is notarized or installed. On Windows x64 and Linux x64 the same command builds that system's package, unsigned: the folder `desktop/out/hide-win32-x64/` or `hide-linux-x64/` with the same binaries (`.exe` on Windows, with Herdr's `conpty/` beside `herdr.exe`) and `hide-host-helper--x86_64` in its `resources/`, archived to `hide-v-windows-x64.zip` (the system's `tar.exe`) or `hide-v-linux-x64.tar.gz` beside a `.sha256`. Each system packages only itself, and a machine of another architecture than its pinned Herdr asset is refused | -| `node desktop/scripts/smoke-package.mjs ` | On Windows or Linux only: checks a package against its `.sha256`, unpacks it into a temporary folder, and with a private home and state folder runs the bundled `herdr --version`, the device helper, `hide-agent-hooks doctor`, and `hide connect`, `/health`, the embedded shell, first-launch CLI and hooks, a command from a fresh shell, the completed retirement row, replacement by a second package fixture, refreshed paths, same-build reuse, standalone refusal and `hide stop`, then waits for each daemon pid it started to end (ten seconds, a named failure beyond that) before it removes the folder, with no removal retry; `.github/workflows/package.yml` runs it after each package. It refuses macOS, where first-launch kit behavior is covered by the isolated desktop suite | +| `node desktop/scripts/smoke-package.mjs ` | On Windows or Linux only: checks a package against its `.sha256`, unpacks it into a temporary folder, and with a private home (stand-in `claude` and `codex` programs in `~/.local/bin`, so both agents are installed) and state folder runs the bundled `herdr --version`, the device helper, `hide-agent-hooks doctor`, and `hide connect`, `/health`, the embedded shell, first-launch CLI and hooks, a command from a fresh shell, the completed retirement row, replacement by a second package fixture, refreshed paths, same-build reuse, standalone refusal and `hide stop`, then waits for each daemon pid it started to end (ten seconds, a named failure beyond that) before it removes the folder, with no removal retry; `.github/workflows/package.yml` runs it after each package. It refuses macOS, where first-launch kit behavior is covered by the isolated desktop suite | The app attaches to whatever daemon the environment names: without `HIDE_STATE_DIR` it is the operator's own at `~/.hide/state`. For QA, set `HIDE_STATE_DIR`, `HOME`, `HERDR_SOCKET_PATH` and `HIDE_DESKTOP_USER_DATA_DIR` to private paths, as `desktop/e2e/fixture.ts` does and refuses to launch without.