mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-12-01 08:59:32 +01:00
Merge #773 feat(desktop): install Codeman from the app, with no Terminal and no password
Conflicts resolved as on test/desktop-macbook: install.sh usage() lists CODEMAN_NO_ADMIN=1 or 0 and #773's CODEMAN_AI_CLI and CODEMAN_PROGRESS=1; probe.rs keeps #781's agent() with TIMEOUT, MAX_BODY and probe_within all pub; the desktop README keeps both known-limits entries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
4b349b57f6
16 files changed
+4699
-227
No files matched your search
+97
-17
@@ -28,9 +28,9 @@ cannot do.
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| **This Mac** | The connect screen's first tab looks for Codeman on this Mac and offers what fits: *Open Codeman* when it runs, *Start Codeman* when it is installed but stopped, *Install Codeman on this Mac* when it is not there. The address comes from Codeman's LaunchAgent (port, sub-path, HTTPS). When nothing answers there but one of your own Codeman servers runs (found with `ps` and `lsof`: a `codeman web --port 4000` in a terminal, say), the tab opens that one, or says where it listens; it never offers to start a second server, which would take over the first one's sessions, and Start refuses while one runs. A server that runs but listens nowhere yet (the first seconds after login, a restart) shows as *starting*: the tab looks again every second and, when a connect to this Mac had just been refused, opens Codeman once it is up. Start asks launchd to run the LaunchAgent (`kickstart`, or `bootstrap` when it is not loaded), so the server keeps its own settings and supervision; without a LaunchAgent it runs `codeman web -d`. The login comes from where Codeman keeps it: the LaunchAgent's `CODEMAN_USERNAME`/`CODEMAN_PASSWORD`, else `~/.codeman/.env` (what Codeman's command-line clients read), `admin` by default. It goes only to `127.0.0.1` on that Codeman's port, only while one of your own Codeman processes holds that port, is never saved to the Keychain, and never reaches the page. Whether Codeman is installed is looked up in its files and processes, then the login shell; the interactive profile (nvm in `.zshrc`, say) only on *Check again*. Install opens Terminal with Codeman's installer (`install.sh --local --service --port N`): it may ask for the Mac password (Homebrew, Node.js, tmux) and which AI coding tools to set up, then Codeman runs as a LaunchAgent, so it keeps running when the app quits and starts at login. *Also reach it from my phone and other computers* drops `--local`, and the installer asks how (Tailscale, or the local network with a password). Port 3000 is used unless something else answers there, then the next free one. While the installer runs, the app looks every 3 seconds and opens Codeman as soon as it answers; it stops looking after the first answer, after 30 minutes, or 90 seconds after a finished install whose server never answered (then it offers Start). An install still running in Terminal is recognized by its process, so the tab waits for it instead of offering Install twice. |
|
||||
| **This Mac** | The connect screen's first tab looks for Codeman on this Mac and offers what fits: *Open Codeman* when it runs, *Start Codeman* when it is installed but stopped, *Install Codeman on this Mac* when it is not there. The address comes from Codeman's LaunchAgent (port, sub-path, HTTPS). The tab also finds every Codeman server of yours that already runs on this Mac (with `ps` and `lsof`: a `codeman web --port 4000` in a terminal, a beta instance beside the installed one) and recommends connecting to it. Each one's address is worked out from its listening socket and its command line (`127.0.0.1` for a bind to loopback or to every interface, its own address for a bind to one, `https` with `--https`, the path of `--base-url`), and each is asked once whether Codeman answers there. When nothing answers at the usual address (the LaunchAgent's, or `http://127.0.0.1:3000` without one), *Open Codeman* is for the first found server that does; when none of them can be opened, the tab says *Codeman is already running on this Mac* and lists them. Next to a Codeman that answers, the others are listed under *Also running on this Mac*. A row shows the address, the version, and a *Connect* button, or the reason the app cannot open that one (HTTPS with Codeman's own certificate, no answer). *Connect* is the connect of the Another machine tab with that address filled in: the same check, the login saved for it, the same entry under recent servers. Finding a server connects to nothing by itself. The tab never offers to start a second server, which would take over the first one's sessions, and Start refuses while one runs. A server that runs but listens nowhere yet (the first seconds after login, a restart) shows as *starting*: the tab looks again every second and, when a connect to this Mac had just been refused, opens Codeman once it is up. Start asks launchd to run the LaunchAgent (`kickstart`, or `bootstrap` when it is not loaded), so the server keeps its own settings and supervision; without a LaunchAgent it runs `codeman web -d`. The login comes from where Codeman keeps it: the LaunchAgent's `CODEMAN_USERNAME`/`CODEMAN_PASSWORD`, else `~/.codeman/.env` (what Codeman's command-line clients read), `admin` by default. It goes only to `127.0.0.1` on that Codeman's port, only while one of your own Codeman processes holds that port, is never saved to the Keychain, and never reaches the page. Whether Codeman is installed is looked up in its files and processes, then the login shell; the interactive profile (nvm in `.zshrc`, say) only on *Check again*. Install sets Codeman up from the app itself, with no Terminal and no password (see Decisions). It fetches the installer, asks it what is on this Mac, then asks two things: which coding agent to install, only when this Mac has none (the list comes from the installer, and *Skip for now* is there), and who can reach Codeman (this Mac only, or the local network with a password). A checklist follows the install, the installer's output is one click away, and Cancel stops it; installing again picks up where it stopped. Codeman runs as a LaunchAgent, so it keeps running when the app quits and starts at login. Port 3000 is used unless something else answers there, then the next free one. Closing the app does not stop an install: it runs on its own, and the app picks it up when it opens again. When it is done the app looks every 3 seconds and opens Codeman as soon as it answers; it stops looking after the first answer, after 30 minutes, or 90 seconds after a finished install whose server never answered (then it offers Start). *Install in Terminal instead* runs the installer in a Terminal window, for what the app cannot do (see Known limits): it may ask for the Mac password (Homebrew) and asks its own questions there. The app offers it by itself on a Mac where the graphical install cannot finish. An install still running in Terminal is recognized by its process, so the tab waits for it instead of offering Install twice. *Add a coding agent*, on this tab and in the app menu whenever Codeman is on this Mac, is the same chooser after the install: pick one agent, watch it install, open Codeman. It needs no password, leaves a running Codeman alone, and can be cancelled or left running like an install. After *Skip for now* the app says Codeman has no agent yet and offers this before it opens Codeman. |
|
||||
| **Another machine** | The second tab connects to a server by address (below). *Codeman is not installed there yet?* opens Terminal, connects with `ssh -t` and runs Codeman's installer on that machine, which asks its questions there; the app then suggests `http://<host>:3000` and the installer prints the real address at the end. The SSH login is checked to the characters of a user and host name (no option can be slipped in) and may carry a `:port`. The remote command runs under `bash -o pipefail`, so a failed download fails the install instead of reporting success. The same tab shows the one-line install command, with a Copy button, to run on a machine by hand. |
|
||||
| **Connect screen** | Server address, recent servers, a login for password-protected servers (password kept in the macOS Keychain), auto-connect at launch. An address typed without `http://` or `https://` gets `http://`, except a tailnet name with no port (`machine.tailnet.ts.net`, which is `tailscale serve`), which gets `https://`. It explains each failure: nothing listening; wrong password; too many failed logins (the password field stays open, since a single-user Codeman accepts the right password even then); unknown host name; an address this Mac cannot reach (with a pointer to the Local Network setting); an `http://` address on a port that only speaks HTTPS; an untrusted certificate; a redirect, with a button for the suggested `https://` address; not a Codeman server. A multi-user account that must change its password connects, and Codeman's own dialog asks for the new one. If the server page has not started showing within 15 seconds, or you press Cancel while it opens, the connect screen comes back with a notice. A login that would cross the network over plain `http://` to another machine says so. Return opens or starts the Codeman on this Mac and Esc cancels a connect, as in a Mac dialog (Install always takes a click). On a Mac whose WebKit is too old for Codeman it says so and Connect stays off (see Known limits). |
|
||||
| **Connect screen** | Server address, recent servers, a login for password-protected servers (password kept in the macOS Keychain), auto-connect at launch. An address typed without `http://` or `https://` gets `http://`, except a tailnet name with no port (`machine.tailnet.ts.net`, which is `tailscale serve`), which gets `https://`. It explains each failure: nothing listening; wrong password; too many failed logins (the password field stays open, since a single-user Codeman accepts the right password even then); unknown host name; an address this Mac cannot reach (with a pointer to the Local Network setting); an `http://` address on a port that only speaks HTTPS; an untrusted certificate; a redirect, with a button for the suggested `https://` address; not a Codeman server. A multi-user account that must change its password connects, and Codeman's own dialog asks for the new one. If the server page has not started showing within 15 seconds, or you press Cancel while it opens, the connect screen comes back with a notice. A login that would cross the network over plain `http://` to another machine says so. Return opens or starts the Codeman on this Mac (or connects to the one found here, when that is the tab's main button) and Esc cancels a connect, as in a Mac dialog (Install always takes a click). On a Mac whose WebKit is too old for Codeman it says so and Connect stays off (see Known limits). |
|
||||
| **Start Codeman** | On the This Mac tab, and when `http://127.0.0.1:<port>` or `http://localhost:<port>` answers nothing, one click runs `codeman web -d` (or `~/.codeman/app`) with your login shell's environment, so the server gets your real PATH (Homebrew, nvm) for the agents it spawns. zsh, bash and other POSIX shells run the start themselves; fish, nu, xonsh, tcsh and other shells only report their environment, and the start runs under `/bin/sh` with it. Offered for those two addresses only: `codeman web -d` listens on 127.0.0.1. |
|
||||
| **Login** | The app answers the server's HTTP Basic login requests itself, with the login you connected with, so the page keeps working after the server restarts (a restart forgets every session cookie). It answers only for Codeman's own pages under the server's base path: a web tab or a rendered HTML file that asks for a Basic login of its own is left to WebKit and never gets your Codeman password. WebKit keeps no copy of the login, so every request for it gets the current one. Each connect first clears the app's cookies, so connecting to the same server as another user really switches users (local storage, where Codeman keeps its per-device settings, stays; a dashboard in a web tab that keeps its own login in a cookie may ask for it again). A page that still gets a 401 reloads once. If the server refuses the login (the password was changed, say), the app does not keep sending it: it checks it with a single probe, and only if the server refuses that too does the connect screen come back with a notice. That does not take focus from the app you are in: if Codeman is in the background, its Dock icon bounces. |
|
||||
| **Dialogs** | Codeman's `confirm()`, `prompt()` and `alert()` (Delete case, Kill all sessions, Update Codeman, discarding unsaved edits, ...) show as native macOS dialogs. wry implements none of them, and without them WKWebView answers Cancel without showing anything. Each dialog's first line names the page it comes from, and says so when that is an embedded frame (a web tab, a rendered HTML preview), so a frame cannot pass its text off as Codeman's. |
|
||||
@@ -62,6 +62,11 @@ root, `npm run test:browser -- test/desktop-connect-page.browser.test.ts` drives
|
||||
Content-Security-Policy the app serves it with. It is part of the nightly
|
||||
browser suite, not of `npm test`.
|
||||
|
||||
To try a change to `install.sh` before it is merged, build with
|
||||
`CODEMAN_DESKTOP_INSTALLER_URL` (where to get the installer) and
|
||||
`CODEMAN_DESKTOP_INSTALL_BRANCH` (the branch it installs from) set. Both are
|
||||
read at compile time: a shipped app cannot be pointed at another installer.
|
||||
|
||||
The script builds with `--locked` against the committed `Cargo.lock`, targets
|
||||
the macOS version in `macos/Info.plist` (`LSMinimumSystemVersion`, 11.3), and
|
||||
takes the binary from where cargo says it wrote it, so `CARGO_TARGET_DIR` and a
|
||||
@@ -141,19 +146,52 @@ classes of wry's own delegates, so wry stays an unmodified crates.io dependency.
|
||||
- `codeman web -d` gets the port and base path as separate arguments, never as
|
||||
shell text.
|
||||
|
||||
**The installer runs in Terminal, not inside the app.** `install.sh` asks for
|
||||
the administrator password on a terminal (Homebrew, its sudo keep-alive), the
|
||||
Xcode tools arrive as a system dialog, and ssh asks about host keys and
|
||||
passwords on a terminal too, so an install without one fails on the first
|
||||
fresh Mac. The app writes a short script to the per-user temporary folder
|
||||
(mode 0700, created fresh, deleted by the script as it starts) and opens it
|
||||
with `open -b com.apple.Terminal`, which needs no permission; scripting
|
||||
Terminal with osascript would ask for Automation access. The script prints
|
||||
what it runs. A This Mac install downloads the installer to a temporary file
|
||||
and runs it from there, so the installer's input is the terminal. Everything in
|
||||
the scripts is built and unit-tested in `src/setup.rs`; the page sends only
|
||||
which install it wants, whether other devices should reach it, and the SSH
|
||||
login, which is checked before it is quoted.
|
||||
**The app runs the installer itself; Terminal is the fallback.** `install.sh
|
||||
--no-admin` puts Node.js and tmux in the home folder, so a This Mac install needs
|
||||
no password and therefore no terminal, and the two questions only a person can
|
||||
answer arrive as flags (`src/gui_install.rs`). The app downloads the installer
|
||||
once to a private folder, asks it what is on this Mac (`install.sh preflight`,
|
||||
which prints JSON and changes nothing) and draws its choices from that answer.
|
||||
So the app has no list of coding agents of its own: a new one appears without a
|
||||
new app, and the list always matches what the installer can really install
|
||||
here. The installer runs with the login shell's environment, so it finds what
|
||||
this person already has. The page sends only the agent's id, whether other
|
||||
devices may reach Codeman, and that password; the password reaches the
|
||||
installer through its environment, never its command line, where `ps` shows it.
|
||||
|
||||
**The install outlives the app.** Its output goes to a file, never a pipe, and
|
||||
it runs in a process group of its own. With a pipe, quitting the app would kill
|
||||
the installer at its next write; in the app's group, launchd would kill it with
|
||||
the app. The file holds the whole run, so a page that was reloaded, or an app
|
||||
that was opened again, finds the process in `ps` and replays the file from the
|
||||
first line. That is why the app keeps no state about a run. A run that ends
|
||||
without the installer's last `done` line failed, and the first error it reported
|
||||
is the one shown: the ones after it are consequences.
|
||||
|
||||
**Adding an agent is a run of its own.** `install.sh agent <id>` installs one
|
||||
agent and touches neither Codeman nor its service, so it may run next to a live
|
||||
server, which an install must refuse: the installer's service step would replace
|
||||
that server under its sessions. It has its own temporary folder, so `ps` tells the
|
||||
two apart: everything that reads a running install takes it to mean "Codeman is
|
||||
being installed", which an agent run does not. One run goes at a time, since both
|
||||
can write to the runtime folder. It asks `preflight` for the list like an install
|
||||
does, and both pass `--no-admin`: that flag decides which agents count as
|
||||
installable, so without it on both the page could offer one the run refuses. The
|
||||
menu item is on the connect page because that is where the app may run things:
|
||||
from a Codeman page it leaves the page the way *Switch Server* does.
|
||||
|
||||
**Terminal stays for what the app cannot do.** The route with Homebrew asks for
|
||||
the administrator password on a terminal, the Xcode tools arrive as a system
|
||||
dialog, and ssh asks about host keys and passwords on a terminal too. The app
|
||||
writes a short script to the per-user temporary folder (mode 0700, created
|
||||
fresh, deleted by the script as it starts) and opens it with `open -b
|
||||
com.apple.Terminal`, which needs no permission; scripting Terminal with
|
||||
osascript would ask for Automation access. The script prints what it runs. A
|
||||
This Mac install downloads the installer to a temporary file and runs it from
|
||||
there, so the installer's input is the terminal. Everything in the scripts is
|
||||
built and unit-tested in `src/setup.rs`; the page sends only which install it
|
||||
wants, whether other devices should reach it, and the SSH login, which is
|
||||
checked before it is quoted.
|
||||
|
||||
**This Mac's own login comes from where Codeman keeps it.** A Codeman
|
||||
installed with a password keeps it in its LaunchAgent (`install.sh`) or in
|
||||
@@ -169,7 +207,8 @@ with Codeman stopped, whatever else listens there never gets it.
|
||||
data directory and tmux socket attach to each other's live sessions, and
|
||||
`codeman web -d` only notices a server it started itself or one at the same
|
||||
address. So the app looks for running Codeman servers of this user (`ps`)
|
||||
before it offers or runs a start, and opens the one it finds instead.
|
||||
before it offers or runs a start, and offers to connect to the ones it finds
|
||||
instead (`found_addresses` in `src/setup.rs`, unit-tested).
|
||||
|
||||
**Closing the main window quits the app.** Codeman's sessions keep running on
|
||||
the server, so nothing is lost, and reopening takes about a second.
|
||||
@@ -177,7 +216,9 @@ the server, so nothing is lost, and reopening takes about a second.
|
||||
**One reachability probe per user action, and one to check a refused login.**
|
||||
Codeman counts a request without valid credentials against its login rate
|
||||
limit (10 per IP, 15 minutes; a successful login resets the count), so the app
|
||||
never retries in a loop. Once the server refuses the login in a challenge, the
|
||||
never retries in a loop. A look at this Mac asks each Codeman server found
|
||||
here once; the app has a login only for the one at the usual address, so the
|
||||
others are asked without one. Once the server refuses the login in a challenge, the
|
||||
app sends it only once more, in the single probe that checks the refusal. If
|
||||
that probe is refused or rate limited, the connect screen comes back; the
|
||||
app does not send the refused login again. Keeping no copy of the login in WebKit has a cost here: after a server
|
||||
@@ -239,6 +280,31 @@ crosses, so the login is never on a command line.
|
||||
|
||||
## Known limits
|
||||
|
||||
- **A new agent can take a few minutes to show up in a running Codeman.** The
|
||||
server remembers that a CLI is missing, for up to 5 minutes after it last looked
|
||||
(`cliResolveRetryDelayMs`), so that a status poll never spawns a login shell. The
|
||||
app cannot clear that from outside, so the screen after *Add a coding agent* says
|
||||
so. An open Codeman page also needs a reload, because the list of installed
|
||||
agents is part of the page.
|
||||
- **Agents the app can add are the ones `--no-admin` can install.** OMP's macOS
|
||||
install is Homebrew, so it is not offered, also on a Mac that has Homebrew.
|
||||
- **Agents that install with npm use whichever Node.js the login shell finds.**
|
||||
With the Node.js the installer downloaded, or Homebrew's, that folder is yours.
|
||||
The nodejs.org installer leaves `/usr/local/lib/node_modules` to root, so those
|
||||
agents would be expected to fail there, with npm's permission error shown, while
|
||||
the ones with their own installer still work. This has not been tried.
|
||||
- **Only your own Codeman servers on this Mac are found, by their command
|
||||
line.** A server another macOS user runs, or one in a container or a virtual
|
||||
machine, is not listed: connect to it by address under Another machine. A
|
||||
base path that a server started by hand has only in its environment
|
||||
(`CODEMAN_BASE_URL`) is not visible either, so its row has the address
|
||||
without the path; the LaunchAgent's base path is read from its job.
|
||||
- **A found server that is slow to answer shows as not answering.** Next to a
|
||||
Codeman that answers, each other server gets two seconds (five when nothing
|
||||
answers at the usual address). A password-protected one counts the
|
||||
look as a failed login, like any look at a server the app has no login for.
|
||||
*Check again* asks again.
|
||||
|
||||
- **The logo blink rests on a private macOS interface.** Apple documents the
|
||||
setting, not the way the app reaches it, so a macOS update can take it away;
|
||||
the menu then disappears. Every change of the logo writes `LEBacklightMode`,
|
||||
@@ -319,6 +385,20 @@ crosses, so the login is never on a command line.
|
||||
- **No desktop notifications yet.** WKWebView has no Web Notification API.
|
||||
Native notifications are the first item on the list below.
|
||||
- **No service worker.** Codeman works without it; it is only an offline cache.
|
||||
- **The graphical install needs macOS 15, or a tmux that is already there.**
|
||||
tmux comes from the tmux project's own builds, which need macOS 15. On an
|
||||
older Mac without tmux the app says so and offers Terminal, where Homebrew
|
||||
installs it (that takes an administrator once).
|
||||
- **Who can reach it stops at the local network.** Tailscale needs its own
|
||||
login and setup, which the installer does at a terminal. Choose *Install in
|
||||
Terminal instead*, or run `install.sh tailscale` later.
|
||||
- **The agent is chosen during the install.** With Codeman already installed,
|
||||
or after *Skip for now*, an agent is added by hand: its commands are in the
|
||||
installer's closing notes and in [Installing an agent CLI](../../docs/wiki/Installation.md#installing-an-agent-cli).
|
||||
- **An agent only your interactive profile finds counts as missing.** The app
|
||||
reads the login shell's environment, without `.zshrc`, so a CLI on an nvm
|
||||
PATH set up there is offered again as if it were not installed. Installing
|
||||
it again is harmless; *Skip for now* leaves it as it is.
|
||||
- **Installing from the app is macOS only so far**, and installing on another
|
||||
machine needs ssh access to it and `curl` or `wget` there. The app does not
|
||||
know when a remote install is done or which address it chose: the installer
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -91,10 +91,10 @@ fn flavor(shell: &Path) -> Flavor {
|
||||
}
|
||||
|
||||
/// What one process printed, stdout and stderr kept apart.
|
||||
struct Output {
|
||||
code: Option<i32>,
|
||||
stdout: String,
|
||||
stderr: String,
|
||||
pub struct Output {
|
||||
pub code: Option<i32>,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
}
|
||||
|
||||
/// What `codeman` (or `SCRIPT` failing to find it) said, for the connect page.
|
||||
@@ -143,8 +143,18 @@ fn pump<R: Read + Send + 'static>(pipe: Option<R>, stream: usize, tx: mpsc::Send
|
||||
});
|
||||
}
|
||||
|
||||
/// Run `cmd` to completion with stdin closed, or kill it at `deadline`.
|
||||
fn exec(mut cmd: Command, deadline: Instant) -> Result<Output, String> {
|
||||
/// `exec_bounded` for a start.
|
||||
fn exec(cmd: Command, deadline: Instant) -> Result<Output, String> {
|
||||
exec_bounded(
|
||||
cmd,
|
||||
deadline,
|
||||
"Starting Codeman took longer than a minute; it was stopped.",
|
||||
)
|
||||
}
|
||||
|
||||
/// Run `cmd` to completion with stdin closed, or kill it at `deadline` and
|
||||
/// answer `timed_out`.
|
||||
pub fn exec_bounded(mut cmd: Command, deadline: Instant, timed_out: &str) -> Result<Output, String> {
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let mut child = cmd
|
||||
.spawn()
|
||||
@@ -168,7 +178,7 @@ fn exec(mut cmd: Command, deadline: Instant) -> Result<Output, String> {
|
||||
Ok(None) => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err("Starting Codeman took longer than a minute; it was stopped.".into());
|
||||
return Err(timed_out.to_string());
|
||||
}
|
||||
Err(e) => return Err(e.to_string()),
|
||||
}
|
||||
@@ -275,6 +285,17 @@ fn capture_env(
|
||||
}))
|
||||
}
|
||||
|
||||
/// The login shell's environment, for a process the app runs without it (the
|
||||
/// graphical install). `None` when the shell reports none.
|
||||
pub fn login_environment() -> Option<Vec<(String, String)>> {
|
||||
let shell = login_shell();
|
||||
let flags: &[&str] = match flavor(&shell) {
|
||||
Flavor::Posix => &["-l", "-c"],
|
||||
Flavor::Capture(attempts) => attempts.first().copied().unwrap_or(&["-c"]),
|
||||
};
|
||||
capture_env(&shell, flags, Instant::now() + FIND_TIMEOUT).ok()?.ok()
|
||||
}
|
||||
|
||||
/// Run `cmd` in the home folder, where a terminal and the LaunchAgent start
|
||||
/// Codeman too. The server keeps the directory it was started in and uses it
|
||||
/// as the default for a session that names none; an app opened from the Finder
|
||||
|
||||
@@ -24,6 +24,7 @@ mod agents;
|
||||
mod assets;
|
||||
mod config;
|
||||
mod credentials;
|
||||
mod gui_install;
|
||||
mod local_server;
|
||||
mod logo;
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -37,7 +38,8 @@ use std::collections::{HashMap, VecDeque};
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use muda::accelerator::{Accelerator, Code, Modifiers};
|
||||
@@ -105,6 +107,7 @@ const START_REFUSED: &str = "Codeman can only be started here for an http://127.
|
||||
|
||||
mod menu_id {
|
||||
pub const SWITCH: &str = "switch-server";
|
||||
pub const ADD_AGENT: &str = "add-agent";
|
||||
pub const RELOAD: &str = "reload";
|
||||
pub const START_FULLSCREEN: &str = "start-fullscreen";
|
||||
pub const DEVTOOLS: &str = "devtools";
|
||||
@@ -294,6 +297,11 @@ struct App {
|
||||
menu: AppMenu,
|
||||
/// The one Keychain worker; every Keychain job goes through its queue.
|
||||
keychain: Keychain,
|
||||
/// Which reader of the install's output is the current one.
|
||||
install_reader: Arc<AtomicU64>,
|
||||
/// The connect page opens the agent chooser when it next loads: the menu
|
||||
/// asked for it from a Codeman page.
|
||||
add_agent_on_load: bool,
|
||||
/// While the main window may still have to be put into the full screen it
|
||||
/// asked for at launch: when to look next, and how many retries were made.
|
||||
fullscreen_retry: Option<(Instant, u8)>,
|
||||
@@ -386,6 +394,8 @@ fn main() {
|
||||
downloads: HashMap::new(),
|
||||
menu,
|
||||
keychain,
|
||||
install_reader: Arc::new(AtomicU64::new(0)),
|
||||
add_agent_on_load: false,
|
||||
fullscreen_retry: wants_fullscreen.then(|| (Instant::now() + FULLSCREEN_FIRST_CHECK, 0)),
|
||||
logo_watch: logo::Watcher::default(),
|
||||
};
|
||||
@@ -423,6 +433,7 @@ fn build_menu(config: &Config) -> muda::Result<AppMenu> {
|
||||
&about,
|
||||
&PredefinedMenuItem::separator(),
|
||||
&switch,
|
||||
&MenuItem::with_id(menu_id::ADD_AGENT, "Add a Coding Agent to This Mac\u{2026}", true, None),
|
||||
&PredefinedMenuItem::separator(),
|
||||
&PredefinedMenuItem::services(None),
|
||||
&PredefinedMenuItem::separator(),
|
||||
@@ -1179,6 +1190,7 @@ impl App {
|
||||
}
|
||||
match id {
|
||||
menu_id::SWITCH => self.show_connect_page(None, true),
|
||||
menu_id::ADD_AGENT => self.add_agent(),
|
||||
menu_id::RELOAD => self.reload_focused(),
|
||||
menu_id::START_FULLSCREEN => {
|
||||
let value = self.menu.start_fullscreen.is_checked();
|
||||
@@ -1316,6 +1328,76 @@ impl App {
|
||||
});
|
||||
}
|
||||
}
|
||||
ConnectCmd::InstallPrepare => {
|
||||
if choosing {
|
||||
self.in_background(|| match gui_install::prepare() {
|
||||
Ok(plan) => json!({ "type": "installPlan", "plan": plan }),
|
||||
Err(message) => json!({ "type": "installPrepareFailed", "message": message }),
|
||||
});
|
||||
}
|
||||
}
|
||||
ConnectCmd::InstallStart {
|
||||
network_password,
|
||||
ai_cli,
|
||||
} => {
|
||||
if choosing {
|
||||
let proxy = self.proxy.clone();
|
||||
let stale = self.next_install_reader();
|
||||
std::thread::spawn(move || {
|
||||
let plan = gui_install::Plan {
|
||||
port: setup::pick_install_port(),
|
||||
network_password,
|
||||
ai_cli,
|
||||
};
|
||||
let send = |msg| {
|
||||
let _ = proxy.send_event(UserEvent::ToConnectPage(msg));
|
||||
};
|
||||
match gui_install::start(&plan) {
|
||||
Ok(()) => {
|
||||
send(json!({ "type": "installRunning", "port": plan.port }));
|
||||
gui_install::follow(gui_install::Run::Codeman, stale, send);
|
||||
}
|
||||
Err(message) => send(json!({ "type": "installStartFailed", "message": message })),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
ConnectCmd::InstallAttach => {
|
||||
if choosing {
|
||||
self.attach_to_run(gui_install::Run::Codeman);
|
||||
}
|
||||
}
|
||||
ConnectCmd::InstallCancel => {
|
||||
std::thread::spawn(gui_install::cancel);
|
||||
}
|
||||
ConnectCmd::AgentPrepare => {
|
||||
if choosing {
|
||||
self.in_background(|| match gui_install::prepare_agent() {
|
||||
Ok(plan) => json!({ "type": "installPlan", "plan": plan }),
|
||||
Err(message) => json!({ "type": "installPrepareFailed", "message": message }),
|
||||
});
|
||||
}
|
||||
}
|
||||
ConnectCmd::AgentStart { ai_cli } => {
|
||||
if choosing {
|
||||
let proxy = self.proxy.clone();
|
||||
let stale = self.next_install_reader();
|
||||
std::thread::spawn(move || {
|
||||
let send = |msg| {
|
||||
let _ = proxy.send_event(UserEvent::ToConnectPage(msg));
|
||||
};
|
||||
match gui_install::start_agent(&ai_cli) {
|
||||
Ok(()) => gui_install::follow(gui_install::Run::Agent, stale, send),
|
||||
Err(message) => send(json!({ "type": "installStartFailed", "message": message })),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
ConnectCmd::AgentAttach => {
|
||||
if choosing {
|
||||
self.attach_to_run(gui_install::Run::Agent);
|
||||
}
|
||||
}
|
||||
ConnectCmd::InstallRemote { target } => {
|
||||
if choosing {
|
||||
match setup::SshTarget::parse(&target) {
|
||||
@@ -1347,6 +1429,40 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// A new reader of the install's output replaces the one before it: the
|
||||
/// answer is how that new reader learns it was replaced in turn.
|
||||
/// Report a run that is going already to the page, from its first line.
|
||||
fn attach_to_run(&self, run: gui_install::Run) {
|
||||
let proxy = self.proxy.clone();
|
||||
let stale = self.next_install_reader();
|
||||
std::thread::spawn(move || {
|
||||
gui_install::follow(run, stale, |msg| {
|
||||
let _ = proxy.send_event(UserEvent::ToConnectPage(msg));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The agent chooser lives on the connect page: from a Codeman page, this
|
||||
/// leaves it the way Switch Server does.
|
||||
fn add_agent(&mut self) {
|
||||
if matches!(*self.phase.borrow(), Phase::Connect) {
|
||||
if let Some(main) = self.windows.get(&self.main_id) {
|
||||
main.window.set_visible(true);
|
||||
main.window.set_focus();
|
||||
}
|
||||
self.to_connect_page(json!({ "type": "addAgent" }));
|
||||
} else {
|
||||
self.add_agent_on_load = true;
|
||||
self.show_connect_page(None, true);
|
||||
}
|
||||
}
|
||||
|
||||
fn next_install_reader(&self) -> impl Fn() -> bool + Send + 'static {
|
||||
let generation = self.install_reader.clone();
|
||||
let mine = generation.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
move || generation.load(Ordering::SeqCst) != mine
|
||||
}
|
||||
|
||||
/// Run `work` off the event loop (it may run a login shell, plutil,
|
||||
/// Terminal or a probe) and hand what it returns to the connect page.
|
||||
fn in_background(&self, work: impl FnOnce() -> serde_json::Value + Send + 'static) {
|
||||
@@ -1358,6 +1474,7 @@ impl App {
|
||||
|
||||
fn send_init(&mut self) {
|
||||
let notice = self.notice.take();
|
||||
let add_agent = std::mem::take(&mut self.add_agent_on_load);
|
||||
self.to_connect_page(json!({
|
||||
"type": "init",
|
||||
"servers": self.config.servers,
|
||||
@@ -1366,6 +1483,7 @@ impl App {
|
||||
"version": VERSION,
|
||||
"starting": self.start_running(),
|
||||
"notice": notice,
|
||||
"addAgent": add_agent,
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -609,6 +609,27 @@ pub enum ConnectCmd {
|
||||
InstallLocal {
|
||||
network: bool,
|
||||
},
|
||||
/// Fetch the installer and ask it what is on this Mac (gui_install).
|
||||
InstallPrepare,
|
||||
/// Run the graphical install. `network_password`: reachable from other
|
||||
/// devices, with this password. `ai_cli`: an id in the shape of the
|
||||
/// installer's catalogue, which checks it again.
|
||||
InstallStart {
|
||||
network_password: Option<String>,
|
||||
ai_cli: Option<String>,
|
||||
},
|
||||
/// Show the graphical install that is running already.
|
||||
InstallAttach,
|
||||
/// Stop whichever graphical run is going.
|
||||
InstallCancel,
|
||||
/// Fetch the installer to add a coding agent to a Mac that has Codeman.
|
||||
AgentPrepare,
|
||||
/// Add this agent: an id in the shape of the installer's catalogue.
|
||||
AgentStart {
|
||||
ai_cli: String,
|
||||
},
|
||||
/// Show the agent install that is running already.
|
||||
AgentAttach,
|
||||
/// Run the installer on another machine over SSH, in Terminal. `target`
|
||||
/// is what the user typed; setup::SshTarget::parse checks it.
|
||||
InstallRemote {
|
||||
@@ -663,6 +684,23 @@ enum RawConnect {
|
||||
#[serde(default)]
|
||||
network: bool,
|
||||
},
|
||||
InstallPrepare,
|
||||
InstallStart {
|
||||
// rename_all above reaches variant names only, and deny_unknown_fields
|
||||
// would refuse the page's spelling of these.
|
||||
#[serde(default, rename = "networkPassword")]
|
||||
network_password: Option<String>,
|
||||
#[serde(default, rename = "aiCli")]
|
||||
ai_cli: Option<String>,
|
||||
},
|
||||
InstallAttach,
|
||||
InstallCancel,
|
||||
AgentPrepare,
|
||||
AgentStart {
|
||||
#[serde(rename = "aiCli")]
|
||||
ai_cli: String,
|
||||
},
|
||||
AgentAttach,
|
||||
InstallRemote {
|
||||
target: String,
|
||||
},
|
||||
@@ -679,6 +717,17 @@ enum RawHost {
|
||||
SessionExpired,
|
||||
}
|
||||
|
||||
/// The shape of a CLI catalogue id. It becomes one argument of `install.sh`,
|
||||
/// so it could not be read as a flag even without this: it must start with a
|
||||
/// letter.
|
||||
fn is_cli_id(id: &str) -> bool {
|
||||
id.len() <= 32
|
||||
&& id.starts_with(|c: char| c.is_ascii_lowercase())
|
||||
&& id
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
|
||||
}
|
||||
|
||||
fn bounded(s: Option<String>, max: usize) -> Option<Option<String>> {
|
||||
match s {
|
||||
Some(v) if v.len() > max => None,
|
||||
@@ -736,6 +785,24 @@ pub fn parse_ipc(frame_url: &str, body: &str, phase: &Phase, is_main_window: boo
|
||||
RawConnect::OpenExternal { url } if url.len() <= MAX_URL_LEN => ConnectCmd::OpenExternal(url),
|
||||
RawConnect::LocalStatus { quick, deep } => ConnectCmd::LocalStatus { quick, deep },
|
||||
RawConnect::InstallLocal { network } => ConnectCmd::InstallLocal { network },
|
||||
RawConnect::InstallPrepare => ConnectCmd::InstallPrepare,
|
||||
RawConnect::InstallStart {
|
||||
network_password,
|
||||
ai_cli,
|
||||
} => {
|
||||
if ai_cli.as_deref().is_some_and(|id| !is_cli_id(id)) {
|
||||
return None;
|
||||
}
|
||||
ConnectCmd::InstallStart {
|
||||
network_password: bounded(network_password, MAX_FIELD_LEN)?.filter(|p| !p.is_empty()),
|
||||
ai_cli,
|
||||
}
|
||||
}
|
||||
RawConnect::InstallAttach => ConnectCmd::InstallAttach,
|
||||
RawConnect::InstallCancel => ConnectCmd::InstallCancel,
|
||||
RawConnect::AgentPrepare => ConnectCmd::AgentPrepare,
|
||||
RawConnect::AgentStart { ai_cli } if is_cli_id(&ai_cli) => ConnectCmd::AgentStart { ai_cli },
|
||||
RawConnect::AgentAttach => ConnectCmd::AgentAttach,
|
||||
RawConnect::InstallRemote { target } if target.len() <= MAX_FIELD_LEN => {
|
||||
ConnectCmd::InstallRemote { target }
|
||||
}
|
||||
@@ -1599,6 +1666,111 @@ mod tests {
|
||||
assert_eq!(parse_ipc(page, r#"{"cmd":"installLocal"}"#, &loaded, true), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ipc_graphical_install_commands() {
|
||||
let page = "codemanapp://localhost/index.html";
|
||||
let c = |body: &str| parse_ipc(page, body, &Phase::Connect, true);
|
||||
assert_eq!(
|
||||
c(r#"{"cmd":"installPrepare"}"#),
|
||||
Some(Ipc::Connect(ConnectCmd::InstallPrepare))
|
||||
);
|
||||
assert_eq!(
|
||||
c(r#"{"cmd":"installAttach"}"#),
|
||||
Some(Ipc::Connect(ConnectCmd::InstallAttach))
|
||||
);
|
||||
assert_eq!(
|
||||
c(r#"{"cmd":"installCancel"}"#),
|
||||
Some(Ipc::Connect(ConnectCmd::InstallCancel))
|
||||
);
|
||||
// The spelling connect.html sends (test/desktop-connect-install.test.ts
|
||||
// pins the page's side).
|
||||
assert_eq!(
|
||||
c(r#"{"cmd":"installStart","networkPassword":"s3cret","aiCli":"claude"}"#),
|
||||
Some(Ipc::Connect(ConnectCmd::InstallStart {
|
||||
network_password: Some("s3cret".into()),
|
||||
ai_cli: Some("claude".into()),
|
||||
}))
|
||||
);
|
||||
assert_eq!(
|
||||
c(r#"{"cmd":"installStart"}"#),
|
||||
Some(Ipc::Connect(ConnectCmd::InstallStart {
|
||||
network_password: None,
|
||||
ai_cli: None,
|
||||
}))
|
||||
);
|
||||
// An empty password is no password: never a network install without one.
|
||||
assert_eq!(
|
||||
c(r#"{"cmd":"installStart","networkPassword":""}"#),
|
||||
Some(Ipc::Connect(ConnectCmd::InstallStart {
|
||||
network_password: None,
|
||||
ai_cli: None,
|
||||
}))
|
||||
);
|
||||
// Only the shape of an id: nothing that could read as a flag or more.
|
||||
for id in ["--yes", "-y", "Claude", "a b", "a;b", "", "a/b"] {
|
||||
assert_eq!(c(&format!(r#"{{"cmd":"installStart","aiCli":"{id}"}}"#)), None, "{id}");
|
||||
}
|
||||
let long = "a".repeat(33);
|
||||
assert_eq!(c(&format!(r#"{{"cmd":"installStart","aiCli":"{long}"}}"#)), None);
|
||||
let long = "a".repeat(MAX_FIELD_LEN + 1);
|
||||
assert_eq!(
|
||||
c(&format!(r#"{{"cmd":"installStart","networkPassword":"{long}"}}"#)),
|
||||
None
|
||||
);
|
||||
// Nothing else rides along.
|
||||
assert_eq!(c(r#"{"cmd":"installStart","args":["--yes"]}"#), None);
|
||||
assert_eq!(c(r#"{"cmd":"installStart","ai_cli":"claude"}"#), None);
|
||||
// Only the connect page, only in the main window, never a server page.
|
||||
assert_eq!(
|
||||
parse_ipc(page, r#"{"cmd":"installStart"}"#, &Phase::Connect, false),
|
||||
None
|
||||
);
|
||||
let loaded = Phase::Loaded(u("http://127.0.0.1:3000/"));
|
||||
assert_eq!(
|
||||
parse_ipc("http://127.0.0.1:3000/", r#"{"cmd":"installStart"}"#, &loaded, true),
|
||||
None
|
||||
);
|
||||
assert_eq!(parse_ipc(page, r#"{"cmd":"installCancel"}"#, &loaded, true), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ipc_adding_a_coding_agent() {
|
||||
let page = "codemanapp://localhost/index.html";
|
||||
let c = |body: &str| parse_ipc(page, body, &Phase::Connect, true);
|
||||
assert_eq!(
|
||||
c(r#"{"cmd":"agentPrepare"}"#),
|
||||
Some(Ipc::Connect(ConnectCmd::AgentPrepare))
|
||||
);
|
||||
assert_eq!(
|
||||
c(r#"{"cmd":"agentAttach"}"#),
|
||||
Some(Ipc::Connect(ConnectCmd::AgentAttach))
|
||||
);
|
||||
assert_eq!(
|
||||
c(r#"{"cmd":"agentStart","aiCli":"codex"}"#),
|
||||
Some(Ipc::Connect(ConnectCmd::AgentStart { ai_cli: "codex".into() }))
|
||||
);
|
||||
// It names one agent, in the shape of an id, and nothing else.
|
||||
assert_eq!(c(r#"{"cmd":"agentStart"}"#), None);
|
||||
for id in ["--service", "-y", "Codex", "a b", "a;b", "", "a/b"] {
|
||||
assert_eq!(c(&format!(r#"{{"cmd":"agentStart","aiCli":"{id}"}}"#)), None, "{id}");
|
||||
}
|
||||
assert_eq!(c(r#"{"cmd":"agentStart","aiCli":"codex","port":3000}"#), None);
|
||||
assert_eq!(
|
||||
parse_ipc(page, r#"{"cmd":"agentStart","aiCli":"codex"}"#, &Phase::Connect, false),
|
||||
None
|
||||
);
|
||||
let loaded = Phase::Loaded(u("http://127.0.0.1:3000/"));
|
||||
assert_eq!(
|
||||
parse_ipc(
|
||||
"http://127.0.0.1:3000/",
|
||||
r#"{"cmd":"agentStart","aiCli":"codex"}"#,
|
||||
&loaded,
|
||||
true
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ipc_from_connect_page() {
|
||||
let page = "codemanapp://localhost/index.html";
|
||||
|
||||
@@ -9,7 +9,7 @@ use serde::Serialize;
|
||||
use std::time::Duration;
|
||||
use url::Url;
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(5);
|
||||
pub const TIMEOUT: Duration = Duration::from_secs(5);
|
||||
pub const MAX_BODY: u64 = 8 * 1024 * 1024;
|
||||
|
||||
/// The path the probe asks for, relative to the server's base URL.
|
||||
@@ -249,7 +249,7 @@ pub fn agent(timeout: Duration) -> ureq::Agent {
|
||||
}
|
||||
|
||||
/// `probe` with the time the whole exchange may take.
|
||||
fn probe_within(server: &Url, authorization: Option<&str>, timeout: Duration) -> ProbeOutcome {
|
||||
pub fn probe_within(server: &Url, authorization: Option<&str>, timeout: Duration) -> ProbeOutcome {
|
||||
let status_url = match server.join(STATUS_PATH) {
|
||||
Ok(u) => u,
|
||||
Err(e) => return ProbeOutcome::Failed { detail: e.to_string() },
|
||||
|
||||
+627
-104
@@ -1,12 +1,13 @@
|
||||
//! The connect screen's "This Mac" tab and its installs: where the Codeman on
|
||||
//! this Mac listens, whether it is installed, its login, and the installer runs
|
||||
//! for this Mac and for another machine over SSH.
|
||||
//! The connect screen's "This Mac" tab and its Terminal installs: where the
|
||||
//! Codeman on this Mac listens, whether it is installed, its login, which
|
||||
//! other Codeman servers of this user run here, and the installer runs in
|
||||
//! Terminal for this Mac and for another machine over SSH.
|
||||
//! The install most people get runs in the app, in `gui_install.rs`.
|
||||
//!
|
||||
//! The installer always runs in Terminal, never inside the app. `install.sh`
|
||||
//! asks for the administrator password on a terminal (Homebrew, its sudo
|
||||
//! keep-alive), the Xcode tools arrive as a system dialog, and ssh asks about
|
||||
//! host keys and passwords on a terminal too: a run without one fails on the
|
||||
//! first fresh Mac. So the app writes a small script that deletes itself and
|
||||
//! The Terminal route is for what that one cannot do. `install.sh` asks for
|
||||
//! the administrator password on a terminal (Homebrew, its sudo keep-alive),
|
||||
//! the Xcode tools arrive as a system dialog, and ssh asks about host keys and
|
||||
//! passwords on a terminal too. So the app writes a small script that deletes itself and
|
||||
//! hands it to Terminal (`open -b com.apple.Terminal`), which needs no
|
||||
//! permission, unlike scripting Terminal through osascript (an Automation
|
||||
//! prompt). Everything the scripts contain is built here and unit-tested; the
|
||||
@@ -24,12 +25,22 @@ use std::time::Duration;
|
||||
use serde::Serialize;
|
||||
use url::Url;
|
||||
|
||||
use crate::gui_install;
|
||||
use crate::local_server;
|
||||
use crate::policy;
|
||||
use crate::probe::{self, ProbeOutcome};
|
||||
|
||||
/// Codeman's published installer (a redirect to `install.sh` on master).
|
||||
pub const INSTALLER_URL: &str = "https://getcodeman.com/install";
|
||||
/// Codeman's published installer (a redirect to `install.sh` on master). A test
|
||||
/// build of an installer change sets `CODEMAN_DESKTOP_INSTALLER_URL` when it is
|
||||
/// compiled; a shipped app has no way to point this anywhere else, at runtime
|
||||
/// or otherwise.
|
||||
pub const INSTALLER_URL: &str = match option_env!("CODEMAN_DESKTOP_INSTALLER_URL") {
|
||||
Some(url) => url,
|
||||
None => "https://getcodeman.com/install",
|
||||
};
|
||||
|
||||
/// The branch that test build installs Codeman from (`CODEMAN_BRANCH`).
|
||||
pub const INSTALL_BRANCH: Option<&str> = option_env!("CODEMAN_DESKTOP_INSTALL_BRANCH");
|
||||
|
||||
/// What to paste into a terminal on another machine; the SSH install runs the
|
||||
/// same thing there.
|
||||
@@ -83,46 +94,65 @@ pub fn parse_service(job: &serde_json::Value) -> ServiceConfig {
|
||||
.map(|a| a.iter().filter_map(|v| v.as_str()).collect())
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut port = var("CODEMAN_PORT");
|
||||
let mut base = var("CODEMAN_BASE_URL");
|
||||
let mut https = false;
|
||||
// Only what follows the `web` subcommand: node's own flags come before it.
|
||||
let after_web = args
|
||||
.iter()
|
||||
.position(|a| *a == "web")
|
||||
.map_or(&[][..], |i| &args[i + 1..]);
|
||||
let mut it = after_web.iter();
|
||||
while let Some(arg) = it.next() {
|
||||
match *arg {
|
||||
"-p" | "--port" => port = it.next().map(|s| s.to_string()),
|
||||
"--base-url" => base = it.next().map(|s| s.to_string()),
|
||||
"--https" => https = true,
|
||||
// Options that take a value: skip it, so it is never read as a flag.
|
||||
"-H" | "--host" | "--title-hostname" => {
|
||||
it.next();
|
||||
}
|
||||
other => {
|
||||
if let Some(v) = other.strip_prefix("--port=") {
|
||||
port = Some(v.to_string());
|
||||
} else if let Some(v) = other.strip_prefix("--base-url=") {
|
||||
base = Some(v.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
let flags = WebFlags {
|
||||
port: var("CODEMAN_PORT"),
|
||||
base: var("CODEMAN_BASE_URL"),
|
||||
https: false,
|
||||
}
|
||||
.read(after_web);
|
||||
ServiceConfig {
|
||||
port: port
|
||||
port: flags
|
||||
.port
|
||||
.and_then(|p| p.trim().parse::<u16>().ok())
|
||||
.filter(|p| *p > 0)
|
||||
.unwrap_or(DEFAULT_PORT),
|
||||
base_path: normalize_base_path(base.as_deref().unwrap_or("")),
|
||||
https,
|
||||
base_path: normalize_base_path(flags.base.as_deref().unwrap_or("")),
|
||||
https: flags.https,
|
||||
username: var("CODEMAN_USERNAME"),
|
||||
password: var("CODEMAN_PASSWORD"),
|
||||
daemon: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// What Codeman's `web` command takes from the arguments after `web`
|
||||
/// (src/cli.ts). The fields start as what the environment says, or empty.
|
||||
#[derive(Debug, Default)]
|
||||
struct WebFlags {
|
||||
port: Option<String>,
|
||||
base: Option<String>,
|
||||
https: bool,
|
||||
}
|
||||
|
||||
impl WebFlags {
|
||||
fn read(mut self, after_web: &[&str]) -> Self {
|
||||
let mut it = after_web.iter();
|
||||
while let Some(arg) = it.next() {
|
||||
match *arg {
|
||||
"-p" | "--port" => self.port = it.next().map(|s| s.to_string()),
|
||||
"--base-url" => self.base = it.next().map(|s| s.to_string()),
|
||||
"--https" => self.https = true,
|
||||
// Options that take a value: skip it, so it is never read as a flag.
|
||||
"-H" | "--host" | "--title-hostname" => {
|
||||
it.next();
|
||||
}
|
||||
other => {
|
||||
if let Some(v) = other.strip_prefix("--port=") {
|
||||
self.port = Some(v.to_string());
|
||||
} else if let Some(v) = other.strip_prefix("--base-url=") {
|
||||
self.base = Some(v.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Codeman's `normalizeBasePath`, plus its character check: a value Codeman
|
||||
/// would refuse at startup counts as the root here.
|
||||
fn normalize_base_path(input: &str) -> String {
|
||||
@@ -289,7 +319,7 @@ pub fn local_login(url: &Url) -> Option<(String, String)> {
|
||||
}
|
||||
|
||||
/// This user's processes, as `ps` lists them: (pid, command line).
|
||||
fn list_processes() -> Vec<(u32, String)> {
|
||||
pub fn list_processes() -> Vec<(u32, String)> {
|
||||
let Ok(out) = Command::new("/bin/ps")
|
||||
.args(["-x", "-ww", "-o", "pid=", "-o", "command="])
|
||||
.stdin(Stdio::null())
|
||||
@@ -315,6 +345,12 @@ fn parse_ps(text: &str) -> Vec<(u32, String)> {
|
||||
/// `install.sh` clone's `dist/index.js web`, a source checkout's
|
||||
/// `src/index.ts web`), not one of its short-lived control commands.
|
||||
pub fn is_codeman_server(command: &str) -> bool {
|
||||
server_args(command).is_some()
|
||||
}
|
||||
|
||||
/// What follows `web` on a Codeman server's command line, or None for any
|
||||
/// other command.
|
||||
fn server_args(command: &str) -> Option<Vec<&str>> {
|
||||
let words: Vec<&str> = command.split_whitespace().collect();
|
||||
let is_entry = |w: &str| {
|
||||
let name = w.rsplit('/').next().unwrap_or(w);
|
||||
@@ -322,16 +358,18 @@ pub fn is_codeman_server(command: &str) -> bool {
|
||||
};
|
||||
// Any entry word that `web` follows: an earlier word may only look like
|
||||
// one (a folder named codeman in `tsx watch --cwd ~/codeman src/index.ts web`).
|
||||
(0..words.len()).any(|i| {
|
||||
is_entry(words[i])
|
||||
&& words.get(i + 1) == Some(&"web")
|
||||
&& !words[i + 1..].iter().any(|w| matches!(*w, "--stop" | "--status"))
|
||||
})
|
||||
(0..words.len())
|
||||
.find(|&i| {
|
||||
is_entry(words[i])
|
||||
&& words.get(i + 1) == Some(&"web")
|
||||
&& !words[i + 1..].iter().any(|w| matches!(*w, "--stop" | "--status"))
|
||||
})
|
||||
.map(|i| words[i + 2..].to_vec())
|
||||
}
|
||||
|
||||
/// Whether a command line is an install the app started on this Mac (the
|
||||
/// Terminal script, or the installer it downloaded), and the port it asked
|
||||
/// for once the installer runs.
|
||||
/// Terminal script, the installer it downloaded, or the graphical install), and
|
||||
/// the port it asked for once the installer runs.
|
||||
pub fn install_in_progress(command: &str) -> Option<Option<u16>> {
|
||||
let words: Vec<&str> = command.split_whitespace().collect();
|
||||
let name = |w: &&str| w.rsplit('/').next().unwrap_or(w).to_string();
|
||||
@@ -341,7 +379,7 @@ pub fn install_in_progress(command: &str) -> Option<Option<u16>> {
|
||||
}) {
|
||||
return Some(None);
|
||||
}
|
||||
if words.iter().any(|w| name(w).starts_with("codeman-install.")) {
|
||||
if words.iter().any(|w| name(w).starts_with("codeman-install.")) || gui_install::Run::Codeman.matches(command) {
|
||||
let port = words
|
||||
.iter()
|
||||
.position(|w| *w == "--port")
|
||||
@@ -428,14 +466,138 @@ fn serves_loopback_port(found: &[Listener], port: u16) -> bool {
|
||||
.any(|l| l.port == port && matches!(l.host.as_str(), "*" | "127.0.0.1" | "0.0.0.0"))
|
||||
}
|
||||
|
||||
/// The address a listener is reached at: 127.0.0.1 for a loopback or
|
||||
/// all-interfaces bind, else its own address.
|
||||
fn listener_url(l: &Listener) -> Option<Url> {
|
||||
let host = match l.host.as_str() {
|
||||
"*" | "0.0.0.0" => "127.0.0.1",
|
||||
h => h,
|
||||
/// Where the app can try each of this user's Codeman servers, from their
|
||||
/// command lines (`procs`) and listening sockets. `default` is the address the
|
||||
/// app opens by default (local_url); it comes first, then the others by port.
|
||||
///
|
||||
/// One address per server and port: 127.0.0.1 when the server listens there
|
||||
/// or on every interface, `[::1]` when its only loopback socket is the IPv6
|
||||
/// one, else each address it is bound to. A socket beside a loopback one on
|
||||
/// the same port is left out (the Docker bridge listener, which serves hook
|
||||
/// endpoints only). `https` when the command line carries `--https`, and its
|
||||
/// `--base-url` is the path. `ps` does not show a base path kept in the
|
||||
/// environment, which is where install.sh's launchd job keeps it, so a server
|
||||
/// at the default address with no `--base-url` of its own is the default one.
|
||||
pub fn found_addresses(procs: &[(u32, String)], listeners: &[Listener], default: &Url) -> Vec<Url> {
|
||||
let mut urls: Vec<Url> = Vec::new();
|
||||
for (pid, command) in procs {
|
||||
let Some(args) = server_args(command) else {
|
||||
continue;
|
||||
};
|
||||
let flags = WebFlags::default().read(&args);
|
||||
let scheme = if flags.https { "https" } else { "http" };
|
||||
let base = flags.base.as_deref().map(normalize_base_path);
|
||||
let own: Vec<&Listener> = listeners.iter().filter(|l| l.pid == *pid).collect();
|
||||
for l in &own {
|
||||
let beside = |hosts: &[&str]| own.iter().any(|o| o.port == l.port && hosts.contains(&o.host.as_str()));
|
||||
let host = if beside(&["*", "0.0.0.0", "[::]", "127.0.0.1"]) {
|
||||
"127.0.0.1"
|
||||
} else if beside(&["[::1]"]) {
|
||||
"[::1]"
|
||||
} else {
|
||||
l.host.as_str()
|
||||
};
|
||||
let path = base.as_deref().unwrap_or("");
|
||||
let Ok(mut url) = Url::parse(&format!("{scheme}://{host}:{}{path}/", l.port)) else {
|
||||
continue;
|
||||
};
|
||||
if base.is_none() && policy::same_origin(&url, default) {
|
||||
url = default.clone();
|
||||
}
|
||||
if !urls.contains(&url) {
|
||||
urls.push(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
urls.sort_by_key(|u| (u != default, u.port_or_known_default(), u.to_string()));
|
||||
urls
|
||||
}
|
||||
|
||||
/// What the This Mac tab says about one found server.
|
||||
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum FoundState {
|
||||
/// Codeman answers there: Connect opens it.
|
||||
Running,
|
||||
/// Codeman answers there and wants a login.
|
||||
NeedsLogin,
|
||||
/// It serves HTTPS with a certificate the app refuses (Codeman's own
|
||||
/// self-signed one, from `codeman web --https`).
|
||||
Certificate,
|
||||
/// Codeman does not answer there.
|
||||
Unreachable,
|
||||
}
|
||||
|
||||
/// One of this user's Codeman servers on this Mac, for the This Mac tab's
|
||||
/// rows.
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FoundServer {
|
||||
/// Where the app can try it (found_addresses).
|
||||
pub url: String,
|
||||
pub version: Option<String>,
|
||||
pub state: FoundState,
|
||||
/// It is at the address the app opens by default (local_url).
|
||||
pub is_default: bool,
|
||||
}
|
||||
|
||||
/// The row for the server at `url`, from what it answered.
|
||||
fn found_server(url: &Url, answer: &ProbeOutcome, default: &Url) -> FoundServer {
|
||||
let state = match answer {
|
||||
ProbeOutcome::Ok { .. } | ProbeOutcome::PasswordChangeRequired => FoundState::Running,
|
||||
_ if answers(answer) => FoundState::NeedsLogin,
|
||||
// A Codeman started with --https closes a plain http connection.
|
||||
ProbeOutcome::TlsUntrusted { .. } | ProbeOutcome::MaybeHttps => FoundState::Certificate,
|
||||
_ => FoundState::Unreachable,
|
||||
};
|
||||
Url::parse(&format!("http://{host}:{}/", l.port)).ok()
|
||||
FoundServer {
|
||||
url: url.to_string(),
|
||||
version: match answer {
|
||||
ProbeOutcome::Ok { version } => Some(version.clone()),
|
||||
_ => None,
|
||||
},
|
||||
state,
|
||||
is_default: url == default,
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a found server gets to answer when the tab only lists it.
|
||||
const FOUND_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Ask the servers at `urls`, all at the same time, so the look takes as long
|
||||
/// as the slowest answer and no longer. Without a login: the one the app can
|
||||
/// read belongs to the default address (login_for).
|
||||
fn ask_found(urls: &[Url], patience: Duration) -> Vec<ProbeOutcome> {
|
||||
std::thread::scope(|scope| {
|
||||
let asking: Vec<_> = urls
|
||||
.iter()
|
||||
.map(|url| scope.spawn(move || probe::probe_within(url, None, patience)))
|
||||
.collect();
|
||||
asking
|
||||
.into_iter()
|
||||
.map(|a| {
|
||||
a.join().unwrap_or_else(|_| ProbeOutcome::Failed {
|
||||
detail: "The check stopped.".into(),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
/// The address the This Mac tab is about, with its answer: the default one,
|
||||
/// or, when nothing answers there, the first found server that does (a
|
||||
/// `codeman web --port 4000` in a terminal, a bind to one network address).
|
||||
fn shown<'a>(
|
||||
default: &'a Url,
|
||||
answer: &'a ProbeOutcome,
|
||||
found: &'a [(Url, ProbeOutcome)],
|
||||
) -> (&'a Url, &'a ProbeOutcome) {
|
||||
if *answer == ProbeOutcome::Refused {
|
||||
if let Some((url, answer)) = found.iter().find(|(_, a)| answers(a)) {
|
||||
return (url, answer);
|
||||
}
|
||||
}
|
||||
(default, answer)
|
||||
}
|
||||
|
||||
/// What the This Mac tab shows.
|
||||
@@ -449,8 +611,8 @@ pub enum LocalState {
|
||||
/// A Codeman server of this user runs but listens nowhere yet: it is
|
||||
/// still starting (the LaunchAgent at login, a restart).
|
||||
Starting,
|
||||
/// A Codeman server of this user runs, but not at an address the app can
|
||||
/// open (bound to one network address, say): see `elsewhere`.
|
||||
/// A Codeman server of this user runs, but none answers at an address the
|
||||
/// app can open (HTTPS with Codeman's own certificate, say): see `found`.
|
||||
RunningElsewhere,
|
||||
/// Nothing answers, and Codeman is installed.
|
||||
Stopped,
|
||||
@@ -478,12 +640,19 @@ pub struct LocalStatus {
|
||||
pub installed: bool,
|
||||
/// `install.sh` finished its work (its `.install-complete` marker).
|
||||
pub install_complete: bool,
|
||||
/// An install the app started is still running in Terminal, and the
|
||||
/// port it asked for once that is known.
|
||||
/// An install the app started is still running, and the port it asked
|
||||
/// for once that is known.
|
||||
pub install_running: bool,
|
||||
pub install_port: Option<u16>,
|
||||
/// For RunningElsewhere: the addresses that Codeman listens on.
|
||||
pub elsewhere: Vec<String>,
|
||||
/// That install is the graphical one, not a Terminal window: the page can
|
||||
/// show it (gui_install::follow), also after the app was quit.
|
||||
pub install_in_app: bool,
|
||||
/// A coding agent is being added the same way. Not an install: it says
|
||||
/// nothing about Codeman, which may well be running.
|
||||
pub agent_install_in_app: bool,
|
||||
/// Every Codeman server of this user that listens on this Mac, the one at
|
||||
/// the default address first: the tab offers to connect to each.
|
||||
pub found: Vec<FoundServer>,
|
||||
/// The probe's outcome, for the connect page's explanations.
|
||||
pub outcome: ProbeOutcome,
|
||||
}
|
||||
@@ -530,55 +699,44 @@ pub enum Depth {
|
||||
pub fn inspect(depth: Depth) -> LocalStatus {
|
||||
let home = dirs::home_dir().unwrap_or_default();
|
||||
let service = read_service();
|
||||
let url = local_url(service.as_ref());
|
||||
let default = local_url(service.as_ref());
|
||||
let procs = list_processes();
|
||||
let servers = codeman_servers(&procs);
|
||||
let found = listeners(&servers);
|
||||
let listening = listeners(&servers);
|
||||
let install = running_install(&procs);
|
||||
let install_in_app = procs.iter().any(|(_, c)| gui_install::Run::Codeman.matches(c));
|
||||
let agent_install_in_app = procs.iter().any(|(_, c)| gui_install::Run::Agent.matches(c));
|
||||
|
||||
// The login goes only to this user's own Codeman on that port.
|
||||
let auth = if serves_loopback_port(&found, url.port_or_known_default().unwrap_or(0)) {
|
||||
login_for(&url, service.as_ref(), &read_env_file()).map(|(u, p)| policy::basic_auth_header(&u, &p))
|
||||
let auth = if serves_loopback_port(&listening, default.port_or_known_default().unwrap_or(0)) {
|
||||
login_for(&default, service.as_ref(), &read_env_file()).map(|(u, p)| policy::basic_auth_header(&u, &p))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut outcome = probe::probe(&url, auth.as_deref());
|
||||
let mut url = url;
|
||||
let mut elsewhere = Vec::new();
|
||||
let answer = probe::probe(&default, auth.as_deref());
|
||||
|
||||
// Nothing at the usual address, but a Codeman server of this user runs:
|
||||
// find where (a `codeman web --port 4000` in a terminal, a bind to one
|
||||
// network address), so the tab never offers to start a second server on
|
||||
// the same sessions.
|
||||
if outcome == ProbeOutcome::Refused && !servers.is_empty() {
|
||||
let mut ports_seen = Vec::new();
|
||||
for l in &found {
|
||||
if ports_seen.contains(&(l.host.clone(), l.port)) {
|
||||
continue;
|
||||
}
|
||||
ports_seen.push((l.host.clone(), l.port));
|
||||
let Some(candidate) = listener_url(l) else {
|
||||
continue;
|
||||
};
|
||||
let answer = probe::probe(&candidate, None);
|
||||
if matches!(
|
||||
answer,
|
||||
ProbeOutcome::Ok { .. }
|
||||
| ProbeOutcome::NeedsLogin
|
||||
| ProbeOutcome::BadCredentials
|
||||
| ProbeOutcome::RateLimited { .. }
|
||||
| ProbeOutcome::PasswordChangeRequired
|
||||
) {
|
||||
url = candidate;
|
||||
outcome = answer;
|
||||
break;
|
||||
}
|
||||
elsewhere.push(format!("{}:{}", l.host, l.port));
|
||||
}
|
||||
if outcome == ProbeOutcome::Refused && elsewhere.is_empty() {
|
||||
elsewhere = servers.iter().map(|pid| format!("process {pid}")).collect();
|
||||
}
|
||||
// Every address one of this user's Codeman servers listens at. The one at
|
||||
// the default address has just answered; the others are asked now, once
|
||||
// each. With nothing at the default address, the first of them that
|
||||
// answers is what the tab opens, as it always was, so each gets the
|
||||
// probe's usual time; otherwise they are only listed, and get less.
|
||||
let patience = if answer == ProbeOutcome::Refused {
|
||||
probe::TIMEOUT
|
||||
} else {
|
||||
FOUND_TIMEOUT
|
||||
};
|
||||
let addresses = found_addresses(&procs, &listening, &default);
|
||||
let others: Vec<Url> = addresses.iter().filter(|u| **u != default).cloned().collect();
|
||||
let mut answered: Vec<(Url, ProbeOutcome)> = others.iter().cloned().zip(ask_found(&others, patience)).collect();
|
||||
// found_addresses puts the default address first.
|
||||
if addresses.first() == Some(&default) {
|
||||
answered.insert(0, (default.clone(), answer.clone()));
|
||||
}
|
||||
let found: Vec<FoundServer> = answered.iter().map(|(u, a)| found_server(u, a, &default)).collect();
|
||||
// The tab never offers to start a second server on the same sessions: it
|
||||
// opens the one that answers, or lists where they listen.
|
||||
let (url, outcome) = shown(&default, &answer, &answered);
|
||||
let (url, outcome) = (url.clone(), outcome.clone());
|
||||
|
||||
let app = home.join(".codeman/app");
|
||||
let install_complete = app.join(".install-complete").is_file();
|
||||
@@ -596,10 +754,7 @@ pub fn inspect(depth: Depth) -> LocalStatus {
|
||||
Depth::Login => local_server::installed(false),
|
||||
Depth::Interactive => local_server::installed(true),
|
||||
};
|
||||
let state = local_state(&outcome, !servers.is_empty(), !found.is_empty(), installed);
|
||||
if state != LocalState::RunningElsewhere {
|
||||
elsewhere.clear();
|
||||
}
|
||||
let state = local_state(&outcome, !servers.is_empty(), !listening.is_empty(), installed);
|
||||
let version = match &outcome {
|
||||
ProbeOutcome::Ok { version } => Some(version.clone()),
|
||||
_ => None,
|
||||
@@ -614,7 +769,9 @@ pub fn inspect(depth: Depth) -> LocalStatus {
|
||||
install_complete,
|
||||
install_running: install.is_some(),
|
||||
install_port: install.flatten(),
|
||||
elsewhere,
|
||||
install_in_app,
|
||||
agent_install_in_app,
|
||||
found,
|
||||
outcome,
|
||||
}
|
||||
}
|
||||
@@ -624,7 +781,7 @@ pub fn inspect(depth: Depth) -> LocalStatus {
|
||||
/// attach to the first one's live sessions (src/config/instance.ts), and
|
||||
/// `codeman web -d` only notices a server it started itself or one at the
|
||||
/// same address.
|
||||
fn already_running() -> Option<String> {
|
||||
pub fn already_running() -> Option<String> {
|
||||
let servers = codeman_servers(&list_processes());
|
||||
let pid = servers.first()?;
|
||||
let found = listeners(&servers);
|
||||
@@ -1389,9 +1546,375 @@ mod tests {
|
||||
assert!(serves_loopback_port(&found, 4000));
|
||||
assert!(!serves_loopback_port(&found, 3999));
|
||||
assert!(!serves_loopback_port(&found, 5000));
|
||||
assert_eq!(listener_url(&found[1]).unwrap().as_str(), "http://172.17.0.1:3999/");
|
||||
assert_eq!(listener_url(&found[2]).unwrap().as_str(), "http://127.0.0.1:4000/");
|
||||
assert_eq!(listener_url(&found[3]).unwrap().as_str(), "http://[::1]:5000/");
|
||||
// The same four sockets as the addresses the app can try, by port.
|
||||
assert_eq!(
|
||||
addresses(&procs, &found, "http://127.0.0.1:3000/"),
|
||||
[
|
||||
"http://127.0.0.1:3000/",
|
||||
"http://172.17.0.1:3999/",
|
||||
"http://127.0.0.1:4000/",
|
||||
"http://[::1]:5000/"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
fn server(pid: u32, flags: &str) -> (u32, String) {
|
||||
(pid, format!("node /opt/homebrew/bin/codeman web{flags}"))
|
||||
}
|
||||
|
||||
fn listener(pid: u32, host: &str, port: u16) -> Listener {
|
||||
Listener {
|
||||
pid,
|
||||
host: host.into(),
|
||||
port,
|
||||
}
|
||||
}
|
||||
|
||||
/// found_addresses, as strings. The page sends one back in a `connect`,
|
||||
/// so each must be an address the connect takes as it is: the app saves
|
||||
/// a server, and finds its saved login, under that exact string.
|
||||
fn addresses(procs: &[(u32, String)], listeners: &[Listener], default: &str) -> Vec<String> {
|
||||
found_addresses(procs, listeners, &u(default))
|
||||
.iter()
|
||||
.map(|url| {
|
||||
assert_eq!(policy::normalize_server_url(url.as_str()).as_ref(), Ok(url));
|
||||
url.to_string()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_found_server_becomes_an_address_the_app_can_try() {
|
||||
let default = "http://127.0.0.1:3000/";
|
||||
let one = |flags: &str, listeners: &[Listener]| addresses(&[server(1, flags)], listeners, default);
|
||||
|
||||
// Every interface and IPv4 loopback are reached at 127.0.0.1.
|
||||
for host in ["*", "0.0.0.0", "[::]", "127.0.0.1"] {
|
||||
assert_eq!(
|
||||
one(" --port 4000", &[listener(1, host, 4000)]),
|
||||
["http://127.0.0.1:4000/"],
|
||||
"{host}"
|
||||
);
|
||||
}
|
||||
// IPv6 loopback keeps its own address only when it is the server's
|
||||
// only loopback socket.
|
||||
assert_eq!(one("", &[listener(1, "[::1]", 5000)]), ["http://[::1]:5000/"]);
|
||||
assert_eq!(
|
||||
one("", &[listener(1, "[::1]", 5000), listener(1, "127.0.0.1", 5000)]),
|
||||
["http://127.0.0.1:5000/"]
|
||||
);
|
||||
// A dual-stack bind shows as two sockets, both `*`: one address.
|
||||
assert_eq!(
|
||||
one("", &[listener(1, "*", 5000), listener(1, "*", 5000)]),
|
||||
["http://127.0.0.1:5000/"]
|
||||
);
|
||||
// A bind to one address stays that address.
|
||||
assert_eq!(
|
||||
one(" --host 192.168.1.5", &[listener(1, "192.168.1.5", 3000)]),
|
||||
["http://192.168.1.5:3000/"]
|
||||
);
|
||||
|
||||
// --https and --base-url come from the command line, in both spellings.
|
||||
assert_eq!(
|
||||
one(" --https --port 4000 --base-url /codeman/", &[listener(1, "*", 4000)]),
|
||||
["https://127.0.0.1:4000/codeman/"]
|
||||
);
|
||||
assert_eq!(
|
||||
one(" -p 4000 --base-url=cm", &[listener(1, "127.0.0.1", 4000)]),
|
||||
["http://127.0.0.1:4000/cm/"]
|
||||
);
|
||||
// The value of --host is never read as a flag, and a base path Codeman
|
||||
// would refuse counts as none.
|
||||
assert_eq!(
|
||||
one(" --host --https -p 4000", &[listener(1, "127.0.0.1", 4000)]),
|
||||
["http://127.0.0.1:4000/"]
|
||||
);
|
||||
assert_eq!(
|
||||
one(" -p 4000 --base-url /a?b", &[listener(1, "127.0.0.1", 4000)]),
|
||||
["http://127.0.0.1:4000/"]
|
||||
);
|
||||
// What comes before `web` is node's business.
|
||||
assert_eq!(
|
||||
addresses(
|
||||
&[(1, "node --https /Users/k/.codeman/app/dist/index.js web".to_string())],
|
||||
&[listener(1, "*", 4000)],
|
||||
default
|
||||
),
|
||||
["http://127.0.0.1:4000/"]
|
||||
);
|
||||
|
||||
// A server with two listeners. Beside a loopback socket on the same
|
||||
// port, another one is the same server (the Docker bridge listener);
|
||||
// on another port, or with no loopback socket, each is an address.
|
||||
assert_eq!(
|
||||
one("", &[listener(1, "127.0.0.1", 3001), listener(1, "172.17.0.1", 3001)]),
|
||||
["http://127.0.0.1:3001/"]
|
||||
);
|
||||
assert_eq!(
|
||||
one("", &[listener(1, "172.17.0.1", 3999), listener(1, "127.0.0.1", 3001)]),
|
||||
["http://127.0.0.1:3001/", "http://172.17.0.1:3999/"]
|
||||
);
|
||||
assert_eq!(
|
||||
one("", &[listener(1, "192.168.1.5", 3001), listener(1, "100.64.0.7", 3001)]),
|
||||
["http://100.64.0.7:3001/", "http://192.168.1.5:3001/"]
|
||||
);
|
||||
|
||||
// Only the sockets of Codeman servers count: not a control command's,
|
||||
// another program's, or one whose process `ps` did not list.
|
||||
let procs = [
|
||||
server(1, " --port 4000"),
|
||||
(2, "node /opt/homebrew/bin/codeman attach w1".to_string()),
|
||||
(3, "python3 -m http.server 8000".to_string()),
|
||||
];
|
||||
let sockets = [
|
||||
listener(2, "*", 4100),
|
||||
listener(3, "*", 8000),
|
||||
listener(9, "*", 9000),
|
||||
listener(1, "*", 4000),
|
||||
];
|
||||
assert_eq!(addresses(&procs, &sockets, default), ["http://127.0.0.1:4000/"]);
|
||||
assert!(addresses(&procs, &sockets[..3], default).is_empty());
|
||||
// An address that makes no URL is left out.
|
||||
assert!(one("", &[listener(1, "not a host", 3001)]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn found_addresses_start_with_the_default_one_then_go_by_port() {
|
||||
// install.sh's launchd job: a bare `web`, the base path in its environment.
|
||||
let default = "http://127.0.0.1:3001/codeman/";
|
||||
let procs = [
|
||||
(
|
||||
10,
|
||||
"node /x/tsx/cli.mjs /Users/k/codeman/src/index.ts web --port 5000".to_string(),
|
||||
),
|
||||
(
|
||||
20,
|
||||
"/opt/homebrew/bin/node /Users/k/.codeman/app/dist/index.js web".to_string(),
|
||||
),
|
||||
server(30, " -p 4000 --https"),
|
||||
// The same address twice: a second process on the port of the first.
|
||||
server(40, " --port 5000"),
|
||||
];
|
||||
let sockets = [
|
||||
listener(10, "*", 5000),
|
||||
listener(20, "*", 3001),
|
||||
listener(30, "127.0.0.1", 4000),
|
||||
listener(40, "127.0.0.1", 5000),
|
||||
];
|
||||
assert_eq!(
|
||||
addresses(&procs, &sockets, default),
|
||||
[
|
||||
"http://127.0.0.1:3001/codeman/",
|
||||
"https://127.0.0.1:4000/",
|
||||
"http://127.0.0.1:5000/"
|
||||
]
|
||||
);
|
||||
// The same list whatever order `ps` and `lsof` gave.
|
||||
let mut reversed_procs = procs.to_vec();
|
||||
reversed_procs.reverse();
|
||||
let mut reversed_sockets = sockets.to_vec();
|
||||
reversed_sockets.reverse();
|
||||
assert_eq!(
|
||||
addresses(&reversed_procs, &reversed_sockets, default),
|
||||
addresses(&procs, &sockets, default)
|
||||
);
|
||||
|
||||
// On the default port, a command line with its own base path or
|
||||
// scheme is taken at its word: it may be another server than the job's.
|
||||
let on_3001 = |flags: &str| addresses(&[server(1, flags)], &[listener(1, "*", 3001)], default);
|
||||
assert_eq!(on_3001(" --port 3001"), [default]);
|
||||
assert_eq!(on_3001(" --port 3001 --base-url /codeman"), [default]);
|
||||
assert_eq!(
|
||||
on_3001(" --port 3001 --base-url /other"),
|
||||
["http://127.0.0.1:3001/other/"]
|
||||
);
|
||||
assert_eq!(on_3001(" --port 3001 --base-url /"), ["http://127.0.0.1:3001/"]);
|
||||
assert_eq!(on_3001(" --port 3001 --https"), ["https://127.0.0.1:3001/"]);
|
||||
// 127.0.0.1 only: a bind to another address is not the default one.
|
||||
assert_eq!(
|
||||
addresses(&[server(1, "")], &[listener(1, "192.168.1.5", 3001)], default),
|
||||
["http://192.168.1.5:3001/"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_found_server_row_says_what_answered() {
|
||||
let default = u("http://127.0.0.1:3000/");
|
||||
let at = u("http://127.0.0.1:4000/");
|
||||
let row = |answer: ProbeOutcome| found_server(&at, &answer, &default);
|
||||
assert_eq!(
|
||||
row(ProbeOutcome::Ok {
|
||||
version: "1.49.0".into()
|
||||
}),
|
||||
FoundServer {
|
||||
url: "http://127.0.0.1:4000/".into(),
|
||||
version: Some("1.49.0".into()),
|
||||
state: FoundState::Running,
|
||||
is_default: false,
|
||||
}
|
||||
);
|
||||
let state = |answer: ProbeOutcome| {
|
||||
let row = row(answer);
|
||||
assert_eq!(row.version, None);
|
||||
row.state
|
||||
};
|
||||
assert_eq!(state(ProbeOutcome::PasswordChangeRequired), FoundState::Running);
|
||||
for login in [
|
||||
ProbeOutcome::NeedsLogin,
|
||||
ProbeOutcome::BadCredentials,
|
||||
ProbeOutcome::RateLimited {
|
||||
sent_credentials: false,
|
||||
retry_after_secs: Some(60),
|
||||
},
|
||||
] {
|
||||
assert_eq!(state(login), FoundState::NeedsLogin);
|
||||
}
|
||||
for certificate in [
|
||||
ProbeOutcome::TlsUntrusted {
|
||||
detail: "invalid peer certificate: UnknownIssuer".into(),
|
||||
},
|
||||
ProbeOutcome::MaybeHttps,
|
||||
] {
|
||||
assert_eq!(state(certificate), FoundState::Certificate);
|
||||
}
|
||||
for silent in [
|
||||
ProbeOutcome::Refused,
|
||||
ProbeOutcome::Timeout,
|
||||
ProbeOutcome::Unreachable,
|
||||
ProbeOutcome::HostNotAllowed,
|
||||
ProbeOutcome::NotCodeman { status: 403 },
|
||||
ProbeOutcome::Failed { detail: "x".into() },
|
||||
] {
|
||||
assert_eq!(state(silent), FoundState::Unreachable);
|
||||
}
|
||||
assert!(found_server(&default, &ProbeOutcome::Refused, &default).is_default);
|
||||
|
||||
// As the connect page reads it.
|
||||
assert_eq!(
|
||||
serde_json::to_value(row(ProbeOutcome::Ok {
|
||||
version: "1.49.0".into()
|
||||
}))
|
||||
.unwrap(),
|
||||
json!({ "url": "http://127.0.0.1:4000/", "version": "1.49.0", "state": "running", "isDefault": false })
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(found_server(&default, &ProbeOutcome::NeedsLogin, &default)).unwrap(),
|
||||
json!({ "url": "http://127.0.0.1:3000/", "version": null, "state": "needsLogin", "isDefault": true })
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value([FoundState::Certificate, FoundState::Unreachable]).unwrap(),
|
||||
json!(["certificate", "unreachable"])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tab_is_about_the_default_address_unless_nothing_answers_there() {
|
||||
let default = u("http://127.0.0.1:3000/");
|
||||
let ok = ProbeOutcome::Ok {
|
||||
version: "1.49.0".into(),
|
||||
};
|
||||
let refused = ProbeOutcome::Refused;
|
||||
let found = vec![
|
||||
(
|
||||
u("https://127.0.0.1:4000/"),
|
||||
ProbeOutcome::TlsUntrusted { detail: "x".into() },
|
||||
),
|
||||
(u("http://127.0.0.1:5000/"), ProbeOutcome::NeedsLogin),
|
||||
(u("http://127.0.0.1:6000/"), ok.clone()),
|
||||
];
|
||||
// Nothing at the default address: the first found server that
|
||||
// answers, one that wants a login included.
|
||||
assert_eq!(
|
||||
shown(&default, &refused, &found),
|
||||
(&found[1].0, &ProbeOutcome::NeedsLogin)
|
||||
);
|
||||
assert_eq!(shown(&default, &refused, &found[2..]), (&found[2].0, &ok));
|
||||
// None of them answers: the tab stays on the default address, and
|
||||
// local_state makes that RunningElsewhere.
|
||||
assert_eq!(shown(&default, &refused, &found[..1]), (&default, &refused));
|
||||
assert_eq!(shown(&default, &refused, &[]), (&default, &refused));
|
||||
// Whatever else the default address says is what the tab shows; the
|
||||
// servers found elsewhere are only listed.
|
||||
for answer in [
|
||||
ok.clone(),
|
||||
ProbeOutcome::NeedsLogin,
|
||||
ProbeOutcome::NotCodeman { status: 404 },
|
||||
ProbeOutcome::Timeout,
|
||||
ProbeOutcome::MaybeHttps,
|
||||
] {
|
||||
assert_eq!(shown(&default, &answer, &found), (&default, &answer));
|
||||
}
|
||||
}
|
||||
|
||||
/// Against real sockets: every address is asked, at the same time, and
|
||||
/// the answers come back in the order of the addresses.
|
||||
#[test]
|
||||
fn found_servers_are_asked_together() {
|
||||
use std::io::Read;
|
||||
use std::net::TcpListener;
|
||||
use std::sync::mpsc;
|
||||
|
||||
/// A server for one request: it reads it, and answers with `response`
|
||||
/// if `ready` says so.
|
||||
fn serve(response: String, ready: impl FnOnce() -> bool + Send + 'static) -> Url {
|
||||
let l = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = l.local_addr().unwrap().port();
|
||||
std::thread::spawn(move || {
|
||||
if let Ok((mut s, _)) = l.accept() {
|
||||
let mut head = Vec::new();
|
||||
let mut buf = [0u8; 4096];
|
||||
while !head.windows(4).any(|w| w == b"\r\n\r\n") {
|
||||
match s.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => head.extend_from_slice(&buf[..n]),
|
||||
}
|
||||
}
|
||||
if ready() {
|
||||
let _ = s.write_all(response.as_bytes());
|
||||
}
|
||||
}
|
||||
});
|
||||
u(&format!("http://127.0.0.1:{port}/"))
|
||||
}
|
||||
fn response(status_line: &str, body: &str) -> String {
|
||||
format!(
|
||||
"HTTP/1.1 {status_line}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
}
|
||||
|
||||
// The first server answers only once the second has been asked. Asked
|
||||
// one after the other, it would hang up without an answer.
|
||||
let (asked, was_asked) = mpsc::channel::<()>();
|
||||
let first = serve(
|
||||
response("200 OK", r#"{"success":true,"data":{"version":"9.9.9"}}"#),
|
||||
move || was_asked.recv_timeout(Duration::from_secs(4)).is_ok(),
|
||||
);
|
||||
let second = serve(response("401 Unauthorized", "Unauthorized"), move || {
|
||||
asked.send(()).is_ok()
|
||||
});
|
||||
let closed = {
|
||||
let l = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
u(&format!("http://127.0.0.1:{}/", l.local_addr().unwrap().port()))
|
||||
};
|
||||
assert_eq!(
|
||||
ask_found(&[first, second, closed], probe::TIMEOUT),
|
||||
[
|
||||
ProbeOutcome::Ok {
|
||||
version: "9.9.9".into()
|
||||
},
|
||||
ProbeOutcome::NeedsLogin,
|
||||
ProbeOutcome::Refused,
|
||||
]
|
||||
);
|
||||
|
||||
// One that does not answer in the time it is given.
|
||||
let slow = serve(String::new(), || {
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
false
|
||||
});
|
||||
assert_eq!(ask_found(&[slow], Duration::from_millis(300)), [ProbeOutcome::Timeout]);
|
||||
assert!(ask_found(&[], FOUND_TIMEOUT).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user