Add Update and restart, a remembered window and safer copy and paste to the desktop app

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-17 18:07:59 -08:00
1 parent c07e679105
commit 710c751c2f
24 files changed
+4347 -422

No files matched your search

+46 -16
View File
@@ -7,12 +7,16 @@ session. The fresh agent gets a console session of its own, so the Session meter
It is an addition: `/plan2code` typed inside an agent works exactly as before, with or
without the app.
![The launch card: which agent, model and effort to start on, with permission checks as their own tick.](screenshots/app-launch-dark.webp)
![The app with the dashboard on the left and the agent's terminal docked on the right.](screenshots/app-terminal-dark.webp)
## Get it
The installer offers the app after the skills and the `plan2code` command:
```
npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git
npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git#release
```
Answer **Y** to "Also install the Plan2Code desktop app?" (it is the default). It downloads the file
@@ -38,10 +42,19 @@ verified. `plan2code-app`'s own `npm run build` can produce `.msi`/NSIS/`.dmg`/`
(Tauri's bundler is on), but the release workflow does not build or publish them; nothing today
downloads or runs one.
### Manual download
Only when you cannot run the installer. Open the [latest release](https://github.com/jparkerweb/plan2code/releases/latest), then:
1. Download the file for your system from the table above, and `plan2code-app-<version>-SHA256SUMS.txt` beside it.
2. Verify it: the hash you compute must match that file's line in the checksum list. On macOS use `shasum -a 256 <file>`, on Linux `sha256sum <file>`, on Windows PowerShell `Get-FileHash <file> -Algorithm SHA256`.
3. Put it in `~/.plan2code/app/` (on Windows `%USERPROFILE%\.plan2code\app\`) and name it `plan2code-app` (`plan2code-app.exe` on Windows), so `plan2code` finds it.
4. On macOS and Linux, make it runnable: `chmod +x ~/.plan2code/app/plan2code-app`.
You also need Node.js 18 or newer (the app checks at start and says what to install) and:
- **Windows:** the WebView2 runtime, which comes with Windows 11 and current Windows 10.
- **Linux:** WebKitGTK 4.1 (`libwebkit2gtk-4.1`) and a desktop session.
- **Linux:** WebKitGTK 4.1 (`libwebkit2gtk-4.1`) and a desktop session. Install it with `sudo apt install libwebkit2gtk-4.1-0` (Debian, Ubuntu) or `sudo dnf install webkit2gtk4.1` (Fedora).
## Start it
@@ -50,7 +63,7 @@ Run `plan2code` in your project, as always. When the app is installed and a wind
running the agent in your terminal. The desktop shortcut the installer can create runs the same
command, so it opens the app too; it asks for the folder first, with **Choose a folder** at the top and the folders you opened lately under it (with none yet, it goes straight to the folder dialog).
Start the app itself (from the Start menu, the Dock or a launcher) and it asks for a folder the same way: **Choose a folder** first, then your recent folders, newest first. It no longer reopens the last folder on its own.
You can also start the app file itself: double-click it in `~/.plan2code/app/`, or run it from a terminal. Nothing adds it to the Start menu, the Dock or a launcher menu, so pin the file yourself if you want a shortcut. It asks for a folder the same way: **Choose a folder** first, then your recent folders, newest first. It no longer reopens the last folder on its own.
Three things keep today's terminal flow:
@@ -123,9 +136,10 @@ to that offers the same **Reconnect the console** button — never "Restart the
The console also knows when it is running inside the app (the agent it talks to carries that signal):
its session meter, the "Before you close this" guide on a finished step, and the dashboard's red-session
banner all point at the app's own **New Session** button instead of a command to paste into a new
conversation, since New Session already does that in one click. The dashboard's **UPDATE AVAILABLE**
banner still shows, beside the bar's own **Update available**, and its steps say to run the command in a
terminal outside the app and then reopen the app (see "Keep it up to date" below). A slash command still offered to continue a step (such as `/plan2code-4-finalize`) stays
conversation, since New Session already does that in one click. The dashboard's **Update available**
banner still shows, beside the bar's own **Update available**: its dialog points at the bar's **Update and
restart** first, with the command as the fallback, run in a terminal outside the app before reopening the
app (see "Keep it up to date" below). A slash command still offered to continue a step (such as `/plan2code-4-finalize`) stays
exactly as it would in a terminal: paste it into the app's own terminal panel, which runs the real
agent CLI.
@@ -136,6 +150,12 @@ while you do something else. It is in the app only: the dashboard shows an **Imp
card there, and nowhere else. Pick a spec, answer a short setup, press **Start the loop**, and the app
confirms it once in its own window before anything runs.
![The Implementation Loop setup screen.](screenshots/loop-setup-dark.webp)
![The Loop's banner while a phase builds, with Stop after this phase.](screenshots/loop-banner-dark.webp)
![The Loop's stop screen, with the evidence for why it stopped.](screenshots/loop-stop-dark.webp)
**How it runs.** Each phase gets a fresh agent session, so a long spec never grows one tired
conversation. The app, not the agent, decides when a phase counts: it reads the spec's marks, runs the
quick check, marks the phase done and commits it. With commits on, it commits to the branch you are on and never
@@ -148,7 +168,7 @@ not), so your own edits never end up inside a phase's commit.
- **Fix findings**: **Smart pick** (the default) has a fresh agent read the findings and fix only the
ones worth fixing, recording every skip. A skipped Critical stops the phase. **By level** fixes the
Critical, Warning and Suggestion findings you tick (all three start ticked).
- **Strength per phase** (off): turn on **Set strength per phase** to see one row per phase still to build under four headed columns, **Match my session**, **Thrifty**, **Balanced** and **Best**, and click a dot in a row to pick (the arrow keys move along a row), or use **Set all to** for one pick. A thick line steps through each row's picked dot, so the choices read at a glance, and the model each pick becomes shows at the end of its row. A phase you leave untouched runs on the model the app was launched with, as before. A phase whose agent crashes or goes quiet gets its one retry (when the retry tick is on) one step up (Thrifty to Balanced, Balanced to Best; Best stays Best; **Match my session** runs on the launch model and its retry stays there), and the phase's helpers follow the same strength. Which model each word means for your agent is set in User Preferences, **Agents & models**, under **Strengths in the loop**; an agent with nothing mapped shows the toggle off with a link there. The picks are remembered per project and spec, and a pick for a phase that is done or gone is dropped.
- **Strength per phase** (off): turn on **Set strength per phase** to see one row per phase still to build under four headed columns, **Match my session**, **Thrifty**, **Balanced** and **Best**, and click a dot in a row to pick (the arrow keys move along a row), or use **Set all to** for one pick. A thick line steps through each row's picked dot, so the choices read at a glance, and the model each pick becomes shows at the end of its row. A phase you leave untouched runs on the model the app was launched with, as before. A phase whose agent crashes or goes quiet gets its one retry (when the retry tick is on) one step up (Thrifty to Balanced, Balanced to Best; Best stays Best; **Match my session** runs on the launch model and its retry stays there), and the phase's subagents follow the same strength. Which model each word means for your agent is set in User Preferences, **Agents & models**, under **Strengths in the loop**; an agent with nothing mapped shows the toggle off with a link there. The picks are remembered per project and spec, and a pick for a phase that is done or gone is dropped.
- **When a phase asks something**: **Take the agent's best guess** (the default), which records the
assumption as a `[?]` task, **Pause and wait for me**, or **Stop the loop**.
- **After the last phase**: **Stop and offer Finalize** (the default) or **Run Finalize automatically**.
@@ -202,7 +222,7 @@ with, and it needs permission checks off. With them on, an agent would wait on a
sees, so **Start the loop** stays grayed out until you turn them off (see
[Permission checks are off by default](#permission-checks-are-off-by-default-same-as-the-terminal)).
**What is locked while it drives.** Answers, sign-offs, launches, Workspace, Helpers, **Back** and
**What is locked while it drives.** Answers, sign-offs, launches, Workspace, Subagents, **Back** and
**New Session** are read-only, and Ask is off, except for a question the loop is waiting on. Activities, Notebook, Help, Preferences, the documents
and the code review stay usable, so you can watch, play, or read along.
@@ -252,11 +272,17 @@ clean tree. The in-app **Help** has a matching topic, **Implementation Loop**, w
`plan2code update` brings the skills, the `plan2code` command and the app up together.
When a newer release is out, the app's top bar shows **Update available** with **Copy update command**,
and the dashboard shows its **UPDATE AVAILABLE** banner. Neither updates for you: the app cannot replace
itself while it runs (Windows will not overwrite a running file), so copy the command, run it in a
terminal outside the app (not the app's terminal panel, which runs your agent), then close the app and
open it again.
When a newer release is out, the app's top bar shows **Update available** with **Update and restart**
and a **What's new** link to the release page. **Update and restart** installs the newest release (the
same installer `plan2code update` runs, with its progress in the bar) and then reopens the app on the
same project; no terminal is needed. A running file cannot be overwritten on Windows, but the installer
renames it aside and the app then restarts into the new one. If an agent or a loop is running, the app
asks first (the same check as closing the window, with Stay as the default); answer Stay and the bar
offers **Restart Plan2Code** for when you are ready. If the update fails, the app you have keeps running
and the bar says why; you can press the button again or run `plan2code update` in a terminal. After the
restart the bar says **Updated to vX** once. The app asks again every few hours while it stays open, and
says so when it cannot check (git missing, or no answer from GitHub). The dashboard's own **Update
available** banner points at **Update and restart** too, and keeps the terminal command as the fallback.
If the app and the installed skills ever differ in version, the app's top bar says so and offers **Update
skills**, which brings the skills level with the app's own version when you press it. That one is a
@@ -267,14 +293,18 @@ then asks whether your own data in `~/.plan2code/` (notebooks, handoffs, setting
`--yes` skips both questions and keeps that data; add `--purge` to delete it. Close the app first:
Windows cannot delete a running file.
## The first release is unsigned
## The app is not code-signed
The app is not code-signed yet, so your system may stop it the first time it starts. It is the same
The app is not code-signed, so your system may stop it the first time it starts. Signing is not planned for now. It is the same
file the installer verified against the release's checksum list.
**macOS.** If macOS says the app "cannot be opened because Apple cannot check it for malicious
software": open **System Settings**, then **Privacy & Security**, scroll to the message about
`plan2code-app`, and press **Open Anyway**. Start `plan2code` again and confirm.
`plan2code-app`, and press **Open Anyway**. Start `plan2code` again and confirm. If **Open Anyway** does not appear, remove the quarantine mark and start it again:
```
xattr -d com.apple.quarantine ~/.plan2code/app/plan2code-app
```
**Windows.** If SmartScreen shows "Windows protected your PC": press **More info**, then **Run
anyway**.
+477 -4
View File
@@ -47,6 +47,137 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "async-broadcast"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
dependencies = [
"event-listener",
"event-listener-strategy",
"futures-core",
"pin-project-lite",
]
[[package]]
name = "async-channel"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
dependencies = [
"concurrent-queue",
"event-listener-strategy",
"futures-core",
"pin-project-lite",
]
[[package]]
name = "async-executor"
version = "1.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
dependencies = [
"async-task",
"concurrent-queue",
"fastrand",
"futures-lite",
"pin-project-lite",
"slab",
]
[[package]]
name = "async-io"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
dependencies = [
"autocfg",
"cfg-if",
"concurrent-queue",
"futures-io",
"futures-lite",
"parking",
"polling",
"rustix",
"slab",
"windows-sys 0.61.2",
]
[[package]]
name = "async-lock"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f"
dependencies = [
"event-listener",
"event-listener-strategy",
"pin-project-lite",
]
[[package]]
name = "async-process"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
dependencies = [
"async-channel",
"async-io",
"async-lock",
"async-signal",
"async-task",
"blocking",
"cfg-if",
"event-listener",
"futures-lite",
"rustix",
]
[[package]]
name = "async-recursion"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "async-signal"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"
dependencies = [
"async-io",
"async-lock",
"atomic-waker",
"cfg-if",
"futures-core",
"futures-io",
"rustix",
"signal-hook-registry",
"slab",
"windows-sys 0.61.2",
]
[[package]]
name = "async-task"
version = "4.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
[[package]]
name = "async-trait"
version = "0.1.92"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "atk"
version = "0.18.2"
@@ -148,6 +279,19 @@ dependencies = [
"objc2",
]
[[package]]
name = "blocking"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa"
dependencies = [
"async-channel",
"async-task",
"futures-io",
"futures-lite",
"piper",
]
[[package]]
name = "brotli"
version = "9.0.0"
@@ -346,6 +490,15 @@ dependencies = [
"memchr",
]
[[package]]
name = "concurrent-queue"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "cookie"
version = "0.18.2"
@@ -728,6 +881,33 @@ version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"
[[package]]
name = "endi"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
[[package]]
name = "enumflags2"
version = "0.7.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
dependencies = [
"enumflags2_derive",
"serde",
]
[[package]]
name = "enumflags2_derive"
version = "0.7.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "equivalent"
version = "1.0.3"
@@ -755,9 +935,29 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "event-listener"
version = "5.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
dependencies = [
"parking",
"pin-project-lite",
]
[[package]]
name = "event-listener-strategy"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
dependencies = [
"event-listener",
"pin-project-lite",
]
[[package]]
name = "fake-agent"
version = "3.1.0"
version = "3.1.1"
dependencies = [
"serde_json",
"terminal_size",
@@ -912,6 +1112,19 @@ version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
[[package]]
name = "futures-lite"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
dependencies = [
"fastrand",
"futures-core",
"futures-io",
"parking",
"pin-project-lite",
]
[[package]]
name = "futures-macro"
version = "0.3.34"
@@ -1255,6 +1468,12 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hermit-abi"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
[[package]]
name = "hex"
version = "0.4.3"
@@ -1551,6 +1770,25 @@ version = "2.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
[[package]]
name = "is-docker"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3"
dependencies = [
"once_cell",
]
[[package]]
name = "is-wsl"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5"
dependencies = [
"is-docker",
"once_cell",
]
[[package]]
name = "itoa"
version = "1.0.18"
@@ -2201,6 +2439,17 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "open"
version = "5.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95"
dependencies = [
"dunce",
"is-wsl",
"libc",
]
[[package]]
name = "openssl"
version = "0.10.81"
@@ -2250,6 +2499,16 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
[[package]]
name = "ordered-stream"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"
dependencies = [
"futures-core",
"pin-project-lite",
]
[[package]]
name = "pango"
version = "0.18.3"
@@ -2275,6 +2534,12 @@ dependencies = [
"system-deps",
]
[[package]]
name = "parking"
version = "2.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
[[package]]
name = "parking_lot"
version = "0.12.5"
@@ -2363,6 +2628,17 @@ version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "piper"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"
dependencies = [
"atomic-waker",
"fastrand",
"futures-io",
]
[[package]]
name = "pkg-config"
version = "0.3.34"
@@ -2371,7 +2647,7 @@ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "plan2code-app"
version = "3.1.0"
version = "3.1.1"
dependencies = [
"chrono",
"libc",
@@ -2382,6 +2658,8 @@ dependencies = [
"tauri",
"tauri-build",
"tauri-plugin-dialog",
"tauri-plugin-opener",
"tauri-plugin-window-state",
"winapi",
]
@@ -2424,6 +2702,20 @@ dependencies = [
"miniz_oxide 0.8.9",
]
[[package]]
name = "polling"
version = "3.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
dependencies = [
"cfg-if",
"concurrent-queue",
"hermit-abi",
"pin-project-lite",
"rustix",
"windows-sys 0.61.2",
]
[[package]]
name = "portable-atomic"
version = "1.15.0"
@@ -3083,6 +3375,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
@@ -3513,6 +3815,43 @@ dependencies = [
"url",
]
[[package]]
name = "tauri-plugin-opener"
version = "2.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54592c6718b42ab198bf11bda6a428a3553ca2f2f8e506df56f6a063ec328331"
dependencies = [
"dunce",
"glob",
"objc2-app-kit",
"objc2-foundation",
"open",
"schemars 0.8.22",
"serde",
"serde_json",
"tauri",
"tauri-plugin",
"thiserror 2.0.21",
"url",
"windows",
"zbus",
]
[[package]]
name = "tauri-plugin-window-state"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d6815cab7b212f9cfe16a9d79d8d22f9e14159e4a9460f7dec1467167a008e3"
dependencies = [
"bitflags 2.13.2",
"log",
"serde",
"serde_json",
"tauri",
"tauri-plugin",
"thiserror 2.0.21",
]
[[package]]
name = "tauri-runtime"
version = "2.12.2"
@@ -3620,10 +3959,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.3.4",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -3916,9 +4255,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
@@ -3968,6 +4319,17 @@ version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "uds_windows"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset",
"tempfile",
"windows-sys 0.61.2",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
@@ -4726,6 +5088,76 @@ dependencies = [
"synstructure",
]
[[package]]
name = "zbus"
version = "5.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907"
dependencies = [
"async-broadcast",
"async-executor",
"async-io",
"async-lock",
"async-process",
"async-recursion",
"async-task",
"async-trait",
"blocking",
"enumflags2",
"event-listener",
"futures-core",
"futures-lite",
"hex",
"libc",
"ordered-stream",
"rustix",
"serde",
"serde_repr",
"tracing",
"uds_windows",
"uuid",
"windows-sys 0.61.2",
"winnow 1.0.4",
"zbus_macros",
"zbus_names",
"zvariant",
]
[[package]]
name = "zbus_macros"
version = "5.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40"
dependencies = [
"proc-macro-crate 3.5.0",
"proc-macro2",
"quote",
"syn 3.0.9",
"zbus_names",
"zvariant",
"zvariant_utils",
]
[[package]]
name = "zbus_names"
version = "4.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd"
dependencies = [
"serde",
"winnow 1.0.4",
"zvariant",
]
[[package]]
name = "zcheapstr"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920"
dependencies = [
"serde",
]
[[package]]
name = "zerofrom"
version = "0.1.8"
@@ -4797,3 +5229,44 @@ name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zvariant"
version = "5.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7"
dependencies = [
"endi",
"enumflags2",
"serde",
"winnow 1.0.4",
"zcheapstr",
"zvariant_derive",
"zvariant_utils",
]
[[package]]
name = "zvariant_derive"
version = "5.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d"
dependencies = [
"proc-macro-crate 3.5.0",
"proc-macro2",
"quote",
"syn 3.0.9",
"zvariant_utils",
]
[[package]]
name = "zvariant_utils"
version = "4.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3"
dependencies = [
"proc-macro2",
"quote",
"serde",
"syn 3.0.9",
"winnow 1.0.4",
]
+7 -3
View File
@@ -1,6 +1,10 @@
# plan2code-app
The Plan2Code desktop app (v3.0): one window with the dashboard, a terminal panel for the agent, and a **New Session** button. Built with Tauri 2 (Rust and a web view).
Users: see [docs/desktop-app.md](../docs/desktop-app.md). This file is for people who build the app.
The Plan2Code desktop app: one window with the dashboard, a terminal panel for the agent, and a **New Session** button. Built with Tauri 2 (Rust and a web view).
![The desktop app: the dashboard on the left and the agent's terminal docked on the right.](../docs/screenshots/app-terminal-dark.webp)
The app is optional. The Node web console and the skills never depend on it, so running `/plan2code` inside an agent with no app works exactly as before.
@@ -39,14 +43,14 @@ Needs the Rust toolchain pinned in `rust-toolchain.toml`, Node 18+, and the Taur
cd plan2code-app
npm install
npm run dev # run the app
npm run build # build the installable bundle
npm run build # build the app and local installer bundles (the release ships only the plain executable)
```
## Tests
```
cd plan2code-app
node scripts/vendor.mjs # once: the xterm files cargo builds against
node scripts/vendor.mjs # once: the xterm files and the console's tokens.css cargo builds against
cargo fmt --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "fake-agent"
version = "3.1.0"
version = "3.1.1"
description = "A stand-in agent program for the Plan2Code app's tests"
edition = "2021"
publish = false
+9 -2
View File
@@ -1,15 +1,16 @@
{
"name": "plan2code-app",
"version": "3.1.0",
"version": "3.1.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "plan2code-app",
"version": "3.1.0",
"version": "3.1.1",
"dependencies": {
"@tauri-apps/api": "2.12.4",
"@xterm/addon-fit": "0.11.0",
"@xterm/addon-web-links": "0.12.0",
"@xterm/xterm": "6.0.0"
},
"devDependencies": {
@@ -249,6 +250,12 @@
"integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==",
"license": "MIT"
},
"node_modules/@xterm/addon-web-links": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/@xterm/addon-web-links/-/addon-web-links-0.12.0.tgz",
"integrity": "sha512-4Smom3RPyVp7ZMYOYDoC/9eGJJJqYhnPLGGqJ6wOBfB8VxPViJNSKdgRYb8NpaM6YSelEKbA2SStD7lGyqaobw==",
"license": "MIT"
},
"node_modules/@xterm/xterm": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz",
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "plan2code-app",
"version": "3.1.0",
"version": "3.1.1",
"private": true,
"description": "Plan2Code desktop app (Tauri). Separate from the repo root so the root and the web console stay dependency-free.",
"scripts": {
@@ -11,6 +11,7 @@
"dependencies": {
"@tauri-apps/api": "2.12.4",
"@xterm/addon-fit": "0.11.0",
"@xterm/addon-web-links": "0.12.0",
"@xterm/xterm": "6.0.0"
},
"devDependencies": {
+8 -3
View File
@@ -1,5 +1,8 @@
// Copies the xterm files the page loads from node_modules into ui/vendor/, so the
// page is plain files with no bundler. Run before `tauri dev` and `tauri build`.
// Copies the files the page loads from outside ui/ into ui/vendor/, so the page is
// plain files with no bundler: the xterm files from node_modules, and the web
// console's own tokens.css (its colors, type, radii and layers), so the shell
// wears the same ones and cannot drift from them. Run before `tauri dev` and
// `tauri build`.
import { copyFileSync, mkdirSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -12,6 +15,8 @@ const files = [
['node_modules/@xterm/xterm/lib/xterm.js', 'xterm.js'],
['node_modules/@xterm/xterm/css/xterm.css', 'xterm.css'],
['node_modules/@xterm/addon-fit/lib/addon-fit.js', 'addon-fit.js'],
['node_modules/@xterm/addon-web-links/lib/addon-web-links.js', 'addon-web-links.js'],
['../src/web-console/public/styles/tokens.css', 'tokens.css'],
];
for (const [from, to] of files) copyFileSync(join(root, from), join(out, to));
console.log(`vendored ${files.length} xterm files into ui/vendor/`);
console.log(`vendored ${files.length} files into ui/vendor/`);
+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "plan2code-app"
version = "3.1.0"
version = "3.1.1"
description = "Plan2Code desktop app"
edition = "2021"
publish = false
@@ -15,6 +15,8 @@ tauri-build = { version = "2.5", features = [] }
[dependencies]
tauri = { version = "2.12", features = [] }
tauri-plugin-dialog = "2"
tauri-plugin-opener = "2.7"
tauri-plugin-window-state = "2.5"
portable-pty = "0.9.0"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
@@ -1,7 +1,7 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Permissions for the main window: its own commands need none, so only listening to the page events the app sends, plus setting the window's own title to the open project's name and putting it in and out of full screen for an Activities game",
"description": "Permissions for the main window: its own commands need none, so only listening to the page events the app sends, plus setting the window's own title to the open project's name and putting it in and out of full screen for an Activities game, plus showing and theming it, the window-state plugin, and opening http and https links (the terminal's clickable URLs) in the default browser, through the opener plugin and nothing else it can do",
"windows": ["main"],
"permissions": ["core:event:allow-listen", "core:event:allow-unlisten", "core:window:allow-set-title", "core:window:allow-is-fullscreen", "core:window:allow-set-fullscreen"]
"permissions": ["core:event:allow-listen", "core:event:allow-unlisten", "core:window:allow-set-title", "core:window:allow-is-fullscreen", "core:window:allow-set-fullscreen", "core:window:allow-show", "core:window:allow-set-theme", "window-state:default", {"identifier": "opener:allow-open-url", "allow": [{"url": "https://*"}, {"url": "http://*"}]}]
}
+1
View File
@@ -22,4 +22,5 @@ pub mod session_reader;
pub mod settings;
#[cfg(windows)]
pub mod task_dialog;
pub mod ui_confirm;
pub mod versions;
+113 -2
View File
@@ -1131,14 +1131,17 @@ pub fn prompt_support(agent: &Agent) -> bool {
// -------------------------------------------------------- starting a loop
/// `specs/<name>`: one folder directly under `specs/`, not a link.
/// `specs/<name>`: one folder directly under `specs/`, not a link. The name may
/// hold dots (`polish-3.2`) but never start with one, which also refuses `.`
/// and `..`, matching the page's `isDeletableSpecDir`.
pub fn validate_spec(project: &Path, spec: &str) -> Result<(), String> {
let bad = || format!("not a spec folder: {spec}");
let name = spec.strip_prefix("specs/").ok_or_else(bad)?;
if name.is_empty()
|| name.starts_with('.')
|| !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
{
return Err(bad());
}
@@ -1390,6 +1393,70 @@ pub fn confirm_text(rec: &RunningRecord) -> String {
text
}
/// The same Start confirm as lines for the shell's modal: the question, the quick check in a code
/// block, the resume notes as text, and the trunk warning as an amber callout, with no literal
/// backticks (`confirm_text` stays the plain-text form).
pub fn confirm_lines(rec: &RunningRecord) -> Vec<crate::ui_confirm::ConfirmLine> {
use crate::ui_confirm::ConfirmLine;
let name = rec.spec.strip_prefix("specs/").unwrap_or(&rec.spec);
let n = rec.phases.len();
let phases = if n == 1 {
"1 phase".to_string()
} else {
format!("{n} phases")
};
let mut lines = vec![ConfirmLine::text(format!("Build {phases} of {name}?"))];
let check = rec.setup.quick_check.trim();
if check.is_empty() {
lines.push(ConfirmLine::text("No quick check is set."));
} else {
lines.push(ConfirmLine::text(
"After each phase the app runs this quick check:",
));
lines.push(ConfirmLine::code(check));
}
if !rec.rebuilt.is_empty() {
let list: Vec<String> = rec.rebuilt.iter().map(|n| format!("Phase {n}")).collect();
lines.push(ConfirmLine::text(format!(
"{} is marked done but has no commit in the log, so it is built again.",
list.join(" and ")
)));
}
if let Some(files) = rec.resumed_files {
let files = if files == 1 {
"1 uncommitted file".to_string()
} else {
format!("{files} uncommitted files")
};
lines.push(ConfirmLine::text(format!(
"The resumed phase's commit will take {files} already in the tree."
)));
}
if !rec.setup.notify_url.is_empty() {
let when = if rec.setup.notify_phases {
"after each phase, when the loop needs you, or when it ends"
} else {
"When the loop needs you or ends"
};
lines.push(ConfirmLine::text(format!(
"{}, {}.",
capitalized(when),
loop_notify::describe(
rec.setup.notify_kind,
&rec.setup.notify_url,
&rec.setup.notify_param
)
)));
}
if commits_to_trunk(rec) {
let branch = rec.branch.as_deref().unwrap_or_default();
lines.push(ConfirmLine::callout(format!(
"You are on {branch}: every phase will commit straight to it. Start only if that is what you want."
)));
}
lines
}
fn capitalized(text: &str) -> String {
let mut chars = text.chars();
chars
@@ -3778,6 +3845,44 @@ mod tests {
.contains("After each phase, when the loop needs you, or when it ends"));
}
#[test]
fn the_start_confirm_as_lines_has_the_check_in_a_code_block_and_the_trunk_warning_as_a_callout()
{
let mut s = setup();
s.quick_check = "npm test".into();
s.commit = true;
let mut rec = RunningRecord::new("p".into(), "specs/x".into(), s, vec![phase(1), phase(2)]);
rec.branch = Some("main".into());
let lines = confirm_lines(&rec);
assert_eq!(lines[0].text, "Build 2 phases of x?");
assert!(lines
.iter()
.any(|l| l.kind == "code" && l.text == "npm test"));
let callout = lines
.iter()
.find(|l| l.kind == "callout")
.expect("a callout");
assert!(callout
.text
.contains("You are on main: every phase will commit straight to it."));
assert!(
lines.iter().all(|l| !l.text.contains('`')),
"no literal backticks"
);
assert_eq!(
lines.last().map(|l| l.kind),
Some("callout"),
"the warning reads last"
);
rec.setup.quick_check = String::new();
rec.branch = Some("feature/x".into());
let plain = confirm_lines(&rec);
assert!(plain.iter().any(|l| l.text == "No quick check is set."));
assert!(plain
.iter()
.all(|l| l.kind != "callout" && l.kind != "code"));
}
#[test]
fn no_web_address_means_no_call_and_an_older_entry_reads_with_none() {
assert_eq!(notify(&setup(), "x"), None);
@@ -4657,9 +4762,15 @@ second line"
let dir = std::env::temp_dir().join(format!("plan2code-loop-spec-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("specs").join("lunch-vote")).unwrap();
std::fs::create_dir_all(dir.join("specs").join("polish-3.2")).unwrap();
std::fs::create_dir_all(dir.join("specs").join(".hidden")).unwrap();
std::fs::write(dir.join("specs").join("a-file"), "x").unwrap();
assert!(validate_spec(&dir, "specs/lunch-vote").is_ok());
assert!(validate_spec(&dir, "specs/polish-3.2").is_ok());
for bad in [
"specs/.hidden",
"specs/.",
"specs/..",
"specs/missing",
"specs/a-file",
"specs/../x",
+431 -66
View File
@@ -1,7 +1,7 @@
// Hide the extra console window on Windows release builds.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::path::Path;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
@@ -22,6 +22,7 @@ use plan2code_app_lib::session_reader;
use plan2code_app_lib::settings;
#[cfg(windows)]
use plan2code_app_lib::task_dialog;
use plan2code_app_lib::ui_confirm;
use plan2code_app_lib::versions;
use tauri::ipc::{Channel, InvokeResponseBody};
use tauri::{Emitter, Manager, State};
@@ -42,12 +43,9 @@ struct AppState {
page: PageChannel,
// This window's endpoint for pages the agent's `console.mjs open` wants shown here.
announce: Arc<Mutex<Option<AnnounceServer>>>,
// The Node version `main()` found before opening the window (Task 1.7 exits
// cleanly on anything else, so this is always a passing version once the
// window exists), and which binary that was, with `resolved_path`'s PATH
// (Task 9.9): the first-run checklist's Node row names both.
node_version: Option<String>,
node_binary: Option<String>,
// The Node check's result: it runs on a background thread after the
// window opens (Task 9.10), so this is unchecked until it reports.
node: Mutex<NodeReport>,
// What the taskbar entry last said, and whether it may say anything.
attention: Mutex<AttentionState>,
// The app itself, once it is set up: the agent's sink clears the taskbar
@@ -60,6 +58,69 @@ struct AppState {
// kept after the running record is gone so Resume, Fix together with an agent and
// Finalize still work. Memory only.
last_loop: Mutex<Option<LastLoop>>,
// The version this app was running before an "Update and restart" brought it up: read
// from app.json once at launch (and cleared there), for the page to say "Updated to vX".
updated_from: Option<String>,
// Confirms the shell's own modal is asked (ui_confirm.rs): the answers still to come, and
// whether the page has begun listening for requests (until then the OS box asks instead).
confirms: ui_confirm::Pending,
confirm_ready: AtomicBool,
}
/// What the Node check found, as the page reads it (`app_state` and the
/// `node-status` event share this shape). `checked` is false until the check
/// has finished; `problem` is the failure message, if any.
#[derive(Clone, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct NodeReport {
checked: bool,
version: Option<String>,
binary: Option<String>,
problem: Option<String>,
}
/// Run the Node check off the main thread and publish its result: store it,
/// tell the page, and on a failure show the dialog and end the app, as
/// `main()` did before the window existed (FR-13).
fn spawn_node_check(app: tauri::AppHandle) {
std::thread::spawn(move || {
let status = node_check::check_node();
let problem = node_check::problem_message(&status);
let version = match &status {
node_check::NodeStatus::Ok(version) => Some(version.clone()),
_ => None,
};
let binary = version
.as_ref()
.and_then(|_| node_check::node_binary_path());
let report = NodeReport {
checked: true,
version,
binary,
problem: problem.clone(),
};
if let Ok(mut slot) = app.state::<AppState>().node.lock() {
*slot = report.clone();
}
let _ = app.emit("node-status", &report);
if let Some(message) = problem {
// The first button is the default: Open nodejs.org, then the app ends either way.
let open_site = app
.dialog()
.message(&message)
.title("Plan2Code needs Node.js")
.kind(MessageDialogKind::Error)
.buttons(MessageDialogButtons::OkCancelCustom(
"Open nodejs.org".to_string(),
"Quit".to_string(),
))
.blocking_show();
if open_site {
let _ = open_url("https://nodejs.org");
}
std::process::exit(1);
}
});
}
// The console page's last state as the taskbar shows it (attention.rs), and
@@ -146,7 +207,12 @@ fn agent_availability(refresh: Option<bool>) -> serde_json::Value {
// is an error: the page never names the link itself.
#[tauri::command]
fn open_install_page(id: String) -> Result<(), String> {
let url = agents::install_page_url(&id)?;
open_url(&agents::install_page_url(&id)?)
}
// Opens a web address in the default browser, with the same switches as the console
// open-link.mjs.
fn open_url(url: &str) -> Result<(), String> {
// The same switches as the console open-link.mjs.
if std::env::var_os("NO_BROWSER").is_some_and(|v| !v.is_empty())
|| std::env::var_os("PLAN2CODE_NO_BROWSER").is_some_and(|v| !v.is_empty())
@@ -155,11 +221,11 @@ fn open_install_page(id: String) -> Result<(), String> {
}
let mut command = if cfg!(windows) {
let mut c = std::process::Command::new("rundll32.exe");
c.args(["url.dll,FileProtocolHandler", &url]);
c.args(["url.dll,FileProtocolHandler", url]);
c
} else if cfg!(target_os = "macos") {
let mut c = std::process::Command::new("open");
c.arg(&url);
c.arg(url);
c
} else {
let browser = std::env::var("BROWSER")
@@ -167,7 +233,7 @@ fn open_install_page(id: String) -> Result<(), String> {
.filter(|b| !b.is_empty())
.unwrap_or_else(|| "xdg-open".to_string());
let mut c = std::process::Command::new(browser);
c.arg(&url);
c.arg(url);
c
};
command
@@ -480,6 +546,100 @@ struct QuitOpen;
impl Drop for QuitOpen {
fn drop(&mut self) {
QUIT_OPEN.store(false, Ordering::SeqCst);
// Stay was the answer (a Quit has already taken the plan): no restart is pending.
if let Ok(mut plan) = RESTART_ON_QUIT.lock() {
*plan = None;
}
}
}
// What an "Update and restart" starts once the app has shut down: the app file to run, the
// project folder to hand it, and this app's version for the "Updated to vX" note.
struct RestartPlan {
exe: PathBuf,
project: Option<PathBuf>,
from_version: String,
}
// Set by `restart_app`, taken by `quit_app`. A Stay answer to the quit check clears it
// (`QuitOpen`'s drop), so a later ordinary quit never restarts.
static RESTART_ON_QUIT: Mutex<Option<RestartPlan>> = Mutex::new(None);
// Starts the new app, detached so it outlives this process. The note for its first page goes
// to app.json first.
fn spawn_restart(plan: &RestartPlan) -> Result<(), String> {
if let Some(file) = settings::settings_file() {
let _ = settings::save_updated_from(&file, &plan.from_version);
}
let mut command = std::process::Command::new(&plan.exe);
command
.args(versions::restart_args(plan.project.as_deref()))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x0000_0008 | 0x0000_0200); // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
}
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
command
.spawn()
.map(|_| ())
.map_err(|e| format!("could not start {}: {e}", plan.exe.display()))
}
// Asks through the shell's own modal and waits for the answer: one look for every confirm, with the
// safe button first and focused. None when the page cannot show it (no window yet, or its modal is
// not listening): the caller then asks with the OS box. Blocks, so never call it on the event loop.
fn ask_in_window(
app: &tauri::AppHandle,
build: impl FnOnce(String) -> ui_confirm::ConfirmRequest,
) -> Option<bool> {
let state = app.state::<AppState>();
if !state.confirm_ready.load(Ordering::SeqCst) || app.get_webview_window("main").is_none() {
return None;
}
let (id, rx) = state.confirms.register();
let request = build(id.clone());
if app.emit("confirm-request", &request).is_err() {
state.confirms.forget(&id);
return None;
}
let yes = ui_confirm::wait_for(&rx, ui_confirm::ANSWER_TIMEOUT);
state.confirms.forget(&id);
// Whatever the page still shows for this request goes away with it.
let _ = app.emit("confirm-cancel", &id);
Some(yes)
}
// The modal's answer, by the id the request carried. A stale or invented id changes nothing.
#[tauri::command]
fn confirm_answer(state: State<'_, AppState>, id: String, yes: bool) {
state.confirms.answer(&id, yes);
}
// The page is listening for `confirm-request` from now on.
#[tauri::command]
fn confirm_ready(state: State<'_, AppState>) {
state.confirm_ready.store(true, Ordering::SeqCst);
// A page that has only now started listening (a reload) shows no older modal: whatever was
// asked before it listened is Cancel, not a thread waiting out the timeout with the quit
// check (QUIT_OPEN) held.
state.confirms.cancel_all();
}
// The bar's "..." menu and the macOS menu's Quit: the same quit check as closing the window.
#[tauri::command]
fn request_quit(app: tauri::AppHandle) {
if agent_is_active(&app) {
confirm_quit(&app);
} else {
quit_app(&app);
}
}
@@ -523,27 +683,46 @@ fn confirm_quit(app: &tauri::AppHandle) {
QuitCase::Waiting => MessageDialogKind::Info,
QuitCase::Working => MessageDialogKind::Warning,
};
// The plugin makes its first button the default, so off Windows Enter
// means Quit. Stay first would make Esc quit instead, since the plugin
// reads Esc as "not the first button".
// Off Windows the shell's own modal asks, with Stay first and focused, so Stay is the default
// answer everywhere (the plugin's box makes Quit the default). The OS box is the fallback for a
// page that cannot show it. Both wait off the event loop.
let app = app.clone();
app.dialog()
.message(prompt.message.clone())
.title(prompt.heading.clone())
.kind(kind)
.buttons(MessageDialogButtons::OkCancelCustom(
prompt.quit.clone(),
prompt.stay.clone(),
))
.show({
let app = app.clone();
move |quit| {
let _open = open;
std::thread::spawn(move || {
let _open = open;
#[cfg(not(windows))]
{
let asked = ask_in_window(&app, |id| {
ui_confirm::quit_request(
id,
&prompt.heading,
&prompt.message,
&prompt.quit,
&prompt.stay,
)
});
if let Some(quit) = asked {
if quit {
quit_app(&app);
}
return;
}
});
}
// The plugin makes its first button the default, so here Enter means Quit. Stay first
// would make Esc quit instead, since the plugin reads Esc as "not the first button".
let quit = app
.dialog()
.message(prompt.message.clone())
.title(prompt.heading.clone())
.kind(kind)
.buttons(MessageDialogButtons::OkCancelCustom(
prompt.quit.clone(),
prompt.stay.clone(),
))
.blocking_show();
if quit {
quit_app(&app);
}
});
}
// A running loop counts even between two phases, when no agent runs for a moment.
@@ -557,6 +736,7 @@ fn agent_is_active(app: &tauri::AppHandle) -> bool {
// its record is dropped without a word to the page, so its watch thread never
// takes the ended agent for a crash.
fn quit_app(app: &tauri::AppHandle) {
let restart = RESTART_ON_QUIT.lock().ok().and_then(|mut plan| plan.take());
let state = app.state::<AppState>();
loop_driver::abandon(&state.loop_run);
if let Some(agent) = current_agent(&state) {
@@ -567,6 +747,11 @@ fn quit_app(app: &tauri::AppHandle) {
let _ = console.stop();
}
}
if let Some(plan) = restart {
if let Err(error) = spawn_restart(&plan) {
eprintln!("plan2code: restart failed: {error}");
}
}
app.exit(0);
}
@@ -723,15 +908,24 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
let first_run_done = settings_file
.as_ref()
.is_some_and(|file| settings::load_first_run_done(file));
let node = state.node.lock().map(|n| n.clone()).unwrap_or_default();
let terminal_font_size = settings_file
.as_ref()
.map_or(settings::DEFAULT_TERMINAL_FONT_SIZE, |file| {
settings::load_terminal_font_size(file)
});
serde_json::json!({
"projectDir": project.as_ref().map(|p| p.dir.to_string_lossy().into_owned()),
"projectDirSource": project.as_ref().map(|p| p.source),
"lastAgent": last_agent,
"launchModel": state.launch.model,
// Task 1.7 already exits before the window opens on a missing or too-old
// Node, so this is always a pass; the checklist's Node row just names it.
"nodeVersion": state.node_version,
"nodeBinary": state.node_binary,
// The Node check runs after the window opens: `nodeChecked` is false
// until it finishes, then `node-status` is emitted with the same
// fields. A failure shows its dialog and ends the app.
"nodeChecked": node.checked,
"nodeVersion": node.version,
"nodeBinary": node.binary,
"nodeProblem": node.problem,
"skillsVersion": versions::installed_skills_version(),
"firstRunDone": first_run_done,
// The launcher always passes `--project` alongside `--agent`, so an
@@ -739,6 +933,14 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
// or launch card shown.
"autoStart": state.launch.agent,
"termPanel": term_panel,
"terminalFontSize": terminal_font_size,
"copyOnSelect": settings_file.as_ref().map_or_else(
settings::default_copy_on_select,
|file| settings::load_copy_on_select(file),
),
// Set only on the launch right after an "Update and restart": the version the old app
// ran. The page says "Updated to v<this app's version>" once.
"updatedFrom": state.updated_from,
// The Desktop app switch, for the page's User Preferences.
"taskbarSignal": state.attention.lock().map_or(true, |guard| guard.enabled),
})
@@ -753,6 +955,30 @@ fn save_term_panel(dock: String, fraction: f64, collapsed: bool) -> Result<(), S
settings::save_term_panel(&file, &dock, fraction, collapsed)
}
/// The terminal's font size (Ctrl/Cmd plus, minus and 0), kept in app.json.
/// A size outside 8 to 32 is refused.
#[tauri::command]
fn save_terminal_font_size(size: u32) -> Result<(), String> {
let file = settings::settings_file().ok_or("no home folder found")?;
settings::save_terminal_font_size(&file, size)
}
/// Copy-on-select for the terminal (Task 10.6): whether selecting text copies it at once.
/// The saved choice, or the OS default (on for Linux, off on Windows and macOS).
#[tauri::command]
fn get_copy_on_select() -> bool {
settings::settings_file().map_or_else(settings::default_copy_on_select, |file| {
settings::load_copy_on_select(&file)
})
}
/// Save the copy-on-select choice in app.json.
#[tauri::command]
fn set_copy_on_select(on: bool) -> Result<(), String> {
let file = settings::settings_file().ok_or("no home folder found")?;
settings::save_copy_on_select(&file, on)
}
/// The first-run checklist passed once: later launches go straight to the
/// launch card (Task 9.4).
#[tauri::command]
@@ -771,15 +997,19 @@ fn version_status(app: tauri::AppHandle) -> versions::VersionStatus {
)
}
/// The newest GitHub release's version when it is newer than this app, else none (also none on
/// any failure to ask). The page asks once at start and never waits on it.
/// The release check: `{ latest, problem }`. `latest` is the newest GitHub release's version
/// when it is newer than this app, else null; `problem` is a short sentence when the check
/// could not run (git missing, no network), else null. The page asks at start and again every
/// few hours, and never waits on it.
#[tauri::command]
async fn check_new_release(app: tauri::AppHandle) -> Option<String> {
async fn check_new_release(app: tauri::AppHandle) -> versions::ReleaseCheck {
let version = app.package_info().version.to_string();
tauri::async_runtime::spawn_blocking(move || versions::check_new_release(&version))
.await
.ok()
.flatten()
.unwrap_or_else(|_| versions::ReleaseCheck {
latest: None,
problem: Some("Could not check for updates: the check did not finish.".to_string()),
})
}
/// What `update_skills` resolves with: the installer's last line, and the version status
@@ -813,6 +1043,60 @@ async fn update_skills(
Ok(UpdateOutcome { message, status })
}
/// "Update and restart", step one: the installer unpinned (the newest release, not this app's
/// own tag), with its output live on `progress`. On success the old app keeps running until
/// `restart_app`; on failure it stays as it was and the error is a readable reason.
#[tauri::command]
async fn update_to_newest(
app: tauri::AppHandle,
progress: Channel<String>,
) -> Result<UpdateOutcome, String> {
let message = tauri::async_runtime::spawn_blocking(move || {
versions::run_update_newest(|line| {
let _ = progress.send(line.to_string());
})
})
.await
.map_err(|e| e.to_string())??;
let status = versions::status(
&app.package_info().version.to_string(),
versions::installed_skills_version(),
);
Ok(UpdateOutcome { message, status })
}
/// "Update and restart", step two: start the freshly installed app with this one's `--project`
/// and end this one. With an agent or loop running it first asks through the existing quit
/// check (Windows TaskDialog, or the shell's own modal elsewhere; the plugin box only while the page is not listening) and answers "asking"; Stay leaves
/// everything as it was. `confirmed: true` skips that check, for a page that has already asked
/// in its own confirm. Answers "restarting" when it goes ahead. Fails, leaving this app
/// running, when the installed app file is missing.
#[tauri::command]
fn restart_app(
app: tauri::AppHandle,
state: State<'_, AppState>,
confirmed: bool,
) -> Result<&'static str, String> {
let exe = versions::installed_app_path()
.ok_or("the new app file was not found, so Plan2Code was not restarted")?;
let project = state
.project
.lock()
.ok()
.and_then(|p| p.as_ref().map(|p| p.dir.clone()));
*RESTART_ON_QUIT.lock().map_err(|e| e.to_string())? = Some(RestartPlan {
exe,
project,
from_version: app.package_info().version.to_string(),
});
if !confirmed && agent_is_active(&app) {
confirm_quit(&app);
return Ok("asking");
}
quit_app(&app);
Ok("restarting")
}
/// The OS folder picker, the folder picker's Choose a folder row on a bare
/// start; a choice goes to the top of the recent folders.
#[tauri::command(async)]
@@ -1176,16 +1460,36 @@ async fn start_loop(
&& last.confirmed_notify == notify
});
if !unchanged {
let go = app
.dialog()
.message(loop_driver::confirm_text(&record))
.title("Implementation Loop")
.kind(MessageDialogKind::Info)
.buttons(MessageDialogButtons::OkCancelCustom(
"Start".to_string(),
"Cancel".to_string(),
))
.blocking_show();
// The shell's modal: the quick check in a code block, the trunk warning as a callout.
let lines = loop_driver::confirm_lines(&record);
let asker = app.clone();
let asked = tauri::async_runtime::spawn_blocking(move || {
ask_in_window(&asker, |id| ui_confirm::ConfirmRequest {
id,
title: "Start the Implementation Loop?".to_string(),
lines,
primary: "Start".to_string(),
cancel: "Cancel".to_string(),
danger: false,
safe_first: true,
})
})
.await
.map_err(|e| e.to_string())?;
let go = match asked {
Some(go) => go,
// The page cannot show it: the OS box, with the same words as one paragraph.
None => app
.dialog()
.message(loop_driver::confirm_text(&record))
.title("Implementation Loop")
.kind(MessageDialogKind::Info)
.buttons(MessageDialogButtons::OkCancelCustom(
"Start".to_string(),
"Cancel".to_string(),
))
.blocking_show(),
};
if !go {
return Ok(false);
}
@@ -1382,26 +1686,76 @@ fn loop_dashboard(state: State<'_, AppState>) -> Result<serde_json::Value, Strin
Ok(session)
}
fn main() {
// Without Node 18+ the console and skills cannot run: say so and stop (FR-13).
let status = node_check::check_node();
let node_problem = node_check::problem_message(&status);
let node_version = match &status {
node_check::NodeStatus::Ok(version) => Some(version.clone()),
_ => None,
};
let node_binary = node_version
.as_ref()
.and_then(|_| node_check::node_binary_path());
/// True when the window-state plugin's file does not exist yet.
fn first_launch(app: &tauri::AppHandle) -> bool {
use tauri_plugin_window_state::AppHandleExt;
app.path()
.app_config_dir()
.map(|dir| !dir.join(app.filename()).exists())
.unwrap_or(false)
}
// macOS gets a real menu bar: Plan2Code (About, Check for Updates, Help, Quit) and the standard Edit
// menu, so Copy, Paste and Select All work in the page's fields. The three custom items tell the
// page (the same actions as the bar's "..." menu); Quit is the predefined one, and the exit it asks
// for goes through the quit check in the run loop below.
#[cfg(target_os = "macos")]
fn build_mac_menu(app: &mut tauri::App) -> tauri::Result<()> {
use tauri::menu::{MenuBuilder, MenuItemBuilder, SubmenuBuilder};
let about = MenuItemBuilder::with_id("about", "About Plan2Code").build(app)?;
let check = MenuItemBuilder::with_id("check-updates", "Check for Updates...").build(app)?;
let help = MenuItemBuilder::with_id("help", "Plan2Code Help").build(app)?;
let app_menu = SubmenuBuilder::new(app, "Plan2Code")
.item(&about)
.item(&check)
.separator()
.item(&help)
.separator()
.quit()
.build()?;
let edit = SubmenuBuilder::new(app, "Edit")
.undo()
.redo()
.separator()
.cut()
.copy()
.paste()
.select_all()
.build()?;
let menu = MenuBuilder::new(app).items(&[&app_menu, &edit]).build()?;
app.set_menu(menu)?;
app.on_menu_event(|app, event| {
let id = event.id().as_ref();
if matches!(id, "about" | "check-updates" | "help") {
let _ = app.emit("app-menu", id);
}
});
Ok(())
}
fn main() {
let args = std::env::args().collect::<Vec<_>>();
tauri::Builder::default()
.plugin(tauri_plugin_dialog::init())
// Opens the terminal's http and https links (the capability scopes it to those).
.plugin(tauri_plugin_opener::init())
// Size and position come back on the next launch. Not VISIBLE (the
// window stays hidden until the page shows it), nor DECORATIONS or
// FULLSCREEN (an Activities game's full screen must not stick).
.plugin(
tauri_plugin_window_state::Builder::default()
.with_state_flags(
tauri_plugin_window_state::StateFlags::SIZE
| tauri_plugin_window_state::StateFlags::POSITION
| tauri_plugin_window_state::StateFlags::MAXIMIZED,
)
.build(),
)
.manage(AppState {
project: Mutex::new(project::resolve(&args)),
launch: project::launch_choice(&args),
node_version,
node_binary,
updated_from: settings::settings_file()
.and_then(|file| settings::take_updated_from(&file)),
attention: Mutex::new(AttentionState {
last: None,
enabled: settings::settings_file()
@@ -1411,6 +1765,9 @@ fn main() {
})
.invoke_handler(tauri::generate_handler![
platform_info,
confirm_answer,
confirm_ready,
request_quit,
agent_availability,
open_install_page,
agent_start,
@@ -1420,10 +1777,15 @@ fn main() {
agent_reattach,
app_state,
save_term_panel,
save_terminal_font_size,
save_first_run_done,
version_status,
check_new_release,
update_skills,
update_to_newest,
restart_app,
get_copy_on_select,
set_copy_on_select,
pick_project_folder,
recent_folders,
open_recent_folder,
@@ -1496,14 +1858,17 @@ fn main() {
// Without it the agent opens pages the plain way; nothing else breaks.
Err(error) => eprintln!("plan2code: no announce endpoint: {error}"),
}
if let Some(message) = &node_problem {
app.dialog()
.message(message)
.title("Plan2Code needs Node.js")
.kind(MessageDialogKind::Error)
.blocking_show();
std::process::exit(1);
// First launch ever (the window-state plugin has saved nothing yet):
// open maximized. Later launches get the saved size, position and
// maximized state from the plugin.
if first_launch(app.handle()) {
if let Some(window) = app.get_webview_window("main") {
let _ = window.maximize();
}
}
#[cfg(target_os = "macos")]
build_mac_menu(app)?;
spawn_node_check(app.handle().clone());
Ok(())
})
.build(tauri::generate_context!())
+135 -4
View File
@@ -77,14 +77,65 @@ fn node_override_dir(args: &[String]) -> Option<String> {
#[cfg(unix)]
fn login_shell_path() -> Option<String> {
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
// `printenv PATH`, not `echo $PATH`: fish expands `$PATH` to a list and
// echoes it space-separated, which is no PATH at all.
let out = Command::new(&shell)
.args(["-lc", "echo $PATH"])
.args(["-lc", "printenv PATH"])
.output()
.ok()?;
let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
let path = parse_path_output(&String::from_utf8_lossy(&out.stdout));
(out.status.success() && !path.is_empty()).then_some(path)
}
/// A PATH out of a shell's output: the last non-empty line (a login shell's
/// profile may print a banner first), and a space-separated list of absolute
/// folders (what fish's `echo $PATH` prints) turned into a `:` list. A single
/// folder with a space in its name is left alone.
#[cfg_attr(windows, allow(dead_code))]
fn parse_path_output(output: &str) -> String {
let line = output
.lines()
.map(str::trim)
.rfind(|l| !l.is_empty())
.unwrap_or("");
let tokens: Vec<&str> = line.split_whitespace().collect();
let spaced_list = !line.contains(':')
&& tokens.len() > 1
&& tokens
.iter()
.all(|t| t.starts_with('/') || t.starts_with('~'));
if spaced_list {
tokens.join(":")
} else {
line.to_string()
}
}
/// What the PATH lookup is named after in the failure message: the login
/// shell on macOS and Linux (its own file name, such as `fish`), the saved
/// system and user PATH on Windows.
pub fn path_source_label() -> String {
#[cfg(unix)]
{
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
shell_name(&shell)
}
#[cfg(not(unix))]
{
"Windows (the system and user PATH)".to_string()
}
}
#[cfg_attr(windows, allow(dead_code))]
fn shell_name(shell: &str) -> String {
let name = shell.rsplit(['/', '\\']).next().unwrap_or(shell);
if name.is_empty() {
"sh".to_string()
} else {
name.to_string()
}
}
static RESOLVED_PATH: Mutex<Option<String>> = Mutex::new(None);
/// The PATH every process this app spawns should run with: an explicit
@@ -250,13 +301,28 @@ pub fn node_binary_path() -> Option<String> {
/// The plain message shown when the check fails; `None` when Node is fine.
pub fn problem_message(status: &NodeStatus) -> Option<String> {
problem_message_from(status, &path_source_label())
}
/// `problem_message` with the PATH source named by the caller, so a test need
/// not depend on this machine's shell.
pub fn problem_message_from(status: &NodeStatus, source: &str) -> Option<String> {
let advice = format!(
"Install the current LTS release from https://nodejs.org and start Plan2Code again.
Looked on PATH from {source}."
);
match status {
NodeStatus::Ok(_) => None,
NodeStatus::TooOld(v) => Some(format!(
"Plan2Code needs Node.js {MIN_NODE_MAJOR} or newer, and this computer has {v}.\n\nInstall the current LTS release from https://nodejs.org and start Plan2Code again."
"Plan2Code needs Node.js {MIN_NODE_MAJOR} or newer, and this computer has {v}.
{advice}"
)),
NodeStatus::Missing => Some(format!(
"Plan2Code needs Node.js {MIN_NODE_MAJOR} or newer, and it was not found.\n\nInstall the current LTS release from https://nodejs.org and start Plan2Code again."
"Plan2Code needs Node.js {MIN_NODE_MAJOR} or newer, and it was not found.
{advice}"
)),
}
}
@@ -372,4 +438,69 @@ mod tests {
let inherited = std::env::var("PATH").unwrap_or_default();
assert!(resolved_path().ends_with(&inherited));
}
#[test]
fn the_failure_message_names_where_it_looked() {
let text = problem_message_from(&NodeStatus::Missing, "fish").unwrap();
assert!(text.contains("Looked on PATH from fish."));
assert!(text.contains("https://nodejs.org"));
assert!(problem_message_from(&NodeStatus::Ok("v20.0.0".into()), "fish").is_none());
}
#[test]
fn shell_names_come_from_the_last_path_part() {
assert_eq!(shell_name("/usr/bin/fish"), "fish");
assert_eq!(shell_name("/bin/zsh"), "zsh");
assert_eq!(shell_name("bash"), "bash");
assert_eq!(shell_name(""), "sh");
}
#[test]
fn a_colon_path_is_kept_as_it_is() {
assert_eq!(
parse_path_output(
"/usr/local/bin:/usr/bin:/bin
"
),
"/usr/local/bin:/usr/bin:/bin"
);
}
#[test]
fn fish_s_space_separated_list_becomes_a_colon_list() {
assert_eq!(
parse_path_output(
"/home/sam/.nvm/bin /usr/local/bin /usr/bin
"
),
"/home/sam/.nvm/bin:/usr/local/bin:/usr/bin"
);
}
#[test]
fn a_banner_before_the_path_and_a_folder_with_a_space_are_handled() {
assert_eq!(
parse_path_output(
"Welcome back
/usr/bin:/bin
"
),
"/usr/bin:/bin"
);
assert_eq!(
parse_path_output(
"/Users/Jo Smith/bin
"
),
"/Users/Jo Smith/bin"
);
assert_eq!(
parse_path_output(
"
"
),
""
);
}
}
+141
View File
@@ -10,6 +10,13 @@ const TERM_FRACTION_KEY: &str = "termFraction";
const TERM_COLLAPSED_KEY: &str = "termCollapsed";
const FIRST_RUN_DONE_KEY: &str = "firstRunDone";
const TASKBAR_SIGNAL_KEY: &str = "taskbarSignal";
const TERMINAL_FONT_SIZE_KEY: &str = "terminalFontSize";
const COPY_ON_SELECT_KEY: &str = "copyOnSelect";
const UPDATED_FROM_KEY: &str = "updatedFrom";
pub const DEFAULT_TERMINAL_FONT_SIZE: u32 = 13;
pub const TERMINAL_FONT_SIZE_MIN: u32 = 8;
pub const TERMINAL_FONT_SIZE_MAX: u32 = 32;
/// The terminal pane's remembered shape: which edge it docks to, how much of
/// the window it takes (a fraction, not collapsed or maximized), and whether
@@ -111,6 +118,34 @@ pub fn save_term_panel(
write(file, settings)
}
/// The terminal's font size in pixels: the saved one, clamped to its range,
/// or 13 when the file has none (an old file) or holds something else.
pub fn load_terminal_font_size(file: &Path) -> u32 {
read(file)
.get(TERMINAL_FONT_SIZE_KEY)
.and_then(|v| v.as_u64())
.map_or(DEFAULT_TERMINAL_FONT_SIZE, |size| {
size.clamp(
u64::from(TERMINAL_FONT_SIZE_MIN),
u64::from(TERMINAL_FONT_SIZE_MAX),
) as u32
})
}
/// Save the terminal's font size, keeping any other key the file holds. A
/// size outside 8 to 32 is rejected rather than saved.
pub fn save_terminal_font_size(file: &Path, size: u32) -> Result<(), String> {
if !(TERMINAL_FONT_SIZE_MIN..=TERMINAL_FONT_SIZE_MAX).contains(&size) {
return Err(format!("font size out of range: {size}"));
}
let mut settings = read(file);
settings.insert(
TERMINAL_FONT_SIZE_KEY.to_string(),
serde_json::Value::from(size),
);
write(file, settings)
}
/// Whether the first-run checklist has already passed once. Once it has,
/// later launches go straight to the launch card (Task 9.4).
pub fn load_first_run_done(file: &Path) -> bool {
@@ -147,6 +182,54 @@ pub fn save_taskbar_signal(file: &Path, on: bool) -> Result<(), String> {
write(file, settings)
}
/// Copy-on-select's default: on for Linux, where selecting text is the
/// copy gesture, off on Windows and macOS, where it would replace what the
/// person last copied.
pub fn default_copy_on_select() -> bool {
cfg!(target_os = "linux")
}
/// Whether selecting text in the terminal copies it at once (Task 10.6). The
/// saved choice, or the per-OS default when the file has none or holds
/// something other than a boolean.
pub fn load_copy_on_select(file: &Path) -> bool {
read(file)
.get(COPY_ON_SELECT_KEY)
.and_then(|v| v.as_bool())
.unwrap_or_else(default_copy_on_select)
}
/// Save the choice, keeping any other key the file holds.
pub fn save_copy_on_select(file: &Path, on: bool) -> Result<(), String> {
let mut settings = read(file);
settings.insert(COPY_ON_SELECT_KEY.to_string(), serde_json::Value::Bool(on));
write(file, settings)
}
/// Note the version the app was running before an "Update and restart", for
/// the new app to say "Updated to vX" once (`take_updated_from`).
pub fn save_updated_from(file: &Path, version: &str) -> Result<(), String> {
let mut settings = read(file);
settings.insert(
UPDATED_FROM_KEY.to_string(),
serde_json::Value::String(version.to_string()),
);
write(file, settings)
}
/// The version noted by `save_updated_from`, read once: the key is removed
/// as it is read, so the message shows one time only.
pub fn take_updated_from(file: &Path) -> Option<String> {
let mut settings = read(file);
let from = settings
.remove(UPDATED_FROM_KEY)?
.as_str()
.map(str::to_string)
.filter(|v| !v.is_empty());
let _ = write(file, settings);
from
}
fn write(file: &Path, settings: serde_json::Map<String, serde_json::Value>) -> Result<(), String> {
if let Some(parent) = file.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
@@ -278,4 +361,62 @@ mod tests {
assert_eq!(loaded.fraction, 0.25);
let _ = std::fs::remove_dir_all(file.parent().unwrap());
}
#[test]
fn the_terminal_font_size_defaults_round_trips_and_keeps_other_keys() {
let file = temp_file("font-size");
assert_eq!(load_terminal_font_size(&file), 13, "missing file");
save_last_agent(&file, "claude").unwrap();
assert_eq!(
load_terminal_font_size(&file),
13,
"old file without the field"
);
save_terminal_font_size(&file, 18).unwrap();
assert_eq!(load_terminal_font_size(&file), 18);
assert_eq!(load_last_agent(&file).as_deref(), Some("claude"));
save_term_panel(&file, "bottom", 0.4, false).unwrap();
assert_eq!(load_terminal_font_size(&file), 18);
}
#[test]
fn an_out_of_range_terminal_font_size_is_refused_and_a_bad_one_on_disk_is_clamped() {
let file = temp_file("font-size-range");
assert!(save_terminal_font_size(&file, 7).is_err());
assert!(save_terminal_font_size(&file, 33).is_err());
assert_eq!(load_terminal_font_size(&file), 13, "nothing was written");
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(&file, r#"{"terminalFontSize": 400}"#).unwrap();
assert_eq!(load_terminal_font_size(&file), 32);
std::fs::write(&file, r#"{"terminalFontSize": 2}"#).unwrap();
assert_eq!(load_terminal_font_size(&file), 8);
std::fs::write(&file, r#"{"terminalFontSize": "big"}"#).unwrap();
assert_eq!(load_terminal_font_size(&file), 13);
}
#[test]
fn copy_on_select_defaults_per_os_and_keeps_a_saved_choice() {
let file = temp_file("copy-on-select");
// No file: Linux copies on select, Windows and macOS do not.
assert_eq!(default_copy_on_select(), cfg!(target_os = "linux"));
assert_eq!(load_copy_on_select(&file), cfg!(target_os = "linux"));
save_copy_on_select(&file, !default_copy_on_select()).unwrap();
assert_eq!(load_copy_on_select(&file), !default_copy_on_select());
save_copy_on_select(&file, default_copy_on_select()).unwrap();
assert_eq!(load_copy_on_select(&file), default_copy_on_select());
// Something other than a boolean reads as the default.
std::fs::write(&file, r#"{"copyOnSelect":"yes"}"#).unwrap();
assert_eq!(load_copy_on_select(&file), default_copy_on_select());
}
#[test]
fn the_updated_marker_is_read_once_and_keeps_other_keys() {
let file = temp_file("updated-from");
assert_eq!(take_updated_from(&file), None);
save_last_agent(&file, "claude").unwrap();
save_updated_from(&file, "3.1.0").unwrap();
assert_eq!(take_updated_from(&file).as_deref(), Some("3.1.0"));
assert_eq!(take_updated_from(&file), None);
assert_eq!(load_last_agent(&file).as_deref(), Some("claude"));
}
}
+217
View File
@@ -0,0 +1,217 @@
//! Confirms the Rust side asks the person, drawn by the shell's own modal (`ui/app.js`
//! `confirmModal`) instead of the OS message box: one look, Stay or Cancel first and focused,
//! `role="alertdialog"`. This module is the request's shape and the table of waiting answers; it
//! knows nothing about Tauri. main.rs emits a `confirm-request` event with a [`ConfirmRequest`]
//! and blocks on the [`Receiver`] until the page calls `confirm_answer`.
use std::collections::HashMap;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::Mutex;
use std::time::Duration;
/// How long a confirm may stay unanswered before it counts as Cancel (a reloaded window would
/// otherwise leave its thread waiting for good).
pub const ANSWER_TIMEOUT: Duration = Duration::from_secs(15 * 60);
/// One line of a confirm's body: plain text, a code block or an amber callout.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct ConfirmLine {
pub kind: &'static str,
pub text: String,
}
impl ConfirmLine {
pub fn text(text: impl Into<String>) -> Self {
Self {
kind: "text",
text: text.into(),
}
}
pub fn code(text: impl Into<String>) -> Self {
Self {
kind: "code",
text: text.into(),
}
}
pub fn callout(text: impl Into<String>) -> Self {
Self {
kind: "callout",
text: text.into(),
}
}
}
/// What the modal shows. `safe_first` puts Cancel (or Stay) first and gives it focus; `danger`
/// colors the primary as the named danger verb.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConfirmRequest {
pub id: String,
pub title: String,
pub lines: Vec<ConfirmLine>,
pub primary: String,
pub cancel: String,
pub danger: bool,
pub safe_first: bool,
}
/// The answers still to come, by request id.
#[derive(Default)]
pub struct Pending {
waiting: Mutex<HashMap<String, Sender<bool>>>,
next: Mutex<u64>,
}
impl Pending {
/// A new request id and the receiver its answer arrives on.
pub fn register(&self) -> (String, Receiver<bool>) {
let id = {
let mut next = self.next.lock().unwrap_or_else(|e| e.into_inner());
*next += 1;
format!("confirm-{}", *next)
};
let (tx, rx) = channel();
self.waiting
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(id.clone(), tx);
(id, rx)
}
/// The page's answer. False when no such request is waiting (a stale or invented id), which
/// changes nothing.
pub fn answer(&self, id: &str, yes: bool) -> bool {
let tx = self
.waiting
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(id);
tx.is_some_and(|tx| tx.send(yes).is_ok())
}
/// Answers every waiting request with Cancel: a page that has just started listening is not
/// showing an older modal, so whatever was asked before it listened will never be answered.
pub fn cancel_all(&self) {
let waiting = std::mem::take(&mut *self.waiting.lock().unwrap_or_else(|e| e.into_inner()));
for tx in waiting.into_values() {
let _ = tx.send(false);
}
}
/// Forgets a request that was never answered (a timeout, or a window that could not be told).
pub fn forget(&self, id: &str) {
self.waiting
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(id);
}
}
/// Waits for an answer: true only for an explicit yes; a timeout, a dropped sender or a no is Cancel.
pub fn wait_for(rx: &Receiver<bool>, timeout: Duration) -> bool {
rx.recv_timeout(timeout).unwrap_or(false)
}
/// The quit check's request: the safe answer (Stay) first and focused, the quit verb last.
pub fn quit_request(
id: String,
heading: &str,
message: &str,
quit: &str,
stay: &str,
) -> ConfirmRequest {
ConfirmRequest {
id,
title: heading.to_string(),
lines: vec![ConfirmLine::text(message)],
primary: quit.to_string(),
cancel: stay.to_string(),
danger: true,
safe_first: true,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_answer_reaches_the_waiting_request_once() {
let pending = Pending::default();
let (id, rx) = pending.register();
assert!(pending.answer(&id, true));
assert!(wait_for(&rx, Duration::from_millis(50)));
assert!(
!pending.answer(&id, true),
"answered already: a second answer finds nothing"
);
}
#[test]
fn ids_are_distinct_and_an_unknown_id_answers_nothing() {
let pending = Pending::default();
let (a, _ra) = pending.register();
let (b, _rb) = pending.register();
assert_ne!(a, b);
assert!(!pending.answer("confirm-999", true));
}
#[test]
fn cancel_all_answers_every_waiting_request_with_cancel() {
let pending = Pending::default();
let (a, ra) = pending.register();
let (b, rb) = pending.register();
pending.cancel_all();
assert!(!wait_for(&ra, Duration::from_millis(50)));
assert!(!wait_for(&rb, Duration::from_millis(50)));
assert!(
!pending.answer(&a, true) && !pending.answer(&b, true),
"nothing is left waiting"
);
pending.cancel_all();
}
#[test]
fn no_answer_in_time_is_cancel_and_so_is_a_no() {
let pending = Pending::default();
let (id, rx) = pending.register();
assert!(
!wait_for(&rx, Duration::from_millis(10)),
"timeout is Cancel"
);
let (id2, rx2) = pending.register();
pending.answer(&id2, false);
assert!(!wait_for(&rx2, Duration::from_millis(50)));
pending.forget(&id);
assert!(
!pending.answer(&id, true),
"a forgotten request takes no answer"
);
}
#[test]
fn the_quit_request_puts_stay_first_and_quit_last_as_the_danger_verb() {
let request = quit_request("c1".into(), "Done for now?", "It ends.", "Quit", "Stay");
assert!(request.safe_first && request.danger);
assert_eq!(
(request.primary.as_str(), request.cancel.as_str()),
("Quit", "Stay")
);
let json = serde_json::to_value(&request).unwrap();
assert_eq!(json["safeFirst"], true, "camelCase for the page");
assert_eq!(json["lines"][0]["kind"], "text");
}
#[test]
fn no_text_carries_an_em_dash() {
let request = quit_request("c1".into(), "Done for now?", "It ends.", "Quit", "Stay");
for text in [
&request.title,
&request.lines[0].text,
&request.primary,
&request.cancel,
] {
assert!(!text.contains('\u{2014}'));
}
}
}
+160 -12
View File
@@ -105,10 +105,32 @@ pub fn newer_release(app: &str, ls_remote: &str) -> Option<String> {
(parse(&latest)? > parse(app)?).then_some(latest)
}
/// Ask GitHub for the newest release and return its version when it is newer than `app`.
/// None on any failure (no git, no network, a login prompt, the timeout): a missing answer
/// is never a reason to nag. No prompt and no console window.
pub fn check_new_release(app: &str) -> Option<String> {
/// What a release check found, as the page reads it: `latest` is the newest release's version
/// when it is newer than the app; `problem` is a short sentence when the check itself could not
/// run (no git, no network, a timeout), else none. An app that is simply current has neither.
#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct ReleaseCheck {
pub latest: Option<String>,
pub problem: Option<String>,
}
/// The check's result from `git ls-remote --tags` output, or the reason it could not run.
pub fn release_check_from(app: &str, tags: Result<String, String>) -> ReleaseCheck {
match tags {
Ok(text) => ReleaseCheck {
latest: newer_release(app, &text),
problem: None,
},
Err(reason) => ReleaseCheck {
latest: None,
problem: Some(format!("Could not check for updates: {reason}.")),
},
}
}
/// `git ls-remote --tags` output, or a short reason it could not be had. No prompt and no
/// console window.
fn fetch_tags() -> Result<String, String> {
let mut command = Command::new("git");
command
.env("PATH", crate::node_check::resolved_path())
@@ -126,8 +148,14 @@ pub fn check_new_release(app: &str) -> Option<String> {
use std::os::windows::process::CommandExt;
command.creation_flags(0x08000000); // CREATE_NO_WINDOW, as the console calls are
}
let mut child = command.spawn().ok()?;
let mut stdout = child.stdout.take()?;
let mut child = command.spawn().map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
"git was not found on PATH".to_string()
} else {
"git could not be run".to_string()
}
})?;
let mut stdout = child.stdout.take().ok_or("git gave no output")?;
let (tx, rx) = mpsc::channel::<String>();
std::thread::spawn(move || {
let mut text = String::new();
@@ -138,19 +166,72 @@ pub fn check_new_release(app: &str) -> Option<String> {
Ok(text) => {
let ok = child.wait().is_ok_and(|status| status.success());
if ok {
newer_release(app, &text)
Ok(text)
} else {
None
Err("GitHub did not answer".to_string())
}
}
Err(_) => {
let _ = child.kill();
let _ = child.wait();
None
Err("GitHub did not answer in time".to_string())
}
}
}
/// Ask GitHub for the newest release and report it when it is newer than `app`. A failure
/// (no git, no network, a login prompt, the timeout) comes back as a `problem` sentence, never
/// as an error: nothing waits on it.
pub fn check_new_release(app: &str) -> ReleaseCheck {
release_check_from(app, fetch_tags())
}
/// The app file an "Update and restart" starts: `PLAN2CODE_APP` (the launcher's override, also
/// for tests), else the installer's own place, `~/.plan2code/app/plan2code-app[.exe]`, which an
/// update has just replaced; else none. Never this process's own path: a running file the
/// installer renamed aside would still be the old build.
pub fn installed_app_path() -> Option<PathBuf> {
let file = match std::env::var_os("PLAN2CODE_APP").filter(|v| !v.is_empty()) {
Some(file) => PathBuf::from(file),
None => std::env::home_dir()?
.join(".plan2code")
.join("app")
.join(if cfg!(windows) {
"plan2code-app.exe"
} else {
"plan2code-app"
}),
};
file.is_file().then_some(file)
}
/// The arguments the restarted app gets: the same `--project` folder, when there is one.
pub fn restart_args(project: Option<&Path>) -> Vec<std::ffi::OsString> {
match project {
Some(dir) => vec!["--project".into(), dir.as_os_str().to_owned()],
None => Vec::new(),
}
}
/// Which release an installer run installs. `Pinned` is the desktop app's own tag (Update
/// skills never pulls in work the app does not know about); `Newest` passes no tag, so the
/// launcher picks the newest published release itself (Update and restart).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UpdateTarget<'a> {
Pinned(&'a str),
Newest,
}
/// The launcher's arguments after its script path for `target`.
pub fn update_args(target: UpdateTarget) -> Vec<String> {
let mut args = vec!["update".to_string()];
if let UpdateTarget::Pinned(version) = target {
args.push("--tag".to_string());
args.push(format!("v{version}"));
}
args
}
/// Run the existing installer's update (`plan2code update`, through the launcher's own copy),
/// which brings the skills, the launcher and the app level. Pinned to the release tag `app_version`
/// names, not `main`, so Update skills never pulls in work the app does not know about yet. Blocks
@@ -161,11 +242,25 @@ pub fn run_update(app_version: &str, on_line: impl FnMut(&str)) -> Result<String
run_update_within(app_version, UPDATE_TIMEOUT, on_line)
}
/// "Update and restart"'s install: the same installer and progress readout, unpinned, so the
/// launcher installs the newest release (the newest-tag rule of `plan2code update`).
pub fn run_update_newest(on_line: impl FnMut(&str)) -> Result<String, String> {
run_installer(UpdateTarget::Newest, UPDATE_TIMEOUT, on_line)
}
/// `run_update`, with the timeout as a parameter so a test can use a short one instead of
/// `UPDATE_TIMEOUT`'s real five minutes.
fn run_update_within(
app_version: &str,
timeout: Duration,
on_line: impl FnMut(&str),
) -> Result<String, String> {
run_installer(UpdateTarget::Pinned(app_version), timeout, on_line)
}
fn run_installer(
target: UpdateTarget,
timeout: Duration,
mut on_line: impl FnMut(&str),
) -> Result<String, String> {
let launcher = launcher_dir()
@@ -184,9 +279,7 @@ fn run_update_within(
command.env("PATH", crate::node_check::resolved_path());
command
.arg(&launcher)
.arg("update")
.arg("--tag")
.arg(format!("v{app_version}"))
.args(update_args(target))
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
@@ -408,4 +501,59 @@ mod tests {
});
assert!(result.unwrap_err().contains("is missing"));
}
#[test]
fn the_target_picks_a_pinned_or_an_unpinned_install() {
assert_eq!(
update_args(UpdateTarget::Pinned("3.1.0")),
vec!["update", "--tag", "v3.1.0"]
);
assert_eq!(update_args(UpdateTarget::Newest), vec!["update"]);
}
#[test]
fn a_restart_hands_over_the_same_project_folder() {
assert_eq!(
restart_args(Some(Path::new("/work/app"))),
vec![
std::ffi::OsString::from("--project"),
std::ffi::OsString::from("/work/app")
]
);
assert!(restart_args(None).is_empty());
}
#[test]
fn run_update_newest_passes_no_tag() {
let result = with_fake_launcher(
"newest",
"console.log(process.argv.slice(2).join(' '));",
|| run_update_newest(|_| {}),
);
assert_eq!(result, Ok("update".to_string()));
}
#[test]
fn a_release_check_says_why_it_could_not_run() {
assert_eq!(
release_check_from("3.0.0", Ok(TAGS.to_string())),
ReleaseCheck {
latest: Some("3.10.0".into()),
problem: None
}
);
assert_eq!(
release_check_from("3.10.0", Ok(TAGS.to_string())),
ReleaseCheck {
latest: None,
problem: None
}
);
let failed = release_check_from("3.0.0", Err("git was not found on PATH".into()));
assert_eq!(failed.latest, None);
assert_eq!(
failed.problem.as_deref(),
Some("Could not check for updates: git was not found on PATH.")
);
}
}
+5 -2
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Plan2Code",
"version": "3.1.0",
"version": "3.1.1",
"identifier": "com.plan2code.desktop",
"build": {
"frontendDist": "../ui",
@@ -14,7 +14,10 @@
"title": "Plan2Code",
"width": 1280,
"height": 800,
"maximized": true,
"minWidth": 960,
"minHeight": 600,
"visible": false,
"backgroundColor": "#171513",
"dragDropEnabled": false,
"url": "index.html"
}
+820 -122
View File
File diff suppressed because it is too large. Load diff
+238 -115
View File
@@ -5,62 +5,75 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' ipc: http://ipc.localhost; frame-src http://127.0.0.1:*; object-src 'none'; base-uri 'none'">
<title>Plan2Code</title>
<script src="theme-early.js"></script>
<link rel="stylesheet" href="vendor/xterm.css">
<link rel="stylesheet" href="vendor/tokens.css">
<style>
html, body { margin: 0; height: 100%; font-family: system-ui, sans-serif; background: #1e1e1e; color: #ddd; }
body { display: flex; flex-direction: column; overflow: hidden; }
/* The colors, type, radii and layers come from the console's own
tokens.css (copied into vendor/ by scripts/vendor.mjs), so the shell and the
page cannot drift apart. That file also sets a few global rules (box
sizing and thin scrollbars on everything, text selection, a focus ring):
the shell keeps those and sets its own body below. data-theme on <html>
is set by theme-early.js before the first paint and by app.js when the
console says the theme changed; the accent custom properties are set the
same way. */
html, body { margin: 0; height: 100%; }
body { display: flex; flex-direction: column; overflow: hidden; min-height: 0; background: var(--bg); color: var(--ink); font: var(--fs-sm)/var(--lh-ui) var(--sans); }
/* The one keyboard focus ring for the whole shell, in the highlight color.
A part that wears another color (the loop banner) sets --focus-ring. */
:is(button, select, input, [role="menu"], [role="separator"]):focus-visible { outline: 2px solid var(--focus-ring, var(--accent)); outline-offset: 2px; }
/* A command named in a message (meter.js commandSegments). */
:is(#agent-status, #next-step-text, .first-run-detail, #launch-missing) code { color: var(--ink); font-size: 0.95em; }
/* The console's dark tokens and its default highlight (Ocean). app.js sets
the four accent ones to the person's own highlight once the console page
says which it is, and keeps them for the next launch. */
:root {
--panel: #201d1a; --panel-2: #262220; --ink: #f0ece5; --ink-2: #b6afa3; --ink-3: #8b8376; --rule-2: #46403a;
--accent: #619fe5; --accent-soft: #1a2533; --accent-ink: #0c1117; --accent-line: #3d5978;
}
#bar { flex: none; border-bottom: 1px solid #444; }
/* The console's top bar buttons (.btn small ghost), sized to this bar:
#bar { flex: none; border-bottom: 1px solid var(--rule); }
/* The console's top bar buttons (.btn sm ghost), sized to this bar:
quiet until hovered, then in the highlight color. New Session is the
one that is often the next step, so it wears the highlight outline at
rest, like the console's standby buttons. */
#bar button {
appearance: none; font: inherit; font-size: 12px; font-weight: 600; line-height: 1.2;
padding: 4px 10px; border-radius: 8px; cursor: pointer;
padding: 4px 10px; border-radius: var(--radius-md); cursor: pointer;
border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink-2);
transition: background 0.12s, border-color 0.12s, color 0.12s;
transition: background var(--dur-1), border-color var(--dur-1), color var(--dur-1);
}
#bar button:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); background: var(--panel-2); }
#bar button:disabled { opacity: 0.45; cursor: not-allowed; }
#bar button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
#bar #agent-restart { background: transparent; border-color: var(--accent-line); color: var(--accent); }
#bar #agent-restart:hover:not(:disabled) { background: var(--accent-soft); border-color: var(--accent); }
#bar-row { height: 34px; flex: none; display: flex; align-items: center; gap: 10px; padding: 0 10px; font-size: 12px; white-space: nowrap; overflow-x: auto; overflow-y: hidden; }
#bar-row { height: 34px; flex: none; display: flex; align-items: center; gap: 10px; padding: 0 10px; font-size: 12px; white-space: nowrap; overflow: hidden; }
#bar-row > * { flex: none; }
#bar [hidden] { display: none !important; }
/* A narrow window drops parts instead of scrolling (app.js fitBar, meter.js
barFit): the model text first, then the status line; the agent menu holds
both then. */
#bar-row.no-model #agent-model, #bar-row.no-status #agent-status { display: none; }
#agent-menu-more { margin: 0; padding: 0 8px 6px; color: var(--ink-3); line-height: 1.45; overflow-wrap: anywhere; }
#agent-menu-more:empty { display: none; }
/* The project and agent menus' triggers: plain text until hovered, a
caret saying there is more behind them. */
#bar .bar-menu { display: inline-flex; align-items: center; gap: 6px; flex: none; border-color: transparent; background: transparent; color: var(--ink); padding: 4px 8px; }
#bar .bar-menu:hover:not(:disabled), #bar .bar-menu[aria-expanded="true"] { background: var(--panel-2); border-color: transparent; color: var(--ink); }
.bar-caret { color: var(--ink-3); font-size: 10px; }
#project-name { max-width: 220px; overflow: hidden; text-overflow: ellipsis; }
.agent-dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: #666; }
.agent-dot.is-ok { background: #6a9955; }
.agent-dot.is-warn { background: #d7ba7d; }
.agent-dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: var(--ink-3); }
.agent-dot.is-ok { background: var(--ok); }
.agent-dot.is-warn { background: var(--stage); }
#agent-ended, #agent-model { color: var(--ink-3); font-weight: 400; }
#agent-model { max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#agent-bypass { flex: none; font-size: 11px; font-weight: 600; line-height: 1.3; padding: 0 7px; border-radius: 999px; border: 1px solid #d7ba7d; color: #d7ba7d; }
#agent-bypass { flex: none; font-size: 11px; font-weight: 600; line-height: 1.3; padding: 0 7px; border-radius: var(--radius-pill); border: 1px solid var(--stage); color: var(--stage); }
#agent-none { color: var(--ink-3); }
#agent-status { color: var(--ink-3); overflow: hidden; text-overflow: ellipsis; min-width: 0; max-width: 320px; }
#agent-status.is-error { color: #f48771; }
#agent-status.is-error { color: var(--warn); }
/* The Implementation Loop, for as long as one runs: the loudest thing in the
window on purpose. The accent says it is working; amber says it needs you. */
#loop-banner {
--banner-color: var(--accent); --banner-bg: var(--accent-soft); --banner-line: var(--accent-line);
--banner-color: var(--accent); --banner-bg: var(--accent-soft); --banner-line: var(--accent-line); --focus-ring: var(--banner-color);
flex: none; display: flex; flex-wrap: wrap; align-items: center; gap: 8px 20px;
padding: 10px 14px 10px 16px; font-size: 13px; color: var(--ink);
background: var(--banner-bg); border-bottom: 1px solid var(--banner-line); box-shadow: inset 4px 0 0 var(--banner-color);
}
#loop-banner[hidden] { display: none; }
#loop-banner[data-tone="waiting"] { --banner-color: #e5a93c; --banner-bg: #3a2b10; --banner-line: #7a5a1e; }
#loop-banner[data-tone="waiting"] { --banner-color: var(--stage); --banner-bg: var(--stage-soft); --banner-line: color-mix(in srgb, var(--stage) 45%, var(--panel)); }
#loop-now { flex: 1 1 320px; min-width: 0; display: grid; gap: 3px; }
#loop-headline { display: flex; align-items: center; gap: 9px; }
#loop-dot { flex: none; width: 10px; height: 10px; border-radius: 50%; background: var(--banner-color); animation: loop-pulse 1.8s ease-in-out infinite; }
@@ -76,28 +89,27 @@
@keyframes loop-pip { 50% { opacity: 0.4; } }
#loop-spec { color: var(--ink-2); font-weight: 600; }
#loop-elapsed { font-variant-numeric: tabular-nums; }
#loop-retries { color: #f48771; }
#loop-retries { color: var(--warn); }
#loop-actions { flex: none; display: flex; flex-wrap: wrap; gap: 8px; }
#loop-actions button {
appearance: none; font: inherit; font-size: 12.5px; font-weight: 600; line-height: 1.2;
padding: 6px 12px; border-radius: 8px; cursor: pointer;
padding: 6px 12px; border-radius: var(--radius-md); cursor: pointer;
border: 1px solid var(--banner-line); background: var(--panel); color: var(--ink);
}
#loop-actions button:hover:not(:disabled) { border-color: var(--banner-color); background: var(--panel-2); }
#loop-actions button:disabled { cursor: default; opacity: 0.65; }
#loop-actions button:focus-visible { outline: 2px solid var(--banner-color); outline-offset: 2px; }
#loop-actions #loop-error { align-self: center; max-width: 320px; color: #f48771; font-size: 12.5px; overflow-wrap: anywhere; }
#loop-actions #loop-error { align-self: center; max-width: 320px; color: var(--warn); font-size: 12.5px; overflow-wrap: anywhere; }
#loop-actions [hidden] { display: none; }
#loop-actions #loop-stop-now { color: #f48771; }
#loop-actions #loop-stop-now:hover:not(:disabled) { border-color: #f48771; }
#loop-actions #loop-stop-now { color: var(--warn); }
#loop-actions #loop-stop-now:hover:not(:disabled) { border-color: var(--warn); }
@media (prefers-reduced-motion: reduce) { #loop-dot, .loop-pip.current { animation: none; } }
#bar-grow { flex: 1; min-width: 0; }
/* The one next step for the console or the skills, at the right end. */
#next-step { display: flex; align-items: center; gap: 8px; flex: none; }
#next-step-text { overflow: hidden; text-overflow: ellipsis; max-width: 320px; }
#next-step-text.is-ok { color: #6a9955; }
#next-step-text.is-warn { color: #d7ba7d; }
#next-step-text.is-err { color: #f48771; }
#next-step-text.is-ok { color: var(--ok); }
#next-step-text.is-warn { color: var(--stage); }
#next-step-text.is-err { color: var(--warn); }
#next-step-text.is-busy::before {
content: ""; display: inline-block; width: 8px; height: 8px; margin-right: 6px; vertical-align: -1px;
border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: bar-spin 0.8s linear infinite;
@@ -105,18 +117,27 @@
@keyframes bar-spin { to { transform: rotate(360deg); } }
#bar #next-step-button { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
#bar #next-step-button:hover:not(:disabled) { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); filter: brightness(1.12); }
#next-step-more { color: var(--ink-3); font-size: 11px; border-bottom: 1px dotted var(--ink-3); cursor: help; }
/* "+N more": a button that opens the list of the other pending steps. */
#bar #next-step-more { font-size: var(--fs-2xs); font-weight: 600; padding: 2px 8px; border-radius: var(--radius-pill); color: var(--ink-2); }
#more-menu { min-width: 280px; }
.more-step { padding: 6px 8px; display: grid; gap: 4px; }
.more-step + .more-step { border-top: 1px solid var(--rule); }
.more-step p { margin: 0; color: var(--ink-2); line-height: 1.45; overflow-wrap: anywhere; }
.more-step p.is-ok { color: var(--ok); }
.more-step p.is-warn { color: var(--stage); }
.more-step p.is-err { color: var(--warn); }
#bar .more-step button { justify-self: start; width: auto; padding: 4px 10px; border: 1px solid var(--rule-2); background: var(--panel); }
/* The menus sit outside the scrolling row (fixed, placed under their
trigger by app.js), so the row's overflow never clips them. */
.bar-dropdown {
position: fixed; z-index: 20; min-width: 240px; max-width: 380px; padding: 6px; box-sizing: border-box;
font-size: 12px; background: var(--panel); border: 1px solid var(--rule-2); border-radius: 8px; box-shadow: 0 10px 28px rgba(0, 0, 0, 0.45);
position: fixed; z-index: var(--z-menu); min-width: 240px; max-width: 380px; padding: 6px; box-sizing: border-box;
font-size: 12px; background: var(--panel); border: 1px solid var(--rule-2); border-radius: var(--radius-md); box-shadow: var(--shadow-2);
}
.bar-dropdown-head { margin: 0; padding: 4px 8px 8px; color: var(--ink-3); line-height: 1.45; overflow-wrap: anywhere; }
.bar-dropdown-head b { color: var(--ink); font-weight: 600; }
.bar-dropdown-head .is-warn { color: #d7ba7d; }
.bar-dropdown-head .is-warn { color: var(--stage); }
#bar .bar-dropdown button {
display: block; width: 100%; text-align: left; font-weight: 400; padding: 6px 8px; border: 0; border-radius: 6px;
display: block; width: 100%; text-align: left; font-weight: 400; padding: 6px 8px; border: 0; border-radius: var(--radius-sm);
background: transparent; color: var(--ink);
}
#bar .bar-dropdown button:hover:not(:disabled), #bar .bar-dropdown button:focus-visible { background: var(--panel-2); color: var(--accent); }
@@ -127,12 +148,14 @@
#dashboard { flex: 1; min-height: 0; min-width: 0; position: relative; }
/* An Activities game in full screen: the console's frame over the whole
window, the bar and the terminal left as they are underneath. */
body.console-full #console-frame { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 1000; }
#console-frame { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; background: #1e1e1e; }
#dashboard-state { position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; background: #1e1e1e; text-align: center; padding: 16px; box-sizing: border-box; }
body.console-full #console-frame { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: var(--z-overlay); }
#console-frame { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; background: var(--bg); }
#dashboard-state { position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; background: var(--bg); text-align: center; padding: 16px; box-sizing: border-box; }
#dashboard-state[hidden] { display: none; }
#dashboard-state-text { margin: 0; max-width: 60ch; overflow-wrap: anywhere; color: #bbb; }
#dashboard-state-text { margin: 0; max-width: 60ch; overflow-wrap: anywhere; color: var(--ink-2); }
#dashboard-state-planny[hidden] { display: none; }
/* The plain Planny (no mug) is the first frame's "Starting Plan2Code"; the coffee break adds the mug and the reaching arm. */
#dashboard-state-planny.is-plain .ps-reach, #dashboard-state-planny:not(.is-plain) .ps-rest { display: none; }
/* Drawn and colored like the console's own Planny (styles/planny.css):
an outlined shell, the star eye, a lip of a smile, round hands. */
#dashboard-state-planny { width: 104px; height: auto; overflow: visible; }
@@ -146,7 +169,7 @@
#dashboard-state-planny .ps-eye { fill: var(--ink); }
#dashboard-state-planny .ps-mug { fill: var(--panel-2); stroke-width: 1; }
#dashboard-state-planny .ps-handle { stroke-width: 0.9; }
#dashboard-state-planny .ps-coffee { fill: #9a6b47; }
#dashboard-state-planny .ps-coffee { fill: var(--stage); }
#dashboard-state-planny .ps-steam path {
fill: none; stroke: var(--ink-3); stroke-width: 0.7; stroke-linecap: round;
animation: ps-steam 2.4s ease-in-out infinite; opacity: 0;
@@ -166,95 +189,132 @@
#dashboard-state-actions { display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; }
#dashboard-state-actions button {
appearance: none; font: inherit; font-size: 13.5px; font-weight: 600; line-height: 1.2;
padding: 7px 13px; border-radius: 8px; cursor: pointer;
padding: 7px 13px; border-radius: var(--radius-md); cursor: pointer;
border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink);
transition: filter 0.12s, background 0.12s;
transition: filter var(--dur-1), background var(--dur-1);
}
#dashboard-state-actions button:hover { background: var(--panel-2); }
#dashboard-state-actions button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
#dashboard-state-actions #dashboard-state-button { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
#dashboard-state-actions #dashboard-state-button:hover { background: var(--accent); filter: brightness(1.08); }
#dashboard-state-actions button[hidden] { display: none; }
/* What a bug report needs (the session URL, the last health check), quiet under the buttons. */
#dashboard-state-details { margin: 0; max-width: 60ch; font-size: 12px; color: var(--ink-3); overflow-wrap: anywhere; user-select: text; }
#dashboard-state-details[hidden] { display: none; }
/* "Details": the raw text of an error, behind a plain link-style button. */
#dashboard-state-toggle { appearance: none; border: 0; background: transparent; font: inherit; font-size: 12px; color: var(--ink-3); text-decoration: underline; cursor: pointer; padding: 2px 4px; }
#dashboard-state-toggle:hover { color: var(--ink); }
#dashboard-state-toggle[hidden] { display: none; }
/* One busy style for every wait: the bar's spinner, above the words. */
#dashboard-state-busy { width: 18px; height: 18px; border: 2px solid var(--ink-3); border-right-color: transparent; border-radius: 50%; animation: bar-spin 0.8s linear infinite; }
#dashboard-state-busy[hidden] { display: none; }
@media (prefers-reduced-motion: reduce) { #dashboard-state-busy { animation: none; border-right-color: var(--ink-3); opacity: 0.6; } }
/* The one confirm modal, drawn here and not in the page, so the page cannot spoof it. */
#confirm-modal { position: fixed; inset: 0; z-index: var(--z-overlay); display: flex; align-items: center; justify-content: center; padding: 16px; background: var(--scrim); }
#confirm-modal[hidden] { display: none; }
#confirm-panel { width: min(460px, 100%); max-height: 100%; overflow: auto; box-sizing: border-box; padding: 18px 20px; background: var(--panel); color: var(--ink); border: 1px solid var(--rule-2); border-radius: var(--radius); box-shadow: var(--shadow-3); }
#confirm-panel:focus { outline: none; }
#confirm-title { margin: 0 0 10px; font-size: 16px; line-height: 1.3; }
#confirm-body { display: grid; gap: 8px; color: var(--ink-2); font-size: 13.5px; line-height: 1.5; overflow-wrap: anywhere; }
#confirm-body p { margin: 0; }
#confirm-body pre { margin: 0; padding: 8px 10px; background: var(--field); border: 1px solid var(--rule); border-radius: var(--radius-sm); font-family: var(--mono); font-size: 12.5px; color: var(--ink); white-space: pre-wrap; user-select: text; }
#confirm-body .confirm-callout { padding: 8px 10px; border-radius: var(--radius-sm); border: 1px solid color-mix(in srgb, var(--stage) 45%, transparent); background: var(--stage-soft); color: var(--ink); }
#confirm-actions { display: flex; gap: 10px; justify-content: flex-end; flex-wrap: wrap; margin-top: 16px; }
#confirm-actions button { appearance: none; font: inherit; font-size: 13.5px; font-weight: 600; line-height: 1.2; padding: 7px 14px; border-radius: var(--radius-md); cursor: pointer; border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink); }
#confirm-actions button:hover { background: var(--panel-2); }
#confirm-actions button.is-primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
#confirm-actions button.is-danger { border-color: var(--warn); color: var(--warn); }
#confirm-actions button.is-primary.is-danger { background: var(--warn); color: var(--panel); }
/* The terminal's right-click menu: Copy, Paste, Clear, and the copy-on-select switch. */
#term-menu { position: fixed; z-index: var(--z-menu); min-width: 210px; padding: 4px; box-sizing: border-box; font-size: 12.5px; background: var(--panel); border: 1px solid var(--rule-2); border-radius: var(--radius-md); box-shadow: var(--shadow-2); }
#term-menu[hidden] { display: none; }
#term-menu button { appearance: none; display: flex; justify-content: space-between; gap: 18px; width: 100%; text-align: left; font: inherit; padding: 6px 8px; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--ink); cursor: pointer; }
#term-menu button:hover:not(:disabled), #term-menu button:focus-visible { background: var(--panel-2); color: var(--accent); }
#term-menu button:disabled { color: var(--ink-3); cursor: default; }
#term-menu .term-menu-key { color: var(--ink-3); }
#term-menu hr { border: 0; border-top: 1px solid var(--rule); margin: 4px 0; }
/* The bar's "..." menu, at the right. */
#bar #app-menu-button { flex: none; font-weight: 700; letter-spacing: 1px; padding: 2px 9px; }
#app-menu-button[hidden] { display: none; }
#app-menu .menu-key { float: right; margin-left: 18px; color: var(--ink-3); }
#launch-card {
position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column;
align-items: stretch; justify-content: center; gap: 10px; background: #1e1e1e;
align-items: stretch; justify-content: center; gap: 10px; background: var(--bg);
padding: 24px; box-sizing: border-box; width: min(360px, 100%); margin: 0 auto;
}
#launch-card[hidden] { display: none; }
#launch-card h2 { margin: 0 0 6px; font-size: 17px; text-align: center; }
#launch-card label { font-size: 12px; color: #9ab; }
#launch-card label { font-size: 12px; color: var(--ink-2); }
#launch-card select, #launch-card input[type="text"] {
width: 100%; box-sizing: border-box; margin: 4px 0 2px; padding: 6px 8px;
background: #2a2a2a; color: #ddd; border: 1px solid #555; border-radius: 4px; font: inherit;
background: var(--field); color: var(--ink); border: 1px solid var(--rule-2); border-radius: var(--radius-sm); font: inherit;
}
#launch-missing { margin: 0; font-size: 12px; color: #d7ba7d; }
#launch-notice { margin: 0; font-size: 12px; color: #9ab; }
#launch-missing { margin: 0; font-size: 12px; color: var(--stage); }
#launch-notice { margin: 0; font-size: 12px; color: var(--ink-2); }
#launch-notice[hidden] { display: none; }
/* Set up an agent, shown wherever the app says "no agent". */
.setup-agent-btn { font: inherit; font-size: 12px; margin-top: 4px; padding: 3px 10px; cursor: pointer;
background: var(--accent); color: var(--accent-ink); border: 1px solid var(--accent); border-radius: 4px; }
background: var(--accent); color: var(--accent-ink); border: 1px solid var(--accent); border-radius: var(--radius-sm); }
/* The way out of the setup page: a bar button, so it never covers the page. */
#setup-close[hidden] { display: none; }
#launch-missing code { color: #ddd; }
#launch-agents-warning { margin: 0; font-size: 12px; color: #d7ba7d; white-space: pre-line; }
#launch-agents-warning { margin: 0; font-size: 12px; color: var(--stage); white-space: pre-line; }
#launch-agents-warning[hidden] { display: none; }
.agent-explainer { margin: 0; font-size: 12px; line-height: 1.5; }
.agent-explainer ul { margin: 4px 0; padding-left: 18px; }
.agent-explainer code { color: #ddd; }
.agent-explainer code { color: var(--ink); }
.agent-explainer button, #launch-missing button { font: inherit; font-size: 12px; margin-left: 6px; padding: 1px 8px; cursor: pointer; }
.agent-explainer .agent-link, #launch-missing .agent-link { background: none; border: 0; padding: 0; color: #75beff; text-decoration: underline; }
.agent-explainer .agent-link, #launch-missing .agent-link { background: none; border: 0; padding: 0; color: var(--accent); text-decoration: underline; }
#launch-effort-row[hidden], #launch-model-row[hidden] { display: none; }
#launch-bypass-row { display: flex; align-items: center; gap: 8px; color: #ccc; font-size: 13px; cursor: pointer; }
#launch-bypass-row { display: flex; align-items: center; gap: 8px; color: var(--ink); font-size: 13px; cursor: pointer; }
#launch-bypass-row input { margin: 0; }
#launch-bypass-warning { margin: 0; font-size: 12px; color: #d7ba7d; }
#launch-bypass-warning { margin: 0; font-size: 12px; color: var(--stage); }
#launch-bypass-warning[hidden] { display: none; }
#launch-start {
margin-top: 6px; padding: 8px; background: #2d6a4f; color: #fff; border: 0; border-radius: 4px;
margin-top: 6px; padding: 8px; background: var(--accent); color: var(--accent-ink); border: 0; border-radius: var(--radius-sm);
font: inherit; font-weight: 600; cursor: pointer;
}
#launch-start:hover { background: #357a5c; }
#launch-start:disabled { background: #444; color: #888; cursor: not-allowed; }
#launch-start:hover:not(:disabled) { filter: brightness(1.08); }
#launch-start:disabled { background: var(--rule); color: var(--ink-3); cursor: not-allowed; }
/* The folder picker: full screen on a bare start, a dialog over the page
(with Cancel) from Change project. Choose a folder comes first; each
recent folder shows its name with the full path muted under it. */
#folder-picker {
position: absolute; inset: 0; z-index: 2; display: flex; align-items: center; justify-content: center;
background: #1e1e1e; padding: 24px; box-sizing: border-box;
background: var(--bg); padding: 24px; box-sizing: border-box;
}
#folder-picker[hidden] { display: none; }
#folder-picker.is-dialog { background: rgba(0, 0, 0, 0.55); }
#folder-picker.is-dialog { background: var(--scrim); }
#folder-picker-panel { display: flex; flex-direction: column; gap: 12px; width: min(440px, 100%); max-height: 100%; }
#folder-picker.is-dialog #folder-picker-panel {
background: var(--panel); border: 1px solid var(--rule-2); border-radius: 10px; padding: 18px; box-sizing: border-box;
background: var(--panel); border: 1px solid var(--rule-2); border-radius: var(--radius); padding: 18px; box-sizing: border-box;
}
#folder-picker h2 { margin: 0; font-size: 17px; text-align: center; }
#folder-picker-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; overflow-y: auto; }
.folder-picker-row {
appearance: none; width: 100%; text-align: left; font: inherit; cursor: pointer;
display: flex; flex-direction: column; gap: 2px; padding: 8px 12px; border-radius: 8px;
display: flex; flex-direction: column; gap: 2px; padding: 8px 12px; border-radius: var(--radius-md);
border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink);
}
.folder-picker-row:hover:not(:disabled) { background: var(--panel-2); border-color: var(--accent-line); }
.folder-picker-row:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.folder-picker-row:disabled { opacity: 0.6; cursor: default; }
.folder-picker-row.is-browse { font-weight: 600; background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
.folder-picker-row.is-browse:hover:not(:disabled) { background: var(--accent); border-color: var(--accent); filter: brightness(1.08); }
.folder-picker-label { font-size: 13.5px; }
.folder-picker-detail { font-size: 12px; color: var(--ink-3); overflow-wrap: anywhere; }
#folder-picker-error { margin: 0; font-size: 12px; color: #d7ba7d; }
#folder-picker-error { margin: 0; font-size: 12px; color: var(--stage); }
#folder-picker-error[hidden], #folder-picker-cancel[hidden] { display: none; }
#folder-picker-cancel {
align-self: center; appearance: none; font: inherit; font-size: 13.5px; font-weight: 600; padding: 7px 13px;
border-radius: 8px; cursor: pointer; border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink);
border-radius: var(--radius-md); cursor: pointer; border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink);
}
#folder-picker-cancel:hover { background: var(--panel-2); }
#folder-picker-cancel:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
#first-run {
position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column;
align-items: stretch; justify-content: center; gap: 14px; background: #1e1e1e;
align-items: stretch; justify-content: center; gap: 14px; background: var(--bg);
padding: 24px; box-sizing: border-box; width: min(420px, 100%); margin: 0 auto;
}
#first-run[hidden] { display: none; }
@@ -262,54 +322,78 @@
#first-run-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
.first-run-row { display: flex; align-items: flex-start; gap: 8px; font-size: 13px; }
.first-run-mark { flex: none; width: 16px; text-align: center; font-weight: 700; }
.first-run-row.is-pass .first-run-mark { color: #6a9955; }
.first-run-row.is-fail .first-run-mark { color: #d7ba7d; }
.first-run-row.is-pass .first-run-mark { color: var(--ok); }
.first-run-row.is-fail .first-run-mark { color: var(--stage); }
.first-run-body { flex: 1; min-width: 0; }
.first-run-title { color: #ddd; }
.first-run-detail { color: #9ab; font-size: 12px; margin-top: 2px; }
.first-run-detail code { color: #ddd; }
.first-run-title { color: var(--ink); }
.first-run-detail { color: var(--ink-2); font-size: 12px; margin-top: 2px; }
.first-run-row button {
margin-top: 4px; background: none; border: 1px solid #555; color: #ccc; border-radius: 3px;
margin-top: 4px; background: none; border: 1px solid var(--rule-2); color: var(--ink); border-radius: var(--radius-xs);
font: inherit; font-size: 12px; padding: 3px 8px; cursor: pointer;
}
.first-run-row button:hover { background: #333; }
.first-run-row button:hover { background: var(--panel-2); }
#first-run-start {
margin-top: 6px; padding: 8px; background: #2d6a4f; color: #fff; border: 0; border-radius: 4px;
margin-top: 6px; padding: 8px; background: var(--accent); color: var(--accent-ink); border: 0; border-radius: var(--radius-sm);
font: inherit; font-weight: 600; cursor: pointer;
}
#first-run-start:hover { background: #357a5c; }
#first-run-start:disabled { background: #444; color: #888; cursor: not-allowed; }
#first-run-start:hover:not(:disabled) { filter: brightness(1.08); }
#first-run-start:disabled { background: var(--rule); color: var(--ink-3); cursor: not-allowed; }
#term-handle { flex: none; background: #2a2a2a; }
#term-handle:hover { background: #3d3d3d; }
/* The splitter between the console and the terminal: a 6px hit area with a
1px line, in the highlight color on hover, keyboard focus and drag (and the
shell's one focus ring, above, on keyboard focus). */
#term-handle { flex: none; position: relative; touch-action: none; }
#term-handle::after { content: ""; position: absolute; background: var(--rule); transition: background var(--dur-1); }
#term-handle:hover::after, #term-handle:focus-visible::after, #term-handle.is-dragging::after { background: var(--accent); }
#term-handle[hidden] { display: none; }
#workspace:not(.dock-right) #term-handle { height: 6px; cursor: row-resize; }
#workspace:not(.dock-right) #term-handle::after { left: 0; right: 0; top: 2px; height: 1px; }
#workspace.dock-right #term-handle { width: 6px; cursor: col-resize; }
#workspace.dock-right #term-handle::after { top: 0; bottom: 0; left: 2px; width: 1px; }
#term-panel { flex: none; display: flex; flex-direction: column; min-height: 0; min-width: 0; }
#workspace:not(.dock-right) #term-panel { border-top: 1px solid #444; }
#workspace.dock-right #term-panel { border-left: 1px solid #444; }
#term-panel { flex: none; display: flex; flex-direction: column; min-height: 0; min-width: 0; background: var(--panel); }
#workspace:not(.dock-right) #term-panel.collapsed { border-top: 1px solid var(--rule); }
#workspace.dock-right #term-panel.collapsed { border-left: 1px solid var(--rule); }
#term-panel.collapsed { height: 28px !important; }
#workspace.dock-right #term-panel.collapsed { width: 28px !important; height: auto !important; }
#term-panel.collapsed #term { display: none; }
#term-toolbar { flex: none; display: flex; align-items: center; gap: 6px; padding: 3px 6px; background: #252525; font-size: 11px; }
#workspace.dock-right #term-toolbar { flex-direction: column; align-items: stretch; }
/* The terminal's own bar: a title on the left, the quiet pill, then three
icon buttons (dock, maximize, collapse) that name themselves by label. */
#term-toolbar { flex: none; display: flex; align-items: center; gap: 6px; padding: 2px 6px; min-height: 28px; box-sizing: border-box; background: var(--panel-2); border-bottom: 1px solid var(--rule); font-size: var(--fs-xs); }
#term-title { color: var(--ink-2); font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; flex: 0 3 auto; }
#term-toolbar-spacer { flex: 1; min-height: 0; }
#term-toolbar button {
background: none; border: 1px solid #555; color: #ccc; border-radius: 3px;
font-size: 11px; padding: 2px 6px; cursor: pointer; font-family: inherit;
#term-toolbar .term-icon {
appearance: none; display: inline-flex; align-items: center; justify-content: center; flex: none;
width: 24px; height: 24px; padding: 0; border-radius: var(--radius-sm); cursor: pointer;
border: 1px solid transparent; background: transparent; color: var(--ink-2); font: inherit;
transition: background var(--dur-1), color var(--dur-1), border-color var(--dur-1);
}
#term-toolbar button:hover { background: #333; }
#term-toolbar button[aria-pressed="true"] { color: #fff; border-color: #888; }
#term-toolbar .term-icon:hover { background: var(--panel); border-color: var(--rule-2); color: var(--ink); }
#term-toolbar .term-icon[aria-pressed="true"] { background: var(--accent-soft); border-color: var(--accent-line); color: var(--accent); }
#term-toolbar .term-icon svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; }
/* One icon per state, shown by the button's own attributes. */
#term-dock .ic-bottom, #term-dock[data-dock="right"] .ic-right { display: none; }
#term-dock[data-dock="right"] .ic-bottom { display: block; }
#term-maximize .ic-restore, #term-maximize[aria-pressed="true"] .ic-max { display: none; }
#term-maximize[aria-pressed="true"] .ic-restore { display: block; }
#term-collapse svg { transition: transform var(--dur-2) var(--ease-out); }
#workspace.dock-right #term-collapse svg { transform: rotate(-90deg); }
#term-collapse[aria-pressed="true"] svg { transform: rotate(180deg); }
#workspace.dock-right #term-collapse[aria-pressed="true"] svg { transform: rotate(90deg); }
#term-panel.collapsed #term-dock, #term-panel.collapsed #term-maximize { display: none; }
/* Docked right and collapsed, the panel is a 28px-wide strip: "View Agent
Terminal" does not fit sideways, so it reads top-to-bottom instead, rotated the
same way a reader would turn the panel to read it. */
#workspace.dock-right #term-panel.collapsed #term-toolbar { padding: 6px 2px; align-items: center; }
#workspace.dock-right #term-panel.collapsed #term-collapse {
writing-mode: vertical-rl; text-orientation: mixed; padding: 6px 2px;
/* Docked right and collapsed, the panel is a 28px-wide strip: only the
expand button and the pill fit, the pill reading top to bottom. */
#workspace.dock-right #term-panel.collapsed #term-toolbar { flex-direction: column; padding: 4px 2px; align-items: center; border-bottom: 0; }
#workspace.dock-right #term-panel.collapsed #term-title { display: none; }
#workspace.dock-right #term-panel.collapsed #term-badge { writing-mode: vertical-rl; padding: 6px 2px; }
/* A pill in words where a bare dot sat: the agent has been quiet while the
panel is small or collapsed. Pressing it opens the terminal. */
#term-badge {
appearance: none; flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; font: inherit; font-size: var(--fs-2xs); font-weight: 600; line-height: 1.3; white-space: nowrap;
padding: 1px 9px; border-radius: var(--radius-pill); cursor: pointer;
border: 1px solid color-mix(in srgb, var(--stage) 45%, transparent); background: var(--stage-soft); color: var(--stage);
}
#term-badge { color: #d7ba7d; font-size: 14px; line-height: 1; }
#term-badge:hover { border-color: var(--stage); }
#term-badge[hidden] { display: none; }
#term { flex: 1; min-height: 0; min-width: 0; padding: 4px; }
</style>
@@ -330,17 +414,28 @@
<span id="next-step" role="status" hidden>
<span id="next-step-text"></span>
<button id="next-step-button" hidden></button>
<span id="next-step-more" hidden></span>
<button id="next-step-more" type="button" aria-haspopup="menu" aria-expanded="false" aria-controls="more-menu" hidden></button>
<button id="next-step-notes" type="button" hidden>What's new</button>
</span>
<!-- The compact menu at the right end: About, Check for updates, Help, Quit. -->
<button id="app-menu-button" class="bar-menu" type="button" aria-haspopup="menu" aria-expanded="false" aria-controls="app-menu" aria-label="Plan2Code menu" title="Plan2Code menu">&#8943;</button>
</div>
<div id="project-menu" class="bar-dropdown" role="menu" aria-label="Project" hidden>
<div id="project-menu" class="bar-dropdown" role="menu" aria-label="Project" tabindex="-1" hidden>
<p class="bar-dropdown-head">Project<br><b id="project-path"></b></p>
<button id="change-project" role="menuitem">Change project...</button>
</div>
<div id="agent-menu" class="bar-dropdown" role="menu" aria-label="Agent" hidden>
<div id="agent-menu" class="bar-dropdown" role="menu" aria-label="Agent" tabindex="-1" hidden>
<p id="agent-menu-head" class="bar-dropdown-head"></p>
<p id="agent-menu-more"></p>
<button id="change-agent" role="menuitem" hidden>Change agent...</button>
</div>
<div id="app-menu" class="bar-dropdown" role="menu" aria-label="Plan2Code" tabindex="-1" hidden>
<button id="app-about" role="menuitem">About Plan2Code</button>
<button id="app-check-updates" role="menuitem">Check for updates</button>
<button id="app-help" role="menuitem">Help</button>
<button id="app-quit" role="menuitem">Quit</button>
</div>
<div id="more-menu" class="bar-dropdown" role="menu" aria-label="More steps" tabindex="-1" hidden></div>
</header>
<!-- The Implementation Loop, while one runs (app.js loop-state, meter.js loopBanner). -->
<section id="loop-banner" aria-label="Implementation Loop" hidden>
@@ -367,33 +462,38 @@
<div id="workspace">
<main id="dashboard">
<iframe id="console-frame" title="Plan2Code console dashboard" allow="clipboard-write"></iframe>
<div id="dashboard-state" hidden>
<div id="dashboard-state">
<!-- Planny on a coffee break: shown only before a New Session press,
the one state here that is a question rather than a status. The
console's own Planny (shell, star eye, smile, feet, resting left
arm) with the right arm reaching out to a steaming mug. -->
<svg id="dashboard-state-planny" viewBox="0 7 29 23" aria-hidden="true" focusable="false" hidden>
<svg id="dashboard-state-planny" class="is-plain" viewBox="0 7 22 23" aria-hidden="true" focusable="false">
<rect class="ps-foot" x="5.7" y="27.1" width="3.6" height="1.7" rx="0.85" />
<rect class="ps-foot" x="12.7" y="27.1" width="3.6" height="1.7" rx="0.85" />
<rect class="ps-shell" x="3" y="7" width="16" height="20" rx="3.2" />
<path class="ps-eye" d="M11 10.95 L11.79 12.91 L13.9 13.06 L12.28 14.42 L12.79 16.47 L11 15.35 L9.21 16.47 L9.72 14.42 L8.1 13.06 L10.21 12.91 Z" />
<path class="ps-smile" d="M8.3 18.4 Q11 21 13.7 18.4" />
<g class="ps-arm"><path d="M3 18 L1.3 21" /><circle cx="1.3" cy="21" r="0.85" /></g>
<g class="ps-steam">
<g class="ps-steam ps-reach">
<path d="M23 17.3 q-0.6 -0.9 0 -1.8 t0 -1.8" />
<path d="M24.4 17.1 q0.6 -0.9 0 -1.8 t0 -1.8" />
<path d="M25.8 17.3 q-0.6 -0.9 0 -1.8 t0 -1.8" />
</g>
<g class="ps-arm"><path d="M19 18 L21.6 20.6" /><circle cx="21.6" cy="20.6" r="0.85" /></g>
<path class="ps-handle" d="M26.7 19.6 h0.3 a1.15 1.15 0 0 1 0 2.3 h-0.3" />
<rect class="ps-mug" x="22.4" y="18.4" width="4.3" height="4.6" rx="0.8" />
<rect class="ps-coffee" x="23" y="19" width="3.1" height="0.8" rx="0.35" />
<g class="ps-arm ps-rest"><path d="M19 18 L20.7 21" /><circle cx="20.7" cy="21" r="0.85" /></g>
<g class="ps-arm ps-reach"><path d="M19 18 L21.6 20.6" /><circle cx="21.6" cy="20.6" r="0.85" /></g>
<path class="ps-handle ps-reach" d="M26.7 19.6 h0.3 a1.15 1.15 0 0 1 0 2.3 h-0.3" />
<rect class="ps-mug ps-reach" x="22.4" y="18.4" width="4.3" height="4.6" rx="0.8" />
<rect class="ps-coffee ps-reach" x="23" y="19" width="3.1" height="0.8" rx="0.35" />
</svg>
<p id="dashboard-state-text"></p>
<span id="dashboard-state-busy" role="presentation" hidden></span>
<p id="dashboard-state-text">Starting Plan2Code</p>
<span id="dashboard-state-actions">
<button id="dashboard-state-button" hidden></button>
<button id="dashboard-state-secondary" hidden></button>
<button id="dashboard-state-cancel" hidden>Cancel</button>
</span>
<button id="dashboard-state-toggle" type="button" aria-expanded="false" aria-controls="dashboard-state-details" hidden>Details</button>
<p id="dashboard-state-details" hidden></p>
</div>
<div id="folder-picker" hidden>
<div id="folder-picker-panel" role="dialog" aria-labelledby="folder-picker-title">
@@ -435,20 +535,43 @@
<button id="launch-start" type="submit">Start agent</button>
</form>
</main>
<div id="term-handle" title="Drag to resize the terminal panel"></div>
<section id="term-panel">
<!-- The splitter: arrow keys, Home and End, and a double-click that returns it to the default (app.js). -->
<div id="term-handle" role="separator" aria-orientation="horizontal" aria-label="Terminal size" aria-controls="term-panel" aria-valuemin="10" aria-valuemax="60" aria-valuenow="25" tabindex="0" title="Drag to resize the terminal. Arrow keys also work; double-click resets it."></div>
<section id="term-panel" aria-label="Terminal">
<div id="term-toolbar">
<span id="term-badge" title="The agent has been quiet a while" hidden>●</span>
<span id="term-title">Terminal</span>
<button id="term-badge" type="button" title="The agent has been quiet a while. Open the terminal to check." hidden>Agent may need you</button>
<span id="term-toolbar-spacer"></span>
<button id="term-dock" type="button">Dock right</button>
<button id="term-maximize" type="button" aria-pressed="false">Maximize</button>
<button id="term-collapse" type="button" aria-pressed="false">Collapse</button>
<button id="term-dock" class="term-icon" type="button" data-dock="bottom" aria-label="Dock the terminal on the right" title="Dock on the right">
<svg class="ic-right" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><rect x="2" y="3" width="12" height="10" rx="1.5"/><path d="M10 3v10"/></svg>
<svg class="ic-bottom" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><rect x="2" y="3" width="12" height="10" rx="1.5"/><path d="M2 9h12"/></svg>
</button>
<button id="term-maximize" class="term-icon" type="button" aria-pressed="false" aria-label="Make the terminal larger" title="Make it larger">
<svg class="ic-max" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><rect x="3" y="3" width="10" height="10" rx="1.5"/></svg>
<svg class="ic-restore" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><rect x="3" y="5.5" width="7.5" height="7.5" rx="1.2"/><path d="M6 5.5V4.2c0-.7.5-1.2 1.2-1.2h5.1c.7 0 1.2.5 1.2 1.2v5.1c0 .7-.5 1.2-1.2 1.2h-1.8"/></svg>
</button>
<button id="term-collapse" class="term-icon" type="button" aria-pressed="false" aria-label="Collapse the terminal" title="Collapse">
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false"><path d="M4 6l4 4 4-4"/></svg>
</button>
</div>
<div id="term"></div>
</section>
</div>
<div id="term-menu" role="menu" aria-label="Terminal" hidden></div>
<!-- The one confirm dialog (app.js confirmModal): outside the page's frame, so the page cannot spoof it. -->
<div id="confirm-modal" hidden>
<div id="confirm-panel" role="alertdialog" aria-modal="true" aria-labelledby="confirm-title" aria-describedby="confirm-body" tabindex="-1">
<h2 id="confirm-title"></h2>
<div id="confirm-body"></div>
<div id="confirm-actions">
<button id="confirm-cancel" type="button"></button>
<button id="confirm-primary" type="button" class="is-primary"></button>
</div>
</div>
</div>
<script src="vendor/xterm.js"></script>
<script src="vendor/addon-fit.js"></script>
<script src="vendor/addon-web-links.js"></script>
<script type="module" src="app.js"></script>
</body>
</html>
+439 -14
View File
@@ -9,14 +9,39 @@ export const NEXT_STEP_LABELS = {
reconnect: 'Reconnect the console',
'restart-console': 'Reconnect the console',
update: 'Update skills',
'copy-update': 'Copy update command',
'update-restart': 'Update and restart',
'restart-app': 'Restart Plan2Code',
};
// What a person runs in a terminal to move to the newest release: the same line the web
// console's banner gives. The app cannot replace itself, and Update skills is pinned to the
// app's own version, so only this brings the app, the skills and the launcher up together.
// What a person can still run in a terminal to move to the newest release, the same line the
// web console's banner gives. The app updates itself ("Update and restart"); Update skills
// stays pinned to the app's own version, so this line is the fallback when that fails.
export const NEW_RELEASE_COMMAND = 'plan2code update';
/** The release notes page of a version, opened through the shell's link opener. */
export function releaseNotesUrl(version) {
return `https://github.com/jparkerweb/plan2code/releases/tag/v${String(version).replace(/^v/, '')}`;
}
// How often the app asks again whether a newer release is out: it stays open for days.
export const UPDATE_RECHECK_MS = 4 * 60 * 60 * 1000;
/**
* What the release check's answer (`{ latest, problem }`, from `check_new_release`) does to the
* bar's release state `current` (the shape barNextSteps reads). An update that is running, or
* done and waiting for its restart, is never replaced by a later check; a version found shows
* "Update available"; a check that could not run (git missing) says so, once; current and no
* problem clears an old "available" or "could not check" state.
*/
export function releaseAfterCheck(current, result) {
if (current && (current.updating !== undefined || current.restartNeeded)) return current;
const latest = result && typeof result.latest === 'string' && result.latest ? result.latest : '';
const problem = result && typeof result.problem === 'string' && result.problem ? result.problem : '';
if (latest) return { latest };
if (problem) return { problem };
return null;
}
/**
* What the console page's **continue** button types into the agent's
* terminal, one write each: the word, then Enter. Claude Code holds typed
@@ -82,7 +107,7 @@ export function lastAgentNotice(list, remembered) {
* update, its Reconnect (which stops the old console first, so the new skills
* are really picked up) covers a console that has also stopped.
*/
export function barNextSteps({ consoleDead = false, version = null, newRelease = null } = {}) {
export function barNextSteps({ consoleDead = false, version = null, newRelease = null, updatedTo = null, notReplaced = null } = {}) {
const v = version || {};
const steps = [];
if (v.kind === 'updated') {
@@ -115,15 +140,34 @@ export function barNextSteps({ consoleDead = false, version = null, newRelease =
break;
}
// Last: the pending fix for a mismatch or a stopped console comes before a release that is
// merely out. `newRelease` is `{ latest, copied, manual }`.
if (newRelease && newRelease.latest) {
steps.push(
newRelease.manual
? { id: 'new-release', text: `Run \`${NEW_RELEASE_COMMAND}\` in a terminal, then reopen the app`, title: `Plan2Code v${newRelease.latest} is out. Run \`${NEW_RELEASE_COMMAND}\` in a terminal, then reopen the app.`, tone: 'warn', action: null }
: newRelease.copied
? { id: 'new-release', text: `Copied: run \`${NEW_RELEASE_COMMAND}\` in a terminal, then reopen the app`, title: `Plan2Code v${newRelease.latest} is out. Run \`${NEW_RELEASE_COMMAND}\` in a terminal, then reopen the app.`, tone: 'ok', action: null }
: { id: 'new-release', text: `Update available: v${newRelease.latest}`, title: `Plan2Code v${newRelease.latest} is out. Copy the command, run it in a terminal, then reopen the app.`, tone: 'warn', action: 'copy-update' }
);
// merely out. `newRelease` is one of `{ latest }` (out), `{ latest, updating: line }`,
// `{ latest, failed: reason }`, `{ latest, restartNeeded: true }` (installed, waiting for the
// restart) or `{ problem }` (the check could not run); `updatedTo` is the version the app
// restarted into, shown once.
const rel = newRelease || {};
const notes = rel.latest ? { label: "What's new", url: releaseNotesUrl(rel.latest) } : null;
if (rel.latest) {
const latest = rel.latest;
if (rel.restartNeeded) {
steps.push({ id: 'new-release', text: `Updated to v${latest}`, title: `Plan2Code v${latest} is installed. Restart Plan2Code to use it.`, tone: 'ok', action: 'restart-app', link: notes });
} else if (rel.updating !== undefined) {
const line = rel.updating || `Updating to v${latest}...`;
steps.push({ id: 'new-release', text: line, title: line, tone: 'warn', busy: true, action: null });
} else if (rel.failed) {
steps.push({ id: 'new-release', text: 'Update failed', title: `${rel.failed} Plan2Code is still running as it was. You can try again, or run \`${NEW_RELEASE_COMMAND}\` in a terminal.`, tone: 'err', action: 'update-restart', link: notes });
} else {
steps.push({ id: 'new-release', text: `Update available: v${latest}`, title: `Plan2Code v${latest} is out. Update and restart installs it; nothing needs a terminal.`, tone: 'warn', action: 'update-restart', link: notes });
}
} else if (rel.problem) {
steps.push({ id: 'update-check', text: 'Could not check for updates', title: String(rel.problem), tone: 'warn', action: null });
}
if (updatedTo) {
steps.push({ id: 'updated-to', text: `Updated to v${updatedTo}`, title: `Plan2Code was updated to v${updatedTo}.`, tone: 'ok', action: null });
}
// The restart came back on the same version: the release has no desktop app file for this system
// yet, so the installer kept the old one. Said once, instead of "Updated to" the unchanged version.
if (notReplaced) {
steps.push({ id: 'not-replaced', text: 'App not replaced', title: `The skills were updated, but this release has no desktop app for this system yet, so Plan2Code is still on v${notReplaced}.`, tone: 'warn', action: null });
}
return steps.map((step) => ({ ...step, label: step.action ? NEXT_STEP_LABELS[step.action] : null }));
}
@@ -263,6 +307,95 @@ export function helloRetryAction({ loopRunning, loopStep }) {
return loopRunning && loopStep === "Starting" ? "rearm" : "check";
}
/**
* A shell message that names a command marks it with backticks ("run
* `plan2code update`"), and the shell draws each marked command in a <code>
* instead of showing the backticks: the pieces, in order, each plain text or
* a command. A backtick with no partner stays as it is.
*/
export function commandSegments(text) {
const s = String(text ?? "");
const parts = [];
const marked = /`([^`]+)`/g;
let last = 0;
let m;
while ((m = marked.exec(s))) {
if (m.index > last) parts.push({ text: s.slice(last, m.index), code: false });
parts.push({ text: m[1], code: true });
last = marked.lastIndex;
}
if (last < s.length) parts.push({ text: s.slice(last), code: false });
return parts;
}
/**
* The same message for a place that can only hold plain text (a tooltip):
* each marked command in double quotes instead of backticks.
*/
export function plainCommandText(text) {
return String(text ?? "").replace(/`([^`]+)`/g, '"$1"');
}
/**
* Where Up, Down, Home and End move focus in one of the bar's menus of
* `count` items, from item `at` (-1 when focus is on none of them): Up and
* Down wrap around, Home and End go to the ends. Null for any other key, or
* a menu with nothing to move to.
*/
export function menuStep(key, at, count) {
if (!(count > 0)) return null;
switch (key) {
case "ArrowDown":
return at < 0 ? 0 : (at + 1) % count;
case "ArrowUp":
return at < 0 ? count - 1 : (at - 1 + count) % count;
case "Home":
return 0;
case "End":
return count - 1;
default:
return null;
}
}
/**
* What the window says when the console runs but its page sent no hello in
* time, by how many times in a row that has happened: the first time, Reload
* the page; from the second on, "still" with Reconnect the console (stop,
* then start) first and Reload the page beside it, since reloading alone
* could land on the same message forever.
*/
export function pageNotShownView(failures) {
const reload = { action: "reload", label: "Reload the page" };
if (failures >= 2) {
return {
text: "The page still did not load.",
primary: { action: "reconnect", label: NEXT_STEP_LABELS.reconnect },
secondary: reload,
};
}
return { text: "The console is running but its page did not show in this window.", primary: reload, secondary: null };
}
/**
* The session URL with its sign-in key hidden: the address and port are what
* a bug report needs, and the key opens the session.
*/
export function redactSessionUrl(url) {
return String(url || "").replace(/\/s\/[^/?#]+/, "/s/...");
}
/**
* The muted Details line under that message, for bug reports: the session
* URL (its key hidden) and what the last health check said, which is a
* `console_status` state ("running", "dead", "none") or null when the check
* itself failed.
*/
export function pageDetailsLine({ url, health }) {
const where = redactSessionUrl(url) || "none";
return `Details: session ${where}; health check: ${health || "no answer"}`;
}
/** Seconds a waiting message stays before it offers Try reconnecting. */
export const RETRY_AFTER_SECONDS = 10;
@@ -320,3 +453,295 @@ export function taskbarSwitch(data) {
const on = data && data.on;
return typeof on === 'boolean' ? on : null;
}
// The hex shapes the shell takes from the console's `looks` message: four
// #rrggbb shades (fill, soft, ink, line) per theme.
const HEX_COLOR = /^#[0-9a-f]{6}$/i;
const isShadeSet = (shades) => Array.isArray(shades) && shades.length === 4 && shades.every((c) => typeof c === 'string' && HEX_COLOR.test(c));
/**
* What the shell takes from a `looks` message: `{ theme, light, dark }`, the
* resolved theme ("light" or "dark") with both shade sets, or null for
* anything that does not match those shapes (nothing is applied then). The
* page's own sends carry them; a page that predates the theme sends only
* `accent` (the dark shades), which keeps the shell dark with that highlight.
*/
export function looksFromMessage(data) {
if (!data || typeof data !== 'object') return null;
if (data.theme === undefined && data.light === undefined && data.dark === undefined) {
return isShadeSet(data.accent) ? { theme: 'dark', light: null, dark: data.accent } : null;
}
if (data.theme !== 'light' && data.theme !== 'dark') return null;
if (!isShadeSet(data.light) || !isShadeSet(data.dark)) return null;
return { theme: data.theme, light: [...data.light], dark: [...data.dark] };
}
// The terminal font's size steps, in px (Ctrl or Cmd with plus, minus, 0).
export const TERMINAL_FONT_DEFAULT = 13;
export const TERMINAL_FONT_MIN = 8;
export const TERMINAL_FONT_MAX = 32;
/**
* The font size after a terminal zoom key, or null when the key is not one.
* `+` and `=` (the unshifted plus) grow it, `-` shrinks it, `0` returns to the
* default; the result stays within the saved setting's range. `_` is not one:
* Ctrl+Shift+minus is the control-underscore undo of a readline prompt.
*/
export function terminalFontStep(key, size) {
const current = Number.isFinite(size) ? size : TERMINAL_FONT_DEFAULT;
let next;
if (key === '+' || key === '=') next = current + 1;
else if (key === '-') next = current - 1;
else if (key === '0') next = TERMINAL_FONT_DEFAULT;
else return null;
return Math.min(TERMINAL_FONT_MAX, Math.max(TERMINAL_FONT_MIN, next));
}
// One arrow-key step of the splitter: 2% of the window.
export const SPLITTER_STEP = 0.02;
/**
* The terminal panel's share of the window after a key on the splitter, or
* null when the key is not one it uses. The arrow that points away from the
* panel grows it (Up when docked at the bottom, Left when docked right), the
* other shrinks it; Home goes to the smallest share and End to the largest.
* Always within [min, max].
*/
export function splitterFraction(key, fraction, dock, { min, max, step = SPLITTER_STEP }) {
const grow = dock === 'right' ? 'ArrowLeft' : 'ArrowUp';
const shrink = dock === 'right' ? 'ArrowRight' : 'ArrowDown';
let next;
if (key === grow) next = fraction + step;
else if (key === shrink) next = fraction - step;
else if (key === 'Home') next = min;
else if (key === 'End') next = max;
else return null;
return Math.min(max, Math.max(min, next));
}
/** The splitter's aria-valuenow, min and max as whole percents of the window. */
export function splitterAria(fraction, { min, max }) {
return { now: Math.round(fraction * 100), min: Math.round(min * 100), max: Math.round(max * 100) };
}
/**
* The terminal toolbar's title: "Terminal" and, when an agent is known, its
* name after a middle dot.
*/
export function terminalTitle(agentName) {
return agentName ? `Terminal · ${agentName}` : 'Terminal';
}
/**
* Which optional parts of the top bar still fit. `needed` is the row's width
* with everything showing, `available` the room it has, and `model` and `status`
* the widths of the two parts that can leave. The model text goes first, then
* the status line; both then live in the agent menu's head.
*/
export function barFit({ available, needed, model = 0, status = 0 }) {
if (needed <= available) return { model: true, status: true };
if (needed - model <= available) return { model: false, status: true };
return { model: false, status: false };
}
// The terminal's ANSI palettes, one per theme, tuned against the panel color
// each sits on (--panel: #201d1a dark, #ffffff light): every color keeps at
// least 3:1 against it (the dim "bright black" 4.4:1 and up), and the light
// set is the dark set turned darker, since an agent's greens and yellows
// written for a dark screen wash out on white. The console's own state
// colors (--ok, --stage, --warn, --focus) are the green, yellow, red and blue.
export const TERMINAL_ANSI = Object.freeze({
dark: Object.freeze({
black: '#3a3632', red: '#f0897a', green: '#74c28f', yellow: '#e0ab4c', blue: '#6aa3ff', magenta: '#c49bea', cyan: '#6cc4b8', white: '#d9d3c8',
brightBlack: '#8b8376', brightRed: '#f6a89c', brightGreen: '#93d6a9', brightYellow: '#edc578', brightBlue: '#8fb9ff', brightMagenta: '#d6b6f2', brightCyan: '#8fd8ce', brightWhite: '#f0ece5',
}),
light: Object.freeze({
black: '#1d1a17', red: '#b3261e', green: '#2f6b45', yellow: '#8f620f', blue: '#1f5fbf', magenta: '#7a3fa8', cyan: '#1d6f68', white: '#6b645a',
brightBlack: '#756e62', brightRed: '#c9372c', brightGreen: '#2f7d4f', brightYellow: '#9c6c10', brightBlue: '#2a74d6', brightMagenta: '#8d4fc0', brightCyan: '#237e77', brightWhite: '#4a443c',
}),
});
/** The ANSI palette for a theme ("light" or "dark"; anything else is dark). */
export function terminalAnsi(theme) {
return theme === 'light' ? TERMINAL_ANSI.light : TERMINAL_ANSI.dark;
}
/** `#rrggbb` as an `rgba()` string at `alpha`, for the terminal's selection color. */
export function hexToRgba(hex, alpha) {
const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(String(hex).trim());
if (!m) return `rgba(128, 128, 128, ${alpha})`;
return `rgba(${parseInt(m[1], 16)}, ${parseInt(m[2], 16)}, ${parseInt(m[3], 16)}, ${alpha})`;
}
// --- Waits (A1) -------------------------------------------------------------
/** Milliseconds of waiting for the dashboard before the pane admits it is slow. */
export const STILL_WAITING_MS = 12000;
export const STILL_WAITING_TEXT = 'Still waiting. The agent may be asking you something in its terminal.';
/**
* What the pane says while it waits for the agent to open the dashboard: nothing new for the
* first ~12 s; after that, the "still waiting" line with a way to the terminal (an agent can
* sit on its own prompt: trust this folder, a login, an update notice). An agent that already
* ended gets its own line at once, with Change agent beside the terminal button.
*/
export function waitingView({ waitedMs = 0, agentState = 'running' } = {}) {
if (agentState === 'ended') {
return { still: true, text: 'The agent ended before it opened the dashboard.', showTerminal: true, changeAgent: true };
}
if (waitedMs >= STILL_WAITING_MS) return { still: true, text: STILL_WAITING_TEXT, showTerminal: true, changeAgent: false };
return { still: false, text: null, showTerminal: false, changeAgent: false };
}
// --- Friendly errors (A9) ---------------------------------------------------
// Known raw messages (the handoff's A9 list and the Rust side's own texts), each a
// case-insensitive substring and the sentence that replaces it: what happened, then the
// next step. The raw text is kept for a Details view.
const FRIENDLY_ERRORS = [
['console open printed no json', 'The console did not start properly. Try Reconnect the console; if it keeps failing, run `plan2code update` in a terminal.'],
['console open failed', 'The console could not be opened. Try Reconnect the console; if it keeps failing, run `plan2code update` in a terminal.'],
['console stop failed', 'The console did not stop cleanly. Try Reconnect the console.'],
['the web console is not installed', "Plan2Code's skills are missing. Run `plan2code update` in a terminal, then reopen the app."],
['too old to show inside the app', 'The installed Plan2Code console is too old for this app. Press Update skills, then try again.'],
['no agent has been started', 'There is no agent to restart yet. Start one from the launch card first.'],
['no project folder chosen', 'Choose a project folder first: use Change project in the bar.'],
['an agent is already running for this project', 'An agent is already running for this project. Use New Session to replace it.'],
['not a folder', 'That is not a folder. Choose a folder instead.'],
['could not start the agent', 'The agent could not start. Check that it is installed (Set up an agent) and try again.'],
];
/**
* The shell's error text as a sentence with a next step: `{ text, details }`. `details` is the raw
* message, kept behind a "Details" link. `action` ("start the agent") words an unknown error:
* "Could not start the agent. Try again." A "Could not do that: ..." wrapper is looked through to
* the message inside. An empty input gives an empty text.
*/
export function friendlyError(raw, action = '') {
const rawText = String(raw ?? '').trim();
if (!rawText) return { text: '', details: '' };
const inner = rawText.replace(/^could not do that:\s*/i, '');
const lower = inner.toLowerCase();
const hit = FRIENDLY_ERRORS.find(([needle]) => lower.includes(needle));
if (hit) return { text: hit[1], details: rawText };
if (lower === 'busy') return { text: 'The console is busy. Try again in a moment.', details: rawText };
const sentence = action ? `Could not ${action}. Try again.` : 'That did not work. Try again.';
return { text: sentence, details: rawText };
}
/**
* How the bar and the terminal word an agent that ended, from the host's `reason`: exit code 0
* is a normal close ("closed normally", bar word "closed"), anything else keeps "ended" with its
* reason in plain words.
*/
export function endedView(reason) {
const text = String(reason ?? '').trim();
if (/^exited with code 0$/i.test(text)) return { bar: 'closed', sentence: 'closed normally', normal: true };
const code = /^exited with code (\d+)$/i.exec(text);
if (code) return { bar: 'ended', sentence: `stopped with an error (exit code ${code[1]})`, normal: false };
const signal = /^was ended by a signal \((.+)\)$/i.exec(text);
if (signal) return { bar: 'ended', sentence: `was ended from outside the app (${signal[1]})`, normal: false };
return { bar: 'ended', sentence: text ? `ended: ${text}` : 'ended', normal: false };
}
// --- The confirm modal (A10) ------------------------------------------------
/**
* The confirm modal's buttons: the safe button (Cancel, or "Stay" on the quit check) comes first
* and takes focus, the named danger verb comes last. `safeFirst: false` is for a confirm whose
* primary is the harmless one.
*/
export function confirmButtons({ safeFirst = true } = {}) {
return safeFirst ? { order: ['cancel', 'primary'], focus: 'cancel' } : { order: ['primary', 'cancel'], focus: 'primary' };
}
/** Where Tab goes inside the modal: it wraps, so focus never leaves it. `at` is -1 when focus is outside. */
export function trapTab(shift, at, count) {
if (!(count > 0)) return null;
if (at < 0) return shift ? count - 1 : 0;
return shift ? (at - 1 + count) % count : (at + 1) % count;
}
// --- Shortcuts (A11) --------------------------------------------------------
// The key-to-action table. `shift` is whether Shift is part of the chord.
export const SHORTCUTS = Object.freeze([
{ id: 'toggle-terminal', key: '`', shift: false, tip: 'Show or hide the terminal' },
{ id: 'focus-console', key: '1', shift: false, tip: 'Focus the dashboard' },
{ id: 'focus-terminal', key: '2', shift: false, tip: 'Focus the terminal' },
{ id: 'new-session', key: 'n', shift: true, tip: 'New Session' },
{ id: 'change-project', key: 'o', shift: false, tip: 'Change project' },
{ id: 'preferences', key: ',', shift: false, tip: 'Open User Preferences' },
]);
/**
* The shell action a key press stands for, or null. The chord is Cmd on macOS and Ctrl elsewhere,
* with no Alt. One exception: with the terminal focused on Windows and Linux, Ctrl+O is left to
* the agent (Claude Code uses it for its transcript view); Change project stays in the menu.
*/
export function shortcutAction(event, { mac = false, inTerminal = false } = {}) {
if (!event || event.altKey) return null;
const chord = mac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
if (!chord) return null;
const key = String(event.key || '').toLowerCase();
const hit = SHORTCUTS.find((s) => s.key === key && s.shift === Boolean(event.shiftKey));
if (!hit) return null;
if (hit.id === 'change-project' && inTerminal && !mac) return null;
return hit.id;
}
/** A shortcut as the tooltip writes it: "Ctrl+Shift+N", or "Cmd+Shift+N" on a Mac. */
export function shortcutLabel(id, mac = false) {
const hit = SHORTCUTS.find((s) => s.id === id);
if (!hit) return '';
const key = /^[a-z]$/.test(hit.key) ? hit.key.toUpperCase() : hit.key;
return `${mac ? 'Cmd' : 'Ctrl'}+${hit.shift ? 'Shift+' : ''}${key}`;
}
/** A tooltip: the plain words, then the shortcut in parentheses. */
export function tipWithShortcut(text, id, mac = false) {
const label = shortcutLabel(id, mac);
return label ? `${text} (${label})` : text;
}
/**
* The console page forwards the keys it swallows as `{ plan2code: 'shortcut', id }`; the shell takes
* the id only when it is one of the table's, so the page can ask for nothing else.
*/
export function shortcutFromMessage(data) {
const id = data && data.id;
return typeof id === 'string' && SHORTCUTS.some((s) => s.id === id) ? id : null;
}
// --- Copy and paste (A5) ----------------------------------------------------
/**
* What a key press does in the terminal's clipboard handling: "copy" (Ctrl+Shift+C, Cmd+C, and
* Ctrl+C while text is selected, the Windows Terminal rule: with nothing selected Ctrl+C is the
* interrupt and returns null), "paste" (Ctrl+V, Ctrl+Shift+V, Cmd+V), or null. With `mac`, a plain
* Ctrl+C is always the interrupt, as in every macOS terminal: copy there is Cmd+C.
*/
export function clipboardAction(event, hasSelection, { mac = false } = {}) {
if (!event || event.altKey) return null;
const key = String(event.key || '').toLowerCase();
if (key === 'c') {
if (event.metaKey && !event.ctrlKey) return 'copy';
if (event.ctrlKey && !event.metaKey) return event.shiftKey || (hasSelection && !mac) ? 'copy' : null;
return null;
}
if (key === 'v' && (event.ctrlKey || event.metaKey)) return 'paste';
return null;
}
/**
* A raw failure as one sentence for the bar: the first letter capitalized and a full stop at the end
* ("the update did not finish: npm exited with code 1" becomes "The update did not finish: npm exited
* with code 1."), so the reason itself stays readable where friendlyError's generic line would hide it.
*/
export function reasonSentence(raw) {
const text = String(raw ?? '').trim().replace(/\s+/g, ' ');
if (!text) return 'The update did not finish.';
const cap = text[0].toUpperCase() + text.slice(1);
return /[.!?]$/.test(cap) ? cap : cap + '.';
}
+204 -20
View File
@@ -3,9 +3,39 @@
// Needs xterm.js and addon-fit.js loaded first (they set window.Terminal and
// window.FitAddon), and withGlobalTauri for window.__TAURI__.
import { TERMINAL_FONT_DEFAULT, clipboardAction, hexToRgba, terminalAnsi, terminalFontStep } from './meter.js';
// The same platform test app.js uses for its shortcuts.
const IS_MAC = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent || '');
const { invoke } = window.__TAURI__.core;
export async function mountTerminal(container, { onInput, onResize }) {
// A token's value as the page resolves it now (the theme and highlight are
// custom properties on <html>), or `fallback` when it is not set.
function token(name, fallback) {
const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
return value || fallback;
}
// The xterm theme from the shell's tokens: panel and ink for the screen, the
// highlight for the cursor and selection, and the theme's own ANSI palette.
function buildTheme() {
const theme = document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark';
const accent = token('--accent', '#619fe5');
return {
...terminalAnsi(theme),
background: token('--panel', theme === 'light' ? '#ffffff' : '#201d1a'),
foreground: token('--ink', theme === 'light' ? '#1d1a17' : '#f0ece5'),
cursor: accent,
cursorAccent: token('--panel', theme === 'light' ? '#ffffff' : '#201d1a'),
selectionBackground: hexToRgba(accent, 0.35),
};
}
// `onLink(uri)` opens a link the agent printed (the shell hands it to the opener, http and https
// only); `onShortcut(event)` is true when the shell took the key (meter.js shortcutAction);
// `copyOnSelect` is the saved preference and `onCopyOnSelect(on)` saves a change to it.
export async function mountTerminal(container, { onInput, onResize, onFontSize, onLink, onShortcut, copyOnSelect = false, onCopyOnSelect }) {
// Windows' pseudo-terminal rewraps lines itself; xterm needs to know the
// backend and build to cope with that.
const platform = await invoke('platform_info');
@@ -15,13 +45,24 @@ export async function mountTerminal(container, { onInput, onResize }) {
const term = new window.Terminal({
cursorBlink: true,
fontFamily: 'Consolas, Menlo, "DejaVu Sans Mono", monospace',
fontSize: 13,
// The console's own mono stack, so the terminal and the page read as one.
fontFamily: token('--mono', 'Consolas, Menlo, "DejaVu Sans Mono", monospace'),
fontSize: TERMINAL_FONT_DEFAULT,
theme: buildTheme(),
// An agent written for a dark screen can print colors that vanish on white.
minimumContrastRatio: 4.5,
scrollback: 5000,
windowsPty,
});
const fit = new window.FitAddon.FitAddon();
term.loadAddon(fit);
// URLs an agent prints become links; a click opens them through the shell's opener.
if (window.WebLinksAddon && onLink) {
term.loadAddon(new window.WebLinksAddon.WebLinksAddon((event, uri) => {
event.preventDefault();
onLink(uri);
}));
}
term.open(container);
fit.fit();
@@ -47,35 +88,92 @@ export async function mountTerminal(container, { onInput, onResize }) {
window.addEventListener('resize', refit);
new ResizeObserver(refit).observe(container);
// Copy on selection, and an explicit shortcut for it: Ctrl+C is the pty's
// own interrupt, so Ctrl+Shift+C (Windows, Linux) or Cmd+C (macOS) copies
// instead, without being typed. Ctrl+V / Cmd+V paste from the clipboard
// explicitly, rather than depending on the hidden textarea's own native
// paste making it through every webview the same way.
// A new text size: refit at once, so the pty is told the new columns and rows.
function setFontSize(size) {
if (term.options.fontSize === size) return;
term.options.fontSize = size;
refit();
}
// Copy on selection is a preference (off on Windows and macOS, on for Linux by default: the
// Rust side's serde default): an unconditional copy replaced whatever the person had copied.
let copyOnSelectOn = Boolean(copyOnSelect);
term.onSelectionChange(() => {
if (!copyOnSelectOn) return;
const text = term.getSelection();
if (text && navigator.clipboard) navigator.clipboard.writeText(text).catch(() => {});
});
function copySelection() {
const text = term.getSelection();
if (text && navigator.clipboard) navigator.clipboard.writeText(text).catch(() => {});
}
// Paste goes through term.paste(): bracketed when the agent asked for it, one write, and a
// multi-line paste lands as a paste, not as typed lines.
function pasteClipboard() {
if (!navigator.clipboard) return;
navigator.clipboard
.readText()
.then((text) => {
if (text) term.paste(text);
})
.catch(() => {});
}
term.attachCustomKeyEventHandler((event) => {
if (event.type !== 'keydown' || !navigator.clipboard) return true;
const key = event.key.toLowerCase();
if (key === 'c' && ((event.ctrlKey && event.shiftKey) || (event.metaKey && !event.ctrlKey))) {
const text = term.getSelection();
if (text) navigator.clipboard.writeText(text).catch(() => {});
if (event.type !== 'keydown') return true;
// Ctrl or Cmd with plus, minus or 0 zooms the text; the keys never reach the agent.
if ((event.ctrlKey || event.metaKey) && !event.altKey) {
const size = terminalFontStep(event.key, term.options.fontSize);
if (size !== null) {
setFontSize(size);
if (onFontSize) onFontSize(size);
return false;
}
}
// The shell's own shortcuts (meter.js SHORTCUTS) never reach the agent.
if (onShortcut && onShortcut(event)) {
event.preventDefault();
return false;
}
if (key === 'v' && (event.ctrlKey || event.metaKey)) {
navigator.clipboard
.readText()
.then((text) => {
if (text) onInput(text);
})
.catch(() => {});
// Ctrl+C copies while text is selected and is the interrupt otherwise (the Windows Terminal
// rule; on a Mac it is always the interrupt); Ctrl+Shift+C and Cmd+C always copy.
// preventDefault on the paste keys: the browser's own paste event would otherwise reach the
// terminal a second time.
const action = clipboardAction(event, term.hasSelection(), { mac: IS_MAC });
if (action === 'copy') {
copySelection();
// A plain Ctrl+C that copied clears the selection (as Windows Terminal does), so the next
// Ctrl+C is the interrupt again instead of copying the same text over and over.
if (event.ctrlKey && !event.shiftKey) term.clearSelection();
event.preventDefault();
return false;
}
if (action === 'paste') {
event.preventDefault();
pasteClipboard();
return false;
}
return true;
});
// A small right-click menu: Copy, Paste, Clear, and the copy-on-select switch.
const menu = document.getElementById('term-menu');
if (menu) {
wireContextMenu(container, menu, {
hasSelection: () => term.hasSelection(),
copy: copySelection,
paste: pasteClipboard,
clear: () => term.clear(),
copyOnSelect: () => copyOnSelectOn,
toggleCopyOnSelect: () => {
copyOnSelectOn = !copyOnSelectOn;
if (onCopyOnSelect) onCopyOnSelect(copyOnSelectOn);
},
focus: () => term.focus(),
});
}
return {
size: () => ({ cols: term.cols, rows: term.rows }),
// A fresh agent starts on a clean screen.
@@ -85,5 +183,91 @@ export async function mountTerminal(container, { onInput, onResize }) {
},
write: (data) => term.write(data),
focus: () => term.focus(),
setFontSize,
setCopyOnSelect(on) {
copyOnSelectOn = Boolean(on);
},
paste: pasteClipboard,
// Rebuilds the colors and the font from the tokens as they are now: called
// whenever the console says the theme or highlight changed.
applyTheme() {
term.options.theme = buildTheme();
const family = token('--mono', '');
if (family && term.options.fontFamily !== family) {
term.options.fontFamily = family;
refit();
}
},
};
}
// The context menu: Copy, Paste, Clear and the copy-on-select switch. It opens at the pointer,
// closes on a press elsewhere, Escape, a resize or a blur, and takes focus on its first enabled row.
function wireContextMenu(container, menu, actions) {
const close = () => {
menu.hidden = true;
};
const open = (x, y) => {
const rows = [
['Copy', actions.hasSelection(), actions.copy],
['Paste', true, actions.paste],
['Clear', true, actions.clear],
];
menu.replaceChildren();
for (const [label, enabled, run] of rows) {
const button = document.createElement('button');
button.type = 'button';
button.setAttribute('role', 'menuitem');
button.textContent = label;
button.disabled = !enabled;
button.onclick = () => {
close();
run();
actions.focus();
};
menu.append(button);
}
menu.append(document.createElement('hr'));
const toggle = document.createElement('button');
toggle.type = 'button';
toggle.setAttribute('role', 'menuitemcheckbox');
toggle.setAttribute('aria-checked', String(actions.copyOnSelect()));
const state = document.createElement('span');
state.className = 'term-menu-key';
state.textContent = actions.copyOnSelect() ? 'On' : 'Off';
toggle.append('Copy when I select', state);
toggle.onclick = () => {
close();
actions.toggleCopyOnSelect();
actions.focus();
};
menu.append(toggle);
menu.hidden = false;
menu.style.left = `${Math.max(4, Math.min(x, window.innerWidth - menu.offsetWidth - 4))}px`;
menu.style.top = `${Math.max(4, Math.min(y, window.innerHeight - menu.offsetHeight - 4))}px`;
const first = [...menu.querySelectorAll('button')].find((b) => !b.disabled);
if (first) first.focus();
};
container.addEventListener('contextmenu', (event) => {
event.preventDefault();
open(event.clientX, event.clientY);
});
menu.addEventListener('keydown', (event) => {
const items = [...menu.querySelectorAll('button')].filter((b) => !b.disabled);
const at = items.indexOf(document.activeElement);
if (event.key === 'Escape') {
event.preventDefault();
close();
actions.focus();
} else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
const step = event.key === 'ArrowDown' ? 1 : -1;
items[(at + step + items.length) % items.length].focus();
}
});
document.addEventListener('pointerdown', (event) => {
if (!menu.hidden && !menu.contains(event.target)) close();
});
window.addEventListener('blur', close);
window.addEventListener('resize', close);
}
+38
View File
@@ -0,0 +1,38 @@
// Runs in <head>, before the first paint (a plain script, not a module, so the
// parser waits for it): puts the theme and the highlight the console last told
// the shell on <html>, so a relaunch opens in the right colors with no flash.
// app.js keeps the same two keys current (applyLooks). A script of its own
// because the page's CSP allows no inline script.
(function () {
var root = document.documentElement;
var theme = 'dark';
var shades = null;
try {
var saved = localStorage.getItem('p2c-app:theme');
if (saved === 'light' || saved === 'dark') theme = saved;
var accent = JSON.parse(localStorage.getItem('p2c-app:accent'));
// The shades are saved as { light, dark }; an older launch saved only the
// dark four as an array, which is simply ignored.
if (accent && !Array.isArray(accent) && Array.isArray(accent[theme]) && accent[theme].length === 4) shades = accent[theme];
} catch (e) {
// Nothing saved, or storage is blocked: the dark default and Ocean stand.
}
// The window opens hidden and app.js shows it on the first paint. Should that
// module never get as far (a script error), this shows it after a while, so
// the app is never left invisible.
setTimeout(function () {
try {
window.__TAURI__.window.getCurrentWindow().show();
} catch (e) {
// No window API here: nothing to show.
}
}, 6000);
root.setAttribute('data-theme', theme);
root.style.colorScheme = theme;
if (shades) {
var names = ['--accent', '--accent-soft', '--accent-ink', '--accent-line'];
for (var i = 0; i < names.length; i += 1) {
if (/^#[0-9a-f]{6}$/i.test(shades[i])) root.style.setProperty(names[i], shades[i]);
}
}
})();
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env node
// Writes labeled placeholder pictures for the desktop app and the Implementation
// Loop (docs/screenshots/app-*.webp, loop-*.webp) so the docs and the landing page
// carry their final markup before the owner has captured the real window.
// Replace each file with the real capture (same name, same 2560x1600 size);
// nothing else needs editing. The shot list (state, window size, theme) is in
// specs/polish-3-2/phase-11.md's completion summary. Dev-only.
//
// node scripts/make-app-placeholders.mjs [--browser <path>] [--force]
//
// Never overwrites a file that exists unless --force: a real capture stays.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { launchBrowser } from "./browser.mjs";
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const DIR = path.join(ROOT, "docs", "screenshots");
const SHOTS = [
["app-launch-dark", "The launch card", "Which agent, model and effort to start on"],
["app-terminal-dark", "The app with the terminal docked", "The dashboard beside the agent's terminal"],
["loop-setup-dark", "Implementation Loop setup", "The setup screen before a run"],
["loop-banner-dark", "The Loop mid-run", "The banner while a phase builds"],
["loop-stop-dark", "The Loop's stop screen", "Why it stopped, with the evidence"],
];
const force = process.argv.includes("--force");
const flag = process.argv.indexOf("--browser");
const browser = await launchBrowser(flag > 0 ? { executablePath: process.argv[flag + 1] } : {});
try {
const page = await browser.newPage();
for (const [name, title, line] of SHOTS) {
const out = path.join(DIR, `${name}.webp`);
if (fs.existsSync(out) && !force) {
console.log(`${name}.webp exists, kept`);
continue;
}
const data = await page.evaluate(
([t, l]) => {
const c = document.createElement("canvas");
c.width = 2560;
c.height = 1600;
const g = c.getContext("2d");
g.fillStyle = "#171513";
g.fillRect(0, 0, 2560, 1600);
g.strokeStyle = "#46403a";
g.setLineDash([24, 16]);
g.lineWidth = 4;
g.strokeRect(60, 60, 2440, 1480);
g.fillStyle = "#f0ece5";
g.textAlign = "center";
g.font = "700 96px sans-serif";
g.fillText(t, 1280, 740);
g.fillStyle = "#b6afa3";
g.font = "400 56px sans-serif";
g.fillText(l, 1280, 840);
g.fillStyle = "#e0a24a";
g.font = "600 44px sans-serif";
g.fillText("Placeholder: the real capture goes here", 1280, 960);
return c.toDataURL("image/webp", 0.85).split(",")[1];
},
[title, line],
);
fs.writeFileSync(out, Buffer.from(data, "base64"));
console.log(`${name}.webp ${Math.round(fs.statSync(out).size / 1024)} KB`);
}
} finally {
await browser.close();
}
+780 -32
View File
@@ -11,13 +11,14 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { helloRetryAction, retryLabel, RETRY_AFTER_SECONDS, attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, folderPickerRows, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopRunText, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS, NEW_RELEASE_COMMAND } from "../plan2code-app/ui/meter.js";
import { looksFromMessage, terminalFontStep, TERMINAL_FONT_DEFAULT, TERMINAL_FONT_MIN, TERMINAL_FONT_MAX, splitterFraction, splitterAria, terminalTitle, barFit, terminalAnsi, TERMINAL_ANSI, hexToRgba, helloRetryAction, retryLabel, RETRY_AFTER_SECONDS, attentionSignal, commandSegments, plainCommandText, menuStep, pageNotShownView, pageDetailsLine, redactSessionUrl, barNextSteps, continueKeys, defaultRightFraction, folderName, folderPickerRows, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopRunText, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS, NEW_RELEASE_COMMAND, STILL_WAITING_MS, STILL_WAITING_TEXT, waitingView, friendlyError, endedView, confirmButtons, trapTab, SHORTCUTS, shortcutAction, shortcutLabel, tipWithShortcut, shortcutFromMessage, clipboardAction, releaseAfterCheck, releaseNotesUrl, reasonSentence, UPDATE_RECHECK_MS } from "../plan2code-app/ui/meter.js";
import { findBrowser, launchBrowser } from "./browser.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const INDEX_HTML_PATH = path.join(HERE, "../plan2code-app/ui/index.html");
const APP_JS = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/app.js"), "utf8");
const INDEX_HTML = fs.readFileSync(INDEX_HTML_PATH, "utf8");
const METER_JS = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/meter.js"), "utf8");
test("barNextSteps offers nothing while the console runs and the versions agree", () => {
assert.deepEqual(barNextSteps(), []);
@@ -38,32 +39,77 @@ test("only one control for reconnecting the console is ever offered: after an up
assert.deepEqual(steps.map((step) => step.action), ["restart-console"], "the plain reconnect steps aside for the one that stops the old console first");
});
test("a newer GitHub release is offered last, with the command to copy; a mismatch or a stopped console comes first", () => {
test("a newer GitHub release is offered last, as Update and restart with a What's new link; a mismatch or a stopped console comes first", () => {
const newRelease = { latest: "3.0.1" };
const ids = (input) => barNextSteps(input).map((step) => step.id);
assert.deepEqual(ids({ newRelease }), ["new-release"]);
assert.deepEqual(ids({ consoleDead: true, version: { kind: "mismatch", skills: "3.0.0", app: "3.1.0" }, newRelease }), ["console-dead", "mismatch", "new-release"]);
const [step] = barNextSteps({ newRelease });
assert.equal(step.text, "Update available: v3.0.1");
assert.equal(step.label, "Copy update command");
assert.equal(step.action, "copy-update");
assert.equal(NEW_RELEASE_COMMAND, "plan2code update");
assert.equal(step.label, "Update and restart");
assert.equal(step.action, "update-restart");
assert.deepEqual(step.link, { label: "What's new", url: "https://github.com/jparkerweb/plan2code/releases/tag/v3.0.1" });
assert.equal(releaseNotesUrl("v3.0.1"), step.link.url, "a leading v is not doubled");
assert.equal(NEW_RELEASE_COMMAND, "plan2code update", "still the fallback command a failed update names");
assert.deepEqual(barNextSteps({ newRelease: null }), [], "nothing newer, nothing shown");
});
test("after the copy the bar says what to do next; if the clipboard was refused it spells the command out", () => {
const [copied] = barNextSteps({ newRelease: { latest: "3.0.1", copied: true } });
assert.match(copied.text, /^Copied: run `plan2code update` in a terminal/);
assert.equal(copied.action, null);
const [manual] = barNextSteps({ newRelease: { latest: "3.0.1", manual: true } });
assert.match(manual.text, /^Run `plan2code update` in a terminal/);
assert.equal(manual.action, null);
test("the update states: running shows its line and no button, a failure keeps the app up and says why, an installed one offers the restart", () => {
const [running] = barNextSteps({ newRelease: { latest: "3.2.0", updating: "Installing skills (4 of 9)" } });
assert.deepEqual([running.text, running.busy, running.action, running.link ?? null], ["Installing skills (4 of 9)", true, null, null]);
const [starting] = barNextSteps({ newRelease: { latest: "3.2.0", updating: "" } });
assert.equal(starting.text, "Updating to v3.2.0...", "a first line before the installer says anything");
const [failed] = barNextSteps({ newRelease: { latest: "3.2.0", failed: "The update did not finish: npm exited with code 1." } });
assert.deepEqual([failed.text, failed.tone, failed.action, failed.label], ["Update failed", "err", "update-restart", "Update and restart"], "it can be tried again");
assert.match(failed.title, /^The update did not finish: npm exited with code 1\. Plan2Code is still running as it was\./, "the reason, in full, for the tooltip and the list");
assert.match(failed.title, /run `plan2code update` in a terminal/, "the old way stays as the fallback");
const [restart] = barNextSteps({ newRelease: { latest: "3.2.0", restartNeeded: true } });
assert.deepEqual([restart.text, restart.action, restart.label, restart.tone], ["Updated to v3.2.0", "restart-app", "Restart Plan2Code", "ok"]);
const [problem] = barNextSteps({ newRelease: { problem: "Could not check for updates: git was not found on PATH." } });
assert.deepEqual([problem.id, problem.text, problem.action], ["update-check", "Could not check for updates", null], "a missing git is said, not silent");
assert.match(problem.title, /git was not found/);
const [same] = barNextSteps({ notReplaced: "3.1.0" });
assert.deepEqual([same.id, same.text, same.tone, same.action], ["not-replaced", "App not replaced", "warn", null], "the same version after a restart is not 'Updated to'");
assert.match(same.title, /no desktop app for this system yet, so Plan2Code is still on v3\.1\.0\./);
const [after] = barNextSteps({ updatedTo: "3.2.0" });
assert.deepEqual([after.id, after.text, after.tone, after.action], ["updated-to", "Updated to v3.2.0", "ok", null]);
});
test("the app asks once at start for a newer release, and the bar is wired to the copy action", () => {
test("releaseAfterCheck: a recheck never replaces a running or finished update, finds a version, reports a problem and clears an old one", () => {
assert.deepEqual(releaseAfterCheck(null, { latest: "3.2.0", problem: null }), { latest: "3.2.0" });
assert.deepEqual(releaseAfterCheck(null, { latest: null, problem: "Could not check for updates: git was not found on PATH." }), { problem: "Could not check for updates: git was not found on PATH." });
assert.equal(releaseAfterCheck({ latest: "3.2.0" }, { latest: null, problem: null }), null, "current now: the old notice goes");
assert.equal(releaseAfterCheck({ problem: "x" }, { latest: null, problem: null }), null);
const running = { latest: "3.2.0", updating: "Installing" };
assert.equal(releaseAfterCheck(running, { latest: "3.2.0" }), running, "an update that runs is left alone");
const waiting = { latest: "3.2.0", restartNeeded: true };
assert.equal(releaseAfterCheck(waiting, { latest: "3.3.0" }), waiting, "so is one waiting for its restart");
assert.equal(releaseAfterCheck(null, null), null, "no answer, nothing to show");
assert.equal(UPDATE_RECHECK_MS, 4 * 60 * 60 * 1000, "every few hours, not once per launch");
});
test("reasonSentence keeps the installer's reason readable: a capital and a full stop", () => {
assert.equal(reasonSentence("the update did not finish: npm exited with code 1"), "The update did not finish: npm exited with code 1.");
assert.equal(reasonSentence("Already a sentence."), "Already a sentence.");
assert.equal(reasonSentence(" two spaces "), "Two spaces.");
assert.equal(reasonSentence(""), "The update did not finish.");
});
test("the app asks at start and every few hours for a newer release, and the bar is wired to Update and restart", () => {
assert.match(APP_JS, /invoke\('check_new_release'\)/);
assert.match(APP_JS, /'copy-update': copyUpdateCommand/);
assert.match(APP_JS, /barNextSteps\(\{ consoleDead, version: versionState, newRelease \}\)/);
assert.match(APP_JS, /setInterval\(checkNewRelease, UPDATE_RECHECK_MS\)/);
assert.match(APP_JS, /'update-restart': \(\) => updateAndRestart\(\)/);
assert.match(APP_JS, /'restart-app': \(\) => restartApp\(\)/);
assert.doesNotMatch(APP_JS, /copyUpdateCommand|'copy-update'/, "the copy-the-command flow is gone");
const update = APP_JS.slice(APP_JS.indexOf("async function updateAndRestart"), APP_JS.indexOf("async function restartApp"));
assert.match(update, /invoke\('update_to_newest', \{ progress \}\)/, "the unpinned update, through the progress channel");
assert.match(update, /setNewRelease\(\{ latest, failed: reasonSentence\(error\) \}\);\s*\n\s*return;/, "a failure returns before any restart");
const restart = APP_JS.slice(APP_JS.indexOf("async function restartApp"), APP_JS.indexOf("async function showUpdatedTo"));
assert.match(restart, /invoke\('restart_app', \{ confirmed: false \}\)/, "the quit check guards the respawn");
assert.match(APP_JS, /if \(state\.updatedFrom\) void showUpdatedTo\(\);/, "Updated to vX once after the restart");
const noted = APP_JS.slice(APP_JS.indexOf("async function showUpdatedTo"), APP_JS.indexOf("// The About dialog"));
assert.match(noted, /now === appState\.updatedFrom[\s\S]*?notReplaced = now;/, "an unchanged version is said so, never 'Updated to' it");
assert.match(APP_JS, /barNextSteps\(\{ consoleDead, version: versionState, newRelease, updatedTo, notReplaced \}\)/);
});
test("each version state reads and acts as the old version bar did", () => {
@@ -91,7 +137,7 @@ test("every control that reconnects the console carries the same label, never 'R
});
test("app.js draws the bar's right end through barNextSteps, not a hand-rolled copy of its order", () => {
assert.match(APP_JS, /const steps = barNextSteps\(\{ consoleDead, version: versionState, newRelease \}\);/);
assert.match(APP_JS, /const steps = barNextSteps\(\{ consoleDead, version: versionState, newRelease, updatedTo, notReplaced \}\);/);
for (const gone of ["console-again", "version-update", "permissions-note", "console-status", "project-dir"]) {
assert.ok(!INDEX_HTML.includes(`id="${gone}"`), `index.html still has #${gone}`);
}
@@ -196,12 +242,15 @@ test("app.js never sets statePlannyEl.hidden directly: SVGElement does not refle
assert.match(APP_JS, /statePlannyEl\.toggleAttribute\('hidden', !tired\)/);
});
test("the Restart confirmation no longer claims unsaved work, and offers New Session with the tired Planny", () => {
const confirmRestart = APP_JS.slice(APP_JS.indexOf("function confirmRestart"), APP_JS.indexOf("function confirmRestart") + 600);
assert.doesNotMatch(confirmRestart, /not saved/, "not always true, so it is gone from this dialog specifically");
assert.match(confirmRestart, /'Restart the agent on a fresh context window\?',\s*\n\s*'New Session',/);
assert.match(confirmRestart, /\{ tired: true \}/, "the confirm dialog asks for the tired Planny");
assert.match(INDEX_HTML, /<svg id="dashboard-state-planny"[^>]*hidden>/, "the tired Planny starts hidden in the markup");
test("the Restart confirmation is the shell modal, with New Session as its danger verb and Cancel first", () => {
const confirmRestart = APP_JS.slice(APP_JS.indexOf("async function confirmRestart"), APP_JS.indexOf("function showTerminal"));
assert.match(confirmRestart, /await confirmModal\(\{\s*title: 'Restart the agent on a fresh context window\?'/);
assert.match(confirmRestart, /primary: 'New Session',\s*\n\s*danger: true,/);
assert.doesNotMatch(confirmRestart, /showState\(\s*'Restart the agent/, "no longer drawn over the dashboard pane");
// The first frame is "Starting Plan2Code" with a plain Planny (no mug); showState hides or restyles it from then on.
assert.match(INDEX_HTML, /<svg id="dashboard-state-planny" class="is-plain"[^>]*>/, "the plain Planny is in the markup, visible");
assert.doesNotMatch(INDEX_HTML, /<svg id="dashboard-state-planny"[^>]*hidden>/);
assert.match(INDEX_HTML, /<div id="dashboard-state">\s*[\s\S]*?<p id="dashboard-state-text">Starting Plan2Code<\/p>/, "visible from the first frame, saying so");
});
test("defaultRightFraction gives the terminal a roomy width when the window has space for it, down to the floor when it does not", () => {
@@ -228,7 +277,7 @@ test("with nothing saved yet, app.js starts the terminal docked right via defaul
// Docked right and collapsed, the terminal panel is a 28px-wide strip: the
// collapse button's text used to run horizontally off the edge of it
// (visible, unreadable). It now reads top-to-bottom instead.
test("docked right and collapsed, the terminal panel's View Agent Terminal button fits the strip instead of overflowing it", async (t) => {
test("docked right and collapsed, the terminal panel's pill and expand button fit the strip instead of overflowing it", async (t) => {
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
const browser = await launchBrowser();
try {
@@ -238,19 +287,23 @@ test("docked right and collapsed, the terminal panel's View Agent Terminal butto
await page.evaluate(() => {
document.getElementById("workspace").classList.add("dock-right");
document.getElementById("term-panel").classList.add("collapsed");
document.getElementById("term-collapse").textContent = "View Agent Terminal";
document.getElementById("term-collapse").setAttribute("aria-pressed", "true");
document.getElementById("term-badge").hidden = false;
});
const fit = await page.evaluate(() => {
const el = document.getElementById("term-collapse");
return {
writingMode: getComputedStyle(el).writingMode,
overflowsWidth: el.scrollWidth > el.clientWidth,
overflowsPanel: el.getBoundingClientRect().right > document.getElementById("term-panel").getBoundingClientRect().right,
const panel = document.getElementById("term-panel").getBoundingClientRect();
const measure = (id) => {
const el = document.getElementById(id);
const box = el.getBoundingClientRect();
return { writingMode: getComputedStyle(el).writingMode, overflowsWidth: el.scrollWidth > el.clientWidth, spills: box.right > panel.right + 0.5 || box.left < panel.left - 0.5 };
};
return { pill: measure("term-badge"), expand: measure("term-collapse"), titleShown: getComputedStyle(document.getElementById("term-title")).display !== "none" };
});
assert.equal(fit.writingMode, "vertical-rl", "the label is set to run top-to-bottom, not sideways");
assert.equal(fit.overflowsWidth, false, "the label text does not overflow its own box");
assert.equal(fit.overflowsPanel, false, "the button does not spill past the collapsed panel's edge");
assert.equal(fit.pill.writingMode, "vertical-rl", "the pill's label runs top-to-bottom, not sideways");
assert.equal(fit.pill.overflowsWidth, false, "the pill's text does not overflow its own box");
assert.equal(fit.pill.spills, false, "the pill does not spill past the collapsed panel's edge");
assert.equal(fit.expand.spills, false, "the expand button does not spill past the collapsed panel's edge");
assert.equal(fit.titleShown, false, "the title has no room in the strip");
} finally {
await browser.close();
}
@@ -549,3 +602,698 @@ test("main.rs guards the window's agent and project commands, and registers loop
assert.ok(!body("agent_input").includes("refuse_while_looping"), "typing stays open for a trust or login prompt");
assert.match(rust, /generate_handler!\[[\s\S]*?loop_stop_now,\s*loop_state,/);
});
// The string literals of a JavaScript source (quoted and template text), with
// comments and regular expressions skipped: enough of a tokenizer for the
// shell's own files, which the test below holds to the em dash rule (the same
// rule quit_prompt.rs's tests hold its strings to).
function stringLiterals(source) {
const out = [];
const braces = []; // one entry per open `${`, holding the brace depth inside it
let i = 0;
let last = ""; // the last significant code character, to tell a regex from a division
const regexCanStart = () => last === "" || "(,=:[!&|?{};+-*%<>~^".includes(last) || /\b(return|typeof|case|in|of)$/.test(source.slice(Math.max(0, i - 7), i));
const readTemplate = () => {
let text = "";
while (i < source.length) {
const c = source[i];
if (c === "\\") {
text += source.slice(i, i + 2);
i += 2;
continue;
}
if (c === "`") {
i += 1;
out.push(text);
return;
}
if (c === "$" && source[i + 1] === "{") {
i += 2;
out.push(text);
braces.push(0);
return;
}
text += c;
i += 1;
}
};
while (i < source.length) {
const c = source[i];
const next = source[i + 1];
if (/\s/.test(c)) {
i += 1;
continue;
}
if (c === "/" && next === "/") {
i = source.indexOf("\n", i);
if (i < 0) break;
continue;
}
if (c === "/" && next === "*") {
i = source.indexOf("*/", i + 2) + 2;
continue;
}
if (c === "'" || c === '"') {
let j = i + 1;
let text = "";
while (j < source.length && source[j] !== c) {
if (source[j] === "\\") {
text += source.slice(j, j + 2);
j += 2;
} else {
text += source[j];
j += 1;
}
}
out.push(text);
i = j + 1;
last = c;
continue;
}
if (c === "`") {
i += 1;
readTemplate();
last = "`";
continue;
}
if (c === "/" && regexCanStart()) {
let j = i + 1;
let inClass = false;
while (j < source.length && (inClass || source[j] !== "/")) {
if (source[j] === "\\") j += 1;
else if (source[j] === "[") inClass = true;
else if (source[j] === "]") inClass = false;
j += 1;
}
i = j + 1;
while (/[a-z]/i.test(source[i] || "")) i += 1;
last = "/";
continue;
}
if (braces.length && c === "{") braces[braces.length - 1] += 1;
if (braces.length && c === "}") {
if (braces[braces.length - 1] === 0) {
braces.pop();
i += 1;
readTemplate();
last = "`";
continue;
}
braces[braces.length - 1] -= 1;
}
last = c;
i += 1;
}
return out;
}
test("stringLiterals finds the strings and skips comments and regular expressions", () => {
const sample = [
"// a comment \u2014 here",
"const a = 'one'; /* \u2014 */ const b = \"two\";",
"const re = /'not a string'/g;",
"const t = `x ${a ? 'in' : `deep ${b}`} y`;",
"const half = 4 / 2; const c = 'after / division';",
].join("\n");
assert.deepEqual(stringLiterals(sample), ["one", "two", "x ", "in", "deep ", "", " y", "after / division"]);
assert.ok(stringLiterals("const s = 'bad \u2014 dash';").some((text) => text.includes("\u2014")), "a dash inside a string is seen");
assert.ok(stringLiterals("const s = `bad ${x} \u2014 dash`;").some((text) => text.includes("\u2014")), "and inside template text after a placeholder");
});
test("no string in the shell's meter.js or app.js holds an em dash (U+2014)", () => {
for (const [name, source, probe] of [["meter.js", METER_JS, "Reload the page"], ["app.js", APP_JS, "Reloading the page..."]]) {
const strings = stringLiterals(source);
assert.ok(strings.length > 50, `${name}: the tokenizer read its strings (${strings.length})`);
assert.ok(strings.includes(probe), `${name}: the scan reaches the messages it guards`);
for (const text of strings) assert.ok(!text.includes("\u2014"), `${name}: ${text}`);
}
});
test("the first-run checklist's Node row joins version and path with a colon", () => {
assert.match(APP_JS, /const nodeDetail = `\$\{state\.nodeVersion \|\| 'found'\} \(18 or newer\)\$\{state\.nodeBinary \? `: \$\{state\.nodeBinary\}` : ''\}`;/);
});
test("commandSegments puts each backticked command in its own piece, and plainCommandText quotes it for a tooltip", () => {
assert.deepEqual(commandSegments("not found; run `plan2code update`"), [
{ text: "not found; run ", code: false },
{ text: "plan2code update", code: true },
]);
assert.deepEqual(commandSegments("Run `a` then `b`."), [
{ text: "Run ", code: false },
{ text: "a", code: true },
{ text: " then ", code: false },
{ text: "b", code: true },
{ text: ".", code: false },
]);
assert.deepEqual(commandSegments("plain"), [{ text: "plain", code: false }]);
assert.deepEqual(commandSegments("a stray ` stays"), [{ text: "a stray ` stays", code: false }]);
assert.deepEqual(commandSegments(""), []);
assert.deepEqual(commandSegments(null), []);
assert.equal(plainCommandText("Run `plan2code update` in a terminal."), 'Run "plan2code update" in a terminal.');
const [failed] = barNextSteps({ newRelease: { latest: "3.0.1", failed: "The update did not finish." } });
assert.ok(commandSegments(failed.title).some((part) => part.code && part.text === NEW_RELEASE_COMMAND), "a failed update names the command it falls back to, marked as one");
});
test("app.js draws commands in <code> for the bar's next step, the agent status line and the checklist, never as literal backticks", () => {
assert.match(APP_JS, /function commandNodes\(text\) \{[\s\S]*?document\.createElement\('code'\)[\s\S]*?code\.textContent = part\.text;/, "built as nodes, not parsed markup");
assert.match(APP_JS, /nextStepTextEl\.replaceChildren\(\.\.\.commandNodes\(/);
assert.match(APP_JS, /nextStepTextEl\.title = first \? plainCommandText\(first\.title\)/);
assert.match(APP_JS, /agentStatusEl\.replaceChildren\(\.\.\.commandNodes\(text\)\)/);
assert.match(APP_JS, /agentStatusEl\.title = plainCommandText\(text\)/);
assert.match(APP_JS, /if \(typeof detail === 'string'\) detailEl\.append\(\.\.\.commandNodes\(detail\)\)/);
assert.doesNotMatch(APP_JS, /nextStepTextEl\.textContent =|agentStatusEl\.textContent = text/, "no plain-text path left beside them");
});
test("menuStep moves through a menu's items: Up and Down wrap, Home and End go to the ends", () => {
assert.equal(menuStep("ArrowDown", -1, 3), 0, "from outside the items, Down takes the first");
assert.equal(menuStep("ArrowUp", -1, 3), 2, "and Up the last");
assert.equal(menuStep("ArrowDown", 0, 3), 1);
assert.equal(menuStep("ArrowDown", 2, 3), 0, "Down wraps");
assert.equal(menuStep("ArrowUp", 0, 3), 2, "Up wraps");
assert.equal(menuStep("Home", 2, 3), 0);
assert.equal(menuStep("End", 0, 3), 2);
assert.equal(menuStep("ArrowDown", 0, 1), 0, "one item stays put");
assert.equal(menuStep("ArrowDown", -1, 0), null, "nothing to move to");
assert.equal(menuStep("a", 0, 3), null, "any other key is left alone");
assert.equal(menuStep("Enter", 0, 3), null);
});
test("opening a bar menu focuses its first item, and Up, Down, Home and End move between items", () => {
const toggle = APP_JS.slice(APP_JS.indexOf("function toggleBarMenu"), APP_JS.indexOf("projectMenuBtn.onclick"));
assert.match(toggle, /const \[first\] = barMenuItems\(menu\);\s*\(first \|\| menu\)\.focus\(\);/, "the first item, or the menu itself when none can take focus");
assert.match(APP_JS, /function barMenuItems\(menu\) \{[\s\S]*?\[role="menuitem"\][\s\S]*?!item\.hidden && !item\.disabled/);
assert.match(APP_JS, /menuStep\(event\.key, items\.indexOf\(document\.activeElement\), items\.length\)/);
assert.match(APP_JS, /projectMenu\.addEventListener\('keydown', onBarMenuKey\);/);
assert.match(APP_JS, /agentMenu\.addEventListener\('keydown', onBarMenuKey\);/);
for (const id of ["project-menu", "agent-menu"]) {
assert.match(INDEX_HTML, new RegExp(`<div id="${id}"[^>]*role="menu"[^>]*tabindex="-1"`), `#${id} can hold focus when every item is off`);
}
});
test("the checklist's marks and the quiet dot are named for a screen reader", () => {
const row = APP_JS.slice(APP_JS.indexOf("function firstRunRow"), APP_JS.indexOf("function renderFirstRun"));
assert.match(row, /mark\.setAttribute\('role', 'img'\);/);
assert.match(row, /mark\.setAttribute\('aria-label', pass \? 'Ready' : 'Needs attention'\);/);
// The quiet mark is a labeled pill in words, a button that opens the terminal.
assert.match(INDEX_HTML, /<button id="term-badge" type="button"[^>]*>Agent may need you<\/button>/);
});
test("the shell has one :focus-visible ring, from the tokens", () => {
const rings = INDEX_HTML.match(/[^{}\n]*:focus-visible[^{]*\{[^}]*outline[^}]*\}/g) || [];
assert.equal(rings.length, 1, rings.join("\n"));
assert.match(rings[0], /outline: 2px solid var\(--focus-ring, var\(--accent\)\)/);
assert.match(rings[0], /\[role="separator"\]/, "the splitter wears the same ring, not the global blue one");
assert.match(INDEX_HTML, /#loop-banner \{[^}]*--focus-ring: var\(--banner-color\)/, "the loop banner keeps its own ring color through the token");
});
test("every confirm goes through the shell modal: New Session, Stop now and Change project, with nothing drawn over the dashboard", () => {
assert.doesNotMatch(APP_JS, /leaveConfirm|shownStateNow/, "the in-page confirm's put-it-back code is gone with the confirm");
const stop = APP_JS.slice(APP_JS.indexOf("loopStopNowBtn.onclick"), APP_JS.indexOf("function renderNextStep"));
assert.match(stop, /await confirmModal\(\{\s*title: 'End the agent now\?'/);
assert.match(stop, /primary: 'Stop now',\s*\n\s*danger: true,/);
const change = APP_JS.slice(APP_JS.indexOf("async function changeProject"), APP_JS.indexOf("changeProjectBtn.onclick"));
assert.match(change, /await confirmModal\(\{\s*title: 'Stop the running agent and switch to a different project\?'/);
assert.match(change, /if \(!yes\) return;/, "Cancel changes nothing");
assert.doesNotMatch(APP_JS, /showState\('No dashboard has loaded yet\./, "no bare-line state is left to land in");
const show = APP_JS.slice(APP_JS.indexOf("function showState"), APP_JS.indexOf("function showErrorState"));
assert.match(show, /shownState = \{ text, buttonLabel, onButton, onCancel, options \};/);
assert.match(APP_JS, /function hideState\(\) \{[^}]*shownState = null;/);
});
test("pageNotShownView: Reload the page first, then 'still did not load' with Reconnect the console first", () => {
const first = pageNotShownView(1);
assert.equal(first.text, "The console is running but its page did not show in this window.");
assert.deepEqual(first.primary, { action: "reload", label: "Reload the page" });
assert.equal(first.secondary, null);
for (const n of [2, 3, 7]) {
const again = pageNotShownView(n);
assert.equal(again.text, "The page still did not load.");
assert.deepEqual(again.primary, { action: "reconnect", label: "Reconnect the console" });
assert.deepEqual(again.secondary, { action: "reload", label: "Reload the page" });
}
assert.equal(pageNotShownView(2).primary.label, NEXT_STEP_LABELS.reconnect, "the same label as every other reconnect");
});
test("pageDetailsLine carries the session URL with its key hidden and the last health check", () => {
assert.equal(redactSessionUrl("http://127.0.0.1:51234/s/AbC_123-xyz"), "http://127.0.0.1:51234/s/...");
assert.equal(redactSessionUrl("http://127.0.0.1:51234/s/AbC/?x=1"), "http://127.0.0.1:51234/s/.../?x=1");
assert.equal(redactSessionUrl("http://127.0.0.1:51234/"), "http://127.0.0.1:51234/");
assert.equal(redactSessionUrl(null), "");
assert.equal(pageDetailsLine({ url: "http://127.0.0.1:5000/s/secret", health: "running" }), "Details: session http://127.0.0.1:5000/s/...; health check: running");
assert.equal(pageDetailsLine({ url: null, health: null }), "Details: session none; health check: no answer");
});
test("app.js counts page failures in a row, offers stop-then-start, and shows the Details line", () => {
const noHello = APP_JS.slice(APP_JS.indexOf("async function onNoHello"), APP_JS.indexOf("function showState"));
assert.match(noHello, /pageFailures \+= 1;\s*const view = pageNotShownView\(pageFailures\);/);
assert.match(noHello, /const actions = \{ reload: reloadPage, reconnect: stopAndReconnect \};/);
assert.match(noHello, /pageDetailsLine\(\{ url: currentUrl \|\| status\.url, health: status\.state \}\)/);
assert.match(noHello, /showState\(view\.text, view\.primary\.label, actions\[view\.primary\.action\], undefined, \{ secondary, details \}\)/);
assert.match(noHello, /async function stopAndReconnect\(\) \{[\s\S]*?invoke\('console_stop'\)[\s\S]*?await reconnectConsole\(\);/, "stop, then start");
assert.match(APP_JS, /kind === 'console-ready'\) \{\s*frameReady = true;\s*pageFailures = 0;/, "a hello ends the run of failures");
const announced = APP_JS.slice(APP_JS.indexOf("function showAnnounced"), APP_JS.indexOf("window.__TAURI__.event.listen('console-page'"));
assert.match(announced, /pageFailures = 0;/, "a new page starts over");
assert.match(INDEX_HTML, /<button id="dashboard-state-secondary" hidden><\/button>/);
assert.match(INDEX_HTML, /<p id="dashboard-state-details" hidden><\/p>/);
assert.match(INDEX_HTML, /#dashboard-state-details \{[^}]*color: var\(--ink-3\)/, "muted");
});
// ---- Phase 9: the shell shares the console's tokens and theme ----
const SHADES_LIGHT = ["#206cc3", "#ecf2f9", "#ffffff", "#9ab4d3"];
const SHADES_DARK = ["#619fe5", "#1a2533", "#0c1117", "#3d5978"];
test("looksFromMessage takes the resolved theme with both shade sets, and nothing that does not match their shapes", () => {
assert.deepEqual(looksFromMessage({ plan2code: "looks", accent: SHADES_DARK, theme: "light", light: SHADES_LIGHT, dark: SHADES_DARK }), { theme: "light", light: SHADES_LIGHT, dark: SHADES_DARK });
assert.deepEqual(looksFromMessage({ theme: "dark", light: SHADES_LIGHT, dark: SHADES_DARK }).theme, "dark");
assert.deepEqual(looksFromMessage({ accent: SHADES_DARK }), { theme: "dark", light: null, dark: SHADES_DARK }, "a page that predates the theme keeps the shell dark in its highlight");
for (const bad of [
null, undefined, "dark", 7, [], {},
{ theme: "system", light: SHADES_LIGHT, dark: SHADES_DARK },
{ theme: "dark", light: SHADES_LIGHT },
{ theme: "dark", dark: SHADES_DARK },
{ theme: "dark", light: SHADES_LIGHT, dark: ["#619fe5", "#1a2533", "#0c1117"] },
{ theme: "dark", light: SHADES_LIGHT, dark: ["#619fe5", "#1a2533", "#0c1117", "red"] },
{ theme: "dark", light: SHADES_LIGHT, dark: ["#619fe5", "#1a2533", "#0c1117", "#3d5978; x:y"] },
{ theme: "dark", light: SHADES_LIGHT, dark: ["#619fe5", "#1a2533", "#0c1117", 5] },
{ accent: ["#619fe5", "red", "#0c1117", "#3d5978"] },
]) assert.equal(looksFromMessage(bad), null, JSON.stringify(bad));
});
test("the shell applies the looks message through meter.js and keeps the theme beside the accent for the next launch", () => {
assert.match(APP_JS, /const looks = looksFromMessage\(event\.data\);\s+if \(looks\) applyLooks\(looks, \{ save: true \}\);/);
assert.match(APP_JS, /root\.setAttribute\('data-theme', theme\);/);
assert.match(APP_JS, /localStorage\.setItem\(THEME_KEY, theme\);\s+localStorage\.setItem\(ACCENT_KEY, JSON\.stringify\(\{ light, dark \}\)\);/);
assert.match(APP_JS, /terminal\.applyTheme\(\);\s+setWindowTheme\(theme\);/, "the terminal and the OS title bar follow every change");
assert.match(APP_JS, /getCurrentWindow\(\)\.setTheme\(theme\)/);
assert.doesNotMatch(APP_JS, /applyAccent/, "the dark-only accent path is gone");
const early = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/theme-early.js"), "utf8");
assert.match(early, /p2c-app:theme/);
assert.match(early, /p2c-app:accent/);
assert.match(INDEX_HTML, /<script src="theme-early\.js"><\/script>/, "a classic script in the head, so it runs before the first paint");
assert.ok(INDEX_HTML.indexOf("theme-early.js") < INDEX_HTML.indexOf("<style>"));
assert.match(APP_JS, /getCurrentWindow\(\)\.show\(\)/, "the window opens hidden and is shown on the first paint");
const conf = JSON.parse(fs.readFileSync(path.join(HERE, "../plan2code-app/src-tauri/tauri.conf.json"), "utf8"));
const win = conf.app.windows[0];
assert.equal(win.visible, false);
assert.equal(win.maximized, undefined, "maximizing is left to the first run in main.rs");
assert.ok(win.minWidth >= 900 && win.minHeight >= 500);
assert.match(win.backgroundColor, /^#[0-9a-f]{6}$/i);
});
test("the console's looks message carries the resolved theme and both shade sets", () => {
const looksJs = fs.readFileSync(path.join(HERE, "../src/web-console/public/looks.js"), "utf8");
assert.match(looksJs, /tellApp\("looks", \{ accent: ACCENTS\[looks\.accent\]\.dark, theme: effectiveTheme\(\), light: ACCENTS\[looks\.accent\]\.light, dark: ACCENTS\[looks\.accent\]\.dark \}\);/);
const screen = fs.readFileSync(path.join(HERE, "../src/web-console/public/screens/looks.js"), "utf8");
assert.match(screen, /matchMedia\("\(prefers-color-scheme: dark\)"\)\.addEventListener\("change", \(\) => \{\s+if \(looks\.theme === "system"\) \{\s+applyLooks\(\);/, "a system theme flip re-runs applyLooks, which tells the shell; looks.js adds no second listener");
assert.doesNotMatch(looksJs, /addEventListener\("change"/);
});
test("the shell takes its colors from the console's tokens.css, copied by vendor.mjs, and holds no literal color", () => {
const vendor = fs.readFileSync(path.join(HERE, "../plan2code-app/scripts/vendor.mjs"), "utf8");
assert.match(vendor, /'\.\.\/src\/web-console\/public\/styles\/tokens\.css', 'tokens\.css'/);
const link = INDEX_HTML.indexOf('href="vendor/tokens.css"');
assert.ok(link > 0 && link < INDEX_HTML.indexOf("<style>"), "linked before the shell's own styles");
const css = INDEX_HTML.slice(INDEX_HTML.indexOf("<style>"), INDEX_HTML.indexOf("</style>")).replace(/\/\*[\s\S]*?\*\//g, "");
assert.doesNotMatch(css, /#[0-9a-fA-F]{3,8}\b/, "no hex color left in the styles");
assert.doesNotMatch(css, /\brgba?\(/, "no rgb color left in the styles");
assert.doesNotMatch(css, /:root\s*\{[^}]*--(panel|ink|accent)\b/, "the dark token block is gone");
});
test("the terminal's font steps stay inside the saved range and the keys reach nothing else", () => {
assert.equal(TERMINAL_FONT_DEFAULT, 13);
assert.equal(terminalFontStep("+", 13), 14);
assert.equal(terminalFontStep("=", 13), 14);
assert.equal(terminalFontStep("-", 13), 12);
assert.equal(terminalFontStep("0", 20), 13);
assert.equal(terminalFontStep("+", TERMINAL_FONT_MAX), TERMINAL_FONT_MAX);
assert.equal(terminalFontStep("-", TERMINAL_FONT_MIN), TERMINAL_FONT_MIN);
assert.equal(terminalFontStep("a", 13), null);
assert.equal(terminalFontStep("_", 13), null, "Ctrl+Shift+minus is a readline undo, left to the agent");
assert.equal(terminalFontStep("ArrowUp", 13), null);
assert.equal(terminalFontStep("+", NaN), 14, "no size yet steps from the default");
const term = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/terminal.js"), "utf8");
assert.match(term, /\(event\.ctrlKey \|\| event\.metaKey\) && !event\.altKey/);
assert.match(term, /terminalFontStep\(event\.key, term\.options\.fontSize\)/);
assert.match(APP_JS, /invoke\('save_terminal_font_size', \{ size \}\)/);
assert.match(APP_JS, /terminal\.setFontSize\(Number\.isInteger\(state\.terminalFontSize\)/);
});
// WCAG contrast of one #rrggbb against another.
function luminance(hex) {
const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255).map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
const contrast = (a, b) => {
const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
return (hi + 0.05) / (lo + 0.05);
};
test("the terminal's two ANSI palettes hold sixteen colors each and stay readable on the panel they sit on", () => {
const names = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "brightBlack", "brightRed", "brightGreen", "brightYellow", "brightBlue", "brightMagenta", "brightCyan", "brightWhite"];
const tokens = fs.readFileSync(path.join(HERE, "../src/web-console/public/styles/tokens.css"), "utf8");
const panels = { light: /:root \{[\s\S]*?--panel: (#[0-9a-f]{6})/.exec(tokens)[1], dark: /@media \(prefers-color-scheme: dark\) \{[\s\S]*?--panel: (#[0-9a-f]{6})/.exec(tokens)[1] };
for (const theme of ["light", "dark"]) {
const palette = terminalAnsi(theme);
assert.deepEqual(Object.keys(palette), names, theme);
for (const name of names) {
assert.match(palette[name], /^#[0-9a-f]{6}$/i);
// ANSI black on a dark screen is a background shade by nature.
if (theme === "dark" && name === "black") continue;
const ratio = contrast(palette[name], panels[theme]);
assert.ok(ratio >= (name === "brightBlack" ? 4.4 : 3), `${theme} ${name} ${palette[name]} on ${panels[theme]} is only ${ratio.toFixed(2)}:1`);
}
}
assert.equal(terminalAnsi("system"), TERMINAL_ANSI.dark, "anything but light is dark");
assert.equal(hexToRgba("#619fe5", 0.35), "rgba(97, 159, 229, 0.35)");
assert.equal(hexToRgba("nope", 0.5), "rgba(128, 128, 128, 0.5)");
const term = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/terminal.js"), "utf8");
assert.match(term, /fontFamily: token\('--mono'/, "the console's mono stack");
assert.match(term, /term\.options\.theme = buildTheme\(\)/, "reapplied on every looks message");
assert.match(term, /cursor: accent/);
});
test("the splitter steps by 2% along the dock, clamps, and Home and End go to the ends", () => {
const opts = { min: 0.1, max: 0.6 };
const near = (a, b) => assert.ok(Math.abs(a - b) < 1e-9, `${a} vs ${b}`);
near(splitterFraction("ArrowUp", 0.25, "bottom", opts), 0.27);
near(splitterFraction("ArrowDown", 0.25, "bottom", opts), 0.23);
near(splitterFraction("ArrowLeft", 0.25, "right", opts), 0.27);
near(splitterFraction("ArrowRight", 0.25, "right", opts), 0.23);
assert.equal(splitterFraction("ArrowLeft", 0.25, "bottom", opts), null, "the other axis is not its key");
assert.equal(splitterFraction("ArrowUp", 0.25, "right", opts), null);
assert.equal(splitterFraction("Home", 0.25, "bottom", opts), 0.1);
assert.equal(splitterFraction("End", 0.25, "right", opts), 0.6);
assert.equal(splitterFraction("ArrowUp", 0.6, "bottom", opts), 0.6);
assert.equal(splitterFraction("ArrowDown", 0.1, "bottom", opts), 0.1);
assert.equal(splitterFraction("a", 0.25, "bottom", opts), null);
assert.deepEqual(splitterAria(0.254, opts), { now: 25, min: 10, max: 60 });
});
test("the splitter is a keyboard-usable separator with a 6px hit area and a 1px line", () => {
assert.match(INDEX_HTML, /<div id="term-handle" role="separator" aria-orientation="horizontal"[^>]*aria-valuenow="25"[^>]*tabindex="0"/);
assert.match(INDEX_HTML, /#workspace:not\(\.dock-right\) #term-handle \{ height: 6px;/);
assert.match(INDEX_HTML, /#workspace\.dock-right #term-handle \{ width: 6px;/);
assert.match(INDEX_HTML, /#term-handle::after \{[^}]*background: var\(--rule\)/);
assert.match(INDEX_HTML, /#term-handle:hover::after, #term-handle:focus-visible::after, #term-handle\.is-dragging::after \{ background: var\(--accent\); \}/);
assert.match(APP_JS, /termHandle\.addEventListener\('keydown'[\s\S]*?splitterFraction\(event\.key,/);
assert.match(APP_JS, /termHandle\.addEventListener\('dblclick', \(\) => \{\s+paneFraction = defaultPaneFraction\(\);/);
assert.match(APP_JS, /termHandle\.setAttribute\('aria-orientation', paneDock === 'right' \? 'vertical' : 'horizontal'\);/);
});
test("the terminal toolbar has a title, labeled icon buttons and a labeled pill that opens the terminal", () => {
assert.equal(terminalTitle("Claude Code"), "Terminal \u00b7 Claude Code");
assert.equal(terminalTitle(""), "Terminal");
assert.equal(terminalTitle(), "Terminal");
assert.match(INDEX_HTML, /<span id="term-title">Terminal<\/span>/);
for (const id of ["term-dock", "term-maximize", "term-collapse"]) {
const tag = new RegExp(`<button id="${id}" class="term-icon"[^>]*aria-label="[^"]+"[^>]*title="[^"]+"`);
assert.match(INDEX_HTML, tag, `#${id} is an icon button that names itself`);
}
assert.doesNotMatch(APP_JS, /term(Dock|Maximize|Collapse)Btn\.textContent/, "no changing text on the three buttons");
assert.match(APP_JS, /termTitleEl\.textContent = terminalTitle\(/);
assert.match(APP_JS, /termBadgeEl\.onclick = \(\) => \{\s+if \(paneCollapsed\) \{[^}]*?termCollapseBtn\.click\(\);\s+terminal\.focus\(\);\s+return;\s+\}/, "a collapsed terminal expands, then takes the focus once its layout is back");
assert.match(APP_JS, /terminal\.focus\(\);\s+\};/);
});
test("a small pane docked right keeps its whole toolbar inside it when the pill shows", async (t) => {
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
const browser = await launchBrowser();
try {
const page = await browser.newPage({ viewport: { width: 1280, height: 700 } });
page.on("pageerror", () => {});
await page.goto(pathToFileURL(INDEX_HTML_PATH).href);
await page.evaluate(() => {
document.getElementById("workspace").classList.add("dock-right");
document.getElementById("term-panel").style.width = "192px";
document.getElementById("term-badge").hidden = false;
document.getElementById("term-title").textContent = "Terminal \u00b7 Claude Code";
});
const spill = await page.evaluate(() => {
const panel = document.getElementById("term-panel").getBoundingClientRect();
return ["term-dock", "term-maximize", "term-collapse", "term-badge"].map((id) => ({ id, past: document.getElementById(id).getBoundingClientRect().right - panel.right }));
});
for (const { id, past } of spill) assert.ok(past <= 0.5, `#${id} spills ${past}px past the panel's edge`);
} finally {
await browser.close();
}
});
test("barFit drops the model text first, then the status line, and only when the row is too narrow", () => {
assert.deepEqual(barFit({ available: 900, needed: 800, model: 200, status: 150 }), { model: true, status: true });
assert.deepEqual(barFit({ available: 800, needed: 800, model: 200, status: 150 }), { model: true, status: true }, "exactly fitting is fitting");
assert.deepEqual(barFit({ available: 700, needed: 800, model: 200, status: 150 }), { model: false, status: true });
assert.deepEqual(barFit({ available: 500, needed: 800, model: 200, status: 150 }), { model: false, status: false });
assert.deepEqual(barFit({ available: 500, needed: 800 }), { model: false, status: false }, "no parts measured, none claimed");
});
test("the top bar collapses instead of scrolling, and +N more is a button that lists the other steps", () => {
assert.doesNotMatch(INDEX_HTML, /#bar-row \{[^}]*overflow-x: auto/, "no sideways scrolling row");
assert.match(INDEX_HTML, /#bar-row\.no-model #agent-model, #bar-row\.no-status #agent-status \{ display: none; \}/);
assert.match(APP_JS, /new ResizeObserver\(scheduleFitBar\)\.observe\(barRowEl\);/);
assert.match(APP_JS, /barFit\(\{ available: barRowEl\.clientWidth, needed: barRowEl\.scrollWidth, model, status \}\)/);
assert.doesNotMatch(APP_JS, /barRowEl\.addEventListener\('scroll'/);
assert.match(INDEX_HTML, /<button id="next-step-more" type="button" aria-haspopup="menu" aria-expanded="false" aria-controls="more-menu" hidden><\/button>/);
assert.match(INDEX_HTML, /<div id="more-menu" class="bar-dropdown" role="menu"[^>]*tabindex="-1" hidden><\/div>/);
assert.match(APP_JS, /nextStepMoreEl\.onclick = \(\) => toggleBarMenu\(nextStepMoreEl, moreMenu\);/);
const more = APP_JS.slice(APP_JS.indexOf("function renderMoreMenu"), APP_JS.indexOf("function setVersionState"));
assert.match(more, /commandNodes\(step\.title\)/, "the full sentence, a failed update's last line included");
assert.match(more, /NEXT_STEP_ACTIONS\[step\.action\]/, "each step's own action");
assert.doesNotMatch(APP_JS, /nextStepMoreEl\.title =/, "no longer only in a tooltip");
});
test("the Node.js check's result reaches the page after the window opens, and the first-run checklist waits for it", () => {
assert.match(APP_JS, /async function awaitNodeStatus\(state\) \{\s+if \(state\.nodeChecked\) return;/);
assert.match(APP_JS, /event\.listen\('node-status', \(event\) => finish\(event\.payload\)\)/);
assert.match(APP_JS, /if \(!state\.firstRunDone\) await awaitNodeStatus\(state\);\s+afterProjectKnown\(\);/);
const main = fs.readFileSync(path.join(HERE, "../plan2code-app/src-tauri/src/main.rs"), "utf8");
assert.match(main, /spawn_node_check\(app\.handle\(\)\.clone\(\)\)/, "the check runs off the main thread");
assert.match(main, /app\.emit\("node-status"/);
});
// ---- Phase 10: waits, friendly errors, the confirm modal, shortcuts, links and the clipboard ----
test("waitingView: quiet for 12 s, then says where to look; an ended agent says so at once with Change agent", () => {
assert.equal(STILL_WAITING_MS, 12000);
assert.deepEqual(waitingView({ waitedMs: 0, agentState: "running" }), { still: false, text: null, showTerminal: false, changeAgent: false });
assert.equal(waitingView({ waitedMs: STILL_WAITING_MS - 1, agentState: "running" }).still, false);
const late = waitingView({ waitedMs: STILL_WAITING_MS, agentState: "running" });
assert.deepEqual(late, { still: true, text: STILL_WAITING_TEXT, showTerminal: true, changeAgent: false });
assert.equal(STILL_WAITING_TEXT, "Still waiting. The agent may be asking you something in its terminal.");
const ended = waitingView({ waitedMs: 500, agentState: "ended" });
assert.deepEqual([ended.still, ended.showTerminal, ended.changeAgent], [true, true, true], "no need to wait 12 s for an agent that is gone");
});
test("friendlyError maps each known raw message to a sentence with a next step and keeps the raw text for Details", () => {
const cases = [
["console open printed no JSON: Error: spawn", /did not start properly.*Reconnect the console/],
["console open failed: node: command not found", /could not be opened/],
["console stop failed: busy", /did not stop cleanly/],
["the web console is not installed (looked in $PLAN2CODE_CONSOLE_DIR, a and b)", /skills are missing.*plan2code update/],
["The installed Plan2Code console is too old to show inside the app. Press Update skills, then try again.", /too old for this app.*Update skills/],
["no agent has been started", /no agent to restart yet/],
["no project folder chosen", /Choose a project folder first/],
["an agent is already running for this project", /already running.*New Session/],
["could not start the agent: spawn ENOENT", /could not start.*installed/],
["Could not do that: no agent has been started", /no agent to restart yet/],
["busy", /console is busy/],
];
for (const [raw, pattern] of cases) {
const out = friendlyError(raw);
assert.match(out.text, pattern, raw);
assert.equal(out.details, raw, `the raw text is kept behind Details: ${raw}`);
assert.match(out.text, /[.]$/, "a sentence");
assert.doesNotMatch(out.text, /^[a-z]/, "no lowercase raw text as the headline");
}
});
test("friendlyError words an unknown error by what was being done, and an empty one as nothing", () => {
assert.deepEqual(friendlyError("EPERM: operation not permitted", "start the agent"), { text: "Could not start the agent. Try again.", details: "EPERM: operation not permitted" });
assert.deepEqual(friendlyError("weird", ""), { text: "That did not work. Try again.", details: "weird" });
assert.deepEqual(friendlyError("", "x"), { text: "", details: "" });
assert.deepEqual(friendlyError(null), { text: "", details: "" });
assert.deepEqual(friendlyError(new Error("boom"), "do that"), { text: "Could not do that. Try again.", details: "Error: boom" });
});
test("endedView: exit code 0 is 'closed normally' and the bar no longer says 'ended' for it", () => {
assert.deepEqual(endedView("exited with code 0"), { bar: "closed", sentence: "closed normally", normal: true });
assert.deepEqual(endedView("exited with code 2"), { bar: "ended", sentence: "stopped with an error (exit code 2)", normal: false });
assert.equal(endedView("was ended by a signal (SIGKILL)").sentence, "was ended from outside the app (SIGKILL)");
assert.equal(endedView("stopped: pty gone").sentence, "ended: stopped: pty gone");
assert.equal(endedView("").sentence, "ended");
assert.match(APP_JS, /endedView\(agent\.reason\)/, "the bar, the menu and the terminal line all read the same words");
assert.doesNotMatch(APP_JS, /ended: \$\{agent\.reason\}/, "no raw reason pasted into the terminal line or the menu");
});
test("app.js shows raw errors through friendlyError, never as 'Could not ...: ${error}' text", () => {
assert.doesNotMatch(APP_JS, /Could not (?:start the agent|open the install page|open the setup page|type continue|switch project|read the app state): \$\{/, "the old raw-text sites are gone");
assert.doesNotMatch(APP_JS, /The console could not be reached: \$\{/);
assert.doesNotMatch(APP_JS, /Could not (?:read the recent folders|open the folder picker|open \$\{row\.dir\}): \$\{/, "the folder picker's errors are in plain words too");
assert.match(APP_JS, /setFolderPickerError\(error, 'read the recent folders'\)/);
assert.doesNotMatch(APP_JS, /Could not do that: \$\{/);
assert.match(APP_JS, /function showErrorState\(raw, action, buttonLabel, onButton, onCancel\) \{\s*const friendly = friendlyError\(raw, action\);/);
assert.match(APP_JS, /showErrorState\(error, 'reach the console', 'Retry', reconnectConsole\)/);
assert.match(APP_JS, /setAgentError\(error, 'start the agent'\)/);
assert.match(INDEX_HTML, /<button id="dashboard-state-toggle"[^>]*>Details<\/button>/, "the raw text sits behind Details");
assert.match(APP_JS, /agentStatusEl\.addEventListener\('click', openStatusDetails\)/, "a press on the bar's error opens it in full");
});
test("one busy style for every wait, and the wait timer: waits start through beginWait and end when the page arrives", () => {
assert.match(APP_JS, /const busy = options\.busy !== undefined \? options\.busy : !buttonLabel && !onCancel;/);
assert.match(APP_JS, /beginWait\('Waiting for the agent to open the dashboard\.\.\.'\)/);
assert.match(APP_JS, /beginWait\('Starting the agent\.\.\.'\)/);
assert.match(APP_JS, /function showAnnounced\(notice\) \{\s*endWait\(\);/);
const tick = APP_JS.slice(APP_JS.indexOf("function tickWait"), APP_JS.indexOf("function hideState"));
assert.match(tick, /waitingView\(\{ waitedMs: Date\.now\(\) - waitStartedAt, agentState: agent\.state \}\)/);
assert.match(tick, /'Show the terminal', showTerminal/);
assert.match(tick, /label: 'Change agent'/);
for (const line of ["Reconnecting to the console...", "Opening the page...", "Reloading the page...", "Opening the dashboard...", "The console stopped. Reconnecting..."]) {
assert.ok(APP_JS.includes(`'${line}'`), `progress line shares the ellipsis: ${line}`);
}
});
test("confirmButtons puts the safe button first with focus and the danger verb last; trapTab wraps in both directions", () => {
assert.deepEqual(confirmButtons(), { order: ["cancel", "primary"], focus: "cancel" });
assert.deepEqual(confirmButtons({ safeFirst: true }), { order: ["cancel", "primary"], focus: "cancel" });
assert.deepEqual(confirmButtons({ safeFirst: false }), { order: ["primary", "cancel"], focus: "primary" });
assert.equal(trapTab(false, 0, 2), 1);
assert.equal(trapTab(false, 1, 2), 0, "forward from the last wraps to the first");
assert.equal(trapTab(true, 0, 2), 1, "back from the first wraps to the last");
assert.equal(trapTab(false, -1, 2), 0, "focus outside comes in at the first");
assert.equal(trapTab(true, -1, 2), 1);
assert.equal(trapTab(false, 0, 0), null);
});
test("the confirm modal is an alertdialog in the shell, outside the frame, with the rest of the shell inert while it asks", () => {
assert.match(INDEX_HTML, /<div id="confirm-modal" hidden>\s*<div id="confirm-panel" role="alertdialog" aria-modal="true" aria-labelledby="confirm-title" aria-describedby="confirm-body" tabindex="-1">/);
assert.ok(INDEX_HTML.indexOf('id="confirm-modal"') > INDEX_HTML.indexOf('<section id="term-panel"'), "a sibling after the workspace (and its frame), never inside either");
const modal = APP_JS.slice(APP_JS.indexOf("function confirmModal"), APP_JS.indexOf("// The Rust side asks for a confirm too"));
assert.match(modal, /for \(const part of shellParts\(\)\) part\.inert = true;/);
assert.match(modal, /for \(const part of shellParts\(\)\) part\.inert = false;/);
assert.match(modal, /event\.key !== 'Escape' \|\| confirmModalEl\.hidden[\s\S]*?stopImmediatePropagation\(\);\s*closeConfirm\(false\)/, "Escape cancels, heard on the document in the capture phase so a scrim click does not lose it");
assert.match(APP_JS, /if \(event\.defaultPrevented \|\| event\.key !== 'Escape' \|\| folderPickerEl\.hidden\) return;/, "and a handled Escape never closes the folder picker behind it");
assert.match(APP_JS, /listen\('confirm-cancel'/, "the Rust side can take a request back");
assert.match(modal, /confirmButtons\(\{ safeFirst: primary \? safeFirst : true \}\)/);
assert.match(modal, /\(layout\.focus === 'cancel' \? confirmCancelBtn : confirmPrimaryBtn\)\.focus\(\)/, "focus goes to the safe button");
assert.match(modal, /\{ kind: 'callout'|item\.kind === 'callout'/, "an amber callout line is allowed");
assert.match(modal, /document\.createElement\('pre'\)/, "and a code block");
assert.match(INDEX_HTML, /#confirm-body \.confirm-callout \{[^}]*--stage/, "the callout is amber");
assert.match(APP_JS, /listen\('confirm-request'/, "Rust's own confirms (loop start, the quit check) arrive as requests");
assert.match(APP_JS, /invoke\('confirm_answer', \{ id: req\.id, yes \}\)/);
});
test("shortcutAction: Ctrl or Cmd with the table's keys, never with Alt, and the other platform's modifier is no chord", () => {
const key = (k, mods = {}) => ({ key: k, ctrlKey: false, metaKey: false, shiftKey: false, altKey: false, ...mods });
assert.deepEqual(SHORTCUTS.map((s) => s.id), ["toggle-terminal", "focus-console", "focus-terminal", "new-session", "change-project", "preferences"]);
for (const [k, id, mods] of [["`", "toggle-terminal", {}], ["1", "focus-console", {}], ["2", "focus-terminal", {}], ["N", "new-session", { shiftKey: true }], ["o", "change-project", {}], [",", "preferences", {}]]) {
assert.equal(shortcutAction(key(k, { ctrlKey: true, ...mods })), id, `Ctrl+${k}`);
assert.equal(shortcutAction(key(k, { metaKey: true, ...mods }), { mac: true }), id, `Cmd+${k}`);
assert.equal(shortcutAction(key(k, { metaKey: true, ...mods })), null, `Cmd is no chord on Windows or Linux: ${k}`);
assert.equal(shortcutAction(key(k, { ctrlKey: true, ...mods }), { mac: true }), null, `Ctrl is no chord on a Mac: ${k}`);
assert.equal(shortcutAction(key(k, { ctrlKey: true, altKey: true, ...mods })), null, `Alt cancels it: ${k}`);
}
assert.equal(shortcutAction(key("n", { ctrlKey: true })), null, "New Session needs Shift (plain Ctrl+N is not taken)");
assert.equal(shortcutAction(key("`", { ctrlKey: true, shiftKey: true })), null);
assert.equal(shortcutAction(key("w", { ctrlKey: true })), null);
assert.equal(shortcutAction(null), null);
});
test("Ctrl+O in the terminal on Windows and Linux stays the agent's own (Claude Code's transcript); a Mac and the page still get Change project", () => {
const ctrlO = { key: "o", ctrlKey: true, metaKey: false, shiftKey: false, altKey: false };
assert.equal(shortcutAction(ctrlO, { inTerminal: true }), null);
assert.equal(shortcutAction(ctrlO, { inTerminal: false }), "change-project");
assert.equal(shortcutAction({ ...ctrlO, ctrlKey: false, metaKey: true }, { mac: true, inTerminal: true }), "change-project");
assert.equal(shortcutAction({ ...ctrlO, key: "`" }, { inTerminal: true }), "toggle-terminal", "every other chord works from the terminal");
});
test("shortcut tooltips name the chord for the platform, and the page can only ask for an id in the table", () => {
assert.equal(shortcutLabel("new-session"), "Ctrl+Shift+N");
assert.equal(shortcutLabel("new-session", true), "Cmd+Shift+N");
assert.equal(shortcutLabel("toggle-terminal"), "Ctrl+`");
assert.equal(shortcutLabel("preferences", true), "Cmd+,");
assert.equal(shortcutLabel("nope"), "");
assert.equal(tipWithShortcut("Change project", "change-project"), "Change project (Ctrl+O)");
assert.equal(tipWithShortcut("x", "nope"), "x");
assert.equal(shortcutFromMessage({ plan2code: "shortcut", id: "new-session" }), "new-session");
for (const bad of [{ id: "rm -rf" }, { id: 3 }, {}, null, undefined]) assert.equal(shortcutFromMessage(bad), null);
});
test("the console page's forwarded keys are the shell's table: the same ids, keys and Shift", async () => {
const bridge = await import(pathToFileURL(path.join(HERE, "../src/web-console/public/app-bridge.js")).href);
assert.deepEqual(
bridge.SHORTCUT_KEYS.map(({ id, key, shift }) => ({ id, key, shift })),
SHORTCUTS.map(({ id, key, shift }) => ({ id, key, shift }))
);
assert.equal(bridge.shortcutIdFor({ key: "2", ctrlKey: true, metaKey: false, shiftKey: false, altKey: false }, false), "focus-terminal");
assert.equal(bridge.shortcutIdFor({ key: "2", ctrlKey: true, metaKey: false, shiftKey: false, altKey: false }, true), null);
const core = fs.readFileSync(path.join(HERE, "../src/web-console/public/screens/core.js"), "utf8");
assert.match(core, /tellApp\("shortcut", \{ id \}\)/);
assert.match(core, /onAppMessage\("open-preferences"/);
assert.match(core, /onAppMessage\("open-help"/);
assert.match(APP_JS, /kind === 'shortcut'/);
assert.match(APP_JS, /postMessage\(\{ plan2code: 'open-preferences' \}/);
});
test("app.js routes the shortcuts from every focus position: the terminal's key handler, the shell's document and the page's message", () => {
assert.match(APP_JS, /onShortcut: \(event\) => \{\s*const id = shortcutAction\(event, \{ mac: IS_MAC, inTerminal: true \}\);/);
assert.match(APP_JS, /document\.addEventListener\('keydown', \(event\) => \{\s*if \(event\.defaultPrevented\) return;[\s\S]*?shortcutAction\(event, \{ mac: IS_MAC, inTerminal \}\)/);
const term = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/terminal.js"), "utf8");
assert.match(term, /if \(onShortcut && onShortcut\(event\)\) \{\s*event\.preventDefault\(\);\s*return false;/, "the terminal never types a shell shortcut to the agent");
assert.match(APP_JS, /if \(!changeProjectBtn\.disabled && folderPickerEl\.hidden\) changeProjectBtn\.click\(\);/, "Change project is not run over the bare start's own picker");
assert.match(APP_JS, /tipWithShortcut\(paneCollapsed \? 'Show the terminal' : 'Collapse', 'toggle-terminal', IS_MAC\)/, "shown in tooltips");
});
test("the '...' menu: About, Check for updates, Help and Quit, in the bar's menu pattern", () => {
assert.match(INDEX_HTML, /<button id="app-menu-button" class="bar-menu"[^>]*aria-haspopup="menu"[^>]*aria-controls="app-menu"/);
const menu = INDEX_HTML.slice(INDEX_HTML.indexOf('id="app-menu"'), INDEX_HTML.indexOf('id="more-menu"'));
assert.deepEqual([...menu.matchAll(/role="menuitem">([^<]+)</g)].map((m) => m[1]), ["About Plan2Code", "Check for updates", "Help", "Quit"]);
assert.match(APP_JS, /\[appMenuBtn, appMenu\]/, "it opens, closes and takes focus like the other bar menus");
assert.match(APP_JS, /invoke\('request_quit'\)/);
assert.match(APP_JS, /openLink\(releaseNotesUrl\(status\.app\)\)/, "release notes through the opener");
});
test("links open through the opener plugin, http and https only; the terminal's links and What's new use it", () => {
const open = APP_JS.slice(APP_JS.indexOf("function openLink"), APP_JS.indexOf("function openLink") + 400);
assert.match(open, /\^https\?:/, "anything else is refused before it is sent");
assert.match(open, /invoke\('plugin:opener\|open_url', \{ url \}\)/);
assert.match(APP_JS, /onLink: \(uri\) => openLink\(uri\)/);
assert.match(INDEX_HTML, /<script src="vendor\/addon-web-links\.js"><\/script>/);
const term = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/terminal.js"), "utf8");
assert.match(term, /new window\.WebLinksAddon\.WebLinksAddon\(\(event, uri\) => \{\s*event\.preventDefault\(\);\s*onLink\(uri\);/);
const caps = JSON.parse(fs.readFileSync(path.join(HERE, "../plan2code-app/src-tauri/capabilities/default.json"), "utf8"));
const opener = caps.permissions.find((p) => p && p.identifier === "opener:allow-open-url");
assert.deepEqual(opener.allow.map((a) => a.url).sort(), ["http://*", "https://*"], "scoped to web links");
assert.ok(!caps.permissions.includes("opener:default"), "not the default set (mailto, tel, reveal in folder)");
});
test("clipboardAction: Ctrl+C copies only with a selection (else it is the interrupt), Ctrl+Shift+C and Cmd+C always copy, Ctrl/Cmd+V pastes", () => {
const ev = (key, mods = {}) => ({ key, ctrlKey: false, metaKey: false, shiftKey: false, altKey: false, ...mods });
assert.equal(clipboardAction(ev("c", { ctrlKey: true }), true), "copy");
assert.equal(clipboardAction(ev("c", { ctrlKey: true }), false), null, "no selection: the interrupt goes to the agent");
assert.equal(clipboardAction(ev("C", { ctrlKey: true, shiftKey: true }), false), "copy");
assert.equal(clipboardAction(ev("c", { metaKey: true }), false), "copy");
assert.equal(clipboardAction(ev("v", { ctrlKey: true }), false), "paste");
assert.equal(clipboardAction(ev("V", { ctrlKey: true, shiftKey: true }), false), "paste");
assert.equal(clipboardAction(ev("v", { metaKey: true }), false), "paste");
assert.equal(clipboardAction(ev("c", { ctrlKey: true, altKey: true }), true), null);
assert.equal(clipboardAction(ev("c"), true), null);
assert.equal(clipboardAction(ev("x", { ctrlKey: true }), true), null);
// On a Mac, Ctrl+C is always the interrupt, selection or not; Cmd+C and Ctrl+Shift+C still copy.
assert.equal(clipboardAction(ev("c", { ctrlKey: true }), true, { mac: true }), null);
assert.equal(clipboardAction(ev("c", { metaKey: true }), true, { mac: true }), "copy");
assert.equal(clipboardAction(ev("C", { ctrlKey: true, shiftKey: true }), true, { mac: true }), "copy");
assert.equal(clipboardAction(null, true), null);
});
test("the terminal pastes once and in brackets, copies on select only by preference, and has a Copy / Paste / Clear menu", () => {
const term = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/terminal.js"), "utf8");
assert.match(term, /term\.paste\(text\)/, "bracketed paste, not onInput(text)");
assert.doesNotMatch(term, /if \(text\) onInput\(text\)/, "the old unbracketed paste is gone");
assert.match(term, /if \(action === 'paste'\) \{\s*event\.preventDefault\(\);/, "the browser's own paste event is stopped, so it cannot land a second time");
assert.match(term, /if \(event\.ctrlKey && !event\.shiftKey\) term\.clearSelection\(\);/, "a plain Ctrl+C that copied clears the selection, so the next one is the interrupt");
assert.match(term, /if \(!copyOnSelectOn\) return;/, "no unconditional clipboard write on every selection");
assert.match(term, /\['Copy', actions\.hasSelection\(\), actions\.copy\],\s*\['Paste', true, actions\.paste\],\s*\['Clear', true, actions\.clear\]/);
assert.match(INDEX_HTML, /<div id="term-menu" role="menu"/);
assert.match(APP_JS, /terminal\.setCopyOnSelect\(Boolean\(state\.copyOnSelect\)\)/);
assert.match(APP_JS, /invoke\('save_copy_on_select', \{ on \}\)|invoke\('set_copy_on_select', \{ on \}\)/);
});