From 710c751c2f2b8284075e7fe3d9462745e169123c Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Tue, 17 Nov 2026 18:07:59 -0800 Subject: [PATCH] Add Update and restart, a remembered window and safer copy and paste to the desktop app AI Assisted --- docs/desktop-app.md | 62 +- plan2code-app/Cargo.lock | 481 ++++++++- plan2code-app/README.md | 10 +- plan2code-app/fake-agent/Cargo.toml | 2 +- plan2code-app/package-lock.json | 11 +- plan2code-app/package.json | 3 +- plan2code-app/scripts/vendor.mjs | 11 +- plan2code-app/src-tauri/Cargo.toml | 4 +- .../src-tauri/capabilities/default.json | 4 +- plan2code-app/src-tauri/src/lib.rs | 1 + plan2code-app/src-tauri/src/loop_driver.rs | 115 ++- plan2code-app/src-tauri/src/main.rs | 497 +++++++-- plan2code-app/src-tauri/src/node_check.rs | 139 ++- plan2code-app/src-tauri/src/settings.rs | 141 +++ plan2code-app/src-tauri/src/ui_confirm.rs | 217 ++++ plan2code-app/src-tauri/src/versions.rs | 172 +++- plan2code-app/src-tauri/tauri.conf.json | 7 +- plan2code-app/ui/app.js | 942 +++++++++++++++--- plan2code-app/ui/index.html | 353 ++++--- plan2code-app/ui/meter.js | 453 ++++++++- plan2code-app/ui/terminal.js | 224 ++++- plan2code-app/ui/theme-early.js | 38 + scripts/make-app-placeholders.mjs | 70 ++ scripts/test-app-meter.mjs | 812 ++++++++++++++- 24 files changed, 4347 insertions(+), 422 deletions(-) create mode 100644 plan2code-app/src-tauri/src/ui_confirm.rs create mode 100644 plan2code-app/ui/theme-early.js create mode 100644 scripts/make-app-placeholders.mjs diff --git a/docs/desktop-app.md b/docs/desktop-app.md index 2c2afcf..245c019 100644 --- a/docs/desktop-app.md +++ b/docs/desktop-app.md @@ -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--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 `, on Linux `sha256sum `, on Windows PowerShell `Get-FileHash -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**. diff --git a/plan2code-app/Cargo.lock b/plan2code-app/Cargo.lock index 05b126f..49d872e 100644 --- a/plan2code-app/Cargo.lock +++ b/plan2code-app/Cargo.lock @@ -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", +] diff --git a/plan2code-app/README.md b/plan2code-app/README.md index 98076de..2dd029d 100644 --- a/plan2code-app/README.md +++ b/plan2code-app/README.md @@ -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 diff --git a/plan2code-app/fake-agent/Cargo.toml b/plan2code-app/fake-agent/Cargo.toml index b95ed3d..068356a 100644 --- a/plan2code-app/fake-agent/Cargo.toml +++ b/plan2code-app/fake-agent/Cargo.toml @@ -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 diff --git a/plan2code-app/package-lock.json b/plan2code-app/package-lock.json index cddc7ce..99e7968 100644 --- a/plan2code-app/package-lock.json +++ b/plan2code-app/package-lock.json @@ -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", diff --git a/plan2code-app/package.json b/plan2code-app/package.json index 39fa39e..3b0a6b1 100644 --- a/plan2code-app/package.json +++ b/plan2code-app/package.json @@ -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": { diff --git a/plan2code-app/scripts/vendor.mjs b/plan2code-app/scripts/vendor.mjs index 573a0ca..809c6c9 100644 --- a/plan2code-app/scripts/vendor.mjs +++ b/plan2code-app/scripts/vendor.mjs @@ -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/`); diff --git a/plan2code-app/src-tauri/Cargo.toml b/plan2code-app/src-tauri/Cargo.toml index 6d16595..6362ba9 100644 --- a/plan2code-app/src-tauri/Cargo.toml +++ b/plan2code-app/src-tauri/Cargo.toml @@ -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" diff --git a/plan2code-app/src-tauri/capabilities/default.json b/plan2code-app/src-tauri/capabilities/default.json index 39da663..666fd88 100644 --- a/plan2code-app/src-tauri/capabilities/default.json +++ b/plan2code-app/src-tauri/capabilities/default.json @@ -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://*"}]}] } diff --git a/plan2code-app/src-tauri/src/lib.rs b/plan2code-app/src-tauri/src/lib.rs index 9355be0..fb18fea 100644 --- a/plan2code-app/src-tauri/src/lib.rs +++ b/plan2code-app/src-tauri/src/lib.rs @@ -22,4 +22,5 @@ pub mod session_reader; pub mod settings; #[cfg(windows)] pub mod task_dialog; +pub mod ui_confirm; pub mod versions; diff --git a/plan2code-app/src-tauri/src/loop_driver.rs b/plan2code-app/src-tauri/src/loop_driver.rs index 7b83f10..3f91184 100644 --- a/plan2code-app/src-tauri/src/loop_driver.rs +++ b/plan2code-app/src-tauri/src/loop_driver.rs @@ -1131,14 +1131,17 @@ pub fn prompt_support(agent: &Agent) -> bool { // -------------------------------------------------------- starting a loop -/// `specs/`: one folder directly under `specs/`, not a link. +/// `specs/`: 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 { + 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 = 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", diff --git a/plan2code-app/src-tauri/src/main.rs b/plan2code-app/src-tauri/src/main.rs index 47a6187..c68346f 100644 --- a/plan2code-app/src-tauri/src/main.rs +++ b/plan2code-app/src-tauri/src/main.rs @@ -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>>, - // 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, - node_binary: Option, + // 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, // What the taskbar entry last said, and whether it may say anything. attention: Mutex, // 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>, + // 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, + // 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, + binary: Option, + problem: Option, +} + +/// 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::().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) -> 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, + 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> = 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 { + let state = app.state::(); + 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::(); 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" 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 { +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, +) -> Result { + 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 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::>(); 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!()) diff --git a/plan2code-app/src-tauri/src/node_check.rs b/plan2code-app/src-tauri/src/node_check.rs index 671631e..b440b3f 100644 --- a/plan2code-app/src-tauri/src/node_check.rs +++ b/plan2code-app/src-tauri/src/node_check.rs @@ -77,14 +77,65 @@ fn node_override_dir(args: &[String]) -> Option { #[cfg(unix)] fn login_shell_path() -> Option { 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> = 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 { /// The plain message shown when the check fails; `None` when Node is fine. pub fn problem_message(status: &NodeStatus) -> Option { + 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 { + 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( + " +" + ), + "" + ); + } } diff --git a/plan2code-app/src-tauri/src/settings.rs b/plan2code-app/src-tauri/src/settings.rs index 1237ef1..9483bb0 100644 --- a/plan2code-app/src-tauri/src/settings.rs +++ b/plan2code-app/src-tauri/src/settings.rs @@ -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 { + 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) -> 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")); + } } diff --git a/plan2code-app/src-tauri/src/ui_confirm.rs b/plan2code-app/src-tauri/src/ui_confirm.rs new file mode 100644 index 0000000..b9de0ce --- /dev/null +++ b/plan2code-app/src-tauri/src/ui_confirm.rs @@ -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) -> Self { + Self { + kind: "text", + text: text.into(), + } + } + pub fn code(text: impl Into) -> Self { + Self { + kind: "code", + text: text.into(), + } + } + pub fn callout(text: impl Into) -> 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, + 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>>, + next: Mutex, +} + +impl Pending { + /// A new request id and the receiver its answer arrives on. + pub fn register(&self) -> (String, Receiver) { + 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, 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}')); + } + } +} diff --git a/plan2code-app/src-tauri/src/versions.rs b/plan2code-app/src-tauri/src/versions.rs index c78ad9e..de59b68 100644 --- a/plan2code-app/src-tauri/src/versions.rs +++ b/plan2code-app/src-tauri/src/versions.rs @@ -105,10 +105,32 @@ pub fn newer_release(app: &str, ls_remote: &str) -> Option { (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 { +/// 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, + pub problem: Option, +} + +/// 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) -> 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 { 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 { 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::(); std::thread::spawn(move || { let mut text = String::new(); @@ -138,19 +166,72 @@ pub fn check_new_release(app: &str) -> Option { 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 { + 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 { + 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 { + 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 Result { + 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 { + run_installer(UpdateTarget::Pinned(app_version), timeout, on_line) +} + +fn run_installer( + target: UpdateTarget, + timeout: Duration, mut on_line: impl FnMut(&str), ) -> Result { 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.") + ); + } } diff --git a/plan2code-app/src-tauri/tauri.conf.json b/plan2code-app/src-tauri/tauri.conf.json index 5bcc507..bdab48c 100644 --- a/plan2code-app/src-tauri/tauri.conf.json +++ b/plan2code-app/src-tauri/tauri.conf.json @@ -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" } diff --git a/plan2code-app/ui/app.js b/plan2code-app/ui/app.js index 109a2ee..87f3184 100644 --- a/plan2code-app/ui/app.js +++ b/plan2code-app/ui/app.js @@ -3,10 +3,19 @@ // request) with a drag handle. import { mountTerminal } from './terminal.js'; -import { NEW_RELEASE_COMMAND, attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, lastAgentNotice, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, folderPickerRows, loopBanner, loopLocks, loopStopLabels, loopWindowTitle, helloRetryAction, retryLabel, RETRY_AFTER_SECONDS } from './meter.js'; +import { TERMINAL_FONT_DEFAULT, UPDATE_RECHECK_MS, reasonSentence, releaseNotesUrl, confirmButtons, endedView, friendlyError, releaseAfterCheck, shortcutAction, shortcutFromMessage, shortcutLabel, tipWithShortcut, trapTab, waitingView, attentionSignal, barFit, looksFromMessage, splitterAria, splitterFraction, terminalTitle, barNextSteps, commandSegments, continueKeys, defaultRightFraction, folderName, lastAgentNotice, menuStep, pageDetailsLine, pageNotShownView, pickDefaultAgent, plainCommandText, taskbarSwitch, windowTitleFor, deadConsoleAction, folderPickerRows, loopBanner, loopLocks, loopStopLabels, loopWindowTitle, helloRetryAction, retryLabel, RETRY_AFTER_SECONDS } from './meter.js'; const { invoke, Channel } = window.__TAURI__.core; +// The window opens hidden (tauri.conf.json) and is shown once the first frame +// has painted, so there is no blank or wrongly colored flash. theme-early.js +// shows it anyway after a few seconds, should this module never get here. +function showWindowWhenPainted() { + const show = () => window.__TAURI__.window.getCurrentWindow().show().catch(() => {}); + requestAnimationFrame(() => requestAnimationFrame(show)); +} +showWindowWhenPainted(); + const projectMenuBtn = document.getElementById('project-menu-button'); const projectNameEl = document.getElementById('project-name'); const projectPathEl = document.getElementById('project-path'); @@ -14,6 +23,9 @@ const projectMenu = document.getElementById('project-menu'); const agentMenuBtn = document.getElementById('agent-menu-button'); const agentMenu = document.getElementById('agent-menu'); const agentMenuHeadEl = document.getElementById('agent-menu-head'); +const agentMenuMoreEl = document.getElementById('agent-menu-more'); +const moreMenu = document.getElementById('more-menu'); +const termTitleEl = document.getElementById('term-title'); const agentDotEl = document.getElementById('agent-dot'); const agentNameEl = document.getElementById('agent-name'); const agentEndedEl = document.getElementById('agent-ended'); @@ -77,6 +89,8 @@ const statePlannyEl = document.getElementById('dashboard-state-planny'); const stateText = document.getElementById('dashboard-state-text'); const stateButton = document.getElementById('dashboard-state-button'); const stateCancelEl = document.getElementById('dashboard-state-cancel'); +const stateSecondaryEl = document.getElementById('dashboard-state-secondary'); +const stateDetailsEl = document.getElementById('dashboard-state-details'); const workspaceEl = document.getElementById('workspace'); const termPanel = document.getElementById('term-panel'); const termHandle = document.getElementById('term-handle'); @@ -84,6 +98,21 @@ const termDockBtn = document.getElementById('term-dock'); const termMaximizeBtn = document.getElementById('term-maximize'); const termCollapseBtn = document.getElementById('term-collapse'); const termBadgeEl = document.getElementById('term-badge'); +const stateBusyEl = document.getElementById('dashboard-state-busy'); +const stateToggleEl = document.getElementById('dashboard-state-toggle'); +const appMenuBtn = document.getElementById('app-menu-button'); +const appMenu = document.getElementById('app-menu'); +const nextStepNotesEl = document.getElementById('next-step-notes'); +const confirmModalEl = document.getElementById('confirm-modal'); +const confirmPanelEl = document.getElementById('confirm-panel'); +const confirmTitleEl = document.getElementById('confirm-title'); +const confirmBodyEl = document.getElementById('confirm-body'); +const confirmActionsEl = document.getElementById('confirm-actions'); +const confirmCancelBtn = document.getElementById('confirm-cancel'); +const confirmPrimaryBtn = document.getElementById('confirm-primary'); + +// Cmd on a Mac, Ctrl elsewhere: for the shortcuts and the tooltips that name them. +const IS_MAC = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent || ''); const STATUS_POLL_MS = 5000; const BADGE_POLL_MS = 2000; @@ -120,8 +149,37 @@ const terminal = await mountTerminal(document.getElementById('term'), { onResize: (cols, rows) => { if (agentActive()) invoke('agent_resize', { cols, rows }); }, + // Ctrl or Cmd with plus, minus or 0: remembered for the next launch. + onFontSize: (size) => { + invoke('save_terminal_font_size', { size }).catch(() => { + // A settings file that cannot be written must not stop the zoom. + }); + }, + // A link the agent printed, opened in the default browser (http and https only). + onLink: (uri) => openLink(uri), + // The shell's own shortcuts, typed with the terminal focused: handled here, never typed to the agent. + onShortcut: (event) => { + const id = shortcutAction(event, { mac: IS_MAC, inTerminal: true }); + if (!id) return false; + runShortcut(id); + return true; + }, + onCopyOnSelect: (on) => { + invoke('set_copy_on_select', { on }).catch(() => { + // Not saved: the choice holds until the app closes. + }); + }, }); +// Opens a web link in the default browser through the opener plugin; anything that is not +// http or https is refused here as well as by the plugin's own scope. +function openLink(url) { + if (!/^https?:\/\//i.test(String(url))) return; + invoke('plugin:opener|open_url', { url }).catch((error) => { + setAgentError(error, 'open that link'); + }); +} + // One channel for the page's life: the agent's output arrives as bytes and its // state changes as objects, across restarts too. const agentChannel = new Channel(); @@ -170,8 +228,11 @@ function applyAgentState(next, { skipReset } = {}) { agentMenuBtn.hidden = !(active || ended); agentNoneEl.hidden = active || ended; agentNameEl.textContent = active || ended ? label || 'The agent' : ''; + termTitleEl.textContent = terminalTitle(active || ended ? label || 'The agent' : ''); agentDotEl.className = `agent-dot${active ? (bypassActive ? ' is-warn' : ' is-ok') : ''}`; + const endedWords = ended ? endedView(agent.reason) : null; agentEndedEl.hidden = !ended; + if (endedWords) agentEndedEl.textContent = endedWords.bar; // The model and effort the app started it with, when it knows them: an agent // on its own default model has none to show, and an effort needs a model. const modelText = agent.model ? (agent.effort ? `${agent.model} · ${agent.effort}` : agent.model) : ''; @@ -181,7 +242,7 @@ function applyAgentState(next, { skipReset } = {}) { agentBypassEl.hidden = !bypassActive; renderAgentMenuHead(label || 'The agent', { active, ended, bypassActive }); if (agentMenu.hidden === false && agentMenuBtn.hidden) closeBarMenus(); - restartBtn.title = ended ? 'Start a fresh agent on the same brief' : 'Replace the agent with a fresh one, on a fresh context window'; + restartBtn.title = tipWithShortcut(ended ? 'Start a fresh agent on the same brief' : 'Replace the agent with a fresh one, on a fresh context window', 'new-session', IS_MAC); // The agent is back (a fresh generation, running): the restart message stays // on screen (restarting() below) until its dashboard page is announced. if (restarting && freshScreen && agent.state === 'running') { @@ -190,10 +251,10 @@ function applyAgentState(next, { skipReset } = {}) { if (ended) { // The why sits beside the agent's menu; the menu says the rest. - setAgentStatus(agent.reason); + setAgentStatus(endedWords.sentence); // A failed Restart clears the screen too, so it says so again. if (!wasEnded || freshScreen) { - terminal.write(`\r\n[${label || 'The agent'} ended: ${agent.reason}. Press New Session in the bar to start a fresh one.]\r\n`); + terminal.write(`\r\n[${label || 'The agent'} ${endedWords.sentence}. Press New Session in the bar to start a fresh one.]\r\n`); } } else { // After a Restart the bar says what it left for the dashboard, if anything. @@ -204,10 +265,53 @@ function applyAgentState(next, { skipReset } = {}) { // The short line after the agent's menu: an ended agent's reason or a // Restart's brief note (quiet), or something that went wrong (in red). -function setAgentStatus(text, { error = false } = {}) { - agentStatusEl.textContent = text; - agentStatusEl.title = text; +let statusDetails = ''; + +function setAgentStatus(text, { error = false, details = '' } = {}) { + agentStatusEl.replaceChildren(...commandNodes(text)); + agentStatusEl.title = plainCommandText(text); agentStatusEl.classList.toggle('is-error', error && Boolean(text)); + // A long line is cut at the bar's width: it opens in full (with the raw text, when there is one) on a press. + statusDetails = details; + const pressable = Boolean(text) && (error || Boolean(details)); + agentStatusEl.classList.toggle('is-pressable', pressable); + if (pressable) { + agentStatusEl.setAttribute('role', 'button'); + agentStatusEl.tabIndex = 0; + } else { + agentStatusEl.setAttribute('role', 'status'); + agentStatusEl.removeAttribute('tabindex'); + } +} + +// An error from the shell or the app's Rust side, in plain words with its next step; the raw +// text stays behind a press on the line (meter.js friendlyError). +function setAgentError(raw, action) { + const friendly = friendlyError(raw, action); + setAgentStatus(friendly.text, { error: true, details: friendly.details }); +} + +function openStatusDetails() { + if (!agentStatusEl.classList.contains('is-pressable')) return; + void confirmModal({ title: 'What the bar said', lines: [{ kind: 'text', text: agentStatusEl.textContent }, ...(statusDetails ? [{ kind: 'code', text: statusDetails }] : [])], cancel: 'Close', primary: null }); +} +agentStatusEl.addEventListener('click', openStatusDetails); +agentStatusEl.addEventListener('keydown', (event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + openStatusDetails(); + } +}); + +// A message's nodes, each command it marks with backticks in a +// (meter.js commandSegments): built as text nodes, never parsed as markup. +function commandNodes(text) { + return commandSegments(text).map((part) => { + if (!part.code) return part.text; + const code = document.createElement('code'); + code.textContent = part.text; + return code; + }); } // The first key typed in the terminal while a loop runs: a note beside the agent, @@ -237,26 +341,33 @@ function renderAgentMenuHead(label, { active, ended, bypassActive }) { agentMenuHeadEl.replaceChildren(name, ' is running', document.createElement('br'), 'Permission checks are ', mode); if (bypassActive) agentMenuHeadEl.append(': it runs commands and changes files without asking'); } else if (ended) { - agentMenuHeadEl.replaceChildren(name, ` ended: ${agent.reason}`, document.createElement('br'), 'Nothing starts until you press New Session.'); + agentMenuHeadEl.replaceChildren(name, ` ${endedView(agent.reason).sentence}`, document.createElement('br'), 'Nothing starts until you press New Session.'); } else { agentMenuHeadEl.replaceChildren(); } } -// The bar's two menus (project, agent). They hang outside the scrolling bar -// row, fixed under their trigger, so the row's overflow never clips them. -// Clicking anywhere else (the console frame and the terminal too), Escape, -// a resize or a scroll of the row all close them. +// The bar's three menus (project, agent, and the "+N more" list of pending +// steps). They hang outside the bar row, fixed under their trigger, so the +// row's overflow never clips them. Clicking anywhere else (the console frame +// and the terminal too), Escape or a resize closes them. let openBarMenu = null; +const barMenus = () => [[projectMenuBtn, projectMenu], [agentMenuBtn, agentMenu], [nextStepMoreEl, moreMenu], [appMenuBtn, appMenu]]; + function closeBarMenus() { - for (const [button, menu] of [[projectMenuBtn, projectMenu], [agentMenuBtn, agentMenu]]) { + for (const [button, menu] of barMenus()) { menu.hidden = true; button.setAttribute('aria-expanded', 'false'); } openBarMenu = null; } +// A menu's items that can take focus now: shown and not off. +function barMenuItems(menu) { + return [...menu.querySelectorAll('[role="menuitem"]')].filter((item) => !item.hidden && !item.disabled); +} + function toggleBarMenu(button, menu) { const wasOpen = openBarMenu === menu; closeBarMenus(); @@ -268,24 +379,74 @@ function toggleBarMenu(button, menu) { menu.style.top = `${at.bottom + 4}px`; button.setAttribute('aria-expanded', 'true'); openBarMenu = menu; + // Focus goes into the menu: its first item, or the menu itself (tabindex + // -1) when every item is hidden or off, so Escape still hears the keyboard. + const [first] = barMenuItems(menu); + (first || menu).focus(); +} + +// Up, Down, Home and End move between a menu's items (meter.js menuStep). +function onBarMenuKey(event) { + const items = barMenuItems(event.currentTarget); + const next = menuStep(event.key, items.indexOf(document.activeElement), items.length); + if (next === null) return; + event.preventDefault(); + items[next].focus(); } projectMenuBtn.onclick = () => toggleBarMenu(projectMenuBtn, projectMenu); agentMenuBtn.onclick = () => toggleBarMenu(agentMenuBtn, agentMenu); +nextStepMoreEl.onclick = () => toggleBarMenu(nextStepMoreEl, moreMenu); +appMenuBtn.onclick = () => toggleBarMenu(appMenuBtn, appMenu); +appMenu.addEventListener('keydown', onBarMenuKey); +projectMenu.addEventListener('keydown', onBarMenuKey); +agentMenu.addEventListener('keydown', onBarMenuKey); +moreMenu.addEventListener('keydown', onBarMenuKey); document.addEventListener('pointerdown', (event) => { if (!openBarMenu) return; - if (openBarMenu.contains(event.target) || projectMenuBtn.contains(event.target) || agentMenuBtn.contains(event.target)) return; + if (barMenus().some(([button, menu]) => menu.contains(event.target) || button.contains(event.target))) return; closeBarMenus(); }); document.addEventListener('keydown', (event) => { if (event.key !== 'Escape' || !openBarMenu) return; - const trigger = openBarMenu === projectMenu ? projectMenuBtn : agentMenuBtn; + const [trigger] = barMenus().find(([, menu]) => menu === openBarMenu); closeBarMenus(); trigger.focus(); }); window.addEventListener('blur', closeBarMenus); window.addEventListener('resize', closeBarMenus); -barRowEl.addEventListener('scroll', closeBarMenus); + +// A narrow window drops parts of the bar instead of scrolling it: the model +// text first, then the status line (meter.js barFit), each moving into the +// agent menu. Measured with everything showing, so a wider window brings them +// back; redone when the row's size or its parts change. +let fitQueued = false; + +function fitBar() { + fitQueued = false; + barRowEl.classList.remove('no-model', 'no-status'); + const model = agentModelEl.hidden ? 0 : agentModelEl.offsetWidth; + const status = agentStatusEl.textContent ? agentStatusEl.offsetWidth : 0; + // Only an agent's menu can hold them, so with none the row keeps everything. + const fit = agentMenuBtn.hidden ? { model: true, status: true } : barFit({ available: barRowEl.clientWidth, needed: barRowEl.scrollWidth, model, status }); + const dropModel = !fit.model && model > 0; + const dropStatus = !fit.status && status > 0; + barRowEl.classList.toggle('no-model', dropModel); + barRowEl.classList.toggle('no-status', dropStatus); + const lines = []; + if (dropModel) lines.push(`Started on ${agentModelEl.textContent}`); + if (dropStatus) lines.push(agentStatusEl.textContent); + agentMenuMoreEl.replaceChildren(...lines.flatMap((line, i) => (i ? [document.createElement('br'), line] : [line]))); +} + +function scheduleFitBar() { + if (fitQueued) return; + fitQueued = true; + requestAnimationFrame(fitBar); +} + +new ResizeObserver(scheduleFitBar).observe(barRowEl); +new MutationObserver(scheduleFitBar).observe(barRowEl, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['hidden'] }); // True from a confirmed Restart until the fresh agent's dashboard page is // announced (showAnnounced below): the frame stays blanked with a message the @@ -293,24 +454,30 @@ barRowEl.addEventListener('scroll', closeBarMenus); // before anything can show. let restarting = false; -function confirmRestart(onYes) { +async function confirmRestart(onYes) { if (agent.state !== 'running') { onYes(); return; } - showState( - 'Restart the agent on a fresh context window?', - 'New Session', - () => { - restarting = true; - currentUrl = null; - frameReady = false; - showState('The agent is restarting on a fresh context window. Please wait for the dashboard to load.'); - onYes(); - }, - () => (frameReady ? hideState() : showState('No dashboard has loaded yet.')), - { tired: true } - ); + const yes = await confirmModal({ + title: 'Restart the agent on a fresh context window?', + lines: [{ kind: 'text', text: 'What the agent was doing is not saved.' }], + primary: 'New Session', + danger: true, + }); + if (!yes) return; + restarting = true; + currentUrl = null; + frameReady = false; + showState('The agent is restarting on a fresh context window. Please wait for the dashboard to load.'); + onYes(); +} + +// Shows the agent's terminal: expands a collapsed pane (its own button, so +// focus and the saved setting come too), else just gives it the keyboard. +function showTerminal() { + if (paneCollapsed) termCollapseBtn.click(); + else terminal.focus(); } // What the launch card offers for each agent: whether its CLI was found on @@ -371,7 +538,7 @@ function installPageButton(id) { button.textContent = 'Install page'; button.onclick = () => { invoke('open_install_page', { id }).catch((error) => { - setAgentStatus(`Could not open the install page: ${error}`, { error: true }); + setAgentError(error, 'open the install page'); }); }; return button; @@ -406,14 +573,9 @@ async function openAgentSetup(returnTo) { setupCloseBtn.hidden = false; loadFrame(session.url); } catch (error) { + // A missing console.mjs means the skills install itself is gone (FR-16): friendlyError says so. const text = String(error); - // A missing console.mjs means the skills install itself is gone (FR-16). - setAgentStatus( - text.includes('not installed') || text.includes('console.mjs') - ? "Plan2Code's skills are missing: run `plan2code update`." - : `Could not open the setup page: ${text}`, - { error: true } - ); + setAgentError(text.includes('console.mjs') ? `the web console is not installed: ${text}` : text, 'open the setup page'); } } @@ -529,6 +691,9 @@ function firstRunRow(pass, title, detail) { const mark = document.createElement('span'); mark.className = 'first-run-mark'; mark.textContent = pass ? '✓' : '!'; + // Read out as words: a bare check or exclamation mark says nothing to a screen reader. + mark.setAttribute('role', 'img'); + mark.setAttribute('aria-label', pass ? 'Ready' : 'Needs attention'); const body = document.createElement('div'); body.className = 'first-run-body'; const titleEl = document.createElement('div'); @@ -538,7 +703,7 @@ function firstRunRow(pass, title, detail) { if (detail) { const detailEl = document.createElement('div'); detailEl.className = 'first-run-detail'; - if (typeof detail === 'string') detailEl.textContent = detail; + if (typeof detail === 'string') detailEl.append(...commandNodes(detail)); else detailEl.append(detail); body.append(detailEl); } @@ -551,7 +716,7 @@ function firstRunRow(pass, title, detail) { // never a way to recover from a real failure. function renderFirstRun(state) { firstRunListEl.replaceChildren(); - const nodeDetail = `${state.nodeVersion || 'found'} (18 or newer)${state.nodeBinary ? ` — ${state.nodeBinary}` : ''}`; + const nodeDetail = `${state.nodeVersion || 'found'} (18 or newer)${state.nodeBinary ? `: ${state.nodeBinary}` : ''}`; firstRunListEl.append(firstRunRow(true, 'Node.js', nodeDetail)); const agentsKnown = agentList; @@ -607,13 +772,14 @@ async function startAgent(event) { const effort = !(info && info.custom) && (EFFORT_OPTIONS[kind] || []).length > 0 ? launchEffortEl.value || null : null; const mode = launchBypassEl.checked ? 'bypass' : 'checked'; setAgentStatus(''); - showState('Waiting for the agent to open the dashboard'); + beginWait('Waiting for the agent to open the dashboard...'); const { cols, rows } = terminal.size(); try { await invoke('agent_start', { kind, model, effort, mode, cols, rows }); terminal.focus(); } catch (error) { - setAgentStatus(`Could not start the agent: ${error}`, { error: true }); + endWait(); + setAgentError(error, 'start the agent'); showLaunchCard(); } } @@ -623,7 +789,7 @@ async function agentAction(command) { await invoke(command); terminal.focus(); } catch (error) { - setAgentStatus(String(error), { error: true }); + setAgentError(error, 'do that'); } } @@ -648,6 +814,15 @@ let paneMaximized = false; const paneExtent = () => (paneDock === 'right' ? window.innerWidth : window.innerHeight); +function setButtonLabel(button, label, tip) { + button.setAttribute('aria-label', label); + button.title = tip; +} + +// What a double-click on the splitter returns to: the share a first run starts +// with (docked right, wide enough to keep the console's aside beside it). +const defaultPaneFraction = () => (paneDock === 'right' ? defaultRightFraction(window.innerWidth, { minFraction: MIN_PANE, maxFraction: MAX_PANE }) : 0.25); + function applyPaneLayout() { workspaceEl.classList.toggle('dock-right', paneDock === 'right'); termPanel.classList.toggle('collapsed', paneCollapsed); @@ -661,11 +836,20 @@ function applyPaneLayout() { const fraction = paneMaximized ? MAXIMIZED_PANE : paneFraction; termPanel.style[sizeProp] = `${Math.round(paneExtent() * fraction)}px`; } - termDockBtn.textContent = paneDock === 'right' ? 'Dock bottom' : 'Dock right'; - termMaximizeBtn.textContent = paneMaximized ? 'Restore' : 'Maximize'; + // Icon buttons: what each does, in words, for a screen reader and a tooltip. + termDockBtn.dataset.dock = paneDock; + setButtonLabel(termDockBtn, paneDock === 'right' ? 'Dock the terminal at the bottom' : 'Dock the terminal on the right', paneDock === 'right' ? 'Dock at the bottom' : 'Dock on the right'); + setButtonLabel(termMaximizeBtn, paneMaximized ? 'Restore the terminal size' : 'Make the terminal larger', paneMaximized ? 'Restore the size' : 'Make it larger'); termMaximizeBtn.setAttribute('aria-pressed', String(paneMaximized)); - termCollapseBtn.textContent = paneCollapsed ? 'View Agent Terminal' : 'Collapse'; + setButtonLabel(termCollapseBtn, paneCollapsed ? 'Show the terminal' : 'Collapse the terminal', tipWithShortcut(paneCollapsed ? 'Show the terminal' : 'Collapse', 'toggle-terminal', IS_MAC)); termCollapseBtn.setAttribute('aria-pressed', String(paneCollapsed)); + // The splitter reads as a slider of the panel's share of the window. + termHandle.setAttribute('aria-orientation', paneDock === 'right' ? 'vertical' : 'horizontal'); + const aria = splitterAria(paneMaximized ? MAXIMIZED_PANE : paneFraction, { min: MIN_PANE, max: paneMaximized ? MAXIMIZED_PANE : MAX_PANE }); + termHandle.setAttribute('aria-valuenow', String(aria.now)); + termHandle.setAttribute('aria-valuemin', String(aria.min)); + termHandle.setAttribute('aria-valuemax', String(aria.max)); + termHandle.setAttribute('aria-valuetext', `${aria.now}% of the window`); updateBadge(); tellTerminalState(); } @@ -708,6 +892,8 @@ termCollapseBtn.onclick = () => { termHandle.addEventListener('pointerdown', (event) => { event.preventDefault(); termHandle.setPointerCapture(event.pointerId); + termHandle.classList.add('is-dragging'); + termHandle.focus(); }); termHandle.addEventListener('pointermove', (event) => { if (!termHandle.hasPointerCapture(event.pointerId)) return; @@ -718,8 +904,29 @@ termHandle.addEventListener('pointermove', (event) => { paneMaximized = false; applyPaneLayout(); }); -termHandle.addEventListener('pointerup', (event) => { +function endHandleDrag(event) { if (termHandle.hasPointerCapture(event.pointerId)) termHandle.releasePointerCapture(event.pointerId); + termHandle.classList.remove('is-dragging'); + savePaneSettings(); +} +termHandle.addEventListener('pointerup', endHandleDrag); +termHandle.addEventListener('pointercancel', endHandleDrag); +// Keyboard: arrows resize in 2% steps, Home and End go to the smallest and +// largest share (meter.js splitterFraction). +termHandle.addEventListener('keydown', (event) => { + const next = splitterFraction(event.key, paneMaximized ? MAXIMIZED_PANE : paneFraction, paneDock, { min: MIN_PANE, max: MAX_PANE }); + if (next === null) return; + event.preventDefault(); + paneFraction = next; + paneMaximized = false; + applyPaneLayout(); + savePaneSettings(); +}); +// Double-click: back to the default share. +termHandle.addEventListener('dblclick', () => { + paneFraction = defaultPaneFraction(); + paneMaximized = false; + applyPaneLayout(); savePaneSettings(); }); @@ -728,6 +935,23 @@ termHandle.addEventListener('pointerup', (event) => { // stretch of no new output at all is the giveaway. let lastOutputAt = Date.now(); +// The pill's press: show the terminal and put the keyboard in it. A pane that +// was only small (not collapsed) grows to a share where a prompt can be read. +termBadgeEl.onclick = () => { + if (paneCollapsed) { + // The click lays the pane out before it returns, so the terminal can take focus after it. + termCollapseBtn.click(); + terminal.focus(); + return; + } + if (!paneMaximized && paneFraction < SMALL_PANE * 2) { + paneFraction = Math.max(paneFraction, defaultPaneFraction()); + applyPaneLayout(); + savePaneSettings(); + } + terminal.focus(); +}; + function updateBadge() { const small = paneCollapsed || (!paneMaximized && paneFraction < SMALL_PANE); const quiet = agentActive() && Date.now() - lastOutputAt >= QUIET_BADGE_MS; @@ -770,6 +994,7 @@ window.addEventListener('message', (event) => { const kind = event.data && event.data.plan2code; if (kind === 'console-ready') { frameReady = true; + pageFailures = 0; clearTimeout(helloTimer); hideState(); // The Desktop app switch in its User Preferences shows what app.json holds. @@ -790,6 +1015,10 @@ window.addEventListener('message', (event) => { } else if (kind === 'activities-full') { const on = taskbarSwitch(event.data); if (on !== null) setGameFull(on); + } else if (kind === 'shortcut') { + // A key the page swallowed (the console's frame has the keyboard): only an id from the table. + const id = shortcutFromMessage(event.data); + if (id) runShortcut(id); } else if (kind === 'agent-continue') { typeContinue(); } else if (kind === 'terminal-open') { @@ -800,7 +1029,8 @@ window.addEventListener('message', (event) => { // The bar's own button, so the press is confirmed exactly the same way. if (!restartBtn.hidden) restartBtn.click(); } else if (kind === 'looks') { - applyAccent(event.data.accent, { save: true }); + const looks = looksFromMessage(event.data); + if (looks) applyLooks(looks, { save: true }); } else if (kind === 'loop-facts') { // The setup screen asks what agent a loop would use. The answer is facts // only; the page never sends the app any setup value. @@ -822,7 +1052,7 @@ window.addEventListener('message', (event) => { .then((info) => { source.postMessage({ plan2code: 'loop-dashboard-result', ok: true, error: null }, '*'); if (info && info.url) { - showState('Opening the dashboard'); + showState('Opening the dashboard...'); loadFrame(info.url); } }) @@ -889,33 +1119,53 @@ function typeContinue() { Promise.resolve() ) .catch((error) => { - setAgentStatus(`Could not type continue: ${error}`, { error: true }); + setAgentError(error, 'type continue'); }); } -// The person's highlight color, as the console page last sent it (its dark -// shades: fill, soft, ink, line), so the bar's buttons light in it too. Kept -// here for the next launch, which paints the bar before any page has loaded. +// The theme and highlight color, as the console page last sent them (the +// resolved theme, and the four shades fill, soft, ink, line for each theme). +// The shell wears them: data-theme on picks the tokens' light or dark +// set, the accent custom properties are the person's own, the xterm theme and +// the OS title bar follow. Both are kept for the next launch, which theme-early.js +// reads before the first paint. +const THEME_KEY = 'p2c-app:theme'; const ACCENT_KEY = 'p2c-app:accent'; const ACCENT_VARS = ['--accent', '--accent-soft', '--accent-ink', '--accent-line']; -function applyAccent(shades, { save = false } = {}) { - if (!Array.isArray(shades) || shades.length !== ACCENT_VARS.length) return; - if (!shades.every((c) => typeof c === 'string' && /^#[0-9a-f]{6}$/i.test(c))) return; - ACCENT_VARS.forEach((name, i) => document.documentElement.style.setProperty(name, shades[i])); - if (!save) return; +function applyLooks({ theme, light, dark }, { save = false } = {}) { + const root = document.documentElement; + root.setAttribute('data-theme', theme); + root.style.colorScheme = theme; + const shades = theme === 'light' && light ? light : dark; + ACCENT_VARS.forEach((name, i) => root.style.setProperty(name, shades[i])); + if (save) { + try { + localStorage.setItem(THEME_KEY, theme); + localStorage.setItem(ACCENT_KEY, JSON.stringify({ light, dark })); + } catch { + // Not remembered is fine: the stylesheet's defaults show until a page loads. + } + } + // The terminal reads the tokens, so it goes last. + terminal.applyTheme(); + setWindowTheme(theme); +} + +// The OS title bar follows the shell's theme (Tauri's window theme). A platform +// that ignores it leaves the bar as it was. +function setWindowTheme(theme) { try { - localStorage.setItem(ACCENT_KEY, JSON.stringify(shades)); + window.__TAURI__.window.getCurrentWindow().setTheme(theme).catch(() => {}); } catch { - // Not remembered is fine: the stylesheet's default shows until a page loads. + // An older runtime without setTheme: the title bar keeps the system's look. } } -try { - applyAccent(JSON.parse(localStorage.getItem(ACCENT_KEY))); -} catch { - // Nothing saved, or storage is blocked: the stylesheet's default stands. -} +// A relaunch: theme-early.js already put the saved theme on before the +// first paint; the terminal and the title bar catch up here. +terminal.applyTheme(); +setWindowTheme(document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark'); // No hello in time: ask the console why, and say so with a way forward. async function onNoHello() { @@ -938,13 +1188,35 @@ async function onNoHello() { if (!status || status.state !== 'running') { showState('The console stopped, so the page could not show.', 'Reconnect the console', reconnectConsole); } else { - showState('The console is running but its page did not show in this window.', 'Reload the page', () => { - showState('Reloading the page'); - loadFrame(currentUrl); - }); + // Counted per run of trouble: a hello or a new page starts it again. + pageFailures += 1; + const view = pageNotShownView(pageFailures); + const actions = { reload: reloadPage, reconnect: stopAndReconnect }; + const secondary = view.secondary ? { label: view.secondary.label, onClick: actions[view.secondary.action] } : null; + const details = pageDetailsLine({ url: currentUrl || status.url, health: status.state }); + showState(view.text, view.primary.label, actions[view.primary.action], undefined, { secondary, details }); } } +// Times in a row the console ran but its page did not show (pageNotShownView). +let pageFailures = 0; + +function reloadPage() { + showState('Reloading the page...'); + loadFrame(currentUrl); +} + +// Stop, then start: a console that runs but serves no page is started fresh +// on the same session, not just asked again. +async function stopAndReconnect() { + try { + await invoke('console_stop'); + } catch { + // Nothing to stop is fine: reconnectConsole starts a fresh one either way. + } + await reconnectConsole(); +} + // A waiting message that offers a way out after a countdown: the button shows // disabled, counting down, then turns into `buttonLabel`'s plain retry. let retryTimer = null; @@ -958,10 +1230,20 @@ function stopRetryCountdown() { // One automatic Try reconnecting per run of trouble (cleared when a new page is announced). let autoReconnected = false; -function showState(text, buttonLabel, onButton, onCancel, { tired = false, retryAfter = 0, autoRetry = false } = {}) { +// What the message box shows now, as showState was asked for it (null once +// hidden). +let shownState = null; + +// `secondary` is a second, plain button ({ label, onClick }); `details` a +// muted line under the buttons. +function showState(text, buttonLabel, onButton, onCancel, options = {}) { + const { tired = false, retryAfter = 0, autoRetry = false, secondary = null, details = '', rawDetails = '' } = options; + // One busy style for every wait: a spinner over the words when nothing can be pressed yet. + const busy = options.busy !== undefined ? options.busy : !buttonLabel && !onCancel; // The poll repeats the same waiting message every tick: that must not // restart a countdown that is already running (or its button). if (retryAfter > 0 && !stateBox.hidden && stateText.textContent === text && stateButton.textContent.startsWith('Try reconnecting')) return; + shownState = { text, buttonLabel, onButton, onCancel, options }; stopRetryCountdown(); hideLaunchCard(); hideFirstRun(); @@ -969,12 +1251,24 @@ function showState(text, buttonLabel, onButton, onCancel, { tired = false, retry // `.hidden` property to the attribute, so toggling the property alone left // `hidden` in the markup forever. The attribute itself always works. statePlannyEl.toggleAttribute('hidden', !tired); + // Plain Planny is the first frame's "Starting Plan2Code"; the coffee break adds the mug. + statePlannyEl.classList.toggle('is-plain', !tired); + statePlannyEl.setAttribute('viewBox', tired ? '0 7 29 23' : '0 7 22 23'); stateText.textContent = text; stateButton.hidden = !buttonLabel; stateButton.textContent = buttonLabel || ''; stateButton.onclick = onButton || null; stateCancelEl.hidden = !onCancel; stateCancelEl.onclick = onCancel || null; + stateSecondaryEl.hidden = !secondary; + stateSecondaryEl.textContent = secondary ? secondary.label : ''; + stateSecondaryEl.onclick = secondary ? secondary.onClick : null; + stateBusyEl.hidden = !busy; + // A friendly error keeps its raw text behind Details; a bug-report line (details) shows as it is. + stateDetailsEl.hidden = !details; + stateDetailsEl.textContent = details || rawDetails; + stateToggleEl.hidden = !rawDetails || Boolean(details); + stateToggleEl.setAttribute('aria-expanded', 'false'); stateBox.hidden = false; if (retryAfter > 0 && buttonLabel) { let left = retryAfter; @@ -996,9 +1290,60 @@ function showState(text, buttonLabel, onButton, onCancel, { tired = false, retry } } +// A raw error as a sentence with its next step and a Details link (meter.js friendlyError). +function showErrorState(raw, action, buttonLabel, onButton, onCancel) { + const friendly = friendlyError(raw, action); + showState(friendly.text, buttonLabel, onButton, onCancel, { rawDetails: friendly.details }); +} + +stateToggleEl.onclick = () => { + const open = stateDetailsEl.hidden; + stateDetailsEl.hidden = !open; + stateToggleEl.setAttribute('aria-expanded', String(open)); +}; + +// While the agent starts and the dashboard has not opened: after ~12 s the pane stops saying +// "waiting" alone and says where to look (meter.js waitingView), and an agent that ended gets +// Change agent beside it. +let waitStartedAt = 0; +let waitTimer = null; +let waitKey = ''; + +function beginWait(text) { + waitStartedAt = Date.now(); + waitKey = ''; + showState(text, undefined, undefined, undefined, { waiting: true }); + clearInterval(waitTimer); + waitTimer = setInterval(tickWait, 1000); +} + +function endWait() { + clearInterval(waitTimer); + waitTimer = null; +} + +function tickWait() { + // Gone from the screen (the dashboard came, or something else spoke): nothing left to time. + if (stateBox.hidden || !shownState || !shownState.options.waiting) { + endWait(); + return; + } + const view = waitingView({ waitedMs: Date.now() - waitStartedAt, agentState: agent.state }); + const key = view.still ? `${view.text}|${view.changeAgent}` : ''; + if (!view.still || key === waitKey) return; + waitKey = key; + showState(view.text, 'Show the terminal', showTerminal, undefined, { + waiting: true, + busy: !view.changeAgent, + secondary: view.changeAgent ? { label: 'Change agent', onClick: showLaunchCard } : null, + }); +} + function hideState() { + endWait(); stopRetryCountdown(); stateBox.hidden = true; + shownState = null; } let pollTimer = null; @@ -1008,12 +1353,12 @@ let pollTimer = null; // does, by running the skill), so there is nothing to start before that. async function reconnectConsole() { markConsoleAlive(); - showState('Reconnecting to the console'); + showState('Reconnecting to the console...'); try { const info = await invoke('console_start'); loadFrame(info.url); } catch (error) { - showState(`The console could not be reached: ${error}`, 'Retry', reconnectConsole); + showErrorState(error, 'reach the console', 'Retry', reconnectConsole); // An old console cannot be framed: the fix is the skills update, so offer it. if (String(error).includes('too old')) setVersionState({ kind: 'too-old' }); } @@ -1042,7 +1387,7 @@ async function pollConsole() { markConsoleDead(); if (action === 'reconnect') { reconnects += 1; - showState('The console stopped. Reconnecting'); + showState('The console stopped. Reconnecting...'); await reconnectConsole(); } else if (action === 'no-hello') { onNoHello(); @@ -1066,27 +1411,103 @@ async function checkVersions() { } } -// Once, at start, and never waited on: is a newer Plan2Code release out on GitHub? The Rust -// side asks (the same tag lookup the web console uses) and answers with the newer version, or -// nothing when the app is current or the lookup failed. +// At start, and again every few hours (the app stays open for days), never waited on: is a newer +// Plan2Code release out on GitHub? The Rust side asks (the same tag lookup the web console uses) and +// answers `{ latest, problem }`: the newer version, or a sentence when the check could not run (git +// missing), or neither when the app is current. An update already running is never replaced. async function checkNewRelease() { try { - const latest = await invoke('check_new_release'); - if (latest) setNewRelease({ latest, copied: false }); + setNewRelease(releaseAfterCheck(newRelease, await invoke('check_new_release'))); } catch { // No answer is no reason to nag. } } -async function copyUpdateCommand() { - if (!newRelease) return; +// "Update and restart": the installer runs unpinned (the newest release) through the same progress +// line as Update skills, then the app restarts itself, guarded by the quit check. A failure leaves +// this app running, with the reason in the bar and the old command as the fallback. +async function updateAndRestart() { + if (!newRelease || !newRelease.latest) return; + const latest = newRelease.latest; + setNewRelease({ latest, updating: '' }); + const progress = new Channel(); + progress.onmessage = (line) => { + if (line && newRelease && newRelease.updating !== undefined) setNewRelease({ latest, updating: line }); + }; try { - await navigator.clipboard.writeText(NEW_RELEASE_COMMAND); - setNewRelease({ ...newRelease, copied: true }); - } catch { - // The webview refused the clipboard: the bar spells the command out instead. - setNewRelease({ ...newRelease, manual: true }); + await invoke('update_to_newest', { progress }); + } catch (error) { + setNewRelease({ latest, failed: reasonSentence(error) }); + return; } + await restartApp(latest); +} + +// The respawn itself. With an agent or a loop running the person is asked first (the quit check): +// "asking" leaves the app up, so the bar then offers Restart Plan2Code for when they are ready. +async function restartApp(latest = newRelease && newRelease.latest) { + if (latest) setNewRelease({ latest, updating: 'Restarting Plan2Code...' }); + try { + const outcome = await invoke('restart_app', { confirmed: false }); + if (outcome === 'asking' && latest) setNewRelease({ latest, restartNeeded: true }); + } catch (error) { + if (latest) setNewRelease({ latest, failed: reasonSentence(error) }); + else setAgentError(error, 'restart Plan2Code'); + } +} + +// After the restart: "Updated to vX", once, for a short while. +async function showUpdatedTo() { + try { + const status = await invoke('version_status'); + const now = status.app || null; + // The same version after the restart: the installer kept the old app (no desktop app file in + // that release yet), so it is not "Updated to". + if (now && appState && appState.updatedFrom && now === appState.updatedFrom) { + notReplaced = now; + updatedTo = null; + } else { + updatedTo = now; + notReplaced = null; + } + } catch { + updatedTo = null; + notReplaced = null; + } + renderNextStep(); + setTimeout(() => { + updatedTo = null; + notReplaced = null; + renderNextStep(); + }, UPDATED_NOTE_MS); +} + +// The About dialog and Check for updates, from the bar's menu. +async function showAbout() { + let status = null; + try { + status = await invoke('version_status'); + } catch { + // The dialog still opens, with what it can say. + } + const lines = [{ kind: 'text', text: status && status.app ? `This is Plan2Code v${status.app}.` : 'Plan2Code desktop app.' }]; + if (status && status.skills) lines.push({ kind: 'text', text: `The installed skills are v${status.skills}.` }); + const notes = status && status.app && (await confirmModal({ title: 'About Plan2Code', lines, primary: 'Release notes', cancel: 'Close', safeFirst: true })); + if (notes) openLink(releaseNotesUrl(status.app)); + else if (!status || !status.app) void confirmModal({ title: 'About Plan2Code', lines, cancel: 'Close', primary: null }); +} + +async function checkUpdatesNow() { + let result = null; + try { + result = await invoke('check_new_release'); + } catch { + // Said below. + } + setNewRelease(releaseAfterCheck(newRelease, result)); + if (result && result.latest) return; + const text = result ? result.problem || 'Plan2Code is up to date.' : 'Could not check for updates.'; + void confirmModal({ title: 'Check for updates', lines: [{ kind: 'text', text }], cancel: 'Close', primary: null }); } async function updateSkills() { @@ -1123,6 +1544,7 @@ async function restartConsole() { // it is shows inside the frame itself (the console's own badge and title), // not repeated here. function showAnnounced(notice) { + endWait(); restarting = false; // A new page is a new start: the budget is per run of trouble, not per launch. reconnects = 0; @@ -1133,7 +1555,9 @@ function showAnnounced(notice) { } markConsoleAlive(); if (notice.url !== currentUrl) { - showState('Opening the page'); + // A new page gets its own Reload the page before "still did not load". + pageFailures = 0; + showState('Opening the page...'); loadFrame(notice.url); } } @@ -1182,7 +1606,7 @@ function applyLoopLocks(state) { const { locked, reason } = loopLocks(state); for (const button of [changeProjectBtn, changeAgentBtn]) { button.disabled = locked; - button.title = locked ? reason : ''; + button.title = locked ? reason : button === changeProjectBtn ? tipWithShortcut('Change project', 'change-project', IS_MAC) : ''; } } @@ -1270,16 +1694,33 @@ window.__TAURI__.event // A press that fails shows why next to the buttons, with a Retry for the same press. let loopRetryAction = null; +let loopErrorRaw = ''; +loopErrorEl.tabIndex = 0; +const openLoopError = () => { + void confirmModal({ title: 'What went wrong', lines: [{ kind: 'text', text: loopErrorEl.textContent }, ...(loopErrorRaw ? [{ kind: 'code', text: loopErrorRaw }] : [])], cancel: 'Close', primary: null }); +}; +loopErrorEl.addEventListener('click', openLoopError); +loopErrorEl.addEventListener('keydown', (event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + openLoopError(); + } +}); function hideLoopError() { loopErrorEl.hidden = true; loopErrorEl.textContent = ''; + loopErrorRaw = ''; loopRetryBtn.hidden = true; loopRetryAction = null; } function pressLoop(command, args) { const press = () => invoke(command, args).then(hideLoopError, (e) => { - loopErrorEl.textContent = `Could not do that: ${String(e && e.message ? e.message : e)}`; + // In plain words, with the raw text behind a press on the line. + const friendly = friendlyError(String(e && e.message ? e.message : e), 'do that'); + loopErrorEl.textContent = friendly.text; + loopErrorEl.title = friendly.details; + loopErrorRaw = friendly.details; loopErrorEl.hidden = false; loopRetryBtn.hidden = false; loopRetryAction = press; @@ -1290,17 +1731,15 @@ loopRetryBtn.onclick = () => { if (loopRetryAction) loopRetryAction(); }; loopStopAfterBtn.onclick = () => pressLoop('loop_stop_after_phase', { on: !loopStopAfterOn }); -loopStopNowBtn.onclick = () => - showState( - "End the agent now? This phase's changes stay uncommitted.", - 'Stop now', - () => { - frameReady ? hideState() : showState('No dashboard has loaded yet.'); - pressLoop('loop_stop_now'); - }, - () => (frameReady ? hideState() : showState('No dashboard has loaded yet.')), - { tired: true } - ); +loopStopNowBtn.onclick = async () => { + const yes = await confirmModal({ + title: 'End the agent now?', + lines: [{ kind: 'text', text: "This phase's changes stay uncommitted." }], + primary: 'Stop now', + danger: true, + }); + if (yes) pressLoop('loop_stop_now'); +}; // The right end of the bar: whether the console stopped answering and where // the skills stand against this app, drawn as one next step (meter.js @@ -1308,23 +1747,71 @@ loopStopNowBtn.onclick = () => let consoleDead = false; let versionState = null; let newRelease = null; -const NEXT_STEP_ACTIONS = { reconnect: reconnectConsole, 'restart-console': restartConsole, update: updateSkills, 'copy-update': copyUpdateCommand }; +const NEXT_STEP_ACTIONS = { reconnect: reconnectConsole, 'restart-console': restartConsole, update: updateSkills, 'update-restart': () => updateAndRestart(), 'restart-app': () => restartApp() }; +const UPDATED_NOTE_MS = 20000; +let updatedTo = null; +let notReplaced = null; let nextStepAction = null; function renderNextStep() { - const steps = barNextSteps({ consoleDead, version: versionState, newRelease }); + const steps = barNextSteps({ consoleDead, version: versionState, newRelease, updatedTo, notReplaced }); nextStepEl.hidden = steps.length === 0; const [first, ...rest] = steps; - nextStepTextEl.textContent = first ? first.text : ''; - nextStepTextEl.title = first ? first.title : ''; + nextStepTextEl.replaceChildren(...commandNodes(first ? first.text : '')); + nextStepTextEl.title = first ? plainCommandText(first.title) : ''; nextStepTextEl.className = first ? `is-${first.tone}${first.busy ? ' is-busy' : ''}` : ''; nextStepAction = first && first.action ? NEXT_STEP_ACTIONS[first.action] : null; nextStepBtn.hidden = !nextStepAction; nextStepBtn.disabled = false; nextStepBtn.textContent = first && first.label ? first.label : ''; + // "What's new": the release page, in the default browser. + const notes = first && first.link ? first.link : null; + nextStepNotesEl.hidden = !notes; + nextStepNotesEl.onclick = notes ? () => openLink(notes.url) : null; nextStepMoreEl.hidden = rest.length === 0; nextStepMoreEl.textContent = `+${rest.length} more`; - nextStepMoreEl.title = rest.map((step) => step.title).join('\n'); + nextStepMoreEl.setAttribute('aria-label', `${rest.length} more ${rest.length === 1 ? 'step' : 'steps'}`); + renderMoreMenu(rest); +} + +// The other pending steps, each with its full sentence (a failed update's +// last line included) and its own action, when it has one. +function renderMoreMenu(rest) { + moreMenu.replaceChildren( + ...rest.map((step) => { + const row = document.createElement('div'); + row.className = 'more-step'; + const text = document.createElement('p'); + text.className = `is-${step.tone}`; + text.replaceChildren(...commandNodes(step.title)); + row.append(text); + const action = step.action ? NEXT_STEP_ACTIONS[step.action] : null; + if (action && step.label) { + const button = document.createElement('button'); + button.type = 'button'; + button.setAttribute('role', 'menuitem'); + button.textContent = step.label; + button.onclick = () => { + closeBarMenus(); + action(); + }; + row.append(button); + } + if (step.link) { + const link = document.createElement('button'); + link.type = 'button'; + link.setAttribute('role', 'menuitem'); + link.textContent = step.link.label; + link.onclick = () => { + closeBarMenus(); + openLink(step.link.url); + }; + row.append(link); + } + return row; + }) + ); + if (rest.length === 0 && openBarMenu === moreMenu) closeBarMenus(); } function setVersionState(next) { @@ -1386,9 +1873,12 @@ function closeFolderPicker(dir) { if (resolve) resolve(dir); } -function setFolderPickerError(text) { - folderPickerErrorEl.textContent = text || ''; - folderPickerErrorEl.hidden = !text; +// The picker's error in plain words; the raw text stays as its tooltip (meter.js friendlyError). +function setFolderPickerError(raw, action) { + const friendly = raw ? friendlyError(raw, action) : { text: '', details: '' }; + folderPickerErrorEl.textContent = friendly.text; + folderPickerErrorEl.title = friendly.details; + folderPickerErrorEl.hidden = !friendly.text; } function folderPickerButtons() { @@ -1418,7 +1908,7 @@ async function showFolderPicker({ dialog }) { try { recent = (await invoke('recent_folders')) || []; } catch (error) { - setFolderPickerError(`Could not read the recent folders: ${error}`); + setFolderPickerError(error, 'read the recent folders'); } folderPickerListEl.replaceChildren( ...folderPickerRows(recent).map((row) => { @@ -1461,7 +1951,7 @@ async function chooseFolderRow(row, button, dialog) { if (row.kind === 'browse') dir = await invoke(dialog ? 'change_project' : 'pick_project_folder'); else dir = await invoke('open_recent_folder', { dir: row.dir }); } catch (error) { - setFolderPickerError(row.kind === 'browse' ? `Could not open the folder picker: ${error}` : `Could not open ${row.dir}: ${error}`); + setFolderPickerError(error, row.kind === 'browse' ? 'open the folder picker' : `open ${row.dir}`); } buttons.forEach((b) => { b.disabled = false; }); folderPickerCancelBtn.disabled = false; @@ -1476,7 +1966,7 @@ folderPickerCancelBtn.onclick = () => closeFolderPicker(null); // Escape is heard on the document: a click on the backdrop or the heading // leaves focus on the page, where a listener on the picker never sees it. document.addEventListener('keydown', (event) => { - if (event.key !== 'Escape' || folderPickerEl.hidden) return; + if (event.defaultPrevented || event.key !== 'Escape' || folderPickerEl.hidden) return; if (folderPickerCancelBtn.hidden || folderPickerCancelBtn.disabled) return; event.preventDefault(); closeFolderPicker(null); @@ -1532,19 +2022,19 @@ async function doChangeProject() { frameReady = false; afterProjectKnown(); } catch (error) { - showState(`Could not switch project: ${error}`, 'Try again', doChangeProject); + showErrorState(error, 'switch project', 'Try again', doChangeProject); } } -function changeProject() { +async function changeProject() { if (agentActive()) { - showState( - 'Stop the running agent and switch to a different project? What it was doing is not saved.', - 'Change project', - doChangeProject, - () => (frameReady ? hideState() : showLaunchCard()) - ); - return; + const yes = await confirmModal({ + title: 'Stop the running agent and switch to a different project?', + lines: [{ kind: 'text', text: 'What the agent was doing is not saved.' }], + primary: 'Change project', + danger: true, + }); + if (!yes) return; } doChangeProject(); } @@ -1561,7 +2051,7 @@ async function autoStartAgent(state) { launchAgentEl.value = state.autoStart; if (typeof state.launchModel === 'string' && state.launchModel) launchModelEl.value = state.launchModel; setAgentStatus(''); - showState('Starting the agent...'); + beginWait('Starting the agent...'); const { cols, rows } = terminal.size(); try { await invoke('agent_start', { @@ -1574,7 +2064,8 @@ async function autoStartAgent(state) { }); terminal.focus(); } catch (error) { - setAgentStatus(`Could not start the agent: ${error}`, { error: true }); + endWait(); + setAgentError(error, 'start the agent'); showLaunchCard(); } } @@ -1601,12 +2092,180 @@ async function recoverAfterReload(snapshot) { } } +// --- The one confirm dialog (A10) ------------------------------------------------------------- +// Drawn here, outside the page's frame, so the page can never fake one. `lines` are +// { kind: 'text' | 'code' | 'callout', text }; the safe button comes first and has focus, the +// named danger verb last (meter.js confirmButtons). Resolves true for the primary, false for +// Cancel or Escape. A null `primary` makes it a plain notice with one Close button. +let confirmResolve = null; +let confirmReturnFocus = null; +// The id of the Rust request on screen ('' for the shell's own), so the Rust side can take it back. +let confirmShownId = ''; +const shellParts = () => ['bar', 'loop-banner', 'workspace'].map((id) => document.getElementById(id)).filter(Boolean); + +function confirmModal({ title, lines = [], primary = 'OK', cancel = 'Cancel', danger = false, safeFirst = true, id = '' }) { + if (confirmResolve) closeConfirm(false); + return new Promise((resolve) => { + confirmResolve = resolve; + confirmShownId = id; + confirmReturnFocus = document.activeElement; + confirmTitleEl.textContent = title; + confirmBodyEl.replaceChildren( + ...lines.map((line) => { + const item = typeof line === 'string' ? { kind: 'text', text: line } : line; + if (item.kind === 'code') { + const pre = document.createElement('pre'); + pre.textContent = item.text; + return pre; + } + const p = document.createElement('p'); + if (item.kind === 'callout') p.className = 'confirm-callout'; + p.replaceChildren(...commandNodes(item.text)); + return p; + }) + ); + confirmCancelBtn.textContent = cancel; + confirmPrimaryBtn.hidden = !primary; + confirmPrimaryBtn.textContent = primary || ''; + confirmPrimaryBtn.classList.toggle('is-danger', Boolean(danger)); + const layout = confirmButtons({ safeFirst: primary ? safeFirst : true }); + confirmActionsEl.replaceChildren(...layout.order.map((which) => (which === 'cancel' ? confirmCancelBtn : confirmPrimaryBtn))); + // The rest of the shell is out of reach while it asks. + for (const part of shellParts()) part.inert = true; + confirmModalEl.hidden = false; + (layout.focus === 'cancel' ? confirmCancelBtn : confirmPrimaryBtn).focus(); + }); +} + +function closeConfirm(answer) { + const resolve = confirmResolve; + confirmResolve = null; + confirmShownId = ''; + confirmModalEl.hidden = true; + for (const part of shellParts()) part.inert = false; + const back = confirmReturnFocus; + confirmReturnFocus = null; + if (back && back.isConnected && typeof back.focus === 'function') back.focus(); + if (resolve) resolve(answer); +} + +confirmCancelBtn.onclick = () => closeConfirm(false); +confirmPrimaryBtn.onclick = () => closeConfirm(true); +// Escape is heard on the document, in the capture phase, while the modal is up: a click on the scrim +// leaves focus on the page, where a listener on the modal never sees it, and nothing behind the modal +// (the folder picker, a bar menu) may take the same key. +document.addEventListener( + 'keydown', + (event) => { + if (event.key !== 'Escape' || confirmModalEl.hidden) return; + event.preventDefault(); + event.stopImmediatePropagation(); + closeConfirm(false); + }, + true +); +confirmModalEl.addEventListener('keydown', (event) => { + if (event.key === 'Tab') { + const buttons = [...confirmActionsEl.querySelectorAll('button')].filter((b) => !b.hidden); + const next = trapTab(event.shiftKey, buttons.indexOf(document.activeElement), buttons.length); + if (next === null) return; + event.preventDefault(); + buttons[next].focus(); + } +}); + +// The Rust side asks for a confirm too (the loop start, and the quit check outside Windows): it sends +// the same fields and waits for confirm_answer. Only the fields below are read. When it gives up +// waiting (confirm-cancel) the modal it asked for goes away too. +window.__TAURI__.event.listen('confirm-cancel', (event) => { + if (typeof event.payload === 'string' && event.payload && event.payload === confirmShownId) closeConfirm(false); +}); +window.__TAURI__.event + .listen('confirm-request', async (event) => { + const req = event.payload || {}; + if (typeof req.id !== 'string' || typeof req.title !== 'string') return; + const lines = Array.isArray(req.lines) ? req.lines.filter((l) => l && typeof l.text === 'string').map((l) => ({ kind: ['code', 'callout'].includes(l.kind) ? l.kind : 'text', text: l.text })) : []; + const yes = await confirmModal({ + id: req.id, + title: req.title, + lines, + primary: typeof req.primary === 'string' ? req.primary : 'OK', + cancel: typeof req.cancel === 'string' ? req.cancel : 'Cancel', + danger: req.danger === true, + safeFirst: req.safeFirst !== false, + }); + invoke('confirm_answer', { id: req.id, yes }).catch(() => {}); + }) + // Rust asks through the OS box until the page says it is listening. + .then(() => invoke('confirm_ready').catch(() => {}), () => {}); + +// --- Shortcuts and the bar's "..." menu (A11) ----------------------------------------------- +function runShortcut(id) { + if (!confirmModalEl.hidden) return; + closeBarMenus(); + if (id === 'toggle-terminal') { + termCollapseBtn.click(); + if (paneCollapsed) frame.focus(); + } else if (id === 'focus-console') { + frame.focus(); + } else if (id === 'focus-terminal') { + showTerminal(); + } else if (id === 'new-session') { + if (!restartBtn.hidden) restartBtn.click(); + } else if (id === 'change-project') { + // Not over the bare start's own folder picker: Cancel there would leave no project at all. + if (!changeProjectBtn.disabled && folderPickerEl.hidden) changeProjectBtn.click(); + } else if (id === 'preferences') { + // The console's own dialog: it opens when a page is showing. + if (frameReady && frame.contentWindow) frame.contentWindow.postMessage({ plan2code: 'open-preferences' }, '*'); + } +} + +// Keys pressed anywhere in the shell itself (the bar, the panes' edges). The terminal's own go through +// its key handler (and have the default prevented by then), the console frame's through a message. +document.addEventListener('keydown', (event) => { + if (event.defaultPrevented) return; + const inTerminal = Boolean(event.target && event.target.closest && event.target.closest('#term')); + const id = shortcutAction(event, { mac: IS_MAC, inTerminal }); + if (!id) return; + event.preventDefault(); + runShortcut(id); +}); + +document.getElementById('app-about').onclick = () => { + closeBarMenus(); + void showAbout(); +}; +document.getElementById('app-check-updates').onclick = () => { + closeBarMenus(); + void checkUpdatesNow(); +}; +// Help is the console's own dialog, so it needs a page on screen. +function openHelp() { + if (frameReady && frame.contentWindow) frame.contentWindow.postMessage({ plan2code: 'open-help' }, '*'); + else void confirmModal({ title: 'Help', lines: [{ kind: 'text', text: 'Help opens with the dashboard. Start an agent first, then press ? in the dashboard.' }], cancel: 'Close', primary: null }); +} +document.getElementById('app-help').onclick = () => { + closeBarMenus(); + openHelp(); +}; +// The macOS menu bar's own items (main.rs build_mac_menu) do the same as the "..." menu. +window.__TAURI__.event.listen('app-menu', (event) => { + if (event.payload === 'about') void showAbout(); + else if (event.payload === 'check-updates') void checkUpdatesNow(); + else if (event.payload === 'help') openHelp(); +}); +document.getElementById('app-quit').onclick = () => { + closeBarMenus(); + invoke('request_quit').catch((error) => setAgentError(error, 'quit')); +}; + async function main() { let state; try { state = await invoke('app_state'); } catch (error) { - showState(`Could not read the app state: ${error}`, 'Retry', main); + showErrorState(error, 'read the app state', 'Retry', main); return; } appState = state; @@ -1624,11 +2283,16 @@ async function main() { savePaneSettings(); } applyPaneLayout(); + terminal.setFontSize(Number.isInteger(state.terminalFontSize) ? state.terminalFontSize : TERMINAL_FONT_DEFAULT); + terminal.setCopyOnSelect(Boolean(state.copyOnSelect)); + termTitleEl.title = `Focus the terminal (${shortcutLabel('focus-terminal', IS_MAC)}); focus the dashboard (${shortcutLabel('focus-console', IS_MAC)})`; + if (state.updatedFrom) void showUpdatedTo(); await loadAgentAvailability(); applyDefaultAgent(state.lastAgent); setInterval(updateBadge, BADGE_POLL_MS); checkVersions(); checkNewRelease(); + setInterval(checkNewRelease, UPDATE_RECHECK_MS); let reattach = null; try { @@ -1651,10 +2315,44 @@ async function main() { } if (state.projectDir) { setProjectDir(state.projectDir); + // The checklist's Node.js row needs the check's result, which the app now + // runs after the window opens. + if (!state.firstRunDone) await awaitNodeStatus(state); afterProjectKnown(); } else { chooseStartFolder(); } } +// The Node.js check runs in the background so the window opens at once: +// `nodeChecked` is false until it finishes, and a `node-status` event carries +// the same fields. Waits for it (at most NODE_WAIT_MS) and folds it into `state`. +const NODE_WAIT_MS = 15000; + +async function awaitNodeStatus(state) { + if (state.nodeChecked) return; + await new Promise((resolve) => { + let done = false; + const finish = (report) => { + if (done) return; + done = true; + if (report && typeof report === 'object') { + state.nodeChecked = true; + state.nodeVersion = report.version || null; + state.nodeBinary = report.binary || null; + state.nodeProblem = report.problem || null; + } + resolve(); + }; + window.__TAURI__.event.listen('node-status', (event) => finish(event.payload)).catch(() => finish(null)); + setTimeout(() => finish(null), NODE_WAIT_MS); + // The check may have finished between the first read and the listener. + invoke('app_state') + .then((again) => { + if (again.nodeChecked) finish({ version: again.nodeVersion, binary: again.nodeBinary, problem: again.nodeProblem }); + }) + .catch(() => {}); + }); +} + main(); diff --git a/plan2code-app/ui/index.html b/plan2code-app/ui/index.html index ee542aa..92fbb70 100644 --- a/plan2code-app/ui/index.html +++ b/plan2code-app/ui/index.html @@ -5,62 +5,75 @@ Plan2Code + + @@ -330,17 +414,28 @@ + + -