mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-12-01 08:59:32 +01:00
feat(desktop): install Codeman from the app, with no Terminal and no password
The This Mac tab runs install.sh --no-admin itself. The two questions only a person can answer move into the app: which coding agent to install, shown only when this Mac has none, and who may reach Codeman. The installer's output goes to a file, so a running install survives the app quitting and is picked up again when it reopens. install.sh gains --ai-cli, --progress and a preflight subcommand, which is what the app reads its choices from, so it keeps no copy of the CLI catalogue. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ed74ae41bc
commit
b51632e54b
14 files changed
+2670
-105
No files matched your search
+54
-14
@@ -28,7 +28,7 @@ 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. 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). 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. 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. |
|
||||
| **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. 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. 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. |
|
||||
@@ -54,6 +54,11 @@ cargo test # unit tests
|
||||
open dist/Codeman.app
|
||||
```
|
||||
|
||||
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
|
||||
@@ -133,19 +138,40 @@ 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.
|
||||
|
||||
**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
|
||||
@@ -249,6 +275,20 @@ and the Dock icon bounces.
|
||||
- **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
|
||||
|
||||
@@ -25,10 +25,12 @@
|
||||
background: radial-gradient(1200px 600px at 50% -10%, #111a2b 0%, var(--bg) 60%) fixed, var(--bg);
|
||||
color: var(--text);
|
||||
font: 14px/1.45 -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", system-ui, sans-serif;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
display: flex; justify-content: center;
|
||||
-webkit-user-select: none; user-select: none;
|
||||
}
|
||||
main { width: min(440px, calc(100vw - 48px)); }
|
||||
/* margin:auto, not align-items:center: a flex child taller than the window
|
||||
then starts at the top instead of being cut off above it. */
|
||||
main { width: min(440px, calc(100vw - 48px)); margin: auto; padding: 24px 0; }
|
||||
header { text-align: center; margin-bottom: 26px; }
|
||||
header img { width: 76px; height: 76px; display: block; margin: 0 auto 12px; }
|
||||
h1 { font-size: 24px; font-weight: 650; letter-spacing: -0.01em; margin: 0; }
|
||||
@@ -102,7 +104,6 @@
|
||||
@media (prefers-reduced-motion: reduce) { .dot.busy { animation: none; } }
|
||||
#local-title { font-weight: 600; }
|
||||
.sub { color: var(--muted); font-size: 12px; margin-top: 3px; -webkit-user-select: text; user-select: text; overflow-wrap: anywhere; }
|
||||
#local-network-row[hidden] { display: none; }
|
||||
#elsewhere { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--line); }
|
||||
#elsewhere summary { color: var(--muted); font-size: 13px; cursor: default; list-style: none; }
|
||||
#elsewhere summary::-webkit-details-marker { display: none; }
|
||||
@@ -118,6 +119,81 @@
|
||||
.statusrow { display: flex; gap: 10px; align-items: flex-start; }
|
||||
.statusrow #status { flex: 1; }
|
||||
.statusrow #cancel { margin-top: 10px; }
|
||||
/* The graphical install takes over the card, and its steps differ in height:
|
||||
anchored from the top, so the logo does not jump from one to the next. */
|
||||
main:has(.card.wizard-on) { margin-top: max(0px, calc(14vh - 60px)); margin-bottom: auto; }
|
||||
main:has(.card.wizard-on) header p { display: none; }
|
||||
.card.wizard-on > .tabs, .card.wizard-on > #pane-local, .card.wizard-on > #form,
|
||||
.card.wizard-on > .statusrow, .card.wizard-on > #suggest, .card.wizard-on > .prefs { display: none; }
|
||||
#wizard[hidden], #wizard [hidden] { display: none; }
|
||||
.wiz-head { display: flex; align-items: center; gap: 9px; }
|
||||
.wiz-head .spinner { margin-top: 0; }
|
||||
#wiz-title { font-size: 17px; font-weight: 650; letter-spacing: -0.01em; margin: 0; }
|
||||
#wiz-title:focus { outline: none; }
|
||||
#wiz-lead { margin: 6px 0 0; color: var(--muted); font-size: 13px; }
|
||||
#wiz-message {
|
||||
margin: 12px 0 0; padding: 10px 12px; border: 1px solid rgba(248,113,113,0.4); border-radius: 9px;
|
||||
background: rgba(248,113,113,0.08); color: var(--bad); font-size: 13px; white-space: pre-wrap;
|
||||
overflow-wrap: anywhere; -webkit-user-select: text; user-select: text;
|
||||
}
|
||||
#wiz-message.warn { border-color: rgba(251,191,36,0.4); background: rgba(251,191,36,0.08); color: var(--warn); }
|
||||
.wiz-group { margin-top: 14px; }
|
||||
#wiz-agents { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
|
||||
.choice {
|
||||
display: flex; gap: 9px; align-items: flex-start; padding: 9px 11px; border-radius: 9px;
|
||||
border: 1px solid var(--line-strong); background: #0f1013; cursor: default;
|
||||
}
|
||||
.choice:hover { border-color: #454a55; }
|
||||
.choice:has(input:checked) { border-color: var(--accent-2); background: rgba(59,130,246,0.1); }
|
||||
.choice:has(input:focus-visible) { outline: 2px solid var(--accent-2); outline-offset: 1px; }
|
||||
.choice input { accent-color: var(--accent-2); margin: 2px 0 0; flex: none; }
|
||||
.choice b { display: block; font-weight: 600; }
|
||||
.choice small { display: block; margin-top: 1px; color: var(--muted); font-size: 12px; }
|
||||
#wiz-reach .choice + .choice { margin-top: 6px; }
|
||||
#wiz-password { margin-top: 10px; }
|
||||
#wiz-agent-note { margin: 10px 0 0; color: var(--muted); font-size: 12px; }
|
||||
#wiz-agent-note a, .wiz-link { all: unset; color: #7c8491; cursor: default; }
|
||||
#wiz-agent-note a { color: var(--accent); white-space: nowrap; }
|
||||
#wiz-agent-note a:hover, .wiz-link:hover { color: var(--text); }
|
||||
.wiz-link:focus-visible, #wiz-agent-note a:focus-visible { outline: 2px solid var(--accent-2); outline-offset: 2px; border-radius: 3px; }
|
||||
.wiz-link { display: block; margin: 12px auto 0; font-size: 12px; text-align: center; }
|
||||
#wiz-summary { margin: 14px 0 0; padding: 12px 0 0; border-top: 1px solid var(--line); list-style: none; color: var(--muted); font-size: 12px; }
|
||||
#wiz-summary li { padding: 2px 0 2px 14px; position: relative; }
|
||||
#wiz-summary li::before { content: ''; position: absolute; left: 2px; top: 9px; width: 4px; height: 4px; border-radius: 50%; background: #5d626b; }
|
||||
#wiz-summary li.warn { color: var(--warn); }
|
||||
/* The install's rail: one node per phase, joined by a line that fills in as
|
||||
the phases finish. The running node carries the phase's own clock, because
|
||||
the longest phases print nothing while they work. */
|
||||
#wiz-rail { margin: 16px 0 0; padding: 0; list-style: none; }
|
||||
#wiz-rail li { position: relative; display: flex; align-items: baseline; gap: 10px; padding: 0 0 13px 24px; color: #6b717c; }
|
||||
#wiz-rail li:last-child { padding-bottom: 0; }
|
||||
#wiz-rail li::before {
|
||||
content: ''; position: absolute; left: 4px; top: 6px; width: 8px; height: 8px; box-sizing: content-box;
|
||||
border-radius: 50%; background: var(--panel); border: 1px solid #454a55; z-index: 1;
|
||||
}
|
||||
#wiz-rail li::after { content: ''; position: absolute; left: 8.5px; top: 12px; bottom: -6px; width: 1px; background: var(--line-strong); }
|
||||
#wiz-rail li:last-child::after { display: none; }
|
||||
#wiz-rail li.done { color: var(--text); }
|
||||
#wiz-rail li.done::before { background: var(--ok); border-color: var(--ok); }
|
||||
#wiz-rail li.done::after { background: rgba(74,222,128,0.45); }
|
||||
#wiz-rail li.now { color: var(--text); font-weight: 600; }
|
||||
#wiz-rail li.now::before { background: var(--accent); border-color: var(--accent); box-shadow: 0 0 0 4px rgba(96,165,250,0.18); animation: pulse 1.2s ease-in-out infinite; }
|
||||
#wiz-rail li.failed { color: var(--bad); font-weight: 600; }
|
||||
#wiz-rail li.failed::before { background: var(--bad); border-color: var(--bad); }
|
||||
@media (prefers-reduced-motion: reduce) { #wiz-rail li.now::before { animation: none; } }
|
||||
#wiz-rail .clock { margin-left: auto; color: var(--muted); font-size: 12px; font-weight: 400; font-variant-numeric: tabular-nums; }
|
||||
#wiz-details { margin-top: 14px; }
|
||||
#wiz-details summary { color: var(--muted); font-size: 12px; cursor: default; list-style: none; }
|
||||
#wiz-details summary::-webkit-details-marker { display: none; }
|
||||
#wiz-details summary::before { content: '\25B8'; display: inline-block; width: 13px; transition: transform 0.15s; }
|
||||
#wiz-details[open] summary::before { transform: rotate(90deg); }
|
||||
#wiz-details summary:hover { color: var(--text); }
|
||||
#wiz-log {
|
||||
margin: 8px 0 0; height: 124px; overflow: auto; padding: 8px 10px; border-radius: 8px; background: #0c0d10;
|
||||
border: 1px solid var(--line); color: #aab1bb; font: 11px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
white-space: pre-wrap; overflow-wrap: anywhere; -webkit-user-select: text; user-select: text;
|
||||
}
|
||||
#wizard .actions .wiz-busy { display: inline-flex; align-items: center; gap: 8px; color: var(--muted); font-size: 13px; }
|
||||
footer { margin-top: 18px; text-align: center; color: #5d626b; font-size: 12px; }
|
||||
footer a { color: #7c8491; text-decoration: none; cursor: default; }
|
||||
footer a:hover { color: var(--accent); }
|
||||
@@ -138,6 +214,45 @@
|
||||
<button type="button" role="tab" id="tab-remote" aria-controls="form" aria-selected="false" tabindex="-1">Another machine</button>
|
||||
</div>
|
||||
|
||||
<section id="wizard" aria-labelledby="wiz-title" hidden>
|
||||
<div class="wiz-head"><span class="spinner" id="wiz-spinner" hidden></span><h2 id="wiz-title" tabindex="-1"></h2></div>
|
||||
<p id="wiz-lead"></p>
|
||||
<div id="wiz-message" role="alert" hidden></div>
|
||||
|
||||
<div class="wiz-group" id="wiz-agent-step" hidden>
|
||||
<div id="wiz-agents" role="radiogroup" aria-labelledby="wiz-title"></div>
|
||||
<p id="wiz-agent-note"></p>
|
||||
</div>
|
||||
|
||||
<div class="wiz-group" id="wiz-reach-step" hidden>
|
||||
<div id="wiz-reach" role="radiogroup" aria-labelledby="wiz-title">
|
||||
<label class="choice"><input type="radio" name="reach" value="local" checked>
|
||||
<span><b>Only this Mac</b><small>The safest choice. You can open it to other devices later.</small></span></label>
|
||||
<label class="choice"><input type="radio" name="reach" value="network">
|
||||
<span><b>This Mac and my local network</b><small>Phones and laptops on the same Wi-Fi sign in with a password.</small></span></label>
|
||||
</div>
|
||||
<div id="wiz-password" class="row" hidden>
|
||||
<div><label class="field" for="wiz-pw">Password</label><input id="wiz-pw" type="password" autocomplete="new-password"></div>
|
||||
<div><label class="field" for="wiz-pw2">Repeat it</label><input id="wiz-pw2" type="password" autocomplete="new-password"></div>
|
||||
</div>
|
||||
<ul id="wiz-summary"></ul>
|
||||
</div>
|
||||
|
||||
<ol id="wiz-rail" hidden></ol>
|
||||
<details id="wiz-details" hidden>
|
||||
<summary>Show the installer’s output</summary>
|
||||
<pre id="wiz-log"></pre>
|
||||
</details>
|
||||
|
||||
<div class="actions">
|
||||
<button class="secondary" id="wiz-back" type="button" hidden>Back</button>
|
||||
<button class="secondary" id="wiz-skip" type="button" hidden>Skip for now</button>
|
||||
<button class="primary" id="wiz-next" type="button" hidden></button>
|
||||
<button class="secondary" id="wiz-cancel" type="button" hidden>Cancel install</button>
|
||||
</div>
|
||||
<button class="wiz-link" id="wiz-terminal" type="button" hidden>Install in Terminal instead (asks for your Mac password)</button>
|
||||
</section>
|
||||
|
||||
<p id="webkit" role="alert" hidden>Codeman needs a newer WebKit than this Mac has: macOS 13.3 or later, or Safari 16.4 or later on macOS 11 and 12.</p>
|
||||
|
||||
<section id="pane-local" role="tabpanel" aria-labelledby="tab-local">
|
||||
@@ -148,7 +263,6 @@
|
||||
<div class="sub" id="local-detail"></div>
|
||||
</div>
|
||||
</div>
|
||||
<label class="check" id="local-network-row" hidden><input id="local-network" type="checkbox"> Also reach it from my phone and other computers (the installer asks how)</label>
|
||||
<div class="actions">
|
||||
<button class="primary" id="local-open" type="button" hidden>Open Codeman</button>
|
||||
<button class="primary" id="local-start" type="button" hidden>Start Codeman</button>
|
||||
@@ -236,7 +350,13 @@
|
||||
auto: $('auto'), fullscreen: $('fullscreen'), version: $('version'), webkit: $('webkit'),
|
||||
tabLocal: $('tab-local'), tabRemote: $('tab-remote'), paneLocal: $('pane-local'),
|
||||
localDot: $('local-dot'), localTitle: $('local-title'), localDetail: $('local-detail'),
|
||||
localNetworkRow: $('local-network-row'), localNetwork: $('local-network'),
|
||||
card: document.querySelector('.card'),
|
||||
wizard: $('wizard'), wizSpinner: $('wiz-spinner'), wizTitle: $('wiz-title'), wizLead: $('wiz-lead'), wizMessage: $('wiz-message'),
|
||||
wizAgentStep: $('wiz-agent-step'), wizAgents: $('wiz-agents'), wizAgentNote: $('wiz-agent-note'),
|
||||
wizReachStep: $('wiz-reach-step'), wizPassword: $('wiz-password'), wizPw: $('wiz-pw'), wizPw2: $('wiz-pw2'),
|
||||
wizSummary: $('wiz-summary'), wizRail: $('wiz-rail'), wizDetails: $('wiz-details'), wizLog: $('wiz-log'),
|
||||
wizBack: $('wiz-back'), wizSkip: $('wiz-skip'), wizNext: $('wiz-next'), wizCancel: $('wiz-cancel'),
|
||||
wizTerminal: $('wiz-terminal'),
|
||||
localOpen: $('local-open'), localStart: $('local-start'), localInstall: $('local-install'),
|
||||
localStop: $('local-stop'), localCheck: $('local-check'),
|
||||
elsewhere: $('elsewhere'), ssh: $('ssh'), sshInstall: $('ssh-install'), copy: $('copy')
|
||||
@@ -247,17 +367,21 @@
|
||||
// suggestion: the address the suggest button connects to.
|
||||
// tab: 'local' (This Mac) or 'remote' (Another machine). local: the last
|
||||
// This Mac status from the app. wait: set while an install runs in
|
||||
// Terminal and this page polls for the server it brings up.
|
||||
// Terminal and this page polls for the server it brings up. gui: the
|
||||
// graphical install while its screens are up (newWizard), null otherwise.
|
||||
var state = {
|
||||
servers: [], busy: false, lastUrl: '', startUrl: '', suggestion: '',
|
||||
tab: 'local', local: null, localChecking: false, opening: false, wait: null, waitTimer: 0,
|
||||
stoppedWaiting: false
|
||||
stoppedWaiting: false, gui: null
|
||||
};
|
||||
// While an install runs: how often to look, how long a finished install may
|
||||
// take to answer before Start is offered, and when to stop looking.
|
||||
var WAIT_POLL_MS = 3000;
|
||||
var WAIT_START_GRACE_MS = 90 * 1000;
|
||||
var WAIT_MAX_MS = 30 * 60 * 1000;
|
||||
// The phases `install.sh --progress` reports, in its order.
|
||||
var PHASES = ['runtime', 'agent', 'source', 'packages', 'build', 'service'];
|
||||
var MAX_LOG_LINES = 600;
|
||||
|
||||
function post(msg) { try { window.ipc.postMessage(JSON.stringify(msg)); } catch (e) { /* not in the app */ } }
|
||||
|
||||
@@ -541,7 +665,7 @@
|
||||
|
||||
function renderLocal() {
|
||||
var s = state.local;
|
||||
var show = { open: false, start: false, install: false, stop: false, check: false, network: false };
|
||||
var show = { open: false, start: false, install: false, stop: false, check: false };
|
||||
var dot = '';
|
||||
var title = '';
|
||||
var detail = '';
|
||||
@@ -589,19 +713,17 @@
|
||||
show.check = true;
|
||||
} else if (s.state === 'notInstalled') {
|
||||
title = 'Codeman is not installed on this Mac.';
|
||||
detail = 'Install runs Codeman’s installer in Terminal: a few minutes, and it may ask for your Mac password. ' +
|
||||
detail = 'Install sets it up here in a few minutes, with no password and no Terminal. ' +
|
||||
'Codeman then runs in the background and starts when you log in, so your sessions keep running when this app is closed.';
|
||||
show.install = true;
|
||||
show.network = true;
|
||||
show.check = true;
|
||||
} else if (!s.installed) {
|
||||
// Something else holds Codeman's port; a fresh install takes the next free one.
|
||||
var other = s.outcome || {};
|
||||
title = 'Codeman is not installed on this Mac.';
|
||||
detail = 'Something else answers at ' + s.url + (other.kind === 'notCodeman' ? ' (HTTP ' + other.status + ')' : '') +
|
||||
', so Install sets Codeman up on the next free port. It runs Codeman’s installer in Terminal: a few minutes, and it may ask for your Mac password.';
|
||||
', so Install sets Codeman up on the next free port: a few minutes, with no password and no Terminal.';
|
||||
show.install = true;
|
||||
show.network = true;
|
||||
show.check = true;
|
||||
} else {
|
||||
var o = s.outcome || {};
|
||||
@@ -624,16 +746,24 @@
|
||||
els.localInstall.hidden = !show.install;
|
||||
els.localStop.hidden = !show.stop;
|
||||
els.localCheck.hidden = !show.check;
|
||||
els.localNetworkRow.hidden = !show.network;
|
||||
syncLocalButtons();
|
||||
}
|
||||
|
||||
function onLocalStatus(s) {
|
||||
state.localChecking = false;
|
||||
state.local = s || null;
|
||||
// The graphical install is running without this page (it was reloaded, or
|
||||
// the app was quit and opened again): show it from its first line.
|
||||
if (s && s.installInApp && !state.gui) {
|
||||
state.gui = newWizard('installing');
|
||||
state.gui.port = s.installPort || 3000;
|
||||
post({ cmd: 'installAttach' });
|
||||
renderWizard();
|
||||
return;
|
||||
}
|
||||
// An install from this app is still running (this page was shown again
|
||||
// while it ran): wait for it, unless the user stopped waiting.
|
||||
if (!state.wait && s && s.installRunning && !state.stoppedWaiting && s.state !== 'running' && s.state !== 'needsLogin') {
|
||||
if (!state.wait && s && s.installRunning && !s.installInApp && !state.stoppedWaiting && s.state !== 'running' && s.state !== 'needsLogin') {
|
||||
state.wait = { since: Date.now(), finishedAt: 0, port: s.installPort || 3000 };
|
||||
renderLocal();
|
||||
scheduleWait();
|
||||
@@ -670,12 +800,402 @@
|
||||
post({ cmd: 'startServer', url: state.startUrl });
|
||||
}
|
||||
|
||||
function installLocal() {
|
||||
// The Terminal route: what the graphical install cannot do, and what anyone
|
||||
// may prefer. The installer asks its own questions there.
|
||||
function installInTerminal() {
|
||||
if (state.busy || tooOld || state.opening) return;
|
||||
var network = !!state.gui && state.gui.reach === 'network';
|
||||
closeWizard();
|
||||
selectTab('local');
|
||||
state.opening = true;
|
||||
syncLocalButtons();
|
||||
setStatus('busy', 'Opening Terminal…');
|
||||
post({ cmd: 'installLocal', network: els.localNetwork.checked });
|
||||
post({ cmd: 'installLocal', network: network });
|
||||
}
|
||||
|
||||
function newWizard(step) {
|
||||
return {
|
||||
step: step, plan: null, agent: '', reach: 'local', port: 3000, message: '', phase: '',
|
||||
phaseSince: 0, seen: {}, log: [], ok: false
|
||||
};
|
||||
}
|
||||
|
||||
function openWizard() {
|
||||
if (state.busy || tooOld || state.opening) return;
|
||||
state.gui = newWizard('preparing');
|
||||
post({ cmd: 'installPrepare' });
|
||||
renderWizard();
|
||||
}
|
||||
|
||||
function closeWizard() {
|
||||
clearInterval(state.clock);
|
||||
state.gui = null;
|
||||
renderWizard();
|
||||
renderLocal();
|
||||
}
|
||||
|
||||
function retryWizard() {
|
||||
var reach = state.gui ? state.gui.reach : 'local';
|
||||
var agent = state.gui ? state.gui.agent : '';
|
||||
state.gui = newWizard('preparing');
|
||||
state.gui.reach = reach;
|
||||
state.gui.agent = agent;
|
||||
post({ cmd: 'installPrepare' });
|
||||
renderWizard();
|
||||
}
|
||||
|
||||
function installedAgents() {
|
||||
var g = state.gui;
|
||||
return g && g.plan ? g.plan.clis.filter(function (c) { return c.installed; }) : [];
|
||||
}
|
||||
|
||||
function offeredAgents() {
|
||||
var g = state.gui;
|
||||
return g && g.plan ? g.plan.clis.filter(function (c) { return c.installable; }) : [];
|
||||
}
|
||||
|
||||
function agentById(id) {
|
||||
return offeredAgents().filter(function (c) { return c.id === id; })[0] || null;
|
||||
}
|
||||
|
||||
// The first step the installer's answer calls for. The agent step exists
|
||||
// only when this Mac has no coding agent at all.
|
||||
function onInstallPlan(plan) {
|
||||
var g = state.gui;
|
||||
if (!g || g.step !== 'preparing') return;
|
||||
g.plan = plan;
|
||||
if (plan.blocker) {
|
||||
g.step = 'blocked';
|
||||
} else if (!installedAgents().length && offeredAgents().length) {
|
||||
// Kept across Try again; otherwise the first of the catalogue's order.
|
||||
if (!agentById(g.agent)) g.agent = offeredAgents()[0].id;
|
||||
g.step = 'agent';
|
||||
} else {
|
||||
g.step = 'reach';
|
||||
}
|
||||
renderWizard();
|
||||
}
|
||||
|
||||
function renderAgents() {
|
||||
var g = state.gui;
|
||||
els.wizAgents.textContent = '';
|
||||
offeredAgents().forEach(function (c) {
|
||||
var label = document.createElement('label');
|
||||
label.className = 'choice';
|
||||
var input = document.createElement('input');
|
||||
input.type = 'radio';
|
||||
input.name = 'agent';
|
||||
input.value = c.id;
|
||||
input.checked = c.id === g.agent;
|
||||
input.addEventListener('change', function () {
|
||||
g.agent = c.id;
|
||||
renderAgentNote();
|
||||
});
|
||||
var name = document.createElement('b');
|
||||
name.textContent = c.label;
|
||||
var text = document.createElement('span');
|
||||
text.appendChild(name);
|
||||
label.appendChild(input);
|
||||
label.appendChild(text);
|
||||
els.wizAgents.appendChild(label);
|
||||
});
|
||||
renderAgentNote();
|
||||
}
|
||||
|
||||
function renderAgentNote() {
|
||||
var c = agentById(state.gui.agent);
|
||||
els.wizAgentNote.textContent = '';
|
||||
if (!c) return;
|
||||
els.wizAgentNote.appendChild(document.createTextNode('You sign in to ' + c.label + ' the first time you start it. '));
|
||||
if (/^https:\/\//.test(c.docs)) {
|
||||
var a = document.createElement('a');
|
||||
a.href = '#';
|
||||
a.textContent = 'About ' + c.label;
|
||||
a.addEventListener('click', function (ev) {
|
||||
ev.preventDefault();
|
||||
post({ cmd: 'openExternal', url: c.docs });
|
||||
});
|
||||
els.wizAgentNote.appendChild(a);
|
||||
}
|
||||
}
|
||||
|
||||
function renderSummary() {
|
||||
var g = state.gui;
|
||||
var plan = g.plan;
|
||||
var lines = [{ text: 'Installs into your home folder (about 1 GB), with no administrator password' }];
|
||||
var needs = [];
|
||||
if (plan.needs.node) needs.push('Node.js');
|
||||
if (plan.needs.tmux) needs.push('tmux');
|
||||
if (needs.length) lines.push({ text: 'Downloads ' + needs.join(' and ') });
|
||||
var found = installedAgents();
|
||||
var chosen = agentById(g.agent);
|
||||
if (found.length) {
|
||||
lines.push({ text: 'Uses ' + found.map(function (c) { return c.label; }).join(', ') + ', already on this Mac' });
|
||||
} else if (chosen) {
|
||||
lines.push({ text: 'Installs ' + chosen.label });
|
||||
} else {
|
||||
lines.push({ text: 'No coding agent yet: Codeman opens, but sessions need one to run', warn: true });
|
||||
}
|
||||
lines.push({ text: 'Runs in the background and starts when you log in' });
|
||||
if (plan.needs.git) lines.push({ text: 'This Mac has no git, so you update Codeman by running this install again' });
|
||||
els.wizSummary.textContent = '';
|
||||
lines.forEach(function (line) {
|
||||
var li = document.createElement('li');
|
||||
li.textContent = line.text;
|
||||
if (line.warn) li.className = 'warn';
|
||||
els.wizSummary.appendChild(li);
|
||||
});
|
||||
}
|
||||
|
||||
// Which rows the rail has. A run this page did not start has no plan, so it
|
||||
// shows what the installer reported instead.
|
||||
function railRows() {
|
||||
var g = state.gui;
|
||||
var plan = g.plan;
|
||||
var chosen = agentById(g.agent);
|
||||
var rows = [];
|
||||
PHASES.forEach(function (id) {
|
||||
var label = {
|
||||
runtime: 'Getting Node.js and tmux',
|
||||
agent: 'Installing ' + (chosen ? chosen.label : 'a coding agent'),
|
||||
source: 'Downloading Codeman',
|
||||
packages: 'Installing packages',
|
||||
build: 'Building Codeman',
|
||||
service: 'Starting Codeman'
|
||||
}[id];
|
||||
if (id === 'runtime' && plan) {
|
||||
if (!plan.needs.node && !plan.needs.tmux) return;
|
||||
if (!plan.needs.tmux) label = 'Getting Node.js';
|
||||
if (!plan.needs.node) label = 'Getting tmux';
|
||||
}
|
||||
if (id === 'agent' && (plan ? !chosen : !g.seen.agent)) return;
|
||||
rows.push({ id: id, label: label });
|
||||
});
|
||||
return rows;
|
||||
}
|
||||
|
||||
function clockText(since) {
|
||||
var s = Math.max(0, Math.floor((Date.now() - since) / 1000));
|
||||
return Math.floor(s / 60) + ':' + ('0' + (s % 60)).slice(-2);
|
||||
}
|
||||
|
||||
function renderRail() {
|
||||
var g = state.gui;
|
||||
var current = PHASES.indexOf(g.phase);
|
||||
els.wizRail.textContent = '';
|
||||
railRows().forEach(function (row) {
|
||||
var at = PHASES.indexOf(row.id);
|
||||
var li = document.createElement('li');
|
||||
var name = document.createElement('span');
|
||||
name.textContent = row.label;
|
||||
li.appendChild(name);
|
||||
if (g.ok || at < current) {
|
||||
li.className = 'done';
|
||||
} else if (at === current && g.step === 'failed') {
|
||||
li.className = 'failed';
|
||||
} else if (at === current) {
|
||||
li.className = 'now';
|
||||
li.setAttribute('aria-current', 'step');
|
||||
var clock = document.createElement('span');
|
||||
clock.className = 'clock';
|
||||
clock.id = 'wiz-clock';
|
||||
clock.textContent = clockText(g.phaseSince);
|
||||
li.appendChild(clock);
|
||||
}
|
||||
els.wizRail.appendChild(li);
|
||||
});
|
||||
}
|
||||
|
||||
function renderLog() {
|
||||
var log = els.wizLog;
|
||||
var atEnd = log.scrollTop + log.clientHeight >= log.scrollHeight - 8;
|
||||
log.textContent = state.gui.log.join('\n');
|
||||
if (atEnd) log.scrollTop = log.scrollHeight;
|
||||
}
|
||||
|
||||
function appendLog(lines) {
|
||||
var g = state.gui;
|
||||
if (!lines || !lines.length) return;
|
||||
g.log = g.log.concat(lines).slice(-MAX_LOG_LINES);
|
||||
renderLog();
|
||||
}
|
||||
|
||||
function setPhase(phase) {
|
||||
var g = state.gui;
|
||||
if (!phase || phase === g.phase || PHASES.indexOf(phase) < 0) return;
|
||||
g.phase = phase;
|
||||
g.phaseSince = Date.now();
|
||||
g.seen[phase] = true;
|
||||
renderRail();
|
||||
}
|
||||
|
||||
function onInstallUpdate(msg) {
|
||||
var g = state.gui;
|
||||
if (!g || g.step !== 'installing') return;
|
||||
setPhase(msg.phase);
|
||||
appendLog(msg.log);
|
||||
}
|
||||
|
||||
function onInstallFinished(msg) {
|
||||
var g = state.gui;
|
||||
if (!g) return;
|
||||
appendLog(msg.log);
|
||||
clearInterval(state.clock);
|
||||
if (msg.ok) {
|
||||
g.ok = true;
|
||||
g.step = 'finishing';
|
||||
renderWizard();
|
||||
// The same watch as a Terminal install: it opens Codeman at the first
|
||||
// answer, and offers Start when none comes.
|
||||
state.wait = { since: Date.now(), finishedAt: 0, port: g.port };
|
||||
checkLocal('quick');
|
||||
return;
|
||||
}
|
||||
if (msg.cancelled) {
|
||||
closeWizard();
|
||||
checkLocal('login');
|
||||
setStatus('', 'Install cancelled.', 'Install again to pick up where it stopped.');
|
||||
return;
|
||||
}
|
||||
g.step = 'failed';
|
||||
g.message = msg.error || 'The installer stopped without saying why.';
|
||||
renderWizard();
|
||||
els.wizDetails.open = true;
|
||||
renderLog();
|
||||
}
|
||||
|
||||
// Each screen of the graphical install, drawn from state.gui alone.
|
||||
function renderWizard() {
|
||||
var g = state.gui;
|
||||
els.card.classList.toggle('wizard-on', !!g);
|
||||
els.wizard.hidden = !g;
|
||||
if (!g) return;
|
||||
var step = g.step;
|
||||
var copy = {
|
||||
preparing: ['Looking at this Mac', 'Getting the installer and checking what is already here.'],
|
||||
blocked: ['This Mac needs something first', ''],
|
||||
prepareFailed: ['Could not get the installer', ''],
|
||||
agent: ['Choose a coding agent', 'Codeman runs coding agents, and this Mac has none yet. Pick one to install with Codeman. You can add more later.'],
|
||||
reach: ['Who can reach Codeman?', ''],
|
||||
installing: ['Installing Codeman', 'You can close this window. The install keeps going, and the app picks it up when you open it again.'],
|
||||
finishing: ['Starting Codeman', 'Codeman opens here as soon as it answers.'],
|
||||
failed: ['The install stopped', 'Its full log is in ~/.codeman/install.log. Try again picks up where it stopped.']
|
||||
}[step];
|
||||
els.wizSpinner.hidden = !(step === 'preparing' || step === 'finishing');
|
||||
els.wizTitle.textContent = copy[0];
|
||||
els.wizLead.textContent = copy[1];
|
||||
els.wizLead.hidden = !copy[1];
|
||||
|
||||
var message = step === 'blocked' ? g.plan.blocker : (step === 'prepareFailed' || step === 'failed') ? g.message : '';
|
||||
els.wizMessage.textContent = message;
|
||||
els.wizMessage.hidden = !message;
|
||||
els.wizMessage.className = step === 'blocked' ? 'warn' : '';
|
||||
|
||||
els.wizAgentStep.hidden = step !== 'agent';
|
||||
els.wizReachStep.hidden = step !== 'reach';
|
||||
var running = step === 'installing' || step === 'finishing' || step === 'failed';
|
||||
els.wizRail.hidden = !running;
|
||||
els.wizDetails.hidden = !running;
|
||||
|
||||
if (step === 'agent') renderAgents();
|
||||
if (step === 'reach') {
|
||||
renderSummary();
|
||||
syncReach();
|
||||
}
|
||||
if (running) renderRail();
|
||||
clearInterval(state.clock);
|
||||
if (step === 'installing') {
|
||||
state.clock = setInterval(function () {
|
||||
var clock = $('wiz-clock');
|
||||
if (clock) clock.textContent = clockText(state.gui.phaseSince);
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
var next = {
|
||||
agent: 'Continue', reach: 'Install Codeman', failed: 'Try again', prepareFailed: 'Try again', blocked: 'Install in Terminal'
|
||||
}[step];
|
||||
els.wizNext.hidden = !next;
|
||||
els.wizNext.textContent = next || '';
|
||||
// Not while preparing: a second prepare would clear the folder of the first.
|
||||
els.wizBack.hidden = !(step === 'blocked' || step === 'prepareFailed' || step === 'agent' || step === 'reach');
|
||||
els.wizSkip.hidden = step !== 'agent';
|
||||
els.wizCancel.hidden = step !== 'installing';
|
||||
els.wizCancel.disabled = false;
|
||||
els.wizTerminal.hidden = !(step === 'reach' || step === 'failed' || step === 'prepareFailed');
|
||||
|
||||
if (step === 'agent') {
|
||||
var checked = els.wizAgents.querySelector('input:checked');
|
||||
if (checked) checked.focus();
|
||||
} else if (step === 'reach' || step === 'blocked' || step === 'failed' || step === 'prepareFailed') {
|
||||
els.wizNext.focus();
|
||||
} else {
|
||||
els.wizTitle.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function syncReach() {
|
||||
var g = state.gui;
|
||||
var network = g.reach === 'network';
|
||||
els.wizPassword.hidden = !network;
|
||||
Array.prototype.forEach.call(document.getElementsByName('reach'), function (r) { r.checked = r.value === g.reach; });
|
||||
}
|
||||
|
||||
function startInstall() {
|
||||
var g = state.gui;
|
||||
var password = '';
|
||||
if (g.reach === 'network') {
|
||||
password = els.wizPw.value;
|
||||
if (!password) {
|
||||
els.wizMessage.textContent = 'Set a password for the other devices to sign in with.';
|
||||
els.wizMessage.hidden = false;
|
||||
els.wizPw.focus();
|
||||
return;
|
||||
}
|
||||
if (password !== els.wizPw2.value) {
|
||||
els.wizMessage.textContent = 'The two passwords are different.';
|
||||
els.wizMessage.hidden = false;
|
||||
els.wizPw2.focus();
|
||||
return;
|
||||
}
|
||||
}
|
||||
var msg = { cmd: 'installStart' };
|
||||
if (password) msg.networkPassword = password;
|
||||
if (!installedAgents().length && agentById(g.agent)) msg.aiCli = g.agent;
|
||||
els.wizPw.value = '';
|
||||
els.wizPw2.value = '';
|
||||
g.step = 'installing';
|
||||
g.phase = '';
|
||||
g.seen = {};
|
||||
g.log = [];
|
||||
renderLog();
|
||||
renderWizard();
|
||||
post(msg);
|
||||
}
|
||||
|
||||
function wizardNext() {
|
||||
var g = state.gui;
|
||||
if (!g) return;
|
||||
if (g.step === 'agent') {
|
||||
g.step = 'reach';
|
||||
renderWizard();
|
||||
} else if (g.step === 'reach') {
|
||||
startInstall();
|
||||
} else if (g.step === 'failed' || g.step === 'prepareFailed') {
|
||||
retryWizard();
|
||||
} else if (g.step === 'blocked') {
|
||||
installInTerminal();
|
||||
}
|
||||
}
|
||||
|
||||
function wizardBack() {
|
||||
var g = state.gui;
|
||||
if (!g) return;
|
||||
if (g.step === 'reach' && !installedAgents().length && offeredAgents().length && !g.plan.blocker) {
|
||||
g.step = 'agent';
|
||||
renderWizard();
|
||||
} else {
|
||||
closeWizard();
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleWait() {
|
||||
@@ -686,6 +1206,7 @@
|
||||
function endWait() {
|
||||
clearTimeout(state.waitTimer);
|
||||
state.wait = null;
|
||||
if (state.gui && state.gui.step === 'finishing') closeWizard();
|
||||
}
|
||||
|
||||
// One answer while an install runs. It stops at the first answer from a
|
||||
@@ -822,6 +1343,32 @@
|
||||
renderLocal();
|
||||
scheduleWait();
|
||||
break;
|
||||
case 'installPlan':
|
||||
onInstallPlan(msg.plan);
|
||||
break;
|
||||
case 'installPrepareFailed':
|
||||
if (state.gui && state.gui.step === 'preparing') {
|
||||
state.gui.step = 'prepareFailed';
|
||||
state.gui.message = msg.message || 'Could not get the installer.';
|
||||
renderWizard();
|
||||
}
|
||||
break;
|
||||
case 'installRunning':
|
||||
if (state.gui) state.gui.port = Number(msg.port) || 3000;
|
||||
break;
|
||||
case 'installStartFailed':
|
||||
if (state.gui) {
|
||||
state.gui.step = 'failed';
|
||||
state.gui.message = msg.message || 'Could not start the installer.';
|
||||
renderWizard();
|
||||
}
|
||||
break;
|
||||
case 'installUpdate':
|
||||
onInstallUpdate(msg);
|
||||
break;
|
||||
case 'installFinished':
|
||||
onInstallFinished(msg);
|
||||
break;
|
||||
case 'remoteInstallStarted':
|
||||
state.opening = false;
|
||||
syncLocalButtons();
|
||||
@@ -875,7 +1422,28 @@
|
||||
});
|
||||
els.localOpen.addEventListener('click', openLocal);
|
||||
els.localStart.addEventListener('click', startLocal);
|
||||
els.localInstall.addEventListener('click', installLocal);
|
||||
els.localInstall.addEventListener('click', openWizard);
|
||||
els.wizNext.addEventListener('click', wizardNext);
|
||||
els.wizBack.addEventListener('click', wizardBack);
|
||||
els.wizSkip.addEventListener('click', function () {
|
||||
if (!state.gui) return;
|
||||
state.gui.agent = '';
|
||||
state.gui.step = 'reach';
|
||||
renderWizard();
|
||||
});
|
||||
els.wizCancel.addEventListener('click', function () {
|
||||
els.wizCancel.disabled = true;
|
||||
post({ cmd: 'installCancel' });
|
||||
});
|
||||
els.wizTerminal.addEventListener('click', installInTerminal);
|
||||
Array.prototype.forEach.call(document.getElementsByName('reach'), function (radio) {
|
||||
radio.addEventListener('change', function () {
|
||||
if (!state.gui) return;
|
||||
state.gui.reach = radio.value;
|
||||
els.wizMessage.hidden = true;
|
||||
syncReach();
|
||||
});
|
||||
});
|
||||
els.localStop.addEventListener('click', function () { state.stoppedWaiting = true; endWait(); checkLocal('login'); });
|
||||
els.localCheck.addEventListener('click', function () { if (!state.busy && !state.localChecking) checkLocal('deep'); });
|
||||
els.sshInstall.addEventListener('click', installRemote);
|
||||
|
||||
@@ -0,0 +1,855 @@
|
||||
//! The graphical install: the app runs Codeman's installer itself and the
|
||||
//! connect page is its interface, so a fresh Mac needs neither Terminal nor an
|
||||
//! administrator password.
|
||||
//!
|
||||
//! `install.sh --no-admin` is what makes that possible: it puts Node.js and
|
||||
//! tmux in the home folder, so nothing in it asks for a password, and the two
|
||||
//! questions only a person can answer (which coding agent, who may reach
|
||||
//! Codeman) are asked by the page and passed as flags. The Terminal route in
|
||||
//! `setup.rs` stays for what this one cannot do, a Mac older than macOS 15 with
|
||||
//! no tmux first of all.
|
||||
//!
|
||||
//! `prepare` downloads the installer once into a private folder and asks it
|
||||
//! what is on this Mac (`install.sh preflight`); `start` runs the same file with
|
||||
//! every answer given; `follow` reports what it prints.
|
||||
//!
|
||||
//! **Its output goes to a file, never a pipe.** With a pipe, quitting the app
|
||||
//! would kill the installer at its next write, half way through an install. The
|
||||
//! file also holds the whole run, so `follow` can start over from the top: a
|
||||
//! connect page that was reloaded, or an app that was quit and opened again,
|
||||
//! finds the running install in `ps` and replays it. That is why this module
|
||||
//! keeps no state about a run but the file and the process.
|
||||
|
||||
use std::fs::{self, DirBuilder, File, OpenOptions};
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::local_server;
|
||||
use crate::setup;
|
||||
|
||||
/// The folder under the per-user temporary folder that holds a run. A fixed
|
||||
/// name, so an app that was opened again finds it.
|
||||
const RUN_DIR: &str = "codeman-install";
|
||||
const SCRIPT_FILE: &str = "install.sh";
|
||||
const OUTPUT_FILE: &str = "install.out";
|
||||
|
||||
/// The `install.sh preflight` schema this app understands.
|
||||
const PREFLIGHT_SCHEMA: u32 = 1;
|
||||
|
||||
const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
const PREFLIGHT_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// How often `follow` looks at the output file and the process.
|
||||
const POLL: Duration = Duration::from_millis(500);
|
||||
|
||||
/// How long the installer gets to end after Cancel before it is killed.
|
||||
const CANCEL_GRACE: Duration = Duration::from_secs(5);
|
||||
|
||||
/// One line of output, for the page's details view.
|
||||
const MAX_LOG_LINE: usize = 500;
|
||||
|
||||
/// When the login shell's PATH cannot be read.
|
||||
const FALLBACK_PATH: &str = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";
|
||||
|
||||
/// Lines of the installer's output protocol (`progress_phase` in install.sh).
|
||||
const PROTOCOL_PREFIX: &str = "@@codeman ";
|
||||
|
||||
/// Set by Cancel, so `follow` can tell a cancelled run from a failed one.
|
||||
static CANCELLED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// What `install.sh preflight` found. Fields the installer adds later are
|
||||
/// ignored here, and `schema` changes when one changes meaning.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Preflight {
|
||||
pub schema: u32,
|
||||
pub os: String,
|
||||
pub arch: String,
|
||||
/// Why `--no-admin` cannot finish on this Mac; empty when it can.
|
||||
pub blocker: String,
|
||||
pub needs: Needs,
|
||||
pub clis: Vec<CliEntry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Needs {
|
||||
pub node: bool,
|
||||
pub tmux: bool,
|
||||
pub git: bool,
|
||||
}
|
||||
|
||||
/// One coding agent of the installer's catalogue. The app has no list of its
|
||||
/// own, so a new agent appears here without a new app.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct CliEntry {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub installed: bool,
|
||||
pub installable: bool,
|
||||
pub docs: String,
|
||||
}
|
||||
|
||||
/// What the person chose on the connect page.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Plan {
|
||||
pub port: u16,
|
||||
/// Reachable from other devices, with this login password. `None`: this
|
||||
/// Mac only.
|
||||
pub network_password: Option<String>,
|
||||
/// The catalogue id of the agent to install. `None`: none.
|
||||
pub ai_cli: Option<String>,
|
||||
}
|
||||
|
||||
/// `install.sh`'s flags for a graphical install. The password is not among
|
||||
/// them: anything here can be read in `ps`. Always `--service`, like the
|
||||
/// Terminal route: a LaunchAgent runs Codeman, so it keeps running when the app
|
||||
/// quits. Always `--ai-cli`: without it `CODEMAN_NONINTERACTIVE` would install
|
||||
/// the first agent of the catalogue by itself.
|
||||
pub fn install_args(plan: &Plan) -> Vec<String> {
|
||||
let mut args: Vec<String> = ["--no-admin", "--progress", "--service"]
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
args.push(
|
||||
if plan.network_password.is_some() {
|
||||
"--lan"
|
||||
} else {
|
||||
"--local"
|
||||
}
|
||||
.to_string(),
|
||||
);
|
||||
args.push("--port".to_string());
|
||||
args.push(plan.port.to_string());
|
||||
args.push("--ai-cli".to_string());
|
||||
args.push(plan.ai_cli.clone().unwrap_or_else(|| "none".to_string()));
|
||||
args
|
||||
}
|
||||
|
||||
/// What a graphical install adds to the environment. There is no terminal, so
|
||||
/// `CODEMAN_NONINTERACTIVE` is what lets `headless_guard` go ahead.
|
||||
pub fn install_env(plan: &Plan) -> Vec<(String, String)> {
|
||||
let mut env = vec![("CODEMAN_NONINTERACTIVE".to_string(), "1".to_string())];
|
||||
if let Some(password) = &plan.network_password {
|
||||
env.push(("CODEMAN_PASSWORD".to_string(), password.clone()));
|
||||
}
|
||||
if let Some(branch) = setup::INSTALL_BRANCH {
|
||||
env.push(("CODEMAN_BRANCH".to_string(), branch.to_string()));
|
||||
}
|
||||
env
|
||||
}
|
||||
|
||||
/// Read what `install.sh preflight` printed. An installer without that
|
||||
/// subcommand ends before this; one that speaks another schema stops here.
|
||||
pub fn parse_preflight(stdout: &str) -> Result<Preflight, String> {
|
||||
let found: Preflight = serde_json::from_str(stdout.trim())
|
||||
.map_err(|_| "The installer gave an answer this app cannot read.".to_string())?;
|
||||
if found.schema != PREFLIGHT_SCHEMA {
|
||||
return Err(format!(
|
||||
"This installer speaks a newer language than this app (schema {}). Update Codeman Desktop, or install in Terminal.",
|
||||
found.schema
|
||||
));
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
/// Whether a command line is an install this module started. `preflight` from
|
||||
/// the same file is not one: it has no `--progress`.
|
||||
pub fn is_install_run(command: &str) -> bool {
|
||||
let suffix = format!("/{RUN_DIR}/{SCRIPT_FILE}");
|
||||
let mut words = command.split_whitespace();
|
||||
words.any(|w| w.ends_with(&suffix)) && command.split_whitespace().any(|w| w == "--progress")
|
||||
}
|
||||
|
||||
fn run_dir() -> PathBuf {
|
||||
std::env::temp_dir().join(RUN_DIR)
|
||||
}
|
||||
|
||||
/// A fresh folder for a run, for this user only. The per-user temporary folder
|
||||
/// of macOS is private already; the mode covers a `TMPDIR` that is not.
|
||||
fn fresh_run_dir() -> Result<PathBuf, String> {
|
||||
let dir = run_dir();
|
||||
match fs::remove_dir_all(&dir) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(format!("Could not clear {}: {e}", dir.display())),
|
||||
}
|
||||
DirBuilder::new()
|
||||
.mode(0o700)
|
||||
.create(&dir)
|
||||
.map_err(|e| format!("Could not create {}: {e}", dir.display()))?;
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
/// The login shell's environment, so the installer finds the Node.js, git and
|
||||
/// agents this person already has, wherever their profile puts them on PATH. A
|
||||
/// double-clicked app gets launchd's bare PATH instead (see local_server.rs).
|
||||
fn installer_env() -> Vec<(String, String)> {
|
||||
with_path(local_server::login_environment().unwrap_or_default())
|
||||
}
|
||||
|
||||
fn with_path(mut env: Vec<(String, String)>) -> Vec<(String, String)> {
|
||||
if !env.iter().any(|(k, _)| k == "PATH") {
|
||||
env.push(("PATH".to_string(), FALLBACK_PATH.to_string()));
|
||||
}
|
||||
env
|
||||
}
|
||||
|
||||
fn home() -> PathBuf {
|
||||
dirs::home_dir().unwrap_or_else(|| PathBuf::from("/"))
|
||||
}
|
||||
|
||||
fn download_installer(script: &Path) -> Result<(), String> {
|
||||
let mut cmd = Command::new("/usr/bin/curl");
|
||||
cmd.args(["-fsSL", "--connect-timeout", "15", "-o"])
|
||||
.arg(script)
|
||||
.arg(setup::INSTALLER_URL);
|
||||
let out = local_server::exec_bounded(
|
||||
cmd,
|
||||
Instant::now() + DOWNLOAD_TIMEOUT,
|
||||
"Downloading the installer took too long, so it was stopped.",
|
||||
)?;
|
||||
if out.code == Some(0) && script.is_file() {
|
||||
return Ok(());
|
||||
}
|
||||
let said = out.stderr.trim();
|
||||
Err(if said.is_empty() {
|
||||
"Could not download the installer. Check the internet connection, then try again.".to_string()
|
||||
} else {
|
||||
format!("Could not download the installer. Check the internet connection, then try again.\n{said}")
|
||||
})
|
||||
}
|
||||
|
||||
fn ask_installer(script: &Path, env: &[(String, String)]) -> Result<Preflight, String> {
|
||||
let mut cmd = Command::new("/bin/bash");
|
||||
cmd.arg(script)
|
||||
.args(["preflight", "--no-admin"])
|
||||
.envs(env.iter().map(|(k, v)| (k, v)))
|
||||
.current_dir(home());
|
||||
let out = local_server::exec_bounded(
|
||||
cmd,
|
||||
Instant::now() + PREFLIGHT_TIMEOUT,
|
||||
"The installer took too long to look at this Mac, so it was stopped.",
|
||||
)?;
|
||||
if out.code != Some(0) {
|
||||
return Err("This installer cannot run from the app yet. Install in Terminal instead.".to_string());
|
||||
}
|
||||
parse_preflight(&out.stdout)
|
||||
}
|
||||
|
||||
/// Get the installer and ask it what is on this Mac.
|
||||
pub fn prepare() -> Result<Preflight, String> {
|
||||
if let Some(why) = refuse_start() {
|
||||
return Err(why);
|
||||
}
|
||||
fetch_and_ask()
|
||||
}
|
||||
|
||||
fn fetch_and_ask() -> Result<Preflight, String> {
|
||||
let dir = fresh_run_dir()?;
|
||||
let script = dir.join(SCRIPT_FILE);
|
||||
download_installer(&script)?;
|
||||
ask_installer(&script, &installer_env())
|
||||
}
|
||||
|
||||
/// Why no install may start now: one runs already, or a Codeman server does and
|
||||
/// the installer's service step would replace it under its sessions.
|
||||
fn refuse_start() -> Option<String> {
|
||||
if setup::install_in_app().is_some() {
|
||||
return Some("Codeman is already being installed.".to_string());
|
||||
}
|
||||
setup::already_running()
|
||||
}
|
||||
|
||||
/// Run the installer `prepare` fetched. It outlives the app (see the module
|
||||
/// docs): when an app's job ends, launchd kills what is left in that job's
|
||||
/// process group, so the installer gets a group of its own. A thread reaps it
|
||||
/// if it ends first.
|
||||
pub fn start(plan: &Plan) -> Result<(), String> {
|
||||
if let Some(why) = refuse_start() {
|
||||
return Err(why);
|
||||
}
|
||||
spawn_run(plan)
|
||||
}
|
||||
|
||||
fn spawn_run(plan: &Plan) -> Result<(), String> {
|
||||
let dir = run_dir();
|
||||
let script = dir.join(SCRIPT_FILE);
|
||||
if !script.is_file() {
|
||||
return Err("The installer is gone from the temporary folder. Try again.".to_string());
|
||||
}
|
||||
let output = OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.truncate(true)
|
||||
.mode(0o600)
|
||||
.open(dir.join(OUTPUT_FILE))
|
||||
.map_err(|e| format!("Could not start the installer: {e}"))?;
|
||||
let stderr = output
|
||||
.try_clone()
|
||||
.map_err(|e| format!("Could not start the installer: {e}"))?;
|
||||
CANCELLED.store(false, Ordering::SeqCst);
|
||||
let mut child = Command::new("/bin/bash")
|
||||
.arg(&script)
|
||||
.args(install_args(plan))
|
||||
.envs(installer_env())
|
||||
.envs(install_env(plan))
|
||||
.current_dir(home())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(output)
|
||||
.stderr(stderr)
|
||||
.process_group(0)
|
||||
.spawn()
|
||||
.map_err(|e| format!("Could not start the installer: {e}"))?;
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The process group of `pid`. `setup::install_in_app` may answer with one of
|
||||
/// the installer's subshells, which `ps` shows with the installer's own command
|
||||
/// line, so its pid is not always the group's.
|
||||
fn group_of(pid: u32) -> Option<u32> {
|
||||
let out = Command::new("/bin/ps")
|
||||
.args(["-o", "pgid=", "-p", &pid.to_string()])
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.output()
|
||||
.ok()?;
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
.trim()
|
||||
.parse()
|
||||
.ok()
|
||||
.filter(|g| *g > 1)
|
||||
}
|
||||
|
||||
fn signal_group(group: u32, signal: &str) {
|
||||
let _ = Command::new("/bin/kill")
|
||||
.arg(format!("-{signal}"))
|
||||
.arg("--")
|
||||
.arg(format!("-{group}"))
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status();
|
||||
}
|
||||
|
||||
/// Stop the running install and whatever it started. What it left behind is
|
||||
/// picked up by the next run: `install.sh` re-runs a partial install in full.
|
||||
pub fn cancel() {
|
||||
let Some(group) = setup::install_in_app().and_then(group_of) else {
|
||||
return;
|
||||
};
|
||||
CANCELLED.store(true, Ordering::SeqCst);
|
||||
signal_group(group, "TERM");
|
||||
let deadline = Instant::now() + CANCEL_GRACE;
|
||||
while Instant::now() < deadline {
|
||||
if setup::install_in_app().is_none() {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
signal_group(group, "KILL");
|
||||
}
|
||||
|
||||
/// Drop terminal colour and cursor sequences.
|
||||
fn strip_ansi(line: &str) -> String {
|
||||
let mut out = String::with_capacity(line.len());
|
||||
let mut chars = line.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c != '\u{1b}' {
|
||||
out.push(c);
|
||||
continue;
|
||||
}
|
||||
if chars.peek() == Some(&'[') {
|
||||
chars.next();
|
||||
for next in chars.by_ref() {
|
||||
if ('@'..='~').contains(&next) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One line of the installer's output.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum Line {
|
||||
Phase(String),
|
||||
Error(String),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
fn parse_line(raw: &str) -> Line {
|
||||
let line = strip_ansi(raw.trim_end_matches('\r'));
|
||||
if let Some(rest) = line.strip_prefix(PROTOCOL_PREFIX) {
|
||||
let (word, text) = rest.split_once(' ').unwrap_or((rest, ""));
|
||||
match word {
|
||||
"phase" if !text.is_empty() && text.chars().all(|c| c.is_ascii_lowercase()) => {
|
||||
return Line::Phase(text.to_string())
|
||||
}
|
||||
"error" if !text.is_empty() => return Line::Error(text.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Line::Text(line)
|
||||
}
|
||||
|
||||
/// What a run has said so far.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Progress {
|
||||
partial: Vec<u8>,
|
||||
phase: Option<String>,
|
||||
/// The first error: the cause. The ones after it are its consequences.
|
||||
error: Option<String>,
|
||||
done: bool,
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
fn take_line(&mut self, raw: &str, log: &mut Vec<String>) {
|
||||
match parse_line(raw) {
|
||||
Line::Phase(phase) => {
|
||||
self.done = phase == "done";
|
||||
self.phase = Some(phase);
|
||||
}
|
||||
Line::Error(text) => {
|
||||
self.error.get_or_insert(text);
|
||||
}
|
||||
Line::Text(text) if text.trim().is_empty() => {}
|
||||
Line::Text(text) => log.push(text.chars().take(MAX_LOG_LINE).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Take bytes of output; returns the complete lines to show.
|
||||
pub fn feed(&mut self, bytes: &[u8]) -> Vec<String> {
|
||||
self.partial.extend_from_slice(bytes);
|
||||
let mut log = Vec::new();
|
||||
while let Some(end) = self.partial.iter().position(|b| *b == b'\n') {
|
||||
let rest = self.partial.split_off(end + 1);
|
||||
let line = std::mem::replace(&mut self.partial, rest);
|
||||
self.take_line(String::from_utf8_lossy(&line[..end]).as_ref(), &mut log);
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
/// The output ended: a last line without a newline is complete now.
|
||||
pub fn finish(&mut self) -> Vec<String> {
|
||||
let line = std::mem::take(&mut self.partial);
|
||||
let mut log = Vec::new();
|
||||
self.take_line(String::from_utf8_lossy(&line).as_ref(), &mut log);
|
||||
log
|
||||
}
|
||||
|
||||
pub fn update_message(&self, log: Vec<String>) -> Value {
|
||||
json!({ "type": "installUpdate", "phase": self.phase, "log": log })
|
||||
}
|
||||
|
||||
pub fn finished_message(&self, cancelled: bool, log: Vec<String>) -> Value {
|
||||
json!({
|
||||
"type": "installFinished",
|
||||
"ok": self.done,
|
||||
"cancelled": cancelled && !self.done,
|
||||
"error": self.error,
|
||||
"log": log,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn read_more(file: &mut Option<File>, path: &Path, offset: &mut u64) -> Vec<u8> {
|
||||
if file.is_none() {
|
||||
*file = File::open(path).ok();
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
if let Some(f) = file {
|
||||
if f.seek(SeekFrom::Start(*offset)).is_ok() && f.read_to_end(&mut bytes).is_ok() {
|
||||
*offset += bytes.len() as u64;
|
||||
}
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Report a run from its first line to its end. `stale` ends this reader
|
||||
/// (the page asked for another). Every look at the process comes BEFORE the read
|
||||
/// of the file, so what it wrote just before it ended is never missed. `done`
|
||||
/// ends the run by itself: a subshell of the installer that lingers looks just
|
||||
/// like the installer, and must not keep the page waiting.
|
||||
pub fn follow(stale: impl Fn() -> bool, send: impl Fn(Value)) {
|
||||
let path = run_dir().join(OUTPUT_FILE);
|
||||
let mut file = None;
|
||||
let mut offset = 0;
|
||||
let mut progress = Progress::default();
|
||||
let mut reported = None;
|
||||
loop {
|
||||
if stale() {
|
||||
return;
|
||||
}
|
||||
let running = setup::install_in_app().is_some();
|
||||
let log = progress.feed(&read_more(&mut file, &path, &mut offset));
|
||||
if !running || progress.done {
|
||||
let mut log = log;
|
||||
log.extend(progress.finish());
|
||||
let cancelled = CANCELLED.load(Ordering::SeqCst);
|
||||
if progress.done {
|
||||
let _ = fs::remove_dir_all(run_dir());
|
||||
}
|
||||
send(progress.finished_message(cancelled, log));
|
||||
return;
|
||||
}
|
||||
if !log.is_empty() || reported != progress.phase {
|
||||
reported = progress.phase.clone();
|
||||
send(progress.update_message(log));
|
||||
}
|
||||
std::thread::sleep(POLL);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn plan() -> Plan {
|
||||
Plan {
|
||||
port: 3000,
|
||||
network_password: None,
|
||||
ai_cli: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_this_mac_install_never_waits_for_a_person() {
|
||||
let args = install_args(&plan());
|
||||
for flag in ["--no-admin", "--progress", "--service", "--local"] {
|
||||
assert!(args.iter().any(|a| a == flag), "{flag}");
|
||||
}
|
||||
assert!(!args.iter().any(|a| a == "--lan"));
|
||||
let env = install_env(&plan());
|
||||
assert!(env.contains(&("CODEMAN_NONINTERACTIVE".to_string(), "1".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_always_names_the_agent_so_the_installer_never_picks_one() {
|
||||
let at = |args: &[String]| args[args.iter().position(|a| a == "--ai-cli").unwrap() + 1].clone();
|
||||
assert_eq!(at(&install_args(&plan())), "none");
|
||||
let mut p = plan();
|
||||
p.ai_cli = Some("codex".to_string());
|
||||
assert_eq!(at(&install_args(&p)), "codex");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_password_goes_in_the_environment_and_never_in_the_arguments() {
|
||||
let mut p = plan();
|
||||
p.network_password = Some("hunter2".to_string());
|
||||
let args = install_args(&p);
|
||||
assert!(args.iter().any(|a| a == "--lan"));
|
||||
assert!(!args.iter().any(|a| a == "--local"));
|
||||
assert!(!args.iter().any(|a| a.contains("hunter2")));
|
||||
assert!(!args.iter().any(|a| a.starts_with("--password")));
|
||||
assert!(install_env(&p).contains(&("CODEMAN_PASSWORD".to_string(), "hunter2".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_reads_the_preflight_answer() {
|
||||
let text = r#"{"schema":1,"os":"macos","arch":"arm64","noAdmin":true,"blocker":"",
|
||||
"needs":{"node":true,"tmux":true,"git":false},"later":"ignored",
|
||||
"clis":[{"id":"claude","label":"Claude Code","installed":false,"installable":true,"docs":"https://x"}]}"#;
|
||||
let found = parse_preflight(text).unwrap();
|
||||
assert_eq!(found.arch, "arm64");
|
||||
assert!(found.needs.node && !found.needs.git);
|
||||
assert_eq!(found.clis[0].label, "Claude Code");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_refuses_an_answer_it_cannot_trust() {
|
||||
assert!(parse_preflight("Unknown option").is_err());
|
||||
let newer = r#"{"schema":2,"os":"macos","arch":"arm64","blocker":"","needs":{"node":true,"tmux":true,"git":true},"clis":[]}"#;
|
||||
assert!(parse_preflight(newer).unwrap_err().contains("schema 2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_page_gets_the_preflight_in_its_own_spelling() {
|
||||
let found = Preflight {
|
||||
schema: 1,
|
||||
os: "macos".into(),
|
||||
arch: "arm64".into(),
|
||||
blocker: String::new(),
|
||||
needs: Needs {
|
||||
node: true,
|
||||
tmux: false,
|
||||
git: true,
|
||||
},
|
||||
clis: vec![],
|
||||
};
|
||||
let text = serde_json::to_value(&found).unwrap();
|
||||
assert_eq!(text["needs"]["node"], json!(true));
|
||||
assert_eq!(text["blocker"], json!(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_real_run_counts_as_an_install() {
|
||||
let script = "/var/folders/ab/T/codeman-install/install.sh";
|
||||
assert!(is_install_run(&format!(
|
||||
"/bin/bash {script} --no-admin --progress --service --local --port 3000"
|
||||
)));
|
||||
assert!(!is_install_run(&format!("/bin/bash {script} preflight --no-admin")));
|
||||
assert!(!is_install_run("/bin/bash /tmp/other/install.sh --progress"));
|
||||
assert!(!is_install_run("vim /tmp/codeman-install/notes.txt --progress"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_follows_the_installer_protocol() {
|
||||
assert_eq!(parse_line("@@codeman phase build"), Line::Phase("build".into()));
|
||||
assert_eq!(
|
||||
parse_line("@@codeman error Building Codeman failed (exit 1)"),
|
||||
Line::Error("Building Codeman failed (exit 1)".into())
|
||||
);
|
||||
assert_eq!(parse_line("plain text\r"), Line::Text("plain text".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_not_the_protocol_stays_output() {
|
||||
for line in [
|
||||
"@@codeman phase",
|
||||
"@@codeman phase Not-A-Phase",
|
||||
"@@codeman nonsense here",
|
||||
"@@codeman",
|
||||
] {
|
||||
assert_eq!(parse_line(line), Line::Text(line.into()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colours_do_not_reach_the_page() {
|
||||
assert_eq!(
|
||||
parse_line("\u{1b}[0;34m==>\u{1b}[0m \u{1b}[1mDone\u{1b}[0m"),
|
||||
Line::Text("==> Done".into())
|
||||
);
|
||||
assert_eq!(parse_line("\u{1b}[2K\u{1b}[1Gnpm"), Line::Text("npm".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_split_across_reads_is_read_whole() {
|
||||
let mut p = Progress::default();
|
||||
assert!(p.feed(b"@@codeman pha").is_empty());
|
||||
assert!(p.feed(b"se packages\nHello ").is_empty());
|
||||
assert_eq!(p.phase.as_deref(), Some("packages"));
|
||||
assert_eq!(p.feed(b"world\n"), vec!["Hello world".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_without_a_last_newline_is_kept() {
|
||||
let mut p = Progress::default();
|
||||
p.feed(b"@@codeman phase done");
|
||||
assert!(!p.done);
|
||||
p.finish();
|
||||
assert!(p.done);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_utf8_byte_costs_one_character_not_the_line() {
|
||||
let mut p = Progress::default();
|
||||
let log = p.feed(b"caf\xff bar\n");
|
||||
assert_eq!(log, vec!["caf\u{fffd} bar".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_very_long_line_is_cut() {
|
||||
let mut p = Progress::default();
|
||||
let line = format!("{}\n", "x".repeat(MAX_LOG_LINE * 2));
|
||||
assert_eq!(p.feed(line.as_bytes())[0].chars().count(), MAX_LOG_LINE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_error_is_the_one_reported() {
|
||||
let mut p = Progress::default();
|
||||
p.feed(b"@@codeman error Building Codeman failed\n@@codeman error Installation failed. Partial\n");
|
||||
let done = p.finished_message(false, vec![]);
|
||||
assert_eq!(done["error"], json!("Building Codeman failed"));
|
||||
assert_eq!(done["ok"], json!(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_done_is_success() {
|
||||
let mut p = Progress::default();
|
||||
p.feed(b"@@codeman phase service\n");
|
||||
assert_eq!(p.finished_message(false, vec![])["ok"], json!(false));
|
||||
p.feed(b"@@codeman phase done\n");
|
||||
assert_eq!(p.finished_message(false, vec![])["ok"], json!(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_that_finished_before_cancel_landed_is_not_cancelled() {
|
||||
let mut p = Progress::default();
|
||||
p.feed(b"@@codeman phase done\n");
|
||||
assert_eq!(p.finished_message(true, vec![])["cancelled"], json!(false));
|
||||
let mut q = Progress::default();
|
||||
q.feed(b"@@codeman phase build\n");
|
||||
assert_eq!(q.finished_message(true, vec![])["cancelled"], json!(true));
|
||||
}
|
||||
|
||||
/// The process side, against a stand-in installer: `cargo test` on a Mac
|
||||
/// runs it. One test, because a run is one folder and one process.
|
||||
#[test]
|
||||
fn a_run_outlives_its_reader_and_ends_as_reported() {
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
let plan = Plan {
|
||||
port: 3999,
|
||||
network_password: Some("not-in-ps".to_string()),
|
||||
ai_cli: None,
|
||||
};
|
||||
let stand_in = |body: &str| {
|
||||
let dir = fresh_run_dir().unwrap();
|
||||
fs::write(dir.join(SCRIPT_FILE), format!("#!/bin/bash\n{body}\n")).unwrap();
|
||||
spawn_run(&plan).unwrap();
|
||||
dir
|
||||
};
|
||||
let collect = |stop_after: Option<usize>| {
|
||||
let got = Arc::new(Mutex::new(Vec::<Value>::new()));
|
||||
let (seen, sink) = (got.clone(), got.clone());
|
||||
let calls = AtomicUsize::new(0);
|
||||
follow(
|
||||
move || {
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
stop_after.is_some_and(|n| seen.lock().unwrap().len() >= n)
|
||||
},
|
||||
move |msg| sink.lock().unwrap().push(msg),
|
||||
);
|
||||
let out = got.lock().unwrap().clone();
|
||||
out
|
||||
};
|
||||
|
||||
// A reader that goes away (the page reloaded, the app quit) leaves the
|
||||
// install running, and the next reader gets it from the first line.
|
||||
let dir = stand_in(
|
||||
r#"echo "==> first"
|
||||
echo "@@codeman phase source" >&2
|
||||
while [ ! -f "$(dirname "$0")/go" ]; do sleep 0.1; done
|
||||
echo "==> second"
|
||||
echo "@@codeman phase done" >&2"#,
|
||||
);
|
||||
let first = collect(Some(1));
|
||||
assert_eq!(first[0]["phase"], json!("source"));
|
||||
assert_eq!(first[0]["log"], json!(["==> first"]));
|
||||
assert!(setup::install_in_app().is_some(), "the install stopped with its reader");
|
||||
|
||||
fs::write(dir.join("go"), "").unwrap();
|
||||
let replay = collect(None);
|
||||
let last = replay.last().unwrap();
|
||||
assert_eq!(last["type"], json!("installFinished"));
|
||||
assert_eq!(last["ok"], json!(true));
|
||||
let lines: Vec<&Value> = replay.iter().flat_map(|m| m["log"].as_array().unwrap()).collect();
|
||||
assert_eq!(lines, vec!["==> first", "==> second"]);
|
||||
assert!(!dir.exists(), "a finished run leaves nothing behind");
|
||||
|
||||
// Cancel reaches what the installer started, not only the installer.
|
||||
let marker = "31337";
|
||||
stand_in(&format!(
|
||||
r#"echo "@@codeman phase build" >&2
|
||||
sleep {marker} &
|
||||
( while true; do sleep {marker}; done ) &
|
||||
wait"#
|
||||
));
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
let sleeper = |procs: Vec<(u32, String)>| procs.iter().any(|(_, c)| c == &format!("sleep {marker}"));
|
||||
assert!(sleeper(setup::list_processes()), "the stand-in did not start");
|
||||
cancel();
|
||||
assert!(setup::install_in_app().is_none());
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
assert!(!sleeper(setup::list_processes()), "a child outlived Cancel");
|
||||
let done = collect(None);
|
||||
assert_eq!(done.last().unwrap()["cancelled"], json!(true));
|
||||
assert_eq!(done.last().unwrap()["ok"], json!(false));
|
||||
|
||||
// A subshell that outlives `done` does not keep the page waiting.
|
||||
let dir = stand_in(
|
||||
r#"( while true; do sleep 1; done ) &
|
||||
echo "@@codeman phase done" >&2
|
||||
wait"#,
|
||||
);
|
||||
assert_eq!(collect(None).last().unwrap()["ok"], json!(true));
|
||||
assert!(!dir.exists());
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
cancel();
|
||||
|
||||
// A failure reports its first error, and keeps the output for a look.
|
||||
let dir = stand_in(
|
||||
r#"echo "@@codeman phase packages" >&2
|
||||
echo "@@codeman error npm said no" >&2
|
||||
echo "@@codeman error Installation failed." >&2
|
||||
exit 1"#,
|
||||
);
|
||||
let done = collect(None);
|
||||
let last = done.last().unwrap();
|
||||
assert_eq!(last["ok"], json!(false));
|
||||
assert_eq!(last["cancelled"], json!(false));
|
||||
assert_eq!(last["error"], json!("npm said no"));
|
||||
assert!(dir.join(OUTPUT_FILE).is_file());
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A whole real install, driven down the same path as the page: build with
|
||||
/// `CODEMAN_DESKTOP_INSTALLER_URL` and run under a throwaway HOME with
|
||||
/// `CODEMAN_E2E_AI_CLI` set. Skips `refuse_start`, which a machine with a
|
||||
/// live Codeman would answer, and that machine is where this runs. With
|
||||
/// `CODEMAN_E2E_CANCEL_AT=<phase>` it cancels there instead of finishing.
|
||||
#[test]
|
||||
#[ignore = "installs Codeman: see the comment"]
|
||||
fn a_real_install_under_a_throwaway_home() {
|
||||
let found = fetch_and_ask().unwrap();
|
||||
println!("preflight: {}", serde_json::to_string(&found).unwrap());
|
||||
let ai_cli = std::env::var("CODEMAN_E2E_AI_CLI").ok();
|
||||
let port = std::env::var("CODEMAN_E2E_PORT").unwrap().parse().unwrap();
|
||||
spawn_run(&Plan {
|
||||
port,
|
||||
network_password: None,
|
||||
ai_cli,
|
||||
})
|
||||
.unwrap();
|
||||
let ok = std::sync::Arc::new(AtomicBool::new(false));
|
||||
let result = ok.clone();
|
||||
let started = Instant::now();
|
||||
let cancel_at = std::env::var("CODEMAN_E2E_CANCEL_AT").ok();
|
||||
let cancelling = cancel_at.is_some();
|
||||
let asked = AtomicBool::new(false);
|
||||
follow(
|
||||
|| false,
|
||||
move |msg| {
|
||||
let at = started.elapsed().as_secs();
|
||||
if cancel_at.as_deref().is_some_and(|p| msg["phase"] == json!(p)) && !asked.swap(true, Ordering::SeqCst)
|
||||
{
|
||||
println!("[{at}s] cancelling");
|
||||
std::thread::spawn(cancel);
|
||||
}
|
||||
if msg["type"] == "installFinished" {
|
||||
result.store(msg["ok"] == json!(true), Ordering::SeqCst);
|
||||
println!("[{at}s] {}", serde_json::to_string(&msg).unwrap());
|
||||
} else if !msg["log"].as_array().unwrap().is_empty() {
|
||||
println!("[{at}s] {} {}", msg["phase"], msg["log"]);
|
||||
}
|
||||
},
|
||||
);
|
||||
assert_eq!(
|
||||
ok.load(Ordering::SeqCst),
|
||||
!cancelling,
|
||||
"the install did not end as asked"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_path_is_filled_in() {
|
||||
let env = with_path(vec![("HOME".to_string(), "/Users/a".to_string())]);
|
||||
assert!(env.iter().any(|(k, v)| k == "PATH" && v == FALLBACK_PATH));
|
||||
let own = with_path(vec![("PATH".to_string(), "/mine".to_string())]);
|
||||
assert_eq!(own, vec![("PATH".to_string(), "/mine".to_string())]);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -139,8 +139,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()
|
||||
@@ -158,7 +168,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()),
|
||||
}
|
||||
@@ -265,6 +275,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()
|
||||
}
|
||||
|
||||
/// `script` (SCRIPT or FIND_SCRIPT) under `/bin/sh` with exactly the captured
|
||||
/// environment, so the server gets the profile's PATH, API keys and CODEMAN_*
|
||||
/// settings and nothing of launchd's bare one.
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
mod assets;
|
||||
mod config;
|
||||
mod credentials;
|
||||
mod gui_install;
|
||||
mod local_server;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
@@ -34,7 +35,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};
|
||||
@@ -267,6 +269,8 @@ 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>,
|
||||
/// 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)>,
|
||||
@@ -350,6 +354,7 @@ fn main() {
|
||||
downloads: HashMap::new(),
|
||||
menu,
|
||||
keychain,
|
||||
install_reader: Arc::new(AtomicU64::new(0)),
|
||||
fullscreen_retry: wants_fullscreen.then(|| (Instant::now() + FULLSCREEN_FIRST_CHECK, 0)),
|
||||
};
|
||||
|
||||
@@ -1174,6 +1179,54 @@ 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(stale, send);
|
||||
}
|
||||
Err(message) => send(json!({ "type": "installStartFailed", "message": message })),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
ConnectCmd::InstallAttach => {
|
||||
if choosing {
|
||||
let proxy = self.proxy.clone();
|
||||
let stale = self.next_install_reader();
|
||||
std::thread::spawn(move || {
|
||||
gui_install::follow(stale, |msg| {
|
||||
let _ = proxy.send_event(UserEvent::ToConnectPage(msg));
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
ConnectCmd::InstallCancel => {
|
||||
std::thread::spawn(gui_install::cancel);
|
||||
}
|
||||
ConnectCmd::InstallRemote { target } => {
|
||||
if choosing {
|
||||
match setup::SshTarget::parse(&target) {
|
||||
@@ -1205,6 +1258,14 @@ 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.
|
||||
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) {
|
||||
|
||||
@@ -565,6 +565,18 @@ 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,
|
||||
InstallCancel,
|
||||
/// Run the installer on another machine over SSH, in Terminal. `target`
|
||||
/// is what the user typed; setup::SshTarget::parse checks it.
|
||||
InstallRemote {
|
||||
@@ -619,6 +631,17 @@ 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,
|
||||
InstallRemote {
|
||||
target: String,
|
||||
},
|
||||
@@ -635,6 +658,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,
|
||||
@@ -692,6 +726,21 @@ 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::InstallRemote { target } if target.len() <= MAX_FIELD_LEN => {
|
||||
ConnectCmd::InstallRemote { target }
|
||||
}
|
||||
@@ -1480,6 +1529,73 @@ 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_from_connect_page() {
|
||||
let page = "codemanapp://localhost/index.html";
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
//! 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, 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 +24,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.
|
||||
@@ -289,7 +299,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())
|
||||
@@ -329,8 +339,8 @@ pub fn is_codeman_server(command: &str) -> bool {
|
||||
}
|
||||
|
||||
/// 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();
|
||||
@@ -340,7 +350,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::is_install_run(command) {
|
||||
let port = words
|
||||
.iter()
|
||||
.position(|w| *w == "--port")
|
||||
@@ -351,6 +361,15 @@ pub fn install_in_progress(command: &str) -> Option<Option<u16>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The process of the graphical install running on this Mac, if one does. It
|
||||
/// leads its process group.
|
||||
pub fn install_in_app() -> Option<u32> {
|
||||
list_processes()
|
||||
.into_iter()
|
||||
.find(|(_, command)| gui_install::is_install_run(command))
|
||||
.map(|(pid, _)| pid)
|
||||
}
|
||||
|
||||
fn codeman_servers(procs: &[(u32, String)]) -> Vec<u32> {
|
||||
procs
|
||||
.iter()
|
||||
@@ -465,10 +484,13 @@ 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>,
|
||||
/// 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,
|
||||
/// For RunningElsewhere: the addresses that Codeman listens on.
|
||||
pub elsewhere: Vec<String>,
|
||||
/// The probe's outcome, for the connect page's explanations.
|
||||
@@ -495,6 +517,7 @@ pub fn inspect(depth: Depth) -> LocalStatus {
|
||||
let servers = codeman_servers(&procs);
|
||||
let found = listeners(&servers);
|
||||
let install = procs.iter().find_map(|(_, c)| install_in_progress(c));
|
||||
let install_in_app = procs.iter().any(|(_, c)| gui_install::is_install_run(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)) {
|
||||
@@ -587,6 +610,7 @@ pub fn inspect(depth: Depth) -> LocalStatus {
|
||||
install_complete,
|
||||
install_running: install.is_some(),
|
||||
install_port: install.flatten(),
|
||||
install_in_app,
|
||||
elsewhere,
|
||||
outcome,
|
||||
}
|
||||
@@ -597,7 +621,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);
|
||||
|
||||
Reference in new issue
Block a user