diff --git a/.github/workflows/app.yml b/.github/workflows/app.yml new file mode 100644 index 0000000..c99a5ce --- /dev/null +++ b/.github/workflows/app.yml @@ -0,0 +1,101 @@ +name: app + +on: + push: + branches: [main] + pull_request: + +jobs: + app: + name: app (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [windows-latest, macos-latest, ubuntu-latest] + defaults: + run: + working-directory: plan2code-app + steps: + - uses: actions/checkout@v4.2.2 + - uses: actions/setup-node@v4.4.0 + with: + node-version: 20 + cache: npm + cache-dependency-path: plan2code-app/package-lock.json + - name: Check the versions agree + working-directory: . + run: node scripts/check-versions.mjs + - name: Install the pinned Rust toolchain + shell: bash + # clippy and rustfmt are not part of rust-toolchain.toml's minimal profile. + run: rustup toolchain install "$(grep channel rust-toolchain.toml | cut -d '"' -f2)" --profile minimal --component clippy --component rustfmt + - name: Cache the Cargo registry and build output + uses: actions/cache@v6.1.0 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + plan2code-app/target + key: cargo-${{ runner.os }}-${{ hashFiles('plan2code-app/Cargo.lock') }} + restore-keys: | + cargo-${{ runner.os }}- + - name: Install Linux system packages + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y libwebkit2gtk-4.1-dev build-essential libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev xvfb + - name: Install the app's packages + run: npm ci + - name: Vendor the xterm files cargo needs + # `tauri build` runs this itself (beforeBuildCommand in tauri.conf.json); the cargo + # steps below call straight into cargo and skip that, so they need it run by hand. + run: node scripts/vendor.mjs + - name: Format check + run: cargo fmt --check + - name: Lint + run: cargo clippy --workspace --all-targets -- -D warnings + - name: Test + run: cargo test --workspace + - name: Build + run: cargo build --workspace + - name: Build the app (tauri build --no-bundle) + run: npm run tauri -- build --no-bundle + - name: Smoke-test the built app against the fake agent + shell: bash + # Points the real app at tests/agent_manager.rs's fake-agent fixture (already built + # by the "Build" step above, in target/debug) and checks the real binary comes up and + # stays up for a few seconds instead of crashing. Linux has no display by default. + run: | + exe=plan2code-app + agent=fake-agent + if [ "${{ runner.os }}" = "Windows" ]; then exe="$exe.exe"; agent="$agent.exe"; fi + export PLAN2CODE_APP_AGENT_BIN="$(pwd)/target/debug/$agent" + launch=("target/release/$exe") + if [ "${{ runner.os }}" = "Linux" ]; then launch=(xvfb-run -a "target/release/$exe"); fi + "${launch[@]}" & + pid=$! + sleep 5 + if kill -0 "$pid" 2>/dev/null; then + echo "plan2code-app is still running after 5s; smoke test passed" + kill "$pid" + else + wait "$pid" + echo "plan2code-app exited within 5s (exit code $?); smoke test failed" + exit 1 + fi + + node-tests: + name: npm test (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [windows-latest, macos-latest, ubuntu-latest] + steps: + - uses: actions/checkout@v4.2.2 + - uses: actions/setup-node@v4.4.0 + with: + node-version: 20 + - run: npm install + - run: npm test diff --git a/.github/workflows/release-app.yml b/.github/workflows/release-app.yml new file mode 100644 index 0000000..cd23654 --- /dev/null +++ b/.github/workflows/release-app.yml @@ -0,0 +1,119 @@ +name: release-app + +# Builds the desktop app on four systems when a GitHub release is published, or a v* tag is +# pushed ahead of one, and attaches one file per system, named +# plan2code-app---[.exe], plus one checksum file +# (plan2code-app--SHA256SUMS.txt). install.js fetches the matching file and checks it +# against that list. Linux ships the plain binary, not an AppImage: docs/desktop-app.md documents +# its WebKitGTK 4.1 dependency instead. The first release is unsigned: docs/desktop-app.md says +# how to allow it. + +on: + release: + types: [published] + push: + tags: ['v*'] + +permissions: + contents: write + +jobs: + build: + name: build (${{ matrix.label }}) + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + include: + - { runner: windows-latest, label: windows-x64, built: plan2code-app.exe, suffix: .exe } + - { runner: macos-latest, label: macos-arm64, built: plan2code-app, suffix: '' } + - { runner: macos-13, label: macos-x64, built: plan2code-app, suffix: '' } + - { runner: ubuntu-latest, label: linux-x64, built: plan2code-app, suffix: '' } + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v4.2.2 + - uses: actions/setup-node@v4.4.0 + with: + node-version: 22 + cache: npm + cache-dependency-path: plan2code-app/package-lock.json + - name: Check the versions agree with the release tag + env: + TAG: ${{ github.event.release.tag_name || github.ref_name }} + run: node scripts/check-versions.mjs --tag "$TAG" + - name: Install the pinned Rust toolchain + working-directory: plan2code-app + run: rustup toolchain install "$(grep channel rust-toolchain.toml | cut -d '"' -f2)" --profile minimal + - name: Cache the Cargo registry and build output + uses: actions/cache@v6.1.0 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + plan2code-app/target + key: cargo-release-${{ matrix.label }}-${{ hashFiles('plan2code-app/Cargo.lock') }} + restore-keys: | + cargo-release-${{ matrix.label }}- + - name: Install Linux system packages + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y libwebkit2gtk-4.1-dev build-essential libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev + - name: Install the app's packages + working-directory: plan2code-app + run: npm ci + # One plain executable per system: the web page is built into it, so it needs no installer. + - name: Build + working-directory: plan2code-app + run: npm run tauri -- build --no-bundle + - name: Name the file + run: | + VERSION="$(node -p "require('./plan2code-app/src-tauri/tauri.conf.json').version")" + mkdir -p dist + cp "plan2code-app/target/release/${{ matrix.built }}" "dist/plan2code-app-${VERSION}-${{ matrix.label }}${{ matrix.suffix }}" + - uses: actions/upload-artifact@v4.6.2 + with: + name: app-${{ matrix.label }} + path: dist/* + if-no-files-found: error + + publish: + name: attach to the release + needs: build + runs-on: ubuntu-latest + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ github.event.release.tag_name || github.ref_name }} + steps: + - uses: actions/checkout@v4.2.2 + - uses: actions/download-artifact@v4.3.0 + with: + path: dist + pattern: app-* + merge-multiple: true + - name: Verify every system's file is here + run: | + VERSION="$(node -p "require('./plan2code-app/src-tauri/tauri.conf.json').version")" + cd dist + missing=0 + for name in "plan2code-app-${VERSION}-windows-x64.exe" "plan2code-app-${VERSION}-macos-arm64" "plan2code-app-${VERSION}-macos-x64" "plan2code-app-${VERSION}-linux-x64"; do + if [ ! -f "$name" ]; then + echo "::error::missing release asset $name" + missing=1 + fi + done + [ "$missing" -eq 0 ] + - name: Write the checksum file + run: | + VERSION="$(node -p "require('./plan2code-app/src-tauri/tauri.conf.json').version")" + cd dist + sha256sum plan2code-app-* > "plan2code-app-${VERSION}-SHA256SUMS.txt" + cat "plan2code-app-${VERSION}-SHA256SUMS.txt" + - name: Make sure the release exists + # A tag push alone names no release; create one (same tag, generated notes) so the + # upload below always has somewhere to go, whichever trigger ran it. + run: gh release view "$TAG" || gh release create "$TAG" --title "$TAG" --generate-notes + - name: Attach to the release + run: gh release upload "$TAG" dist/* --clobber diff --git a/docs/desktop-app.md b/docs/desktop-app.md new file mode 100644 index 0000000..f22ab50 --- /dev/null +++ b/docs/desktop-app.md @@ -0,0 +1,109 @@ +# The Plan2Code desktop app + +One window for working with an AI agent. The app opens the Plan2Code dashboard as its main surface, +runs your agent (Claude Code, Devin or Codex) in a terminal panel it owns, and has a **Restart** +button that replaces the agent with a fresh one on a brief the app builds from its own record of the +session. It is an addition: `/plan2code` typed inside an agent works exactly as before, with or +without the app. + +## 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 +``` + +Answer **Y** to "Also install the Plan2Code desktop app?" (it is the default). It downloads the file +for your system from the GitHub release, checks it against the release's checksum list and puts it in +`~/.plan2code/app/`. If a checksum does not match, the file is thrown away and nothing is installed. +If the download fails, the skills and the `plan2code` command are still installed; the installer says +so, and you can run the installer again later. + +Releases carry one file per system: + +| System | File | +| --- | --- | +| Windows (64-bit Intel or AMD) | `plan2code-app--windows-x64.exe` | +| macOS (Apple silicon) | `plan2code-app--macos-arm64` | +| macOS (Intel) | `plan2code-app--macos-x64` | +| Linux (64-bit Intel or AMD) | `plan2code-app--linux-x64` | + +On any other system the installer says there is no build for it and carries on without the 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. + +## Start it + +Run `plan2code` in your project, as always. When the app is installed and a window can open, +`plan2code` asks which agent and model (as before) and then opens the app on that folder instead of +running the agent in your terminal. The desktop shortcut the installer can create runs the same +command, so it opens the app too. + +Three things keep today's terminal flow: + +- **`plan2code --classic`** runs the agent in your terminal even when the app is installed. +- **No display.** On Linux without a display (over SSH, in a container) `plan2code` falls back to the + terminal flow by itself. +- **An SSH or service session on macOS or Windows.** The same fallback applies there, since neither + has a desktop to open a window on either. +- **Not a project folder.** If the folder is not a git repository and has no `AGENTS.md` or `specs/`, + `plan2code` asks you to confirm before opening the app on it. + +## What's in the window + +The first time the app opens on a folder, a checklist confirms Node, the agent CLI, the project +folder and the skills version before anything else shows; a later launch skips straight past it. + +A **launch card** then asks which agent (Claude, Devin or Codex), model and effort (Claude and Codex +only) to start on. Permission checks off is its own tick, unchanged unless you choose it (Restart +keeps whatever you picked); a CLI the app cannot find is named, with how to install it, instead of +just being greyed out. The card is skipped when the launcher already passed an agent to start. + +Once an agent is running, a slim top bar holds the project name, **Restart** and **Change project**, +and a status strip beneath it shows the page the agent opened (not only the dashboard — every console +page, including Ask, Workspace, Notebook, Help, Preferences and Git, opens inside the window), the +agent's name and status, a context meter once one is readable, and the permission mode in use. The +terminal panel has its own toolbar: dock it to the bottom or the right, collapse it to a thin strip, +or maximize it; its size is remembered. An "agent may need you" badge appears on a collapsed or small +panel once the agent has sat quiet for a while. **Change project** asks first if an agent is running, +then stops it and the console before opening the new folder. + +## Keep it up to date + +`plan2code update` brings the skills, the `plan2code` command and the app up together. If the app +and the installed skills ever differ in version, the app's top bar says so and offers **Update +skills**, which runs that same update when you press it. It never updates on its own. + +## The first release is unsigned + +The app is not code-signed yet, so your system may stop it the first time it starts. 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. + +**Windows.** If SmartScreen shows "Windows protected your PC": press **More info**, then **Run +anyway**. + +**Linux.** Nothing to allow. If the file is not executable, run +`chmod +x ~/.plan2code/app/plan2code-app`. + +## Permission checks are off, if you choose it + +The launch card's permission-mode tick is off by default: leave it off and the agent keeps its normal +approval prompts. Turn it on and the agent starts with checks off instead +(`--permission-mode bypassPermissions` in Claude Code, `--permission-mode bypass` in Devin, +`--dangerously-bypass-approvals-and-sandbox` in Codex), reading, writing and running commands in your +project folder without asking; the status strip says so while that agent runs. Restart keeps the same +choice. Work in a folder you are happy for the agent to change, and keep it under version control, +before turning checks off. + +## Remove it + +Choose **Uninstall** in the installer menu: it removes the app with everything else Plan2Code +installed. To remove only the app, delete the `~/.plan2code/app/` folder. diff --git a/plan2code-app/Cargo.lock b/plan2code-app/Cargo.lock new file mode 100644 index 0000000..cc37e7f --- /dev/null +++ b/plan2code-app/Cargo.lock @@ -0,0 +1,4624 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + +[[package]] +name = "alloc-stdlib" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "atk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" +dependencies = [ + "atk-sys", + "glib", + "libc", +] + +[[package]] +name = "atk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2", +] + +[[package]] +name = "brotli" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8b851b75c23ca7873623d612fe49bd1989aeb03d08fb9432187eb253d3d4c6b" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "941cd9bd4ddab83cb46fa5a2d428f1c857b24ac78cb876cf7beb710840934bd7" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] + +[[package]] +name = "cairo-rs" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" +dependencies = [ + "bitflags 2.13.2", + "cairo-sys-rs", + "glib", + "libc", + "once_cell", + "thiserror 1.0.69", +] + +[[package]] +name = "cairo-sys-rs" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "camino" +version = "1.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" +dependencies = [ + "serde_core", +] + +[[package]] +name = "cargo-platform" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea" +dependencies = [ + "serde", +] + +[[package]] +name = "cargo_metadata" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba" +dependencies = [ + "camino", + "cargo-platform", + "semver", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "cargo_toml" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9" +dependencies = [ + "semver", + "serde", + "toml 1.1.8+spec-1.1.0", +] + +[[package]] +name = "cc" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfb" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a347dcabdae9c31b0825fd6a8bed285ec9c2acb89c47827126d52fa4f59cece3" +dependencies = [ + "fnv", + "uuid", + "web-time", +] + +[[package]] +name = "cfg-expr" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" +dependencies = [ + "smallvec", + "target-lexicon", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "time", + "version_check", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" +dependencies = [ + "bitflags 2.13.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" +dependencies = [ + "bitflags 2.13.2", + "core-foundation", + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "cssparser" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "phf", + "smallvec", +] + +[[package]] +name = "cssparser-macros" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a" +dependencies = [ + "quote", + "syn 3.0.9", +] + +[[package]] +name = "ctor" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.9", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dbus" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e" +dependencies = [ + "libc", + "libdbus-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "defmt" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "defmt-parser" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "block2", + "libc", + "objc2", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dlopen2" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4" +dependencies = [ + "dlopen2_derive", + "libc", + "once_cell", + "winapi", +] + +[[package]] +name = "dlopen2_derive" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbbb781877580993a8707ec48672673ec7b81eeba04cfd2310bd28c08e47c8f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "dom_query" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc" +dependencies = [ + "bit-set", + "cssparser", + "foldhash", + "html5ever", + "precomputed-hash", + "selectors", + "tendril", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +dependencies = [ + "serde", +] + +[[package]] +name = "dtoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" + +[[package]] +name = "dtoa-short" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" +dependencies = [ + "dtoa", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "embed-resource" +version = "3.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f" +dependencies = [ + "cc", + "memchr", + "rustc_version", + "toml 1.1.8+spec-1.1.0", + "vswhom", + "winreg 0.56.0", +] + +[[package]] +name = "embed_plist" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "erased-serde" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fake-agent" +version = "3.0.0" +dependencies = [ + "terminal_size", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "field-offset" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" +dependencies = [ + "memoffset", + "rustc_version", +] + +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gdk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691" +dependencies = [ + "cairo-rs", + "gdk-pixbuf", + "gdk-sys", + "gio", + "glib", + "libc", + "pango", +] + +[[package]] +name = "gdk-pixbuf" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec" +dependencies = [ + "gdk-pixbuf-sys", + "gio", + "glib", + "libc", + "once_cell", +] + +[[package]] +name = "gdk-pixbuf-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gdk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7" +dependencies = [ + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkwayland-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69" +dependencies = [ + "gdk-sys", + "glib-sys", + "gobject-sys", + "libc", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkx11" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe" +dependencies = [ + "gdk", + "gdkx11-sys", + "gio", + "glib", + "libc", + "x11", +] + +[[package]] +name = "gdkx11-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d" +dependencies = [ + "gdk-sys", + "glib-sys", + "libc", + "system-deps", + "x11", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "gio" +version = "0.18.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "gio-sys", + "glib", + "libc", + "once_cell", + "pin-project-lite", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "gio-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", + "winapi", +] + +[[package]] +name = "glib" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5" +dependencies = [ + "bitflags 2.13.2", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "futures-util", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", + "libc", + "memchr", + "once_cell", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "glib-macros" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc" +dependencies = [ + "heck 0.4.1", + "proc-macro-crate 2.0.2", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "glib-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" +dependencies = [ + "libc", + "system-deps", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "gobject-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gtk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a" +dependencies = [ + "atk", + "cairo-rs", + "field-offset", + "futures-channel", + "gdk", + "gdk-pixbuf", + "gio", + "glib", + "gtk-sys", + "gtk3-macros", + "libc", + "pango", + "pkg-config", +] + +[[package]] +name = "gtk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414" +dependencies = [ + "atk-sys", + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "system-deps", +] + +[[package]] +name = "gtk3-macros" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d" +dependencies = [ + "proc-macro-crate 1.3.1", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "html5ever" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" +dependencies = [ + "log", + "markup5ever", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "ico" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e795dff5605e0f04bff85ca41b51a96b83e80b281e96231bcaaf1ac35103371" +dependencies = [ + "byteorder", + "png 0.17.16", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "infer" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4" +dependencies = [ + "cfb", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "javascriptcore-rs" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc" +dependencies = [ + "bitflags 1.3.2", + "glib", + "javascriptcore-rs-sys", +] + +[[package]] +name = "javascriptcore-rs-sys" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "jiff" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +dependencies = [ + "defmt", + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "json-patch" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72" +dependencies = [ + "jsonptr", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "jsonptr" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "keyboard-types" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d" +dependencies = [ + "bitflags 2.13.2", + "serde", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libappindicator" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a" +dependencies = [ + "glib", + "gtk", + "gtk-sys", + "libappindicator-sys", + "log", +] + +[[package]] +name = "libappindicator-sys" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf" +dependencies = [ + "gtk-sys", + "libloading", + "once_cell", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libdbus-sys" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043" +dependencies = [ + "pkg-config", +] + +[[package]] +name = "libloading" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +dependencies = [ + "cfg-if", + "winapi", +] + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "markup5ever" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" +dependencies = [ + "log", + "tendril", + "web_atoms", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "muda" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996" +dependencies = [ + "crossbeam-channel", + "dpi", + "gtk", + "keyboard-types", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "once_cell", + "png 0.18.1", + "serde", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "nix" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", + "objc2-exception-helper", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-core-foundation", + "objc2-foundation", + "objc2-quartz-core", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-location" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-exception-helper" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a" +dependencies = [ + "cc", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "block2", + "libc", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", + "objc2-foundation", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image", + "objc2-core-location", + "objc2-core-text", + "objc2-foundation", + "objc2-quartz-core", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-web-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "pango" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4" +dependencies = [ + "gio", + "glib", + "libc", + "once_cell", + "pango-sys", +] + +[[package]] +name = "pango-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_codegen" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plan2code-app" +version = "3.0.0" +dependencies = [ + "chrono", + "libc", + "portable-pty", + "serde", + "serde_json", + "tauri", + "tauri-build", + "tauri-plugin-dialog", + "winapi", +] + +[[package]] +name = "plist" +version = "1.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65dca778f41c79ebbe8b2b2139fee86f01b766b67130d108c7c2b8ffbd949f77" +dependencies = [ + "base64 0.23.1", + "indexmap 2.14.2", + "quick-xml", + "serde", + "time", +] + +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "portable-pty" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a596a2b3d2752d94f51fac2d4a96737b8705dddd311a32b9af47211f08671e" +dependencies = [ + "anyhow", + "bitflags 1.3.2", + "downcast-rs", + "filedescriptor", + "lazy_static", + "libc", + "log", + "nix", + "serial2", + "shared_library", + "shell-words", + "winapi", + "winreg 0.10.1", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit 0.19.15", +] + +[[package]] +name = "proc-macro-crate" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24" +dependencies = [ + "toml_datetime 0.6.3", + "toml_edit 0.20.2", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit 0.25.17+spec-1.1.0", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "rfd" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672" +dependencies = [ + "block2", + "dispatch2", + "glib-sys", + "gobject-sys", + "gtk-sys", + "js-sys", + "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-sys 0.60.2", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schemars" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" +dependencies = [ + "dyn-clone", + "indexmap 1.9.3", + "schemars_derive", + "serde", + "serde_json", + "url", + "uuid", +] + +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.119", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "selectors" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d" +dependencies = [ + "bitflags 2.13.2", + "cssparser", + "derive_more", + "log", + "new_debug_unreachable", + "phf", + "phf_codegen", + "precomputed-hash", + "rustc-hash", + "servo_arc", + "smallvec", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde-untagged" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058" +dependencies = [ + "erased-serde", + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_with" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f" +dependencies = [ + "base64 0.23.1", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.2", + "jiff", + "schemars 0.9.0", + "schemars 1.2.3", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serial2" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b16809bc35793b19ce4e0c53924bc0dce3937f15487997cfdaed936004180730" +dependencies = [ + "cfg-if", + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "serialize-to-javascript" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5" +dependencies = [ + "serde", + "serde_json", + "serialize-to-javascript-impl", +] + +[[package]] +name = "serialize-to-javascript-impl" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "servo_arc" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shared_library" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11" +dependencies = [ + "lazy_static", + "libc", +] + +[[package]] +name = "shell-words" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "softbuffer" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3" +dependencies = [ + "bytemuck", + "js-sys", + "ndk", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "objc2-quartz-core", + "raw-window-handle", + "redox_syscall", + "tracing", + "wasm-bindgen", + "web-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "soup3" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f" +dependencies = [ + "futures-channel", + "gio", + "glib", + "libc", + "soup3-sys", +] + +[[package]] +name = "soup3-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_vcruntime" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff7589a1859b09232522bb9edf076ca7fcf14ded96685d3fa629db73023ffbb7" + +[[package]] +name = "string_cache" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared", + "precomputed-hash", +] + +[[package]] +name = "string_cache_codegen" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "swift-rs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cefd87076fd385308ee4aff597256c902f1fbb4d031de1558efc12f8ffefadd9" +dependencies = [ + "base64 0.21.7", + "serde", + "serde_json", +] + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "system-deps" +version = "6.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" +dependencies = [ + "cfg-expr", + "heck 0.5.0", + "pkg-config", + "toml 0.8.2", + "version-compare", +] + +[[package]] +name = "tao" +version = "0.37.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400" +dependencies = [ + "bitflags 2.13.2", + "block2", + "core-foundation", + "core-graphics", + "crossbeam-channel", + "dbus", + "dispatch2", + "dlopen2", + "dpi", + "gdkwayland-sys", + "gdkx11-sys", + "gtk", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "objc2-ui-kit", + "parking_lot", + "percent-encoding", + "raw-window-handle", + "tao-macros", + "unicode-segmentation", + "url", + "windows", + "windows-core", + "windows-version", + "x11-dl", +] + +[[package]] +name = "tao-macros" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f7eeb6d99155545da6150a1795945f16ac9c178deb2a5f2e74d776107bd5849" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "target-lexicon" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" + +[[package]] +name = "tauri" +version = "2.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f316751027fc2644221d1a448564d519efb07067fda584879d9cda966391d212" +dependencies = [ + "anyhow", + "bytes", + "cookie", + "dirs", + "dunce", + "embed_plist", + "getrandom 0.3.4", + "glob", + "gtk", + "heck 0.5.0", + "http", + "jni", + "libc", + "log", + "mime", + "muda", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "objc2-ui-kit", + "objc2-web-kit", + "percent-encoding", + "plist", + "raw-window-handle", + "reqwest", + "serde", + "serde_json", + "serde_repr", + "serialize-to-javascript", + "swift-rs", + "tauri-build", + "tauri-macros", + "tauri-runtime", + "tauri-runtime-wry", + "tauri-utils", + "thiserror 2.0.21", + "tokio", + "tray-icon", + "url", + "webkit2gtk", + "webview2-com", + "window-vibrancy", + "windows", +] + +[[package]] +name = "tauri-build" +version = "2.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "641dd5fd297c99ab92717b0428cca5b9c6f960b2ac96ca131b3eebc9d70b8ddc" +dependencies = [ + "anyhow", + "cargo_toml", + "dirs", + "glob", + "heck 0.5.0", + "json-patch", + "schemars 0.8.22", + "semver", + "serde", + "serde_json", + "static_vcruntime", + "strsim", + "tauri-utils", + "tauri-winres", + "walkdir", +] + +[[package]] +name = "tauri-codegen" +version = "2.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6585c5b536c00f039d12ce70a9755172d5423bbcfd3969863baa70314c3e02f" +dependencies = [ + "base64 0.23.1", + "brotli", + "ico", + "json-patch", + "plist", + "png 0.18.1", + "proc-macro2", + "quote", + "semver", + "serde", + "serde_json", + "sha2", + "syn 2.0.119", + "tauri-utils", + "thiserror 2.0.21", + "time", + "url", + "uuid", + "walkdir", +] + +[[package]] +name = "tauri-macros" +version = "2.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2e83a0cfa1bae376e8fbbdc0b1692707aed50cd6072ce85cae4789af5d6c19f" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", + "tauri-codegen", + "tauri-utils", +] + +[[package]] +name = "tauri-plugin" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67fb21a77e8f94e8beb3325e583102488659365af0a3948b7ea244c5b779c291" +dependencies = [ + "anyhow", + "glob", + "plist", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri-utils", + "walkdir", +] + +[[package]] +name = "tauri-plugin-dialog" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7461aaacf1901915ea7b9f5cd74f8224a351ed96af0a62c07fce934003cb34b" +dependencies = [ + "log", + "raw-window-handle", + "rfd", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "tauri-plugin-fs", + "thiserror 2.0.21", + "url", +] + +[[package]] +name = "tauri-plugin-fs" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d58eb1d4984e535f47a642ffec09a2da6f5c18a12b5902d12126cb7626d628b" +dependencies = [ + "anyhow", + "dunce", + "glob", + "log", + "objc2-foundation", + "percent-encoding", + "schemars 0.8.22", + "serde", + "serde_json", + "serde_repr", + "tauri", + "tauri-plugin", + "tauri-utils", + "thiserror 2.0.21", + "toml 1.1.8+spec-1.1.0", + "url", +] + +[[package]] +name = "tauri-runtime" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c55766d99cea69055904d1735b93c2049302b2e09effd462120deb5581d78e9" +dependencies = [ + "cookie", + "dpi", + "gtk", + "http", + "jni", + "objc2", + "objc2-ui-kit", + "objc2-web-kit", + "raw-window-handle", + "serde", + "serde_json", + "tauri-utils", + "thiserror 2.0.21", + "url", + "webkit2gtk", + "webview2-com", + "windows", +] + +[[package]] +name = "tauri-runtime-wry" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d61892587aea2a85245bcaec98c6fe46268874c0a0deae5535fb71ca7b93eae" +dependencies = [ + "gtk", + "http", + "jni", + "log", + "objc2", + "objc2-app-kit", + "once_cell", + "percent-encoding", + "raw-window-handle", + "softbuffer", + "tao", + "tauri-runtime", + "tauri-utils", + "url", + "webkit2gtk", + "webview2-com", + "windows", + "wry", +] + +[[package]] +name = "tauri-utils" +version = "2.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "362ab21cd4cc713f2a02b1a9b5688198b1541cfb6907c4281e9190e0f0ef4aa3" +dependencies = [ + "anyhow", + "brotli", + "cargo_metadata", + "ctor", + "dom_query", + "dunce", + "glob", + "http", + "infer", + "json-patch", + "log", + "memchr", + "phf", + "plist", + "proc-macro2", + "quote", + "regex", + "schemars 0.8.22", + "semver", + "serde", + "serde-untagged", + "serde_json", + "serde_with", + "swift-rs", + "thiserror 2.0.21", + "toml 1.1.8+spec-1.1.0", + "url", + "urlpattern", + "uuid", + "walkdir", +] + +[[package]] +name = "tauri-winres" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c52bb6904475a6ca662f15ef787f18ade61d5740a1ee12c45d3b748efdb6f796" +dependencies = [ + "dunce", + "embed-resource", + "toml 1.1.8+spec-1.1.0", +] + +[[package]] +name = "tendril" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08" +dependencies = [ + "new_debug_unreachable", +] + +[[package]] +name = "terminal_size" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" +dependencies = [ + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d" +dependencies = [ + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.3", + "toml_edit 0.20.2", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap 2.14.2", + "serde_core", + "serde_spanned 1.1.2", + "toml_datetime 1.1.2+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 1.0.4", +] + +[[package]] +name = "toml_datetime" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.19.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +dependencies = [ + "indexmap 2.14.2", + "toml_datetime 0.6.3", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" +dependencies = [ + "indexmap 2.14.2", + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.3", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap 2.14.2", + "toml_datetime 1.1.2+spec-1.1.0", + "toml_parser", + "winnow 1.0.4", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow 1.0.4", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tray-icon" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72" +dependencies = [ + "crossbeam-channel", + "dirs", + "libappindicator", + "muda", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "once_cell", + "png 0.18.1", + "serde", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "urlpattern" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df16f50ef4cc145211879a3867ba757076b25dfee812040dcb0658bd9ae7904b" +dependencies = [ + "icu_properties", + "regex", + "serde", + "url", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vswhom" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b" +dependencies = [ + "libc", + "vswhom-sys", +] + +[[package]] +name = "vswhom-sys" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web_atoms" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3" +dependencies = [ + "phf", + "phf_codegen", + "string_cache", + "string_cache_codegen", +] + +[[package]] +name = "webkit2gtk" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793" +dependencies = [ + "bitflags 1.3.2", + "cairo-rs", + "gdk", + "gdk-sys", + "gio", + "gio-sys", + "glib", + "glib-sys", + "gobject-sys", + "gtk", + "gtk-sys", + "javascriptcore-rs", + "libc", + "once_cell", + "soup3", + "webkit2gtk-sys", +] + +[[package]] +name = "webkit2gtk-sys" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5" +dependencies = [ + "bitflags 1.3.2", + "cairo-sys-rs", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "gtk-sys", + "javascriptcore-rs-sys", + "libc", + "pkg-config", + "soup3-sys", + "system-deps", +] + +[[package]] +name = "webview2-com" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6" +dependencies = [ + "webview2-com-macros", + "webview2-com-sys", + "windows", + "windows-core", +] + +[[package]] +name = "webview2-com-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "webview2-com-sys" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb" +dependencies = [ + "thiserror 2.0.21", + "windows", + "windows-core", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "window-vibrancy" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "111e51caca442cafd9bab396628ac4d814880eaea4e63dfd76a12e9f342b5580" +dependencies = [ + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "objc2-quartz-core", + "raw-window-handle", + "windows-sys 0.61.2", + "windows-version", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-version" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "winnow" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "winreg" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +dependencies = [ + "winapi", +] + +[[package]] +name = "winreg" +version = "0.56.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" +dependencies = [ + "cfg-if", + "windows-sys 0.61.2", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "wry" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a819957a01b3119af85e638a38d242af76dbc87d130dca67bfd0441072e21ff0" +dependencies = [ + "base64 0.22.1", + "block2", + "cookie", + "crossbeam-channel", + "dirs", + "dom_query", + "dpi", + "dunce", + "gdkx11", + "gtk", + "http", + "javascriptcore-rs", + "jni", + "libc", + "ndk", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "objc2-ui-kit", + "objc2-web-kit", + "once_cell", + "percent-encoding", + "raw-window-handle", + "sha2", + "soup3", + "tao-macros", + "thiserror 2.0.21", + "url", + "webkit2gtk", + "webkit2gtk-sys", + "webview2-com", + "windows", + "windows-core", + "windows-version", + "x11-dl", +] + +[[package]] +name = "x11" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/plan2code-app/Cargo.toml b/plan2code-app/Cargo.toml new file mode 100644 index 0000000..910b417 --- /dev/null +++ b/plan2code-app/Cargo.toml @@ -0,0 +1,3 @@ +[workspace] +resolver = "2" +members = ["src-tauri", "fake-agent"] diff --git a/plan2code-app/README.md b/plan2code-app/README.md new file mode 100644 index 0000000..1f7d522 --- /dev/null +++ b/plan2code-app/README.md @@ -0,0 +1,34 @@ +# plan2code-app + +The Plan2Code desktop app (v3.0): one window with the dashboard, a terminal panel for the agent, and a Restart button. Built with Tauri 2 (Rust and a web view). + +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. + +## Layout + +| Path | What it is | +|---|---| +| `src-tauri/` | The Rust app | +| `ui/` | The app page (plain HTML, CSS and JavaScript, no framework) | +| `fake-agent/` | A stand-in agent program the tests run in a real pseudo-terminal | +| `package.json` | The app's own npm packages (xterm, the Tauri CLI). Separate from the repo root so the root and the console stay dependency-free | + +## Build and run + +Needs the Rust toolchain pinned in `rust-toolchain.toml`, Node 18+, and the Tauri 2 system packages for your system (WebView2 on Windows, WebKitGTK on Linux). + +``` +cd plan2code-app +npm install +npm run dev # run the app +npm run build # build the installable bundle +``` + +## Tests + +``` +cd plan2code-app +cargo test --workspace +``` + +Real Claude, Devin and Codex are never started by a test. The real window and terminal panel are checked by hand before each release. diff --git a/plan2code-app/RELEASE-CHECKLIST.md b/plan2code-app/RELEASE-CHECKLIST.md new file mode 100644 index 0000000..d734a8a --- /dev/null +++ b/plan2code-app/RELEASE-CHECKLIST.md @@ -0,0 +1,105 @@ +# Release checklist + +Run this before every release of the desktop app, on each system the release builds for: Windows +x64, macOS Apple silicon and Linux x64. Automated tests cover the logic and never start a real +window, a real terminal panel, or a real Claude, Devin or Codex, so everything here is by hand. + +Work from the pre-release build: publish a GitHub pre-release so `release-app.yml` attaches the files, +then install from it. Tick each box per system and note anything that is a rough edge rather than a +failure. + +## Before you start + +- [ ] `node scripts/check-versions.mjs --tag v` passes (version.json, package.json, + CHANGELOG.md and the app's tauri.conf.json, package.json and Cargo.toml all agree) +- [ ] `npm test` passes at the repo root, with the app absent +- [ ] `cargo test --workspace` passes in `plan2code-app/`, and the `app` workflow is green on all + three systems +- [ ] The pre-release has one `plan2code-app---` file per system and a + `plan2code-app--SHA256SUMS.txt` + +## Install and launch (each system) + +- [ ] Run the installer from the pre-release: it offers the app, downloads it, verifies the checksum + and places it in `~/.plan2code/app/` +- [ ] A deliberately corrupted download is rejected with the checksum message, and the skills and + the `plan2code` command are still installed +- [ ] `plan2code` in a project asks for the agent and model, then opens the app on that folder +- [ ] The agent and model picked in the launcher are the ones the app starts at once, with no + launch card or checklist shown first, and Restart keeps them +- [ ] `plan2code --classic` runs the agent in the terminal with the app installed +- [ ] Linux only: with `DISPLAY` and `WAYLAND_DISPLAY` unset, `plan2code` runs the terminal flow +- [ ] The desktop shortcut opens the folder picker and then the app +- [ ] macOS: the first start is stopped by Gatekeeper, **Open Anyway** in System Settings (Privacy & + Security) lets it through, and `docs/desktop-app.md` describes what you saw +- [ ] macOS and Linux: start the app from the Dock, Finder or a `.desktop` file (not a terminal) on + a machine where Node is only on PATH through nvm, Homebrew or Volta: the first-run checklist + still finds Node and the installed CLIs, and the console and an agent still start +- [ ] Windows: SmartScreen's **More info**, then **Run anyway**, lets it through, and + `docs/desktop-app.md` describes what you saw +- [ ] `plan2code update` updates the skills, the command and the app, including while the app is + running (Windows replaces the file by renaming the old one aside) + +## The window (each system) + +- [ ] The dashboard shows in the frame and the terminal panel is visible beneath it +- [ ] Resizing the window keeps both usable; dragging the handle resizes the panel +- [ ] The bar shows the project folder and the context meter; the permission note appears only + while an agent started with checks off is running, never otherwise +- [ ] The first run (no `firstRunDone` saved yet) shows the checklist (Node, an agent CLI, the + project folder, the skills version) before the launch card; a later launch goes straight to + the launch card +- [ ] The launch card offers agent, model, effort (Claude and Codex only) and permission mode + (off is an explicit tick, never the default); a CLI it could not find is named, not just + disabled +- [ ] **Dock the terminal to the right**: the splitter becomes vertical, the toolbar stacks, and the + dashboard keeps the rest of the width; dock it back to the bottom +- [ ] **Collapse** the terminal to a thin strip (either dock) and **Expand** it back; its size from + before collapsing is remembered +- [ ] Collapse the terminal (or shrink it small), let the agent go quiet for a while mid-answer: the + "agent may need you" badge appears on the strip; expanding it clears the badge +- [ ] **Change project** in the top bar, with an agent running: it asks first, then the folder + picker opens; cancelling the picker leaves the running agent and its project untouched +- [ ] Change project, pick a different folder: the old agent and console stop, the new folder opens + on the launch card (or the checklist, if its own first run has not passed yet) +- [ ] Reload the window (or navigate away and back) while an agent is running: the terminal redraws + from where it was, not blank, and the dashboard reconnects to the same session +- [ ] When the app and the installed skills differ in version, the bar offers **Update skills**, and + nothing updates until it is pressed + +## The terminal panel, with each real agent (each system) + +Do each of Claude Code, Devin and Codex for a few minutes: + +- [ ] Startup screen draws correctly +- [ ] Typing a prompt and getting an answer +- [ ] A long streamed answer scrolls and stays readable +- [ ] Resizing the window reflows the agent's screen +- [ ] Pasting several lines +- [ ] A line with Unicode and emoji +- [ ] Select text in the terminal: it copies on its own; Ctrl+Shift+C (Windows, Linux) or Cmd+C + (macOS) copies the selection too; Ctrl+V / Cmd+V pastes +- [ ] Exiting the agent: the bar says it ended and offers Restart + +## Agent lifecycle + +- [ ] Start, then **Restart**: it confirms once, then a fresh agent starts on the same agent, model, + effort and permission mode, and the dashboard shows the pick-up chip with a brief that + matches the session +- [ ] An agent that ends by itself leaves the app asking nothing until Restart or **Change agent** + is pressed; Change agent reopens the launch card with a real choice to make again +- [ ] Closing the window while an agent runs asks first, and "no" keeps the window open +- [ ] Cmd+Q on macOS asks the same +- [ ] Windows only: start a CLI installed through npm (a `.cmd` shim), then Restart; check Task + Manager and confirm no leftover `node.exe` (or the CLI's own process) is left running + +## Context meter + +- [ ] Claude Code and Codex: the meter moves during a long session and the nudge appears once +- [ ] Devin: the meter is labeled as an estimate +- [ ] `~/.claude/settings.json` and your own status line are byte-identical before and after a session + +## Standalone path + +- [ ] `/plan2code` typed inside an agent with the app closed opens the dashboard exactly as before +- [ ] `npm test` still passes with the app installed on this machine diff --git a/plan2code-app/fake-agent/Cargo.toml b/plan2code-app/fake-agent/Cargo.toml new file mode 100644 index 0000000..3a0c31c --- /dev/null +++ b/plan2code-app/fake-agent/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "fake-agent" +version = "3.0.0" +description = "A stand-in agent program for the Plan2Code app's tests" +edition = "2021" +publish = false + +[dependencies] +terminal_size = "0.4" diff --git a/plan2code-app/fake-agent/src/main.rs b/plan2code-app/fake-agent/src/main.rs new file mode 100644 index 0000000..24a3b06 --- /dev/null +++ b/plan2code-app/fake-agent/src/main.rs @@ -0,0 +1,130 @@ +//! A stand-in for Claude, Devin and Codex in the app's tests. +//! +//! It behaves the same on Windows, macOS and Linux. Commands, one per line on +//! stdin (these words are the contract the app's integration tests rely on): +//! +//! STEP print one progress line a second for n seconds, then `STEP DONE` +//! EXIT exit with code c +//! SIZE print the terminal size once +//! PID print the agent's process id as `PID ` +//! echoed back as `echo: ` +//! +//! A change in terminal size is reported on its own as `SIZE x`. + +use std::io::{self, BufRead, Write}; +use std::thread; +use std::time::Duration; + +use terminal_size::{terminal_size, Height, Width}; + +fn size_text() -> Option { + terminal_size().map(|(Width(w), Height(h))| format!("SIZE {w}x{h}")) +} + +fn say(line: &str) { + let mut out = io::stdout().lock(); + let _ = writeln!(out, "{line}\r"); + let _ = out.flush(); +} + +/// What a command line asks the agent to do. +#[derive(Debug, PartialEq, Eq)] +pub enum Command { + Step(u64), + Exit(i32), + Size, + Pid, + /// `ENV NAME`: print the variable's value, for tests of what an agent is given. + Env(String), + Echo(String), +} + +pub fn parse(line: &str) -> Command { + let line = line.trim(); + if let Some(rest) = line.strip_prefix("STEP ") { + if let Ok(n) = rest.trim().parse() { + return Command::Step(n); + } + } + if let Some(rest) = line.strip_prefix("EXIT ") { + if let Ok(code) = rest.trim().parse() { + return Command::Exit(code); + } + } + if line == "SIZE" { + return Command::Size; + } + if line == "PID" { + return Command::Pid; + } + if let Some(name) = line.strip_prefix("ENV ") { + return Command::Env(name.trim().to_string()); + } + Command::Echo(line.to_string()) +} + +fn main() { + say("FAKE-AGENT ready"); + if let Some(size) = size_text() { + say(&size); + } + + // Report a resize on its own, by watching the size, so the same code works + // where there is no resize signal (Windows). + thread::spawn(|| { + let mut last = size_text(); + loop { + thread::sleep(Duration::from_millis(100)); + let now = size_text(); + if now != last { + if let Some(text) = &now { + say(text); + } + last = now; + } + } + }); + + let stdin = io::stdin(); + for line in stdin.lock().lines() { + let Ok(line) = line else { break }; + match parse(&line) { + Command::Step(n) => { + for i in 1..=n { + say(&format!("working {i}/{n}")); + thread::sleep(Duration::from_secs(1)); + } + say("STEP DONE"); + } + Command::Exit(code) => { + say(&format!("exiting {code}")); + std::process::exit(code); + } + Command::Size => say(&size_text().unwrap_or_else(|| "SIZE unknown".into())), + Command::Pid => say(&format!("PID {}", std::process::id())), + Command::Env(name) => say(&format!("ENV {name}={}", std::env::var(&name).unwrap_or_default())), + Command::Echo(text) => say(&format!("echo: {text}")), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_the_command_words() { + assert_eq!(parse("STEP 3"), Command::Step(3)); + assert_eq!(parse("EXIT 7\r\n"), Command::Exit(7)); + assert_eq!(parse("SIZE"), Command::Size); + assert_eq!(parse("PID"), Command::Pid); + assert_eq!(parse("ENV PLAN2CODE_IN_APP"), Command::Env("PLAN2CODE_IN_APP".into())); + assert_eq!(parse("hello there"), Command::Echo("hello there".into())); + } + + #[test] + fn a_bad_number_is_just_an_echo() { + assert_eq!(parse("STEP x"), Command::Echo("STEP x".into())); + assert_eq!(parse("EXIT"), Command::Echo("EXIT".into())); + } +} diff --git a/plan2code-app/package.json b/plan2code-app/package.json new file mode 100644 index 0000000..7622b75 --- /dev/null +++ b/plan2code-app/package.json @@ -0,0 +1,19 @@ +{ + "name": "plan2code-app", + "version": "3.0.0", + "private": true, + "description": "Plan2Code desktop app (Tauri). Separate from the repo root so the root and the web console stay dependency-free.", + "scripts": { + "tauri": "tauri", + "dev": "tauri dev", + "build": "tauri build" + }, + "dependencies": { + "@tauri-apps/api": "2.12.4", + "@xterm/addon-fit": "0.11.0", + "@xterm/xterm": "6.0.0" + }, + "devDependencies": { + "@tauri-apps/cli": "2.12.3" + } +} diff --git a/plan2code-app/rust-toolchain.toml b/plan2code-app/rust-toolchain.toml new file mode 100644 index 0000000..f71b0da --- /dev/null +++ b/plan2code-app/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.98.1" +profile = "minimal" diff --git a/plan2code-app/scripts/vendor.mjs b/plan2code-app/scripts/vendor.mjs new file mode 100644 index 0000000..573a0ca --- /dev/null +++ b/plan2code-app/scripts/vendor.mjs @@ -0,0 +1,17 @@ +// 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`. +import { copyFileSync, mkdirSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = join(dirname(fileURLToPath(import.meta.url)), '..'); +const out = join(root, 'ui', 'vendor'); +mkdirSync(out, { recursive: true }); + +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'], +]; +for (const [from, to] of files) copyFileSync(join(root, from), join(out, to)); +console.log(`vendored ${files.length} xterm files into ui/vendor/`); diff --git a/plan2code-app/src-tauri/Cargo.toml b/plan2code-app/src-tauri/Cargo.toml new file mode 100644 index 0000000..f22878b --- /dev/null +++ b/plan2code-app/src-tauri/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "plan2code-app" +version = "3.0.0" +description = "Plan2Code desktop app" +edition = "2021" +publish = false + +[lib] +name = "plan2code_app_lib" +path = "src/lib.rs" + +[build-dependencies] +tauri-build = { version = "2.5", features = [] } + +[dependencies] +tauri = { version = "2.12", features = [] } +tauri-plugin-dialog = "2" +portable-pty = "0.9.0" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +chrono = "0.4" + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + +[target.'cfg(windows)'.dependencies] +# Already pulled in by portable-pty itself; named directly here only for the +# Job Object APIs it does not expose (ending a `cmd /c` npm shim's whole +# process tree, not just the shim). +winapi = { version = "0.3.9", features = ["handleapi", "jobapi2", "minwindef", "ntdef", "winnt"] } diff --git a/plan2code-app/src-tauri/build.rs b/plan2code-app/src-tauri/build.rs new file mode 100644 index 0000000..d860e1e --- /dev/null +++ b/plan2code-app/src-tauri/build.rs @@ -0,0 +1,3 @@ +fn main() { + tauri_build::build() +} diff --git a/plan2code-app/src-tauri/capabilities/default.json b/plan2code-app/src-tauri/capabilities/default.json new file mode 100644 index 0000000..40fa962 --- /dev/null +++ b/plan2code-app/src-tauri/capabilities/default.json @@ -0,0 +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", + "windows": ["main"], + "permissions": ["core:event:allow-listen", "core:event:allow-unlisten"] +} diff --git a/plan2code-app/src-tauri/icons/128x128.png b/plan2code-app/src-tauri/icons/128x128.png new file mode 100644 index 0000000..c68eb3e Binary files /dev/null and b/plan2code-app/src-tauri/icons/128x128.png differ diff --git a/plan2code-app/src-tauri/icons/128x128@2x.png b/plan2code-app/src-tauri/icons/128x128@2x.png new file mode 100644 index 0000000..711033b Binary files /dev/null and b/plan2code-app/src-tauri/icons/128x128@2x.png differ diff --git a/plan2code-app/src-tauri/icons/32x32.png b/plan2code-app/src-tauri/icons/32x32.png new file mode 100644 index 0000000..8e2f174 Binary files /dev/null and b/plan2code-app/src-tauri/icons/32x32.png differ diff --git a/plan2code-app/src-tauri/icons/icon.icns b/plan2code-app/src-tauri/icons/icon.icns new file mode 100644 index 0000000..35303e8 Binary files /dev/null and b/plan2code-app/src-tauri/icons/icon.icns differ diff --git a/plan2code-app/src-tauri/icons/icon.ico b/plan2code-app/src-tauri/icons/icon.ico new file mode 100644 index 0000000..f4a5c6f Binary files /dev/null and b/plan2code-app/src-tauri/icons/icon.ico differ diff --git a/plan2code-app/src-tauri/icons/icon.png b/plan2code-app/src-tauri/icons/icon.png new file mode 100644 index 0000000..8f7d273 Binary files /dev/null and b/plan2code-app/src-tauri/icons/icon.png differ diff --git a/plan2code-app/src-tauri/src/agent_manager.rs b/plan2code-app/src-tauri/src/agent_manager.rs new file mode 100644 index 0000000..6233ec6 --- /dev/null +++ b/plan2code-app/src-tauri/src/agent_manager.rs @@ -0,0 +1,409 @@ +//! At most one agent per project folder: start it, end it, restart it (always +//! at once: the app confirms with the person first, so nothing here waits for +//! a quiet moment), and notice when it ends by itself. +//! Knows nothing about Tauri: state changes and output go to one callback. + +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::thread; + +use serde::Serialize; + +use crate::agents::{launch_spec, AgentKind, PermissionMode}; +use crate::pty_host::{PtyHost, StartOptions}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(tag = "state", rename_all = "lowercase")] +pub enum AgentState { + Idle, + Running, + /// The agent ended without a Restart press, or could not be started. + Ended { reason: String }, +} + +/// Runs just before a Restart starts the fresh agent, and returns the line the +/// bar shows about it (`None` for no line). It must not call back into the +/// manager: it runs with the manager's state locked. +pub type BeforeFresh = Arc Option + Send + Sync>; + +/// What the page needs to draw the bar. `generation` counts the agents started +/// so far: a new number means a fresh agent, so the terminal clears. +#[derive(Clone, Debug, Serialize)] +pub struct AgentSnapshot { + #[serde(flatten)] + pub state: AgentState, + pub kind: Option, + pub generation: u64, + /// The running (or last started) agent's permission mode, so the bar's + /// note can name it instead of assuming bypass. + pub mode: Option, + /// What the last Restart left for the dashboard, for the bar. + #[serde(rename = "briefNote", skip_serializing_if = "Option::is_none")] + pub brief_note: Option, +} + +pub enum AgentEvent { + Output(Vec), + State(AgentSnapshot), +} + +/// Receives events from several threads. State events are sent while the +/// manager holds its lock, so a sink must not call back into the manager. +pub type Sink = Arc; + +struct Running { + host: Arc, +} + +/// What a Restart starts again, besides the brief: the agent, its model and +/// effort (when it has one), and its permission mode. Restart reuses this +/// whole, unchanged choice (Task 9.6). +#[derive(Clone)] +struct StartChoice { + kind: AgentKind, + model: Option, + effort: Option, + mode: PermissionMode, +} + +/// Recent output from the current generation is kept bounded, so a page +/// reload or a fresh output channel can redraw the screen instead of staying +/// blank. About enough for a full screen redraw with some headroom, never +/// the whole scrollback. +const REPLAY_LIMIT: usize = 256 * 1024; + +/// Appends `bytes` to `replay`, dropping from the front (the oldest) when +/// that would put it over `limit`: the tail, what a redraw actually needs, +/// is always what is kept. +fn append_replay(replay: &mut Vec, bytes: &[u8], limit: usize) { + replay.extend_from_slice(bytes); + if replay.len() > limit { + let excess = replay.len() - limit; + replay.drain(..excess); + } +} + +struct Inner { + state: AgentState, + running: Option, + /// What a Restart starts again: the choice and the brief. + last_start: Option<(StartChoice, Option)>, + size: (u16, u16), + brief_note: Option, + /// Cleared when a fresh agent starts; see `REPLAY_LIMIT`. + replay: Vec, +} + +struct Shared { + folder: PathBuf, + sink: Sink, + before_fresh: Mutex>, + /// Environment every agent this manager starts gets, on top of its own: + /// the in-app signal that sends the agent's console pages to this window. + extra_env: Mutex>, + /// Bumped for every agent started. Output and exits from an older agent + /// compare against it and are dropped. + generation: AtomicU64, + inner: Mutex, +} + +pub struct AgentManager { + shared: Arc, +} + +fn lock(inner: &Mutex) -> MutexGuard<'_, Inner> { + // A panic in another thread must not take the whole app's agent control down. + inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +impl AgentManager { + pub fn new(folder: PathBuf, sink: Sink) -> AgentManager { + AgentManager { + shared: Arc::new(Shared { + folder, + sink, + before_fresh: Mutex::new(None), + extra_env: Mutex::new(Vec::new()), + generation: AtomicU64::new(0), + inner: Mutex::new(Inner { + state: AgentState::Idle, + running: None, + last_start: None, + size: (80, 24), + brief_note: None, + replay: Vec::new(), + }), + }), + } + } + + pub fn folder(&self) -> &PathBuf { + &self.shared.folder + } + + /// Run `hook` before every Restart starts its fresh agent. + pub fn set_before_fresh(&self, hook: BeforeFresh) { + if let Ok(mut slot) = self.shared.before_fresh.lock() { + *slot = Some(hook); + } + } + + /// Give every agent started from now on these variables (replacing any set before). + pub fn set_env(&self, env: Vec<(String, String)>) { + if let Ok(mut slot) = self.shared.extra_env.lock() { + *slot = env; + } + } + + /// Start `kind` on `model`, `effort` and `mode`, with `brief` (`None` is + /// the placeholder brief: the plain `/plan2code` prompt, which opens the + /// dashboard). A second start while an agent runs is refused. Restart + /// reuses this exact choice, so a later call replaces it for good. + pub fn start( + &self, + kind: AgentKind, + model: Option, + effort: Option, + mode: PermissionMode, + brief: Option, + ) -> Result<(), String> { + let mut inner = lock(&self.shared.inner); + if inner.state == AgentState::Running { + return Err("an agent is already running for this project".to_string()); + } + inner.brief_note = None; + let previous = inner.last_start.replace((StartChoice { kind, model, effort, mode }, brief)); + match self.shared.spawn(&mut inner) { + Ok(()) => Ok(()), + Err(e) => { + // A start that never ran must not take away what Restart would + // have started again. + inner.last_start = previous; + Err(e) + } + } + } + + pub fn snapshot(&self) -> AgentSnapshot { + self.shared.snapshot(&lock(&self.shared.inner)) + } + + /// The current generation's recent output, for a page that just mounted + /// (a reload or a fresh window) to redraw instead of staying blank. + pub fn replay(&self) -> Vec { + lock(&self.shared.inner).replay.clone() + } + + /// The model and effort the current (or last) start chose. The bar only + /// ever needs `snapshot`'s `kind` and `mode`; this exists so a test can + /// confirm Restart keeps the other two of the four just as unchanged. + pub fn model_and_effort(&self) -> (Option, Option) { + match &lock(&self.shared.inner).last_start { + Some((choice, _)) => (choice.model.clone(), choice.effort.clone()), + None => (None, None), + } + } + + pub fn is_active(&self) -> bool { + lock(&self.shared.inner).state == AgentState::Running + } + + pub fn input(&self, bytes: &[u8]) -> Result<(), String> { + let host = lock(&self.shared.inner).running.as_ref().map(|r| Arc::clone(&r.host)); + match host { + Some(host) => host.write(bytes), + None => Ok(()), + } + } + + /// The terminal changed size. Remembered, so a fresh agent starts at it. + pub fn resize(&self, cols: u16, rows: u16) -> Result<(), String> { + let mut inner = lock(&self.shared.inner); + inner.size = (cols, rows); + match &inner.running { + Some(running) => running.host.resize(cols, rows), + None => Ok(()), + } + } + + /// Kill the agent (if any) and start a fresh one on the same brief, at + /// once, whatever it is doing. The app asks the person to confirm before + /// calling this: there is no in-between "waiting" state here, because the + /// agent's own output (status lines, a spinner) never truly goes quiet, so + /// a "wait for it to finish" rule would wait forever in practice. Restart + /// also answers an ended agent, where nothing is lost by it. + pub fn restart(&self) -> Result<(), String> { + let mut inner = lock(&self.shared.inner); + if inner.state == AgentState::Idle { + return Err("no agent has been started".to_string()); + } + self.shared.replace(&mut inner) + } + + /// End the agent for good (quitting). Nothing starts afterwards, and the + /// agent's process is gone when this returns. + pub fn stop(&self) { + let host = { + let mut inner = lock(&self.shared.inner); + // Older agents' output and exits stop counting from here. + self.shared.generation.fetch_add(1, Ordering::SeqCst); + let host = inner.running.take().map(|r| r.host); + inner.state = AgentState::Idle; + inner.last_start = None; + self.shared.emit(&inner); + host + }; + if let Some(host) = host { + let _ = host.kill(); + let _ = host.wait(); + } + } +} + +impl Drop for AgentManager { + fn drop(&mut self) { + self.stop(); + } +} + +impl Shared { + fn snapshot(&self, inner: &Inner) -> AgentSnapshot { + AgentSnapshot { + state: inner.state.clone(), + kind: inner.last_start.as_ref().map(|(choice, _)| choice.kind), + mode: inner.last_start.as_ref().map(|(choice, _)| choice.mode), + generation: self.generation.load(Ordering::SeqCst), + brief_note: inner.brief_note.clone(), + } + } + + fn emit(&self, inner: &Inner) { + (self.sink)(AgentEvent::State(self.snapshot(inner))); + } + + /// Start the agent in `inner.last_start` and watch for it to end. + fn spawn(self: &Arc, inner: &mut Inner) -> Result<(), String> { + let (choice, brief) = inner.last_start.clone().ok_or("no agent has been started")?; + let prompt = brief.unwrap_or_else(|| choice.kind.default_prompt().to_string()); + let mut spec = + launch_spec(choice.kind, &self.folder, choice.model.as_deref(), choice.effort.as_deref(), choice.mode, &prompt); + if let Ok(extra) = self.extra_env.lock() { + spec.env.extend(extra.iter().cloned()); + } + let generation = self.generation.fetch_add(1, Ordering::SeqCst) + 1; + + let on_output = { + let shared = Arc::clone(self); + move |bytes: Vec| { + // Taking the lock here, briefly, keeps this behind the state + // change that announces its agent (`spawn`'s caller holds the + // lock until it has emitted), so the page clears its screen + // before the banner. It is released before the send below, + // which can be slow, so typing (`input`) is never stuck + // behind a flood of output. + let stale = { + let mut in_order = lock(&shared.inner); + if shared.generation.load(Ordering::SeqCst) != generation { + true + } else { + append_replay(&mut in_order.replay, &bytes, REPLAY_LIMIT); + false + } + }; + if stale { + return; + } + (shared.sink)(AgentEvent::Output(bytes)); + } + }; + let host = Arc::new(PtyHost::start( + StartOptions { + program: spec.program, + args: spec.args, + env: spec.env, + cwd: Some(spec.cwd), + cols: inner.size.0, + rows: inner.size.1, + }, + on_output, + )?); + + inner.running = Some(Running { host: Arc::clone(&host) }); + inner.state = AgentState::Running; + // A fresh agent starts on a clean screen; its replay must too. + inner.replay.clear(); + self.emit(inner); + + let shared = Arc::clone(self); + thread::spawn(move || { + let reason = match host.wait_described() { + Ok((_, Some(signal))) => format!("was ended by a signal ({signal})"), + Ok((code, None)) => format!("exited with code {code}"), + Err(e) => format!("stopped: {e}"), + }; + shared.on_exit(generation, reason); + }); + Ok(()) + } + + /// Kill the running agent (if any) and start a fresh one on the same + /// brief. A fresh agent that cannot start leaves the state `Ended`. + fn replace(self: &Arc, inner: &mut Inner) -> Result<(), String> { + // Bumping the generation first drops whatever the old agent still says. + self.generation.fetch_add(1, Ordering::SeqCst); + if let Some(old) = inner.running.take() { + let _ = old.host.kill(); + } + let hook = self.before_fresh.lock().ok().and_then(|slot| slot.clone()); + inner.brief_note = hook.and_then(|run| run()); + match self.spawn(inner) { + Ok(()) => Ok(()), + Err(e) => { + inner.state = AgentState::Ended { reason: format!("could not start the agent: {e}") }; + self.emit(inner); + Err(e) + } + } + } + + /// The agent's process ended. Stale if a newer agent has replaced it. + fn on_exit(self: &Arc, generation: u64, reason: String) { + let mut inner = lock(&self.inner); + if self.generation.load(Ordering::SeqCst) != generation { + return; + } + inner.running = None; + // Ended on its own: say why and start nothing. + inner.state = AgentState::Ended { reason }; + self.emit(&inner); + } +} + +#[cfg(test)] +mod replay_tests { + use super::*; + + #[test] + fn under_the_limit_keeps_everything() { + let mut replay = b"hello ".to_vec(); + append_replay(&mut replay, b"world", 20); + assert_eq!(replay, b"hello world"); + } + + #[test] + fn over_the_limit_drops_the_oldest_bytes_and_keeps_the_tail() { + let mut replay = b"0123456789".to_vec(); + append_replay(&mut replay, b"ABCDE", 10); + // 15 bytes written, a 10-byte limit: the oldest 5 ("01234") are gone. + assert_eq!(replay, b"56789ABCDE"); + assert_eq!(replay.len(), 10); + } + + #[test] + fn a_single_write_longer_than_the_limit_keeps_only_its_own_tail() { + let mut replay = Vec::new(); + append_replay(&mut replay, b"0123456789", 4); + assert_eq!(replay, b"6789"); + } +} diff --git a/plan2code-app/src-tauri/src/agents.rs b/plan2code-app/src-tauri/src/agents.rs new file mode 100644 index 0000000..14de9da --- /dev/null +++ b/plan2code-app/src-tauri/src/agents.rs @@ -0,0 +1,473 @@ +//! The agents the app can run and the command line each one starts with. The +//! flags are the ones `src/launcher/plan2code.js` uses today, so the app and +//! `plan2code` start an agent the same way. Knows nothing about Tauri. + +use std::path::{Path, PathBuf}; + +use serde::Serialize; + +/// Tests only: run this program instead of the real agent, for any `AgentKind`, +/// so the fake agent stands in for Claude, Devin and Codex. +pub const AGENT_BIN_ENV: &str = "PLAN2CODE_APP_AGENT_BIN"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum AgentKind { + Claude, + Devin, + Codex, +} + +impl AgentKind { + pub const ALL: [AgentKind; 3] = [AgentKind::Claude, AgentKind::Devin, AgentKind::Codex]; + + /// The id the page and the settings file use. + pub fn id(self) -> &'static str { + match self { + AgentKind::Claude => "claude", + AgentKind::Devin => "devin", + AgentKind::Codex => "codex", + } + } + + pub fn from_id(id: &str) -> Option { + AgentKind::ALL.into_iter().find(|kind| kind.id() == id) + } + + pub fn label(self) -> &'static str { + match self { + AgentKind::Claude => "Claude Code", + AgentKind::Devin => "Devin", + AgentKind::Codex => "Codex", + } + } + + /// What a first start types: the skill that opens the dashboard. Codex + /// mentions a skill with `$name`. + pub fn default_prompt(self) -> &'static str { + match self { + AgentKind::Codex => "$plan2code", + _ => "/plan2code", + } + } + + /// The program this agent runs as, before any PATH resolution. + pub fn program_name(self) -> &'static str { + match self { + AgentKind::Claude => "claude", + AgentKind::Devin => "devin", + AgentKind::Codex => "codex", + } + } + + /// Whether this agent takes a separate reasoning effort. Devin's model + /// ids already carry effort (`swe-2-high`), so it has none of its own. + pub fn has_effort(self) -> bool { + matches!(self, AgentKind::Claude | AgentKind::Codex) + } + + /// Where to install this agent: an npm command or, with no package of its + /// own, the site to install from. The same text `src/launcher/plan2code.js` + /// shows for a missing CLI. + pub fn install_hint(self) -> &'static str { + match self { + AgentKind::Claude => "npm i -g @anthropic-ai/claude-code", + AgentKind::Devin => "https://devin.ai", + AgentKind::Codex => "npm i -g @openai/codex", + } + } +} + +/// Whether permission checks run while the agent works. Bypass is always an +/// explicit pick, shown with a banner while it runs; it is never the silent +/// default. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum PermissionMode { + /// The agent's own approval flow: it asks before a sensitive action. + Checked, + /// Permission checks are off. + Bypass, +} + +impl PermissionMode { + pub fn id(self) -> &'static str { + match self { + PermissionMode::Checked => "checked", + PermissionMode::Bypass => "bypass", + } + } + + pub fn from_id(id: &str) -> Option { + match id { + "checked" => Some(PermissionMode::Checked), + "bypass" => Some(PermissionMode::Bypass), + _ => None, + } + } +} + +/// Whether `program` exists on `path_var`: an exact file on macOS and Linux, +/// or with `.exe`, `.cmd` or `.bat` on Windows (as `windows_command` resolves +/// a program to run). +pub fn find_on_path(program: &str, path_var: &str) -> Option { + let exts: &[&str] = if cfg!(windows) { &["exe", "cmd", "bat"] } else { &[""] }; + path_var.split(if cfg!(windows) { ';' } else { ':' }).filter(|dir| !dir.is_empty()).find_map(|dir| { + exts.iter().find_map(|ext| { + let name = if ext.is_empty() { program.to_string() } else { format!("{program}.{ext}") }; + let candidate = Path::new(dir).join(name); + candidate.is_file().then_some(candidate) + }) + }) +} + +/// Where `kind`'s CLI runs from: the test override when it is set, else its +/// program name on PATH. `None` means it cannot be run. +pub fn installed_at(kind: AgentKind) -> Option { + let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|b| !b.is_empty()); + let program = bin.unwrap_or_else(|| kind.program_name().to_string()); + find_on_path(&program, crate::node_check::resolved_path()) +} + +/// Whether `kind`'s CLI can be run at all. +pub fn is_installed(kind: AgentKind) -> bool { + installed_at(kind).is_some() +} + +/// A command to run in the pseudo-terminal. +#[derive(Debug, PartialEq, Eq)] +pub struct LaunchSpec { + pub program: String, + pub args: Vec, + pub env: Vec<(String, String)>, + pub cwd: PathBuf, +} + +/// How to start `kind` in `folder`. An empty `prompt` starts the agent with +/// nothing typed. `PLAN2CODE_APP_AGENT_BIN` replaces the program (tests only). +pub fn launch_spec( + kind: AgentKind, + folder: &Path, + model: Option<&str>, + effort: Option<&str>, + mode: PermissionMode, + prompt: &str, +) -> LaunchSpec { + let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|bin| !bin.is_empty()); + let mut spec = launch_spec_with(kind, folder, model, effort, mode, prompt, bin.as_deref()); + // The override names a program to run as it is; a real agent is looked up on PATH. + if cfg!(windows) && bin.is_none() { + let (program, args) = windows_command(&spec.program, spec.args, &std::env::var("PATH").unwrap_or_default()); + spec.program = program; + spec.args = args; + } + spec +} + +fn launch_spec_with( + kind: AgentKind, + folder: &Path, + model: Option<&str>, + effort: Option<&str>, + mode: PermissionMode, + prompt: &str, + bin_override: Option<&str>, +) -> LaunchSpec { + let cwd = folder.to_path_buf(); + if let Some(bin) = bin_override { + return LaunchSpec { program: bin.to_string(), args: vec![], env: vec![], cwd }; + } + + let strings = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::>(); + let model_args = |args: &mut Vec| { + if let Some(model) = model { + args.push("--model".to_string()); + args.push(model.to_string()); + } + }; + let bypass = mode == PermissionMode::Bypass; + let mut args = Vec::new(); + let program = match kind { + AgentKind::Claude => { + if !prompt.is_empty() { + args.push(prompt.to_string()); + } + if bypass { + args.extend(strings(&["--permission-mode", "bypassPermissions"])); + } + model_args(&mut args); + if let Some(effort) = effort { + args.push("--effort".to_string()); + args.push(effort.to_string()); + } + "claude" + } + AgentKind::Devin => { + if bypass { + args.extend(strings(&["--permission-mode", "bypass"])); + } + model_args(&mut args); + if !prompt.is_empty() { + args.push("--".to_string()); + args.push(prompt.to_string()); + } + "devin" + } + AgentKind::Codex => { + if bypass { + args.extend(strings(&["--dangerously-bypass-approvals-and-sandbox"])); + } + model_args(&mut args); + if let Some(effort) = effort { + args.push("-c".to_string()); + args.push(format!("model_reasoning_effort={effort}")); + } + if !prompt.is_empty() { + args.push(prompt.to_string()); + } + "codex" + } + }; + // A Dock or Start-menu launch often lacks nvm, Homebrew or Volta's + // directories (Task 9.9): the agent CLI itself, and anything it shells + // out to, needs a PATH that finds them anyway. + let env = vec![("PATH".to_string(), crate::node_check::resolved_path().to_string())]; + LaunchSpec { program: program.to_string(), args, env, cwd } +} + +/// An agent installed with npm is, on Windows, a `.cmd` shim beside an +/// extensionless script, and `CreateProcess` cannot run the script. Look the +/// program up on `path_var` for an `.exe` (run as is), `.cmd` or `.bat` (run +/// through `cmd /c`); a program found as none of them is left alone. +pub fn windows_command(program: &str, args: Vec, path_var: &str) -> (String, Vec) { + for dir in path_var.split(';').filter(|dir| !dir.is_empty()) { + for ext in ["exe", "cmd", "bat"] { + let candidate = Path::new(dir).join(format!("{program}.{ext}")); + if !candidate.is_file() { + continue; + } + if ext == "exe" { + return (candidate.to_string_lossy().into_owned(), args); + } + // The bare file name, not the full path: a path with a space gets + // quoted, and `cmd /c` mangles a command line that starts with a quote. + // `cmd` finds the shim on PATH itself. + let mut wrapped = vec!["/c".to_string(), format!("{program}.{ext}")]; + wrapped.extend(args); + return ("cmd".to_string(), wrapped); + } + } + (program.to_string(), args) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn folder() -> PathBuf { + PathBuf::from("project") + } + + fn args(kind: AgentKind, model: Option<&str>, mode: PermissionMode, prompt: &str) -> Vec { + launch_spec_with(kind, &folder(), model, None, mode, prompt, None).args + } + + #[test] + fn claude_puts_the_prompt_first() { + let spec = launch_spec_with(AgentKind::Claude, &folder(), None, None, PermissionMode::Bypass, "/plan2code", None); + assert_eq!(spec.program, "claude"); + assert_eq!(spec.args, ["/plan2code", "--permission-mode", "bypassPermissions"]); + assert_eq!(spec.cwd, folder()); + // A PATH that can still find nvm, Homebrew or Volta's directories (Task 9.9). + assert_eq!(spec.env.iter().filter(|(k, _)| k == "PATH").count(), 1); + } + + #[test] + fn claude_with_a_model() { + assert_eq!( + args(AgentKind::Claude, Some("sonnet"), PermissionMode::Bypass, "/plan2code"), + ["/plan2code", "--permission-mode", "bypassPermissions", "--model", "sonnet"] + ); + } + + #[test] + fn claude_checked_mode_skips_the_bypass_flag() { + assert_eq!(args(AgentKind::Claude, None, PermissionMode::Checked, "/plan2code"), ["/plan2code"]); + } + + #[test] + fn claude_with_an_effort() { + let spec = + launch_spec_with(AgentKind::Claude, &folder(), None, Some("high"), PermissionMode::Bypass, "/plan2code", None); + assert_eq!(spec.args, ["/plan2code", "--permission-mode", "bypassPermissions", "--effort", "high"]); + } + + #[test] + fn a_full_launch_card_choice_carries_model_effort_and_mode_together() { + let spec = launch_spec_with( + AgentKind::Claude, + &folder(), + Some("opus"), + Some("xhigh"), + PermissionMode::Bypass, + "/plan2code", + None, + ); + assert_eq!( + spec.args, + ["/plan2code", "--permission-mode", "bypassPermissions", "--model", "opus", "--effort", "xhigh"] + ); + let checked = launch_spec_with( + AgentKind::Codex, + &folder(), + Some("gpt-5"), + Some("medium"), + PermissionMode::Checked, + "$plan2code", + None, + ); + assert_eq!(checked.args, ["--model", "gpt-5", "-c", "model_reasoning_effort=medium", "$plan2code"]); + } + + #[test] + fn devin_puts_the_prompt_after_a_double_dash() { + let spec = launch_spec_with(AgentKind::Devin, &folder(), None, None, PermissionMode::Bypass, "/plan2code", None); + assert_eq!(spec.program, "devin"); + assert_eq!(spec.args, ["--permission-mode", "bypass", "--", "/plan2code"]); + } + + #[test] + fn devin_with_a_model_keeps_the_prompt_last() { + assert_eq!( + args(AgentKind::Devin, Some("opus"), PermissionMode::Bypass, "/plan2code"), + ["--permission-mode", "bypass", "--model", "opus", "--", "/plan2code"] + ); + } + + #[test] + fn devin_checked_mode_skips_the_bypass_flag() { + assert_eq!(args(AgentKind::Devin, None, PermissionMode::Checked, "/plan2code"), ["--", "/plan2code"]); + } + + #[test] + fn codex_uses_its_own_flag_and_dollar_prompt() { + let prompt = AgentKind::Codex.default_prompt(); + let spec = launch_spec_with(AgentKind::Codex, &folder(), None, None, PermissionMode::Bypass, prompt, None); + assert_eq!(spec.program, "codex"); + assert_eq!(spec.args, ["--dangerously-bypass-approvals-and-sandbox", "$plan2code"]); + } + + #[test] + fn codex_with_a_model() { + assert_eq!( + args(AgentKind::Codex, Some("gpt-5"), PermissionMode::Bypass, "$plan2code"), + ["--dangerously-bypass-approvals-and-sandbox", "--model", "gpt-5", "$plan2code"] + ); + } + + #[test] + fn codex_with_an_effort_uses_a_config_override() { + let spec = + launch_spec_with(AgentKind::Codex, &folder(), None, Some("low"), PermissionMode::Bypass, "$plan2code", None); + assert_eq!( + spec.args, + ["--dangerously-bypass-approvals-and-sandbox", "-c", "model_reasoning_effort=low", "$plan2code"] + ); + } + + #[test] + fn codex_checked_mode_skips_the_bypass_flag() { + assert_eq!(args(AgentKind::Codex, None, PermissionMode::Checked, "$plan2code"), ["$plan2code"]); + } + + #[test] + fn no_prompt_means_nothing_typed() { + assert_eq!(args(AgentKind::Claude, None, PermissionMode::Bypass, ""), ["--permission-mode", "bypassPermissions"]); + assert_eq!(args(AgentKind::Devin, None, PermissionMode::Bypass, ""), ["--permission-mode", "bypass"]); + assert_eq!(args(AgentKind::Codex, None, PermissionMode::Bypass, ""), ["--dangerously-bypass-approvals-and-sandbox"]); + } + + #[test] + fn a_custom_prompt_is_passed_through() { + assert_eq!( + args(AgentKind::Claude, None, PermissionMode::Bypass, "/plan2code pick up the brief"), + ["/plan2code pick up the brief", "--permission-mode", "bypassPermissions"] + ); + } + + #[test] + fn devin_has_no_effort_of_its_own() { + assert!(!AgentKind::Devin.has_effort()); + assert!(AgentKind::Claude.has_effort()); + assert!(AgentKind::Codex.has_effort()); + } + + #[test] + fn permission_mode_ids_round_trip() { + for mode in [PermissionMode::Checked, PermissionMode::Bypass] { + assert_eq!(PermissionMode::from_id(mode.id()), Some(mode)); + } + assert_eq!(PermissionMode::from_id("nope"), None); + } + + #[test] + fn the_override_replaces_the_program_for_every_kind() { + for kind in AgentKind::ALL { + let spec = launch_spec_with( + kind, + &folder(), + Some("m"), + Some("high"), + PermissionMode::Bypass, + "/plan2code", + Some("fake-agent"), + ); + assert_eq!(spec.program, "fake-agent"); + assert!(spec.args.is_empty()); + } + } + + #[test] + fn find_on_path_sees_only_what_is_really_there() { + let dir = std::env::temp_dir().join(format!("plan2code-findonpath-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let name = if cfg!(windows) { "tool.exe" } else { "tool" }; + std::fs::write(dir.join(name), "").unwrap(); + let path = dir.to_string_lossy().into_owned(); + assert_eq!(find_on_path("tool", &path), Some(dir.join(name))); + assert_eq!(find_on_path("missing-tool", &path), None); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_cmd_shim_runs_through_cmd_and_the_extensionless_script_is_ignored() { + let dir = std::env::temp_dir().join(format!("plan2code-shim-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("tool"), "#!/bin/sh").unwrap(); + std::fs::write(dir.join("tool.cmd"), "@echo off").unwrap(); + std::fs::write(dir.join("real.exe"), "").unwrap(); + let path = dir.to_string_lossy().into_owned(); + let args = vec!["--flag".to_string()]; + + let (program, wrapped) = windows_command("tool", args.clone(), &path); + assert_eq!(program, "cmd"); + assert_eq!(wrapped, ["/c".to_string(), "tool.cmd".to_string(), "--flag".to_string()]); + + let (program, same) = windows_command("real", args.clone(), &path); + assert_eq!(program, dir.join("real.exe").to_string_lossy()); + assert_eq!(same, args); + + assert_eq!(windows_command("missing", args.clone(), &path), ("missing".to_string(), args)); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn ids_round_trip() { + for kind in AgentKind::ALL { + assert_eq!(AgentKind::from_id(kind.id()), Some(kind)); + } + assert_eq!(AgentKind::from_id("nope"), None); + } +} diff --git a/plan2code-app/src-tauri/src/announce.rs b/plan2code-app/src-tauri/src/announce.rs new file mode 100644 index 0000000..8cca756 --- /dev/null +++ b/plan2code-app/src-tauri/src/announce.rs @@ -0,0 +1,365 @@ +//! This window's announce endpoint: `console.mjs open`, run by the agent inside +//! the app, POSTs the page it wants shown here instead of opening a browser. +//! Loopback only, one random token per window, so two windows never hear each +//! other's agents. Knows nothing about Tauri: the caller gets each accepted +//! notice through a callback. + +use std::collections::hash_map::RandomState; +use std::hash::{BuildHasher, Hasher}; +use std::io::{Read, Write}; +use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +/// The most an announce request may weigh: a URL and two short names. +const MAX_REQUEST: usize = 8 * 1024; +const READ_TIMEOUT: Duration = Duration::from_secs(3); + +/// A page the console wants shown: where it is, the session it belongs to and +/// the skill it runs. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PageNotice { + pub url: String, + pub sid: String, + pub workflow: String, +} + +pub type OnPage = Arc; + +pub struct AnnounceServer { + port: u16, + token: String, + /// The page most recently announced: what `GET /session` answers, so an + /// agent's `open` joins the window's current session whatever its own + /// environment (fixed when it started) says. + current: Arc>>, +} + +/// What a checked request asks for. +#[derive(Debug, PartialEq, Eq)] +pub enum Request { + /// `POST /page`: show this page. + Page(PageNotice), + /// `GET /session`: name the session the window shows now. + Session, +} + +/// Why a request was refused, as the status the caller answers with. +#[derive(Debug, PartialEq, Eq)] +pub struct Refused(pub u16, pub &'static str); + +/// A random token from the OS-seeded hasher: 128 bits as hex. The standard +/// library's `RandomState` keys come from the operating system's random source. +fn random_token() -> String { + let mut out = String::new(); + for round in 0..2u8 { + let mut hasher = RandomState::new().build_hasher(); + hasher.write_u8(round); + hasher.write_u128( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0), + ); + out.push_str(&format!("{:016x}", hasher.finish())); + } + out +} + +fn same_token(a: &str, b: &str) -> bool { + // Compared in full whatever the first difference, so timing says nothing. + let (a, b) = (a.as_bytes(), b.as_bytes()); + let mut diff = (a.len() != b.len()) as u8; + for i in 0..a.len().min(b.len()) { + diff |= a[i] ^ b[i]; + } + diff == 0 +} + +/// A console page URL the app may show: plain http on loopback with a port and +/// a `/s//` path, which is all the console ever hands out. +pub fn acceptable_url(url: &str) -> bool { + let Some(rest) = url.strip_prefix("http://127.0.0.1:") else { + return false; + }; + let Some((port, path)) = rest.split_once('/') else { + return false; + }; + port.parse::().is_ok_and(|p| p > 0) && path.starts_with("s/") && !url.contains(char::is_whitespace) +} + +/// Check one request (its head as text, its body as bytes) against `token`. +pub fn check_request(head: &str, body: &[u8], token: &str) -> Result { + let mut lines = head.split("\r\n"); + let request_line = lines.next().unwrap_or(""); + let route = request_line.split(' ').take(2).collect::>(); + if route != ["POST", "/page"] && route != ["GET", "/session"] { + return Err(Refused(404, "not found")); + } + let mut given = None; + for line in lines { + let Some((name, value)) = line.split_once(':') else { continue }; + match name.trim().to_ascii_lowercase().as_str() { + "x-plan2code-token" => given = Some(value.trim().to_string()), + // A browser page sending this would be some site guessing at the port. + "origin" => return Err(Refused(403, "not from a page")), + _ => {} + } + } + if !given.is_some_and(|given| same_token(&given, token)) { + return Err(Refused(403, "bad token")); + } + if route[0] == "GET" { + return Ok(Request::Session); + } + let notice: PageNotice = serde_json::from_slice(body).map_err(|_| Refused(400, "bad body"))?; + if !acceptable_url(¬ice.url) || notice.sid.len() > 128 || notice.workflow.len() > 64 { + return Err(Refused(400, "bad page")); + } + Ok(Request::Page(notice)) +} + +fn reason(status: u16) -> &'static str { + match status { + 200 => "OK", + 204 => "No Content", + 400 => "Bad Request", + 403 => "Forbidden", + _ => "Not Found", + } +} + +fn respond(stream: &mut TcpStream, status: u16, body: &str) { + let _ = write!( + stream, + "HTTP/1.1 {status} {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + reason(status), + body.len() + ); +} + +/// Read one request: the head up to the blank line, then the body the +/// `Content-Length` header names. Anything over `MAX_REQUEST` is refused. +fn read_request(stream: &mut TcpStream) -> Result<(String, Vec), Refused> { + let _ = stream.set_read_timeout(Some(READ_TIMEOUT)); + let mut buf = Vec::new(); + let mut chunk = [0u8; 1024]; + let split = loop { + if let Some(at) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + break at; + } + if buf.len() > MAX_REQUEST { + return Err(Refused(400, "too big")); + } + match stream.read(&mut chunk) { + Ok(0) | Err(_) => return Err(Refused(400, "incomplete")), + Ok(n) => buf.extend_from_slice(&chunk[..n]), + } + }; + let head = String::from_utf8_lossy(&buf[..split]).into_owned(); + let length = head + .split("\r\n") + .filter_map(|line| line.split_once(':')) + .find(|(name, _)| name.trim().eq_ignore_ascii_case("content-length")) + .and_then(|(_, value)| value.trim().parse::().ok()) + .unwrap_or(0); + if length > MAX_REQUEST { + return Err(Refused(400, "too big")); + } + let mut body = buf[split + 4..].to_vec(); + while body.len() < length { + match stream.read(&mut chunk) { + Ok(0) | Err(_) => return Err(Refused(400, "incomplete")), + Ok(n) => body.extend_from_slice(&chunk[..n]), + } + } + body.truncate(length); + Ok((head, body)) +} + +impl AnnounceServer { + /// Listen on a random loopback port. `on_page` runs on the server's own + /// thread for every accepted notice. + pub fn start(on_page: OnPage) -> Result { + let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))).map_err(|e| e.to_string())?; + let port = listener.local_addr().map_err(|e| e.to_string())?.port(); + let token = random_token(); + let expected = token.clone(); + let current: Arc>> = Arc::new(Mutex::new(None)); + let shared = Arc::clone(¤t); + thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + let (status, body) = match read_request(&mut stream) + .and_then(|(head, body)| check_request(&head, &body, &expected)) + { + Ok(Request::Page(notice)) => { + if let Ok(mut slot) = shared.lock() { + *slot = Some(notice.clone()); + } + on_page(notice); + (204, String::new()) + } + Ok(Request::Session) => { + let now = shared.lock().ok().and_then(|slot| slot.clone()); + (200, serde_json::to_string(&now).unwrap_or_else(|_| "null".to_string())) + } + Err(Refused(status, _)) => (status, String::new()), + }; + respond(&mut stream, status, &body); + } + }); + Ok(AnnounceServer { port, token, current }) + } + + pub fn url(&self) -> String { + format!("http://127.0.0.1:{}/page", self.port) + } + + pub fn token(&self) -> &str { + &self.token + } + + /// The page most recently announced, if any. + pub fn current(&self) -> Option { + self.current.lock().ok().and_then(|slot| slot.clone()) + } + + /// What goes on the agent's process so its `console.mjs open` shows pages + /// here. Every value belongs to this window. `embed_origin` is the origin of + /// the app page, so a console the agent starts allows being framed by it. + pub fn agent_env(&self, embed_origin: &str, app_version: &str) -> Vec<(String, String)> { + vec![ + ("PLAN2CODE_IN_APP".to_string(), "1".to_string()), + ("PLAN2CODE_APP_VERSION".to_string(), app_version.to_string()), + ("PLAN2CODE_EMBED_ORIGIN".to_string(), embed_origin.to_string()), + ("PLAN2CODE_APP_ANNOUNCE".to_string(), self.url()), + ("PLAN2CODE_APP_TOKEN".to_string(), self.token.clone()), + ] + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc::channel; + use std::sync::Mutex; + + fn request(token: &str, body: &str) -> (String, Vec) { + ( + format!("POST /page HTTP/1.1\r\nHost: 127.0.0.1\r\nx-plan2code-token: {token}\r\ncontent-length: {}", body.len()), + body.as_bytes().to_vec(), + ) + } + + const GOOD: &str = r#"{"url":"http://127.0.0.1:5000/s/abc/","sid":"s1","workflow":"plan"}"#; + + #[test] + fn accepts_a_good_notice() { + let (head, body) = request("t", GOOD); + let Ok(Request::Page(notice)) = check_request(&head, &body, "t") else { panic!("not accepted") }; + assert_eq!((notice.sid.as_str(), notice.workflow.as_str()), ("s1", "plan")); + let get = "GET /session HTTP/1.1\r\nx-plan2code-token: t"; + assert_eq!(check_request(get, b"", "t"), Ok(Request::Session)); + assert_eq!(check_request(get, b"", "other"), Err(Refused(403, "bad token"))); + } + + #[test] + fn refuses_a_wrong_or_missing_token() { + let (head, body) = request("nope", GOOD); + assert_eq!(check_request(&head, &body, "t"), Err(Refused(403, "bad token"))); + let head = "POST /page HTTP/1.1\r\nHost: x"; + assert_eq!(check_request(head, GOOD.as_bytes(), "t"), Err(Refused(403, "bad token"))); + } + + #[test] + fn refuses_a_browser_origin_and_other_routes() { + let (head, body) = request("t", GOOD); + let with_origin = format!("{head}\r\nOrigin: http://evil.example"); + assert_eq!(check_request(&with_origin, &body, "t"), Err(Refused(403, "not from a page"))); + let other = head.replace("/page", "/other"); + assert_eq!(check_request(&other, &body, "t"), Err(Refused(404, "not found"))); + let get = head.replace("POST", "GET"); + assert_eq!(check_request(&get, &body, "t"), Err(Refused(404, "not found")), "GET is for /session only"); + } + + #[test] + fn refuses_a_bad_body_and_a_url_that_is_not_the_console() { + let (head, _) = request("t", "x"); + assert_eq!(check_request(&head, b"not json", "t"), Err(Refused(400, "bad body"))); + for url in ["http://example.com/s/abc/", "https://127.0.0.1:5/s/a/", "http://127.0.0.1:5/other", "javascript:alert(1)", "http://127.0.0.1:0/s/a/"] { + let body = format!(r#"{{"url":"{url}","sid":"s","workflow":"w"}}"#); + assert_eq!(check_request(&head, body.as_bytes(), "t"), Err(Refused(400, "bad page")), "{url}"); + } + } + + #[test] + fn tokens_differ_between_windows() { + assert_ne!(random_token(), random_token()); + assert_eq!(random_token().len(), 32); + assert!(same_token("abc", "abc") && !same_token("abc", "abd") && !same_token("abc", "ab")); + } + + fn post(port: u16, token: &str, body: &str) -> u16 { + let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + write!( + stream, + "POST /page HTTP/1.1\r\nHost: 127.0.0.1\r\nx-plan2code-token: {token}\r\ncontent-length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + .unwrap(); + let mut answer = String::new(); + stream.read_to_string(&mut answer).unwrap(); + answer.split(' ').nth(1).unwrap().parse().unwrap() + } + + #[test] + fn two_windows_hear_only_their_own_agent() { + let (tx_a, rx_a) = channel(); + let (tx_b, rx_b) = channel(); + let (tx_a, tx_b) = (Mutex::new(tx_a), Mutex::new(tx_b)); + let a = AnnounceServer::start(Arc::new(move |n| tx_a.lock().unwrap().send(n).unwrap())).unwrap(); + let b = AnnounceServer::start(Arc::new(move |n| tx_b.lock().unwrap().send(n).unwrap())).unwrap(); + assert_ne!(a.url(), b.url()); + let port = |s: &AnnounceServer| s.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse::().unwrap(); + + assert_eq!(post(port(&a), a.token(), GOOD), 204); + assert_eq!(post(port(&b), a.token(), GOOD), 403, "window A's token does nothing in window B"); + assert_eq!(rx_a.recv_timeout(Duration::from_secs(3)).unwrap().sid, "s1"); + assert!(rx_b.recv_timeout(Duration::from_millis(300)).is_err()); + } + + #[test] + fn agent_env_names_this_windows_values() { + let server = AnnounceServer::start(Arc::new(|_| {})).unwrap(); + let env = server.agent_env("http://127.0.0.1:1430", "3.0.0"); + let get = |key: &str| env.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone()); + assert_eq!(get("PLAN2CODE_IN_APP").as_deref(), Some("1")); + assert_eq!(get("PLAN2CODE_EMBED_ORIGIN").as_deref(), Some("http://127.0.0.1:1430")); + assert_eq!(get("PLAN2CODE_APP_VERSION").as_deref(), Some("3.0.0")); + assert_eq!(get("PLAN2CODE_APP_ANNOUNCE"), Some(server.url())); + assert_eq!(get("PLAN2CODE_APP_TOKEN").as_deref(), Some(server.token())); + assert_eq!(get("PLAN2CODE_CONSOLE_SID"), None, "the window's session is asked for, not fixed at start"); + } + + #[test] + fn the_current_session_is_what_was_announced_last() { + let server = AnnounceServer::start(Arc::new(|_| {})).unwrap(); + let port: u16 = server.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse().unwrap(); + let ask = |token: &str| { + let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + write!(stream, "GET /session HTTP/1.1\r\nHost: 127.0.0.1\r\nx-plan2code-token: {token}\r\nConnection: close\r\n\r\n").unwrap(); + let mut answer = String::new(); + stream.read_to_string(&mut answer).unwrap(); + answer + }; + assert!(ask(server.token()).ends_with("null"), "nothing announced yet"); + assert_eq!(post(port, server.token(), GOOD), 204); + assert!(ask(server.token()).contains(r#""sid":"s1""#)); + assert!(ask("wrong").starts_with("HTTP/1.1 403")); + assert_eq!(server.current().unwrap().workflow, "plan"); + } +} diff --git a/plan2code-app/src-tauri/src/brief.rs b/plan2code-app/src-tauri/src/brief.rs new file mode 100644 index 0000000..b47fc4c --- /dev/null +++ b/plan2code-app/src-tauri/src/brief.rs @@ -0,0 +1,461 @@ +//! The restart brief: what a fresh agent needs to pick a session up where it +//! stopped, written from the console's session files and the spec on disk. It +//! is derived on demand and never cached. The Ask chat is left out (FR-7). + +use std::fs; +use std::io::Read; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::thread; +use std::time::{Duration, Instant}; + +use serde_json::Value; + +/// How many of the person's most recent answers the brief carries. +const RECENT_ANSWERS: usize = 10; + +/// How many of the session's most recent `events.ndjson` lines the brief carries. +const RECENT_EVENTS: usize = 5; + +/// The git argument for the last five commits, one line each. +const RECENT_COMMITS: &str = "-5"; + +/// How long the one-line next step may run before it is cut. +const NEXT_STEP_MAX: usize = 200; + +/// The skill a console workflow runs, as the dashboard launches it. +pub fn skill_for_workflow(workflow: &str) -> Option<&'static str> { + Some(match workflow { + "init" => "plan2code-init", + "init-update" => "plan2code-init-update", + "pathfinder" => "plan2code-0-pathfinder", + "plan" => "plan2code-1-plan", + "revise-plan" => "plan2code-1b-revise-plan", + "quick-task" => "plan2code-quick-task", + "document" => "plan2code-2-document", + "implement" => "plan2code-3-implement", + "implement-review" => "plan2code-3-implement-review", + "review" => "plan2code-review", + "finalize" => "plan2code-4-finalize", + "handoff" => "plan2code-handoff", + "git" => "plan2code-git", + "changelog" => "plan2code-changelog", + "xray" => "plan2code-xray", + "diagnose" => "plan2code-diagnose", + _ => return None, + }) +} + +/// What the repository looks like now: `git status --short`, and the last +/// commits. `None` when the folder is not a git repository. +pub struct GitSummary { + pub status: String, + pub log: String, +} + +pub fn git_summary(folder: &Path) -> Option { + let status = git(folder, &["status", "--short"])?; + // A repository with no commits yet has no log: the status alone is the record. + let log = git(folder, &["log", RECENT_COMMITS, "--oneline"]).unwrap_or_default(); + Some(GitSummary { status, log }) +} + +/// Longest a git call may hold up the caller. The brief is built while the +/// agent's state is locked, so a slow repository must not stall the window. +const GIT_TIMEOUT: Duration = Duration::from_secs(2); + +fn git(folder: &Path, args: &[&str]) -> Option { + let mut command = Command::new("git"); + command.arg("-C").arg(folder).args(args).stdout(Stdio::piped()).stderr(Stdio::null()); + #[cfg(windows)] + { + 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 out = child.stdout.take()?; + let reader = thread::spawn(move || { + let mut bytes = Vec::new(); + let _ = out.read_to_end(&mut bytes); + bytes + }); + let deadline = Instant::now() + GIT_TIMEOUT; + let status = loop { + if let Some(status) = child.try_wait().ok()? { + break status; + } + if Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + thread::sleep(Duration::from_millis(20)); + }; + let bytes = reader.join().ok()?; + status.success().then(|| String::from_utf8_lossy(&bytes).trim_end().to_string()) +} + +/// The brief as Markdown. `state` is a session's `state.json`; `spec_dir` is +/// the spec folder on disk, when the session has one; `git` is the repository +/// summary, when the folder is one; `events` is the session's `events.ndjson`, +/// oldest first. +pub fn build_brief(state: &Value, spec_dir: Option<&Path>, git: Option<&GitSummary>, events: &[Value]) -> String { + let workflow = str_field(state, "workflow").unwrap_or(""); + let skill = skill_for_workflow(workflow); + let spec = str_field(state, "specDir"); + let mut out = String::new(); + + out.push_str("## Where you were\n\n"); + match skill { + Some(skill) => out.push_str(&format!("- Skill: {skill} (workflow `{workflow}`)\n")), + None => out.push_str(&format!("- Workflow: `{workflow}`\n")), + } + match spec { + Some(spec) => out.push_str(&format!("- Spec: {spec}\n")), + None => out.push_str("- Spec: none yet\n"), + } + out.push('\n'); + + out.push_str("## Progress\n\n"); + let headline = state.get("headline"); + let stage = headline.and_then(|h| str_field(h, "stage")).unwrap_or(""); + let cleared = headline.and_then(|h| h.get("cleared")).and_then(Value::as_u64).unwrap_or(0); + let total = headline.and_then(|h| h.get("total")).and_then(Value::as_u64).unwrap_or(0); + let activity = state.get("agent").and_then(|a| str_field(a, "activity")).map(str::trim).filter(|a| !a.is_empty()); + if !stage.is_empty() { + out.push_str(&format!("{stage}: {cleared} of {total} done.\n")); + if let Some(activity) = activity { + out.push_str(&format!("Doing: {activity}\n")); + } + out.push('\n'); + } else if let Some(activity) = activity { + out.push_str(&format!("Doing: {activity}\n\n")); + } else { + out.push_str("No progress posted yet.\n\n"); + } + + let items = state.get("items").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]); + + out.push_str("### Open questions\n\n"); + let open: Vec<&Value> = items.iter().filter(|i| matches!(str_field(i, "status"), Some("open" | "reopened"))).collect(); + if open.is_empty() { + out.push_str("None.\n\n"); + } else { + for item in open { + out.push_str(&format!("- {}\n", title_of(item))); + } + out.push('\n'); + } + + out.push_str("## Recent answers and decisions\n\n"); + let answered: Vec<&Value> = items.iter().filter(|i| str_field(i, "status") == Some("answered")).collect(); + let recent = &answered[answered.len().saturating_sub(RECENT_ANSWERS)..]; + if recent.is_empty() { + out.push_str("None yet.\n\n"); + } else { + for item in recent { + let answer = answer_text(item); + let answer = if answer.is_empty() { "answered".to_string() } else { answer }; + out.push_str(&format!("- {}: {answer}\n", title_of(item))); + } + out.push('\n'); + } + + if let Some(git) = git { + out.push_str("## Git\n\n"); + out.push_str("Changes:\n\n```\n"); + out.push_str(if git.status.is_empty() { "clean" } else { &git.status }); + out.push_str("\n```\n\n"); + if !git.log.is_empty() { + out.push_str("Last commits:\n\n```\n"); + out.push_str(&git.log); + out.push_str("\n```\n\n"); + } + } + + if !events.is_empty() { + out.push_str("## Recent activity\n\n"); + let recent = &events[events.len().saturating_sub(RECENT_EVENTS)..]; + for event in recent { + out.push_str(&format!("- {}\n", render_event(event))); + } + out.push('\n'); + } + + out.push_str("## Next task\n\n"); + out.push_str(&next_step(spec_dir, skill)); + out.push('\n'); + out +} + +/// One `events.ndjson` line, as a terse line for a fresh agent. A shape this +/// does not special-case falls back to its raw `type`. +fn render_event(event: &Value) -> String { + let kind = str_field(event, "type").unwrap_or("event"); + match kind { + "post" => { + let items = event.get("items").and_then(Value::as_u64).unwrap_or(0); + format!("post ({items} items)") + } + "consume" => match str_field(event, "kind") { + Some(kind) => format!("consume: {kind}"), + None => "consume".to_string(), + }, + "open" => { + if event.get("resumed").and_then(Value::as_bool).unwrap_or(false) { + "open (resumed)".to_string() + } else { + "open".to_string() + } + } + other => other.to_string(), + } +} + +/// The one-line next step: the first open task of the spec's in-progress phase +/// (or, failing that, the first phase not started); otherwise the skill's name; +/// otherwise "Open the dashboard". +pub fn next_step(spec_dir: Option<&Path>, skill: Option<&str>) -> String { + if let Some(task) = spec_dir.and_then(open_task) { + return cut(&task); + } + match skill { + Some(skill) => format!("Continue with {skill}"), + None => "Open the dashboard".to_string(), + } +} + +/// The first `- [ ]` task line of the active phase file, as one line of text. +fn open_task(spec_dir: &Path) -> Option { + let overview = fs::read_to_string(spec_dir.join("overview.md")).ok()?; + let phase = active_phase(&overview)?; + let text = fs::read_to_string(spec_dir.join(format!("phase-{phase}.md"))).ok()?; + let line = text.lines().map(str::trim_start).find(|l| l.starts_with("- [ ]"))?; + Some(line.trim_start_matches("- [ ]").trim().replace("**", "")) +} + +/// The phase number the overview marks in progress (`[/]`), else the first +/// one not started (`[ ]`). +fn active_phase(overview: &str) -> Option { + let phase_of = |line: &str| { + let rest = &line[line.find("phase-")? + "phase-".len()..]; + let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); + digits.parse::().ok() + }; + let rows = || overview.lines().map(str::trim_start).filter(|l| l.starts_with("- [")); + rows().find(|l| l.starts_with("- [/]")).and_then(phase_of).or_else(|| rows().find(|l| l.starts_with("- [ ]")).and_then(phase_of)) +} + +fn cut(text: &str) -> String { + let mut out: String = text.chars().take(NEXT_STEP_MAX).collect(); + if text.chars().count() > NEXT_STEP_MAX { + out.push('…'); + } + out +} + +fn str_field<'a>(value: &'a Value, key: &str) -> Option<&'a str> { + value.get(key).and_then(Value::as_str) +} + +fn title_of(item: &Value) -> String { + let title = str_field(item, "title").or_else(|| str_field(item, "id")).unwrap_or("(untitled)"); + title.trim().to_string() +} + +/// An answer as the person gave it: the option's label for a pick, plus any +/// words they typed. Empty when the answer carries nothing to show. +fn answer_text(item: &Value) -> String { + let Some(answer) = item.get("answer") else { return String::new() }; + let options = item.get("options").and_then(Value::as_array); + let label = |k: &str| { + options + .and_then(|list| list.iter().find(|o| str_field(o, "k") == Some(k))) + .and_then(|o| str_field(o, "text")) + .unwrap_or(k) + .to_string() + }; + let mut parts: Vec = Vec::new(); + if let Some(k) = str_field(answer, "k") { + parts.push(label(k)); + } + if let Some(list) = answer.get("ks").and_then(Value::as_array) { + let picks: Vec = list.iter().filter_map(Value::as_str).map(label).collect(); + if !picks.is_empty() { + parts.push(picks.join(", ")); + } + } + if let Some(yes) = answer.get("yes").and_then(Value::as_bool) { + parts.push(if yes { "yes" } else { "no" }.to_string()); + } + if let Some(verdict) = str_field(answer, "verdict") { + parts.push(verdict.to_string()); + } + if let Some(text) = str_field(answer, "text").map(str::trim).filter(|t| !t.is_empty()) { + parts.push(text.to_string()); + } + parts.join("; ") +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn fixture(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("plan2code-brief-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir + } + + fn mid_implement_spec() -> std::path::PathBuf { + let spec = fixture("spec").join("specs").join("feature"); + fs::create_dir_all(&spec).unwrap(); + fs::write( + spec.join("overview.md"), + "- [x] [Phase 1: Foundations](./phase-1.md)\n- [/] [Phase 2: Restart](./phase-2.md)\n- [ ] [Phase 3: Later](./phase-3.md)\n", + ) + .unwrap(); + fs::write(spec.join("phase-2.md"), "## Tasks\n\n- [x] **Task 2.1:** Done already\n- [ ] **Task 2.2:** Write the **reader**\n- [ ] **Task 2.3:** Later\n").unwrap(); + spec + } + + fn mid_implement_state() -> Value { + json!({ + "schema": 1, + "workflow": "implement", + "specDir": "specs/feature", + "headline": { "stage": "Phase 2: Restart", "cleared": 1, "total": 3 }, + "items": [ + { "id": "q1", "title": "Which format", "status": "answered", "kind": "choice", + "options": [{ "k": "A", "text": "Markdown" }, { "k": "B", "text": "Plain text" }], + "answer": { "k": "A" } }, + { "id": "q2", "title": "Keep the header", "status": "answered", "kind": "confirm", "answer": { "yes": true } }, + { "id": "q3", "title": "Anything else?", "status": "open", "kind": "text" } + ] + }) + } + + #[test] + fn a_mid_implement_session_carries_every_section() { + let spec = mid_implement_spec(); + let git = GitSummary { status: " M src/lib.rs".to_string(), log: "abc1234 Add the reader".to_string() }; + let brief = build_brief(&mid_implement_state(), Some(&spec), Some(&git), &[]); + assert!(brief.contains("Skill: plan2code-3-implement (workflow `implement`)")); + assert!(brief.contains("Spec: specs/feature")); + assert!(brief.contains("Phase 2: Restart: 1 of 3 done.")); + assert!(brief.contains("### Open questions\n\n- Anything else?")); + assert!(brief.contains("- Which format: Markdown")); + assert!(brief.contains("- Keep the header: yes")); + assert!(brief.contains(" M src/lib.rs")); + assert!(brief.contains("abc1234 Add the reader")); + assert!(brief.contains("## Next task\n\nTask 2.2: Write the reader")); + } + + #[test] + fn the_brief_names_only_the_last_ten_answers() { + let items: Vec = (0..12) + .map(|n| json!({ "id": format!("q{n}"), "title": format!("Question {n}"), "status": "answered", "answer": { "text": format!("Answer {n}") } })) + .collect(); + let state = json!({ "schema": 1, "workflow": "pathfinder", "items": items }); + let brief = build_brief(&state, None, None, &[]); + assert!(!brief.contains("Question 0:")); + assert!(!brief.contains("Question 1:")); + assert!(brief.contains("- Question 2: Answer 2")); + assert!(brief.contains("- Question 11: Answer 11")); + } + + #[test] + fn a_pathfinder_session_without_a_spec_says_so() { + let state = json!({ "schema": 1, "workflow": "pathfinder", "headline": { "stage": "Charting", "cleared": 2, "total": 5 } }); + let brief = build_brief(&state, None, None, &[]); + assert!(brief.contains("Skill: plan2code-0-pathfinder")); + assert!(brief.contains("- Spec: none yet")); + assert!(!brief.contains("## Git")); + assert!(brief.contains("## Next task\n\nContinue with plan2code-0-pathfinder")); + } + + #[test] + fn a_session_with_no_spec_and_no_skill_opens_the_dashboard() { + let state = json!({ "schema": 1, "workflow": "dashboard" }); + assert!(build_brief(&state, None, None, &[]).ends_with("## Next task\n\nOpen the dashboard\n")); + } + + #[test] + fn chat_entries_never_reach_the_brief() { + let home = fixture("chat"); + let dir = home.join("sessions").join("s1"); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join("state.json"), r#"{"schema": 1, "workflow": "implement"}"#).unwrap(); + fs::write(dir.join("chat.ndjson"), "{\"kind\":\"ask\",\"text\":\"CHAT-ONLY-WORDS\"}\n").unwrap(); + let session = crate::session_reader::load(&home, "s1").unwrap(); + let brief = build_brief(&session.state, None, None, &[]); + assert!(!brief.contains("CHAT-ONLY-WORDS")); + } + + #[test] + fn a_folder_that_is_not_a_repository_has_no_git_summary() { + assert!(git_summary(&fixture("not-a-repo")).is_none()); + } + + #[test] + fn the_brief_names_what_the_agent_was_doing() { + let state = json!({ + "schema": 1, + "workflow": "implement", + "headline": { "stage": "Phase 2: Restart", "cleared": 1, "total": 3 }, + "agent": { "status": "working", "activity": "Spiking Claude's context signal (Task 10.1)" }, + }); + let brief = build_brief(&state, None, None, &[]); + assert!(brief.contains("Phase 2: Restart: 1 of 3 done.\nDoing: Spiking Claude's context signal (Task 10.1)\n")); + } + + #[test] + fn an_activity_without_a_headline_still_shows() { + let state = json!({ "schema": 1, "workflow": "implement", "agent": { "status": "working", "activity": "Reading the spec" } }); + let brief = build_brief(&state, None, None, &[]); + assert!(brief.contains("Doing: Reading the spec\n")); + assert!(!brief.contains("No progress posted yet.")); + } + + #[test] + fn an_empty_activity_falls_back_to_no_progress_posted() { + let state = json!({ "schema": 1, "workflow": "implement", "agent": { "status": "idle", "activity": "" } }); + let brief = build_brief(&state, None, None, &[]); + assert!(brief.contains("No progress posted yet.")); + } + + #[test] + fn the_brief_names_a_few_recent_events() { + let state = json!({ "schema": 1, "workflow": "implement" }); + let events = vec![ + json!({ "at": "2026-10-23T01:00:00.000Z", "type": "listening", "port": 4100 }), + json!({ "at": "2026-10-23T01:08:00.000Z", "type": "open", "resumed": true }), + json!({ "at": "2026-10-23T01:08:47.152Z", "type": "post", "items": 3 }), + json!({ "at": "2026-10-23T01:09:00.000Z", "type": "consume", "kind": "submit" }), + ]; + let brief = build_brief(&state, None, None, &events); + assert!(brief.contains("## Recent activity\n\n- listening\n- open (resumed)\n- post (3 items)\n- consume: submit\n")); + } + + #[test] + fn only_the_last_five_events_are_named() { + let state = json!({ "schema": 1, "workflow": "implement" }); + let events: Vec = (0..8).map(|n| json!({ "type": "upload", "id": format!("f{n}") })).collect(); + let brief = build_brief(&state, None, None, &events); + assert_eq!(brief.matches("- upload\n").count(), RECENT_EVENTS); + } + + #[test] + fn no_events_means_no_recent_activity_section() { + let state = json!({ "schema": 1, "workflow": "implement" }); + assert!(!build_brief(&state, None, None, &[]).contains("## Recent activity")); + } + + #[test] + fn a_skill_name_maps_to_its_workflow() { + assert_eq!(skill_for_workflow("quick-task"), Some("plan2code-quick-task")); + assert_eq!(skill_for_workflow("unknown"), None); + } +} diff --git a/plan2code-app/src-tauri/src/console_supervisor.rs b/plan2code-app/src-tauri/src/console_supervisor.rs new file mode 100644 index 0000000..e6ca7dc --- /dev/null +++ b/plan2code-app/src-tauri/src/console_supervisor.rs @@ -0,0 +1,373 @@ +//! The Node web console as a supervised child: `console.mjs open` starts a +//! detached server and prints the session's JSON, `stop` ends it, and a plain +//! GET on the session URL is the health check. Knows nothing about Tauri. + +use std::io::{Read, Write}; +use std::net::{TcpStream, ToSocketAddrs}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::Duration; + +use serde::Serialize; + +/// How long a health check waits for the console before calling it dead. The +/// server is on loopback, so anything longer is a hang, not a slow network. +const HEALTH_TIMEOUT: Duration = Duration::from_secs(3); + +/// A running console session, as `console.mjs open` reports it. +#[derive(Clone, Serialize)] +pub struct ConsoleSession { + pub sid: String, + pub url: String, + pub pid: u32, + pub port: u16, + /// The console says it can be framed by the app. An older one does not + /// print this, and its page would be refused in the frame. + pub embed: bool, +} + +/// What the person is told when the installed console is too old for the app. +pub const OLD_CONSOLE: &str = + "The installed Plan2Code console is too old to show inside the app. Press Update skills, then try again."; + +/// One supervised console for one project folder. +pub struct ConsoleSupervisor { + console_dir: PathBuf, + project_dir: PathBuf, + embed_origin: String, + session: ConsoleSession, + stopped: bool, +} + +fn err(e: E) -> String { + e.to_string() +} + +/// A `node console.mjs ...` call with no console window on Windows: the app is +/// a GUI program, so a bare Command would flash one open per call. +fn node_command(console_dir: &Path) -> Command { + let mut command = Command::new("node"); + // A Dock or Start-menu launch often lacks nvm, Homebrew or Volta's + // directories (Task 9.9): run `node` with the PATH that finds it anyway. + command.env("PATH", crate::node_check::resolved_path()); + command.arg(console_dir.join("console.mjs")); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(0x08000000); // CREATE_NO_WINDOW + } + command +} + +/// The origin the app's own page has, which is what the console's embed mode +/// must be told to allow as the frame parent. Tauri serves the page on +/// `http://tauri.localhost` on Windows (and Android) and `tauri://localhost` +/// on macOS and Linux. +pub fn app_origin() -> &'static str { + if cfg!(windows) { + "http://tauri.localhost" + } else { + "tauri://localhost" + } +} + +/// The origin (`scheme://host[:port]`) of the app page's own URL, which is what +/// the console's embed mode must allow as the frame parent. In a release build +/// that is `app_origin()`, but `tauri dev` serves the page from its own dev +/// server on a loopback port, so the real URL is asked rather than assumed. +pub fn origin_of(url: &str) -> Option { + let (scheme, rest) = url.split_once("://")?; + let authority = rest.split(['/', '?', '#']).next()?; + if authority.is_empty() || !matches!(scheme, "http" | "https" | "tauri") { + return None; + } + Some(format!("{scheme}://{authority}")) +} + +/// Where the installed console lives: an explicit override first (tests and +/// dev), then the file the console keeps for the app, then the skill install. +pub fn find_console_dir() -> Result { + let has_console = |dir: &Path| dir.join("console.mjs").is_file(); + if let Ok(dir) = std::env::var("PLAN2CODE_CONSOLE_DIR") { + let dir = PathBuf::from(dir); + if has_console(&dir) { + return Ok(dir); + } + } + // The console writes its pointer under PLAN2CODE_CONSOLE_HOME when that + // relocates it, else under ~/.plan2code/console. + let pointer = match std::env::var("PLAN2CODE_CONSOLE_HOME") { + Ok(home) => PathBuf::from(home).join("console-dir"), + Err(_) => { + let home = std::env::home_dir().ok_or("no home folder found")?; + home.join(".plan2code").join("console").join("console-dir") + } + }; + if let Ok(text) = std::fs::read_to_string(&pointer) { + let dir = PathBuf::from(text.trim()); + if has_console(&dir) { + return Ok(dir); + } + } + let dir = std::env::home_dir() + .ok_or("no home folder found")? + .join(".agents") + .join("skills") + .join("plan2code") + .join("references") + .join("web-console"); + if has_console(&dir) { + return Ok(dir); + } + Err(format!( + "the web console is not installed (looked in $PLAN2CODE_CONSOLE_DIR, {} and {})", + pointer.display(), + dir.display() + )) +} + +/// Parse the one JSON object `console.mjs open` prints on stdout. +fn parse_open_output(stdout: &[u8]) -> Result { + let text = String::from_utf8_lossy(stdout); + let line = text + .lines() + .rev() + .find(|l| l.trim_start().starts_with('{')) + .ok_or_else(|| format!("console open printed no JSON: {}", text.trim()))?; + let value: serde_json::Value = serde_json::from_str(line.trim()).map_err(err)?; + let get = |key: &str| value.get(key).and_then(|v| v.as_str().map(String::from)); + let num = |key: &str| value.get(key).and_then(|v| v.as_u64()); + Ok(ConsoleSession { + sid: get("sid").ok_or("console open: no sid in output")?, + url: get("url").ok_or("console open: no url in output")?, + pid: num("pid").ok_or("console open: no pid in output")? as u32, + port: num("port").ok_or("console open: no port in output")? as u16, + embed: num("embed").is_some_and(|n| n >= 1), + }) +} + +/// Split `http://:` into its parts; the console only ever +/// listens on loopback http. +fn split_url(url: &str) -> Result<(String, u16, String), String> { + let rest = url.strip_prefix("http://").ok_or_else(|| format!("not an http url: {url}"))?; + let (authority, path) = match rest.split_once('/') { + Some((a, p)) => (a, format!("/{p}")), + None => (rest, "/".to_string()), + }; + let (host, port) = authority + .rsplit_once(':') + .ok_or_else(|| format!("no port in url: {url}"))?; + let port: u16 = port.parse().map_err(|_| format!("bad port in url: {url}"))?; + Ok((host.to_string(), port, path)) +} + +impl ConsoleSupervisor { + /// Find the installed console, run `open --workflow dashboard --no-open` in + /// the project folder with `PLAN2CODE_EMBED_ORIGIN` set, and keep the + /// session it prints. + pub fn start(project_dir: PathBuf, embed_origin: String) -> Result { + let console_dir = find_console_dir()?; + let session = Self::open_session(&console_dir, &project_dir, &embed_origin, None)?; + Ok(ConsoleSupervisor { console_dir, project_dir, embed_origin, session, stopped: false }) + } + + /// `open` for the dashboard, or, with `resume`, the same session again on + /// a new server (so the page and its place in a skill survive a dead server). + /// A console the agent's `open` started and announced: this supervisor + /// now owns its health and its stop, though it did not start it. + pub fn adopt( + project_dir: PathBuf, + embed_origin: String, + url: &str, + sid: &str, + ) -> Result { + let console_dir = find_console_dir()?; + let (_, port, _) = split_url(url)?; + let session = ConsoleSession { sid: sid.to_string(), url: url.to_string(), pid: 0, port, embed: true }; + Ok(ConsoleSupervisor { console_dir, project_dir, embed_origin, session, stopped: false }) + } + + fn open_session( + console_dir: &Path, + project_dir: &Path, + embed_origin: &str, + resume: Option<&str>, + ) -> Result { + let mut command = node_command(console_dir); + command.arg("open"); + match resume { + Some(sid) => command.args(["--resume", sid, "--no-open"]), + None => command.args(["--workflow", "dashboard", "--no-open"]), + }; + let output = command + .current_dir(project_dir) + .env("PLAN2CODE_EMBED_ORIGIN", embed_origin) + .output() + .map_err(err)?; + if !output.status.success() { + return Err(format!( + "console open failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + )); + } + let session = parse_open_output(&output.stdout)?; + if !session.embed { + // Do not leave an old console running that the frame cannot show. + let _ = node_command(console_dir) + .args(["stop", "--session", &session.sid]) + .current_dir(project_dir) + .output(); + return Err(OLD_CONSOLE.to_string()); + } + Ok(session) + } + + pub fn session(&self) -> &ConsoleSession { + &self.session + } + + /// The console moved to another address or session (an announced page that + /// is not the one this supervisor opened): health, stop and the restart + /// brief follow it from now on. + pub fn follow(&mut self, url: &str, sid: &str) { + if self.session.url == url && self.session.sid == sid { + return; + } + if let Ok((_, port, _)) = split_url(url) { + self.session.port = port; + } + self.session.url = url.to_string(); + self.session.sid = sid.to_string(); + } + + /// Was `stop()` called on this supervisor. + pub fn stopped(&self) -> bool { + self.stopped + } + + /// A GET on the session URL: any HTTP answer means the server is alive. + pub fn health(&self) -> bool { + if self.stopped { + return false; + } + let Ok((host, port, path)) = split_url(&self.session.url) else { + return false; + }; + let Some(addr) = (host.as_str(), port).to_socket_addrs().ok().and_then(|mut a| a.next()) + else { + return false; + }; + let Ok(mut stream) = TcpStream::connect_timeout(&addr, HEALTH_TIMEOUT) else { + return false; + }; + let _ = stream.set_read_timeout(Some(HEALTH_TIMEOUT)); + let _ = stream.set_write_timeout(Some(HEALTH_TIMEOUT)); + let request = format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n"); + if stream.write_all(request.as_bytes()).is_err() { + return false; + } + let mut status = [0u8; 64]; + match stream.read(&mut status) { + Ok(n) => String::from_utf8_lossy(&status[..n]).starts_with("HTTP/"), + Err(_) => false, + } + } + + /// Health check plus a fresh `open` when the server is gone. Returns true + /// when a new session was started. Never loops: the caller (the bar) asks + /// and shows the outcome. + pub fn restart_if_dead(&mut self) -> Result { + if self.stopped || self.health() { + return Ok(false); + } + // The same session first, so the page and a skill's place in it survive; + // a session that cannot be resumed (gone from disk) starts a new one. + let sid = self.session.sid.clone(); + self.session = Self::open_session(&self.console_dir, &self.project_dir, &self.embed_origin, Some(&sid)) + .or_else(|_| Self::open_session(&self.console_dir, &self.project_dir, &self.embed_origin, None))?; + self.stopped = false; + Ok(true) + } + + /// `console.mjs stop --session `: the console's own orderly shutdown. + pub fn stop(&mut self) -> Result<(), String> { + if self.stopped { + return Ok(()); + } + let output = node_command(&self.console_dir) + .args(["stop", "--session", &self.session.sid]) + .current_dir(&self.project_dir) + .output() + .map_err(err)?; + self.stopped = true; + if !output.status.success() { + return Err(format!( + "console stop failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + )); + } + Ok(()) + } +} + +impl Drop for ConsoleSupervisor { + /// The app going away takes the console it started with it. `stop` is + /// idempotent, so a session ended by hand just returns early here. + fn drop(&mut self) { + let _ = self.stop(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn splits_the_session_url() { + let (host, port, path) = split_url("http://127.0.0.1:51617/s/abc/").unwrap(); + assert_eq!((host.as_str(), port, path.as_str()), ("127.0.0.1", 51617, "/s/abc/")); + let (_, _, path) = split_url("http://localhost:9").unwrap(); + assert_eq!(path, "/"); + assert!(split_url("https://127.0.0.1:1/x").is_err()); + assert!(split_url("http://127.0.0.1/x").is_err()); + } + + #[test] + fn origin_comes_from_the_pages_own_url() { + assert_eq!(origin_of("http://127.0.0.1:1430/index.html").as_deref(), Some("http://127.0.0.1:1430")); + assert_eq!(origin_of("http://tauri.localhost/").as_deref(), Some("http://tauri.localhost")); + assert_eq!(origin_of("https://tauri.localhost").as_deref(), Some("https://tauri.localhost")); + assert_eq!(origin_of("tauri://localhost/index.html?x=1").as_deref(), Some("tauri://localhost")); + assert_eq!(origin_of("file:///x"), None); + assert_eq!(origin_of("not a url"), None); + assert_eq!(origin_of("http:///x"), None); + } + + #[test] + fn an_announced_console_is_adopted_with_its_port() { + // Only needs a console to be installed; skipped where there is none. + let Ok(dir) = find_console_dir() else { return }; + let _ = dir; + let mut sup = ConsoleSupervisor::adopt(PathBuf::from("."), "http://tauri.localhost".into(), "http://127.0.0.1:5555/s/t/", "sid-9").unwrap(); + assert_eq!((sup.session().port, sup.session().sid.as_str()), (5555, "sid-9")); + assert!(sup.session().embed); + assert!(ConsoleSupervisor::adopt(PathBuf::from("."), String::new(), "https://x/", "s").is_err()); + sup.follow("http://127.0.0.1:6000/s/u/", "sid-10"); + assert_eq!((sup.session().port, sup.session().sid.as_str()), (6000, "sid-10")); + // Never started a server here: nothing for Drop to stop. + sup.stopped = true; + } + + #[test] + fn parses_open_output() { + let json = br#"{"ok":true,"sid":"s1","url":"http://127.0.0.1:5/s/t/","port":5,"pid":42,"embed":1} +"#; + let session = parse_open_output(json).unwrap(); + assert_eq!((session.sid.as_str(), session.port, session.pid), ("s1", 5, 42)); + assert!(session.embed); + let old = br#"{"ok":true,"sid":"s1","url":"http://127.0.0.1:5/s/t/","port":5,"pid":42}"#; + assert!(!parse_open_output(old).unwrap().embed, "a console that does not say it embeds is too old"); + assert!(parse_open_output(b"not json\n").is_err()); + assert!(parse_open_output(br#"{"ok":true,"sid":"s1"}"#).is_err()); + } +} diff --git a/plan2code-app/src-tauri/src/context/claude.rs b/plan2code-app/src-tauri/src/context/claude.rs new file mode 100644 index 0000000..baf919d --- /dev/null +++ b/plan2code-app/src-tauri/src/context/claude.rs @@ -0,0 +1,228 @@ +//! Claude's context, read from its own transcript: the last `assistant` message's +//! token usage, as a fraction of its context window. Claude Code writes one file +//! per session under `~/.claude/projects//.jsonl` (relocatable via `CLAUDE_CONFIG_DIR`), +//! and names it after the session's own id, so a project folder's newest file +//! since the agent started is this run's transcript (Task 10.1's spike; the +//! same approach `codex.rs` uses for Codex's log). The entry format is +//! undocumented ("internal and may change between versions" per Claude's own +//! docs), so a usable reading is `BestEffort`, never `Real`. An unreadable line +//! is skipped, and a transcript with no usable line, or no transcript at all, +//! is `Unknown`. + +use std::fs::{self, File}; +use std::io::{Read, Seek, SeekFrom}; +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + +use serde_json::Value; + +use super::{ContextReader, ContextReading}; + +/// How much of a transcript's end is read; the newest usage is near the end. +pub const TAIL_BYTES: u64 = 256 * 1024; + +pub struct ClaudeReader { + pub projects_dir: PathBuf, + pub folder: PathBuf, + /// Only a transcript written at or after this moment belongs to the running agent. + pub since: SystemTime, + /// The context window to read the usage against (`super::window_for`). + pub window: u64, +} + +impl ContextReader for ClaudeReader { + fn read(&self) -> ContextReading { + match newest_transcript(&self.projects_dir.join(encode(&self.folder)), self.since) { + Some(file) => reading_from_file(&file, self.window), + None => ContextReading::Unknown, + } + } +} + +/// `folder` with every non-alphanumeric character replaced by `-`, the way +/// Claude Code names a project's transcripts directory. +fn encode(folder: &Path) -> String { + folder.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect() +} + +/// The newest `*.jsonl` file directly under `dir` that was written at or after `since`. +fn newest_transcript(dir: &Path, since: SystemTime) -> Option { + let entries = fs::read_dir(dir).ok()?; + let mut newest: Option<(SystemTime, PathBuf)> = None; + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().and_then(|e| e.to_str()) != Some("jsonl") { + continue; + } + let Ok(modified) = entry.metadata().and_then(|m| m.modified()) else { continue }; + if modified < since { + continue; + } + if newest.as_ref().is_none_or(|(best, _)| modified > *best) { + newest = Some((modified, path)); + } + } + newest.map(|(_, path)| path) +} + +/// The percent of `window` the last usable `assistant` usage line in `text` used. +pub fn reading_from_text(text: &str, window: u64) -> ContextReading { + for line in text.lines().rev() { + if let Some(percent) = percent_from_line(line, window) { + return ContextReading::BestEffort { percent }; + } + } + ContextReading::Unknown +} + +fn percent_from_line(line: &str, window: u64) -> Option { + if window == 0 { + return None; + } + let value: Value = serde_json::from_str(line).ok()?; + if value.get("type")?.as_str()? != "assistant" { + return None; + } + let usage = value.get("message")?.get("usage")?; + let input = usage.get("input_tokens")?.as_u64()?; + let cache_read = usage.get("cache_read_input_tokens").and_then(Value::as_u64).unwrap_or(0); + let cache_creation = usage.get("cache_creation_input_tokens").and_then(Value::as_u64).unwrap_or(0); + let used = input.saturating_add(cache_read).saturating_add(cache_creation); + Some((used.saturating_mul(100) / window).min(100) as u8) +} + +/// Reads the end of `file`. A file that cannot be opened or read is `Unknown`. +fn reading_from_file(file: &Path, window: u64) -> ContextReading { + let Ok(mut handle) = File::open(file) else { return ContextReading::Unknown }; + let Ok(len) = handle.metadata().map(|m| m.len()) else { return ContextReading::Unknown }; + if len > TAIL_BYTES && handle.seek(SeekFrom::Start(len - TAIL_BYTES)).is_err() { + return ContextReading::Unknown; + } + let mut bytes = Vec::new(); + if handle.read_to_end(&mut bytes).is_err() { + return ContextReading::Unknown; + } + // The first line of a partial tail is cut short; it fails to parse and is skipped. + reading_from_text(&String::from_utf8_lossy(&bytes), window) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + const GOOD: &str = r#"{"type":"assistant","message":{"usage":{"input_tokens":2,"cache_creation_input_tokens":724,"cache_read_input_tokens":205907}}}"#; + + fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("plan2code-claude-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir + } + + fn epoch_plus(secs: u64) -> SystemTime { + SystemTime::UNIX_EPOCH + Duration::from_secs(secs) + } + + fn write_transcript(dir: &Path, name: &str, body: &str, modified: SystemTime) -> PathBuf { + fs::create_dir_all(dir).unwrap(); + let file = dir.join(format!("{name}.jsonl")); + fs::write(&file, body).unwrap(); + File::options().write(true).open(&file).unwrap().set_modified(modified).unwrap(); + file + } + + #[test] + fn the_last_assistant_usage_gives_the_percent_of_the_window() { + assert_eq!(reading_from_text(GOOD, 206_633), ContextReading::BestEffort { percent: 100 }); + assert_eq!(reading_from_text(GOOD, 1_000_000), ContextReading::BestEffort { percent: 20 }); + } + + #[test] + fn a_normal_transcript_is_read_from_the_newest_assistant_line() { + let early = r#"{"type":"assistant","message":{"usage":{"input_tokens":2,"cache_creation_input_tokens":0,"cache_read_input_tokens":99998}}}"#; + let text = format!("{early}\n{GOOD}"); + assert_eq!(reading_from_text(&text, 206_633), ContextReading::BestEffort { percent: 100 }); + } + + #[test] + fn a_partial_last_line_is_skipped_in_favour_of_the_line_before_it() { + let text = format!("{GOOD}\n{{\"type\":\"assistant\",\"mess"); + assert_eq!(reading_from_text(&text, 1_000_000), ContextReading::BestEffort { percent: 20 }); + } + + #[test] + fn non_assistant_and_malformed_lines_are_skipped() { + let text = format!("not json\n{{bad\n{{\"type\":\"user\",\"message\":{{}}}}\n{GOOD}"); + assert_eq!(reading_from_text(&text, 1_000_000), ContextReading::BestEffort { percent: 20 }); + } + + #[test] + fn a_line_with_no_usable_usage_is_unknown() { + assert_eq!(reading_from_text("", 1_000_000), ContextReading::Unknown); + assert_eq!(reading_from_text(r#"{"type":"assistant","message":{}}"#, 1_000_000), ContextReading::Unknown); + assert_eq!(reading_from_text(GOOD, 0), ContextReading::Unknown); + } + + #[test] + fn a_missing_file_is_unknown() { + let reader = ClaudeReader { + projects_dir: temp_dir("missing").join("projects"), + folder: PathBuf::from(r"C:\git\project"), + since: epoch_plus(0), + window: 200_000, + }; + assert_eq!(reader.read(), ContextReading::Unknown); + } + + #[test] + fn a_long_transcript_is_read_from_its_end() { + let dir = temp_dir("long"); + let file = write_transcript(&dir, "long", &format!("{}\n{GOOD}", "x".repeat(TAIL_BYTES as usize + 100)), epoch_plus(0)); + assert_eq!(reading_from_file(&file, 206_633), ContextReading::BestEffort { percent: 100 }); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn the_newest_transcript_for_this_folder_is_read() { + let root = temp_dir("newest"); + let projects = root.join("projects"); + let dir = projects.join(encode(Path::new(r"C:\git\project"))); + write_transcript(&dir, "a-old", GOOD, epoch_plus(100)); + let newest = write_transcript(&dir, "b-new", &GOOD.replace("205907", "500000"), epoch_plus(200)); + let reader = ClaudeReader { projects_dir: projects, folder: PathBuf::from(r"C:\git\project"), since: epoch_plus(0), window: 1_000_000 }; + assert_eq!(reader.read(), ContextReading::BestEffort { percent: 50 }); + let _ = fs::remove_dir_all(root); + let _ = newest; + } + + #[test] + fn a_rotated_file_is_read_from_the_new_one() { + let root = temp_dir("rotated"); + let projects = root.join("projects"); + let dir = projects.join(encode(Path::new(r"C:\git\project"))); + write_transcript(&dir, "first", GOOD, epoch_plus(100)); + let reader = ClaudeReader { projects_dir: projects.clone(), folder: PathBuf::from(r"C:\git\project"), since: epoch_plus(0), window: 1_000_000 }; + assert_eq!(reader.read(), ContextReading::BestEffort { percent: 20 }); + write_transcript(&dir, "second", &GOOD.replace("205907", "500000"), epoch_plus(200)); + assert_eq!(reader.read(), ContextReading::BestEffort { percent: 50 }); + let _ = fs::remove_dir_all(root); + } + + #[test] + fn a_transcript_from_before_the_agent_started_is_ignored() { + let root = temp_dir("since"); + let projects = root.join("projects"); + let dir = projects.join(encode(Path::new(r"C:\git\project"))); + write_transcript(&dir, "old", GOOD, epoch_plus(100)); + let reader = ClaudeReader { projects_dir: projects, folder: PathBuf::from(r"C:\git\project"), since: epoch_plus(200), window: 1_000_000 }; + assert_eq!(reader.read(), ContextReading::Unknown); + let _ = fs::remove_dir_all(root); + } + + #[test] + fn the_cwd_is_encoded_the_way_claude_code_names_its_projects_folder() { + assert_eq!(encode(Path::new(r"C:\git\plan2code")), "C--git-plan2code"); + } +} diff --git a/plan2code-app/src-tauri/src/context/codex.rs b/plan2code-app/src-tauri/src/context/codex.rs new file mode 100644 index 0000000..142a244 --- /dev/null +++ b/plan2code-app/src-tauri/src/context/codex.rs @@ -0,0 +1,315 @@ +//! Codex's context, read from its session log. Codex writes each run to +//! `sessions/YYYY/MM/DD/rollout-*.jsonl` under its home folder (`CODEX_HOME`, +//! or `~/.codex`). The app reads the newest log for its project folder, from +//! its end, and never writes there. The format is undocumented, so the reading +//! is `BestEffort`: an unrecognised line is skipped, and a log with no usable +//! line, or no log at all, is `Unknown`. Nothing here is an error. + +use std::fs::{self, File}; +use std::io::{BufRead, BufReader, Read, Seek, SeekFrom}; +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + +use serde_json::Value; + +use super::{ContextReader, ContextReading}; + +/// How much of a log's end is read. The newest token count is near the end, +/// so a long log is never read whole. +pub const TAIL_BYTES: u64 = 256 * 1024; + +/// How deep the sessions folder is searched: year, month, day, file. +const SEARCH_DEPTH: u32 = 4; + +pub struct CodexReader { + pub sessions_dir: PathBuf, + pub folder: PathBuf, + /// Only logs written at or after this moment belong to the running agent. + pub since: SystemTime, +} + +impl ContextReader for CodexReader { + fn read(&self) -> ContextReading { + match newest_log(&self.sessions_dir, &self.folder, self.since) { + Some(file) => reading_from_file(&file), + None => ContextReading::Unknown, + } + } +} + +/// The percent of the model's window the newest request used, from the last +/// usable `token_count` line in `text`. +pub fn reading_from_text(text: &str) -> ContextReading { + for line in text.lines().rev() { + if let Some(percent) = percent_from_line(line) { + return ContextReading::BestEffort { percent }; + } + } + ContextReading::Unknown +} + +fn percent_from_line(line: &str) -> Option { + let value: Value = serde_json::from_str(line).ok()?; + if value.get("type")?.as_str()? != "event_msg" { + return None; + } + let payload = value.get("payload")?; + if payload.get("type")?.as_str()? != "token_count" { + return None; + } + let info = payload.get("info")?; + let used = info.get("last_token_usage")?.get("input_tokens")?.as_u64()?; + let window = info.get("model_context_window")?.as_u64()?; + if window == 0 { + return None; + } + Some((used.saturating_mul(100) / window).min(100) as u8) +} + +/// Reads the end of `file`. A file that cannot be opened or read is `Unknown`. +fn reading_from_file(file: &Path) -> ContextReading { + let Ok(mut handle) = File::open(file) else { return ContextReading::Unknown }; + let Ok(len) = handle.metadata().map(|m| m.len()) else { return ContextReading::Unknown }; + if len > TAIL_BYTES && handle.seek(SeekFrom::Start(len - TAIL_BYTES)).is_err() { + return ContextReading::Unknown; + } + let mut bytes = Vec::new(); + if handle.read_to_end(&mut bytes).is_err() { + return ContextReading::Unknown; + } + // The first line of a partial tail is cut short; it fails to parse and is skipped. + reading_from_text(&String::from_utf8_lossy(&bytes)) +} + +/// The newest log under `sessions_dir` that was written since `since` and +/// whose first line names `folder` as its working directory. +pub fn newest_log(sessions_dir: &Path, folder: &Path, since: SystemTime) -> Option { + let mut logs = Vec::new(); + collect_logs(sessions_dir, SEARCH_DEPTH, since, &mut logs); + let mut recent: Vec<(SystemTime, PathBuf)> = logs + .into_iter() + .filter_map(|file| { + let modified = fs::metadata(&file).ok()?.modified().ok()?; + (modified >= since).then_some((modified, file)) + }) + .collect(); + recent.sort_by(|a, b| b.0.cmp(&a.0)); + recent.into_iter().map(|(_, file)| file).find(|file| names_folder(file, folder)) +} + +// A day folder not touched since `since` holds no log of this run (creating a +// log updates its own folder, and only that one), so it is skipped: the walk +// stays short however many old logs Codex has kept. Year and month folders are +// always entered, as their own times say nothing about the logs below them. +// `depth` is 2 while the entries of a month folder are listed. +fn collect_logs(dir: &Path, depth: u32, since: SystemTime, out: &mut Vec) { + let Ok(entries) = fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + let touched = fs::metadata(&path).and_then(|m| m.modified()).is_ok_and(|m| m >= since); + if depth > 0 && (depth != 2 || touched) { + collect_logs(&path, depth - 1, since, out); + } + } else if is_rollout(&path) { + out.push(path); + } + } +} + +fn is_rollout(path: &Path) -> bool { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with("rollout-") && name.ends_with(".jsonl")) +} + +/// True when the log's first line is a `session_meta` for `folder`. +fn names_folder(file: &Path, folder: &Path) -> bool { + let Ok(handle) = File::open(file) else { return false }; + let mut first = String::new(); + if BufReader::new(handle).read_line(&mut first).is_err() { + return false; + } + let Ok(value) = serde_json::from_str::(&first) else { return false }; + if value.get("type").and_then(Value::as_str) != Some("session_meta") { + return false; + } + value + .get("payload") + .and_then(|payload| payload.get("cwd")) + .and_then(Value::as_str) + .is_some_and(|cwd| same_folder(cwd, folder)) +} + +/// Compares two folder paths the way Windows does: case, slash style and a +/// trailing separator do not count. +fn same_folder(cwd: &str, folder: &Path) -> bool { + let norm = |s: &str| { + s.trim_start_matches(r"\\?\").trim_end_matches(['\\', '/']).replace('/', "\\").to_ascii_lowercase() + }; + norm(cwd) == norm(&folder.to_string_lossy()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + const GOOD: &str = r#"{"type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"input_tokens":21839},"model_context_window":258400}}}"#; + + fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("plan2code-codex-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir + } + + // A log whose first line names `cwd`, then `body` lines, dated `modified`. + fn write_log(sessions: &Path, name: &str, cwd: &str, body: &str, modified: SystemTime) -> PathBuf { + let day = sessions.join("2026").join("10").join("22"); + fs::create_dir_all(&day).unwrap(); + let file = day.join(format!("rollout-{name}.jsonl")); + let meta = serde_json::json!({ "type": "session_meta", "payload": { "cwd": cwd } }); + fs::write(&file, format!("{meta}\n{body}")).unwrap(); + // `meta` is a JSON value, so its text is escaped for the log. + fs::File::options().write(true).open(&file).unwrap().set_modified(modified).unwrap(); + file + } + + fn epoch_plus(secs: u64) -> SystemTime { + SystemTime::UNIX_EPOCH + Duration::from_secs(secs) + } + + #[test] + fn the_last_token_count_gives_the_percent_of_the_window() { + assert_eq!(reading_from_text(GOOD), ContextReading::BestEffort { percent: 8 }); + } + + #[test] + fn unrecognised_and_malformed_lines_are_skipped() { + let text = format!("not json\n{{bad\n{GOOD}\n{}", r#"{"type":"event_msg","payload":{"type":"other"}}"#); + assert_eq!(reading_from_text(&text), ContextReading::BestEffort { percent: 8 }); + } + + #[test] + fn a_log_with_no_usable_line_is_unknown() { + assert_eq!(reading_from_text(""), ContextReading::Unknown); + assert_eq!(reading_from_text("garbage\n{}"), ContextReading::Unknown); + let zero_window = GOOD.replace("258400", "0"); + assert_eq!(reading_from_text(&zero_window), ContextReading::Unknown); + } + + #[test] + fn an_early_token_count_without_info_is_skipped() { + let early = r#"{"type":"event_msg","payload":{"type":"token_count","info":null}}"#; + assert_eq!(reading_from_text(&format!("{GOOD}\n{early}")), ContextReading::BestEffort { percent: 8 }); + assert_eq!(reading_from_text(early), ContextReading::Unknown); + } + + #[test] + fn only_a_session_meta_with_this_folder_names_it() { + let root = temp_dir("names"); + let folder = Path::new(r"C:\git\project"); + let verbatim = serde_json::json!({ "type": "session_meta", "payload": { "cwd": r"\\?\C:\git\project" } }); + let cases = [ + ("not json".to_string(), false), + (r#"{"type":"other","payload":{"cwd":"x"}}"#.to_string(), false), + (r#"{"type":"session_meta","payload":{}}"#.to_string(), false), + (verbatim.to_string(), true), + ]; + for (i, (line, expected)) in cases.iter().enumerate() { + let file = root.join(format!("rollout-{i}.jsonl")); + fs::write(&file, format!("{line}\n{GOOD}\n")).unwrap(); + assert_eq!(names_folder(&file, folder), *expected, "{line}"); + } + let _ = fs::remove_dir_all(root); + } + + #[test] + fn a_long_log_is_read_from_its_end() { + let dir = temp_dir("long"); + let file = dir.join("long.jsonl"); + fs::write(&file, format!("{}\n{GOOD}\n", "x".repeat(TAIL_BYTES as usize + 100))).unwrap(); + assert_eq!(reading_from_file(&file), ContextReading::BestEffort { percent: 8 }); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn a_missing_log_is_unknown() { + assert_eq!(reading_from_file(Path::new("no-such-dir/rollout-x.jsonl")), ContextReading::Unknown); + } + + #[test] + fn a_missing_sessions_folder_is_unknown() { + let reader = CodexReader { + sessions_dir: temp_dir("none").join("sessions"), + folder: PathBuf::from(r"C:\git\project"), + since: epoch_plus(0), + }; + assert_eq!(reader.read(), ContextReading::Unknown); + } + + #[test] + fn the_newest_log_for_this_folder_is_read() { + let root = temp_dir("newest"); + let sessions = root.join("sessions"); + write_log(&sessions, "a-old", r"C:\git\project", GOOD, epoch_plus(100)); + write_log(&sessions, "b-other", r"C:\git\elsewhere", GOOD, epoch_plus(300)); + let newest = write_log(&sessions, "c-new", r"c:\git\project\", &GOOD.replace("21839", "129200"), epoch_plus(200)); + assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(0)), Some(newest)); + let _ = fs::remove_dir_all(root); + } + + // Sets a folder's modified time; Windows needs the backup-semantics flag to open one. + fn set_dir_modified(dir: &Path, time: SystemTime) { + let mut options = fs::OpenOptions::new(); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.write(true).custom_flags(0x0200_0000); + } + #[cfg(not(windows))] + options.read(true); + options.open(dir).unwrap().set_modified(time).unwrap(); + } + + #[test] + fn old_year_and_month_folders_do_not_hide_todays_log() { + let root = temp_dir("parents"); + let sessions = root.join("sessions"); + let log = write_log(&sessions, "today", r"C:\git\project", GOOD, epoch_plus(500)); + // Creating a log touches only its day folder: the parents keep their old times. + set_dir_modified(&sessions.join("2026"), epoch_plus(10)); + set_dir_modified(&sessions.join("2026").join("10"), epoch_plus(20)); + assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(100)), Some(log)); + // A day folder untouched since the agent started is skipped. + set_dir_modified(&sessions.join("2026").join("10").join("22"), epoch_plus(30)); + assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(100)), None); + let _ = fs::remove_dir_all(root); + } + + #[test] + fn a_log_from_before_the_agent_started_is_ignored() { + let root = temp_dir("since"); + let sessions = root.join("sessions"); + write_log(&sessions, "old", r"C:\git\project", GOOD, epoch_plus(100)); + assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(200)), None); + let _ = fs::remove_dir_all(root); + } + + #[test] + fn a_rotated_log_is_read_from_the_new_file() { + let root = temp_dir("rotated"); + let sessions = root.join("sessions"); + write_log(&sessions, "first", r"C:\git\project", GOOD, epoch_plus(100)); + let reader = CodexReader { + sessions_dir: sessions.clone(), + folder: PathBuf::from(r"C:\git\project"), + since: epoch_plus(0), + }; + assert_eq!(reader.read(), ContextReading::BestEffort { percent: 8 }); + write_log(&sessions, "second", r"C:\git\project", &GOOD.replace("21839", "129200"), epoch_plus(200)); + assert_eq!(reader.read(), ContextReading::BestEffort { percent: 50 }); + let _ = fs::remove_dir_all(root); + } +} diff --git a/plan2code-app/src-tauri/src/context/mod.rs b/plan2code-app/src-tauri/src/context/mod.rs new file mode 100644 index 0000000..9074e0c --- /dev/null +++ b/plan2code-app/src-tauri/src/context/mod.rs @@ -0,0 +1,313 @@ +//! How full the agent's context is. A reader says one of four things: a real +//! number (`Real`, documented by the agent and verified), a best-effort number +//! (`BestEffort`, works today but undocumented), a labeled estimate (`Estimate`) +//! or `Unknown`. Knows nothing about Tauri: the page asks for a reading and +//! draws what it gets. + +pub mod claude; +pub mod codex; + +use std::time::SystemTime; + +use serde::Serialize; + +use crate::agents::AgentKind; + +/// A rough token window used only by the estimate, and by `claude.rs` when no +/// window comes with the signal it reads. The estimate is labeled as one +/// everywhere it is shown, so the exact size does not have to be right. +pub const ESTIMATE_TOKEN_WINDOW: u64 = 200_000; + +/// The window for a model whose id names it a long-context one (Claude Code's +/// `[1m]` model id suffix). +pub const LONG_CONTEXT_TOKEN_WINDOW: u64 = 1_000_000; + +/// The usual rule of thumb: about four characters of text per token. +pub const BYTES_PER_TOKEN: u64 = 4; + +/// The context window to read `kind`'s usage against, or `None` when no +/// window is documented for it at all (Devin today), in which case a byte +/// count is not even a meaningful guess. `model` is the id the person picked, +/// if any; one naming a long-context model (Claude Code's `[1m]` suffix) gets +/// the bigger window. +pub fn window_for(kind: Option, model: Option<&str>) -> Option { + match kind { + Some(AgentKind::Claude) | Some(AgentKind::Codex) => { + let long_context = model.is_some_and(|m| m.to_ascii_lowercase().contains("[1m]")); + Some(if long_context { LONG_CONTEXT_TOKEN_WINDOW } else { ESTIMATE_TOKEN_WINDOW }) + } + Some(AgentKind::Devin) | None => None, + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum ContextReading { + Real { percent: u8 }, + BestEffort { percent: u8 }, + Estimate { percent: u8 }, + Unknown, +} + +/// One agent's way of reading its context. The estimate is the fallback every +/// agent has; a reader for an agent that documents its usage returns `Real`. +pub trait ContextReader { + fn read(&self) -> ContextReading; +} + +/// The percent of `window` that `bytes` of text fills, capped at 100 and +/// rounded up: any text at all reads as at least 1 percent, never a flat 0 +/// while the agent is working. +pub fn estimate_percent(bytes: u64, window: u64) -> u8 { + let tokens = bytes / BYTES_PER_TOKEN; + if tokens == 0 || window == 0 { + return 0; + } + tokens.saturating_mul(100).div_ceil(window).min(100) as u8 +} + +/// Where the output scan is inside a terminal control sequence. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Escape { + #[default] + None, + Esc, + Intermediate, + Csi, + Osc, + OscEnd, +} + +/// Counts the text an agent run has produced and been given. A new agent +/// (a new `generation`) starts the count over, and nothing is counted while +/// no agent runs. +#[derive(Debug, Default)] +pub struct Meter { + generation: u64, + seen: bool, + running: bool, + bytes: u64, + escape: Escape, + kind: Option, + // When the current agent run began: its own log must be written after this. + since: Option, +} + +impl Meter { + /// Called on every agent state change: a new generation resets the count. + pub fn observe(&mut self, generation: u64, running: bool) { + if !self.seen || generation != self.generation { + self.generation = generation; + self.seen = true; + self.bytes = 0; + self.escape = Escape::None; + self.since = Some(SystemTime::now()); + } + self.running = running; + } + + pub fn set_kind(&mut self, kind: Option) { + self.kind = kind; + } + + pub fn kind(&self) -> Option { + self.kind + } + + pub fn since(&self) -> Option { + self.since + } + + /// Output from the agent, or text typed to it, while it runs. + /// Output from the agent. Terminal control sequences (colours, cursor + /// moves, window titles) are not text the agent holds, so only the visible + /// bytes count. A sequence cut across two chunks is still skipped whole. + pub fn add_output(&mut self, chunk: &[u8]) { + let mut visible = 0usize; + for &byte in chunk { + self.escape = match self.escape { + Escape::None => match byte { + 0x1b => Escape::Esc, + b'\n' | b'\t' => { + visible += 1; + Escape::None + } + 0x20..=0x7e | 0x80..=0xff => { + visible += 1; + Escape::None + } + _ => Escape::None, + }, + Escape::Esc => match byte { + b'[' => Escape::Csi, + // OSC, and the other strings that end the same way: DCS, SOS, PM, APC. + b']' | b'P' | b'X' | b'^' | b'_' => Escape::Osc, + // `ESC ( B` and the like: intermediate bytes, then one final byte. + 0x20..=0x2f => Escape::Intermediate, + _ => Escape::None, + }, + Escape::Intermediate => match byte { + 0x20..=0x2f => Escape::Intermediate, + _ => Escape::None, + }, + Escape::Csi => match byte { + 0x40..=0x7e => Escape::None, + _ => Escape::Csi, + }, + Escape::Osc => match byte { + 0x07 => Escape::None, + 0x1b => Escape::OscEnd, + _ => Escape::Osc, + }, + Escape::OscEnd => Escape::None, + }; + } + self.add(visible); + } + + /// Text typed to the agent, or any count of visible bytes. + pub fn add(&mut self, bytes: usize) { + if self.running { + self.bytes = self.bytes.saturating_add(bytes as u64); + } + } + + pub fn reading(&self) -> ContextReading { + if !self.seen || !self.running { + return ContextReading::Unknown; + } + match window_for(self.kind, None) { + Some(window) => ContextReading::Estimate { percent: estimate_percent(self.bytes, window) }, + None => ContextReading::Unknown, + } + } +} + +impl ContextReader for Meter { + fn read(&self) -> ContextReading { + self.reading() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn no_text_is_zero_percent() { + assert_eq!(estimate_percent(0, ESTIMATE_TOKEN_WINDOW), 0); + } + + #[test] + fn half_the_window_is_fifty_percent() { + assert_eq!(estimate_percent(ESTIMATE_TOKEN_WINDOW * BYTES_PER_TOKEN / 2, ESTIMATE_TOKEN_WINDOW), 50); + } + + #[test] + fn more_than_the_window_caps_at_one_hundred() { + assert_eq!(estimate_percent(u64::MAX / 2, ESTIMATE_TOKEN_WINDOW), 100); + } + + #[test] + fn any_text_at_all_rounds_up_instead_of_reading_zero() { + assert_eq!(estimate_percent(BYTES_PER_TOKEN, ESTIMATE_TOKEN_WINDOW), 1); + } + + #[test] + fn a_long_context_model_gets_the_bigger_window() { + assert_eq!(window_for(Some(AgentKind::Claude), Some("claude-sonnet-4-5-20250929[1m]")), Some(LONG_CONTEXT_TOKEN_WINDOW)); + assert_eq!(window_for(Some(AgentKind::Claude), Some("sonnet")), Some(ESTIMATE_TOKEN_WINDOW)); + assert_eq!(window_for(Some(AgentKind::Claude), None), Some(ESTIMATE_TOKEN_WINDOW)); + } + + #[test] + fn devin_and_an_unknown_agent_have_no_basis_for_a_window() { + assert_eq!(window_for(Some(AgentKind::Devin), None), None); + assert_eq!(window_for(None, None), None); + } + + fn counted(chunks: &[&[u8]]) -> u64 { + let mut meter = Meter::default(); + meter.observe(1, true); + for chunk in chunks { + meter.add_output(chunk); + } + meter.bytes + } + + #[test] + fn plain_text_counts_and_control_sequences_do_not() { + assert_eq!(counted(&[b"hello\n"]), 6); + assert_eq!(counted(&[b"\x1b[31mred\x1b[0m"]), 3); + assert_eq!(counted(&[b"\x1b[2K\x1b[1A\x1b[Gx"]), 1); + assert_eq!(counted(&[b"\x1b]0;a title\x07ok"]), 2); + assert_eq!(counted(&[b"\x1b]0;a title\x1b\\ok"]), 2); + } + + #[test] + fn charset_and_string_sequences_are_skipped() { + assert_eq!(counted(&[b"\x1b(Bok"]), 2); + assert_eq!(counted(&[b"\x1bPq#0;2;0;0;0\x1b\\ok"]), 2); + } + + #[test] + fn a_sequence_split_across_chunks_is_still_skipped() { + assert_eq!(counted(&[b"ab\x1b[3", b"1mcd"]), 4); + assert_eq!(counted(&[b"\x1b", b"[0m", b"z"]), 1); + } + + #[test] + fn nothing_running_is_unknown() { + let mut meter = Meter::default(); + assert_eq!(meter.reading(), ContextReading::Unknown); + meter.observe(1, false); + meter.add(10_000); + assert_eq!(meter.reading(), ContextReading::Unknown); + } + + #[test] + fn a_running_agent_is_an_estimate_of_what_it_has_seen() { + let mut meter = Meter::default(); + meter.set_kind(Some(AgentKind::Claude)); + meter.observe(1, true); + meter.add((ESTIMATE_TOKEN_WINDOW * BYTES_PER_TOKEN / 4) as usize); + assert_eq!(meter.reading(), ContextReading::Estimate { percent: 25 }); + } + + #[test] + fn a_fresh_agent_starts_the_count_over() { + let mut meter = Meter::default(); + meter.set_kind(Some(AgentKind::Claude)); + meter.observe(1, true); + meter.add(400_000); + meter.observe(2, true); + assert_eq!(meter.reading(), ContextReading::Estimate { percent: 0 }); + } + + #[test] + fn a_stopped_agent_is_unknown_again() { + let mut meter = Meter::default(); + meter.set_kind(Some(AgentKind::Claude)); + meter.observe(1, true); + meter.add(400_000); + meter.observe(1, false); + assert_eq!(meter.reading(), ContextReading::Unknown); + } + + #[test] + fn an_agent_with_no_documented_window_is_unknown_not_a_guess() { + let mut meter = Meter::default(); + meter.set_kind(Some(AgentKind::Devin)); + meter.observe(1, true); + meter.add(400_000); + assert_eq!(meter.reading(), ContextReading::Unknown); + } + + #[test] + fn no_kind_set_yet_is_unknown_not_a_guess() { + let mut meter = Meter::default(); + meter.observe(1, true); + meter.add(400_000); + assert_eq!(meter.reading(), ContextReading::Unknown); + } +} diff --git a/plan2code-app/src-tauri/src/handoff.rs b/plan2code-app/src-tauri/src/handoff.rs new file mode 100644 index 0000000..240809c --- /dev/null +++ b/plan2code-app/src-tauri/src/handoff.rs @@ -0,0 +1,224 @@ +//! Writes a handoff the dashboard already knows how to list: a `.md` document +//! and its `.json` record in `~/.plan2code/handoffs/`, in the shape +//! `src/web-console/handoffs.mjs` reads (`v: 1`, the local-minute id, `usedAt` +//! null). The console is not changed for this, so the dashboard's **Pick it up +//! here** chip appears as it does for a handoff the Handoff skill wrote. + +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +use chrono::{DateTime, Datelike, Local, SecondsFormat, Timelike, Utc}; +use serde_json::json; + +/// `~/.plan2code/handoffs`, or `PLAN2CODE_HANDOFFS_DIR` when it is moved. +pub fn handoffs_dir() -> Option { + if let Ok(dir) = std::env::var("PLAN2CODE_HANDOFFS_DIR") { + return Some(PathBuf::from(dir)); + } + Some(std::env::home_dir()?.join(".plan2code").join("handoffs")) +} + +/// What the dashboard needs to resume the session the handoff came from. +pub struct Record<'a> { + pub title: &'a str, + pub worktree: &'a str, + pub project: &'a str, + /// `specs/`, or none. + pub spec: Option<&'a str>, + pub workflow: &'a str, + pub skill: &'a str, +} + +/// Write `body` as the handoff's document and the record beside it, under an +/// id made from `when`'s local minute. Returns the id. The record is claimed +/// exclusively, so two writes in the same minute never share an id; a failed +/// write leaves nothing behind. +pub fn write(dir: &Path, when: DateTime, record: &Record, body: &str) -> Result { + validate(record)?; + fs::create_dir_all(dir).map_err(|e| e.to_string())?; + let base = format!( + "{:04}-{:02}-{:02}-{:02}{:02}-handoff", + when.year(), + when.month(), + when.day(), + when.hour(), + when.minute() + ); + let written = when.with_timezone(&Utc).to_rfc3339_opts(SecondsFormat::Millis, true); + for n in 1.. { + let id = if n == 1 { base.clone() } else { format!("{base}-{n}") }; + let md = dir.join(format!("{id}.md")); + let json_file = dir.join(format!("{id}.json")); + if md.exists() { + continue; + } + let mut claim = match OpenOptions::new().write(true).create_new(true).open(&json_file) { + Ok(file) => file, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e.to_string()), + }; + let meta = json!({ + "v": 1, + "id": id, + "title": record.title, + "worktree": record.worktree, + "project": record.project, + "spec": record.spec, + "workflow": record.workflow, + "skill": record.skill, + "written": written, + "fromStop": false, + "usedAt": null, + }); + let text = serde_json::to_string_pretty(&meta).map_err(|e| e.to_string())? + "\n"; + if let Err(e) = claim.write_all(text.as_bytes()) { + let _ = fs::remove_file(&json_file); + return Err(e.to_string()); + } + if let Err(e) = write_document(&md, &title_line(record.title), body) { + let _ = fs::remove_file(&json_file); + return Err(e); + } + return Ok(id); + } + unreachable!("the id loop only ends by returning") +} + +fn write_document(md: &Path, heading: &str, body: &str) -> Result<(), String> { + let mut file = OpenOptions::new().write(true).create_new(true).open(md).map_err(|e| e.to_string())?; + file.write_all(format!("{heading}\n\n{body}").as_bytes()).map_err(|e| e.to_string()) +} + +fn title_line(title: &str) -> String { + format!("# Handoff: {title}") +} + +/// Delete a handoff the person has not picked up (its record has no `usedAt`), +/// both files. A picked-up one, or one already gone, is left alone. +pub fn retire_if_unused(dir: &Path, id: &str) -> Result<(), String> { + let json_file = dir.join(format!("{id}.json")); + let Ok(text) = fs::read_to_string(&json_file) else { return Ok(()) }; + let used = serde_json::from_str::(&text).ok().is_some_and(|meta| !meta["usedAt"].is_null()); + if used { + return Ok(()); + } + for file in [json_file, dir.join(format!("{id}.md"))] { + match fs::remove_file(&file) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e.to_string()), + } + } + Ok(()) +} + +/// The same rules the console applies to the record, so a bad field is refused +/// here rather than written and then ignored. +fn validate(record: &Record) -> Result<(), String> { + let lower_dashes = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_lowercase() || c == '-'); + if !lower_dashes(record.workflow) { + return Err(format!("workflow must be lowercase letters and dashes, got {:?}", record.workflow)); + } + let skill_ok = !record.skill.is_empty() && record.skill.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'); + if !skill_ok { + return Err(format!("skill must be a skill name, got {:?}", record.skill)); + } + if let Some(spec) = record.spec { + let name = spec.strip_prefix("specs/"); + if name.is_none_or(|n| n.is_empty() || n == "." || n == ".." || n.contains('/') || n.contains('\\')) { + return Err(format!("spec must be specs/, got {spec:?}")); + } + } + Ok(()) +} + +/// The clock's local time, for the id. Tests pass their own. +pub fn now() -> DateTime { + Local::now() +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::TimeZone; + + fn fixture(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("plan2code-handoff-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + dir + } + + fn record() -> Record<'static> { + Record { + title: "Restart of plan2code-3-implement", + worktree: "C:\\git\\plan2code", + project: "C:\\git\\plan2code", + spec: Some("specs/feature"), + workflow: "implement", + skill: "plan2code-3-implement", + } + } + + fn at(hour: u32, minute: u32) -> DateTime { + Local.with_ymd_and_hms(2026, 10, 21, hour, minute, 0).unwrap() + } + + #[test] + fn the_record_has_the_shape_the_dashboard_reads() { + let dir = fixture("shape"); + let id = write(&dir, at(13, 52), &record(), "## Next task\n\nTask 5.2").unwrap(); + assert_eq!(id, "2026-10-21-1352-handoff"); + let meta: serde_json::Value = serde_json::from_str(&fs::read_to_string(dir.join(format!("{id}.json"))).unwrap()).unwrap(); + assert_eq!(meta["v"], 1); + assert_eq!(meta["id"], id.as_str()); + assert_eq!(meta["workflow"], "implement"); + assert_eq!(meta["skill"], "plan2code-3-implement"); + assert_eq!(meta["spec"], "specs/feature"); + assert_eq!(meta["fromStop"], false); + assert!(meta["usedAt"].is_null()); + assert!(meta["written"].as_str().unwrap().ends_with('Z')); + let doc = fs::read_to_string(dir.join(format!("{id}.md"))).unwrap(); + assert!(doc.starts_with("# Handoff: Restart of plan2code-3-implement\n\n")); + assert!(doc.contains("## Next task")); + } + + #[test] + fn a_second_write_in_the_same_minute_takes_the_next_id() { + let dir = fixture("clash"); + let first = write(&dir, at(9, 0), &record(), "one").unwrap(); + let second = write(&dir, at(9, 0), &record(), "two").unwrap(); + assert_eq!(first, "2026-10-21-0900-handoff"); + assert_eq!(second, "2026-10-21-0900-handoff-2"); + } + + #[test] + fn a_bad_workflow_is_refused_before_anything_is_written() { + let dir = fixture("bad"); + let mut bad = record(); + bad.workflow = "Implement"; + assert!(write(&dir, at(9, 0), &bad, "x").is_err()); + assert!(!dir.exists()); + } + + #[test] + fn an_unused_handoff_is_retired_and_a_picked_up_one_is_kept() { + let dir = fixture("retire"); + let unused = write(&dir, at(10, 0), &record(), "one").unwrap(); + let used = write(&dir, at(10, 1), &record(), "two").unwrap(); + fs::write(dir.join(format!("{used}.json")), r#"{"v":1,"usedAt":"2026-10-21T10:02:00.000Z"}"#).unwrap(); + retire_if_unused(&dir, &unused).unwrap(); + retire_if_unused(&dir, &used).unwrap(); + assert!(!dir.join(format!("{unused}.json")).exists()); + assert!(!dir.join(format!("{unused}.md")).exists()); + assert!(dir.join(format!("{used}.json")).exists()); + assert!(dir.join(format!("{used}.md")).exists()); + } + + #[test] + fn a_spec_must_be_one_folder_under_specs() { + let mut bad = record(); + bad.spec = Some("specs/a/b"); + assert!(validate(&bad).is_err()); + } +} diff --git a/plan2code-app/src-tauri/src/lib.rs b/plan2code-app/src-tauri/src/lib.rs new file mode 100644 index 0000000..7aa63ca --- /dev/null +++ b/plan2code-app/src-tauri/src/lib.rs @@ -0,0 +1,16 @@ +//! The parts of the app that tests reach directly. + +pub mod agent_manager; +pub mod agents; +pub mod announce; +pub mod brief; +pub mod console_supervisor; +pub mod context; +pub mod handoff; +pub mod node_check; +pub mod project; +pub mod pty_host; +pub mod restart_brief; +pub mod session_reader; +pub mod settings; +pub mod versions; diff --git a/plan2code-app/src-tauri/src/main.rs b/plan2code-app/src-tauri/src/main.rs new file mode 100644 index 0000000..6bf60c4 --- /dev/null +++ b/plan2code-app/src-tauri/src/main.rs @@ -0,0 +1,737 @@ +// Hide the extra console window on Windows release builds. +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] + +use std::sync::{Arc, Mutex}; + +use plan2code_app_lib::announce::AnnounceServer; +use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentState, Sink}; +use plan2code_app_lib::agents::{self, AgentKind, PermissionMode}; +use plan2code_app_lib::console_supervisor::{app_origin, origin_of, ConsoleSupervisor}; +use plan2code_app_lib::context::claude::ClaudeReader; +use plan2code_app_lib::context::codex::CodexReader; +use plan2code_app_lib::context::{self, ContextReader, ContextReading, Meter}; +use plan2code_app_lib::node_check; +use plan2code_app_lib::project::{self, ProjectDir}; +use plan2code_app_lib::restart_brief; +use plan2code_app_lib::settings; +use plan2code_app_lib::versions; +use tauri::ipc::{Channel, InvokeResponseBody}; +use tauri::{Emitter, Manager, State}; +use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind}; + +type PageChannel = Arc>>>; + +// The project the app is working on, the console it supervises for it and the +// agent it runs there. +#[derive(Default)] +struct AppState { + project: Mutex>, + // The agent and model the launcher chose, from its arguments. + launch: project::LaunchChoice, + console: Arc>>, + agent: Mutex>>, + // Where the agent's output and state changes go: the page's latest channel. + page: PageChannel, + // How much text the running agent has produced and been given, for the meter. + context: Arc>, + // This window's endpoint for pages the agent's `console.mjs open` wants shown here. + announce: Mutex>, + // 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 operating system and, on Windows, the build number xterm needs for ConPTY. +#[tauri::command] +fn platform_info() -> serde_json::Value { + let build = if cfg!(windows) { windows_build() } else { None }; + serde_json::json!({ "os": std::env::consts::OS, "windowsBuild": build }) +} + +// What the launch card offers per agent: whether its CLI is on PATH (else how +// to install it), and whether it takes its own reasoning effort. +#[tauri::command] +fn agent_availability() -> serde_json::Value { + let entries: Vec<_> = AgentKind::ALL + .iter() + .map(|&kind| { + let at = agents::installed_at(kind); + serde_json::json!({ + "id": kind.id(), + "label": kind.label(), + "installed": at.is_some(), + // Which binary was used (Task 9.9), when one was found. + "path": at.map(|p| p.to_string_lossy().into_owned()), + "installHint": kind.install_hint(), + "hasEffort": kind.has_effort(), + }) + }) + .collect(); + serde_json::json!(entries) +} + +// `cmd /c ver` prints e.g. `Microsoft Windows [Version 10.0.26300.1234]`. +fn windows_build() -> Option { + let out = std::process::Command::new("cmd").args(["/c", "ver"]).output().ok()?; + let text = String::from_utf8_lossy(&out.stdout); + let version = text.split("Version ").nth(1)?; + version.split('.').nth(2)?.trim().parse().ok() +} + +// Sends the agent's output as raw bytes and its state changes as JSON, on the +// page's latest channel. Nothing is sent while no page has registered one. +// The meter sees every output and state change too, page or no page. +fn page_sink(page: PageChannel, meter: Arc>) -> Sink { + Arc::new(move |event| { + if let Ok(mut meter) = meter.lock() { + match &event { + AgentEvent::Output(bytes) => meter.add_output(bytes), + AgentEvent::State(snapshot) => { + let running = snapshot.state == AgentState::Running; + meter.observe(snapshot.generation, running); + meter.set_kind(snapshot.kind); + } + } + } + let Ok(guard) = page.lock() else { return }; + let Some(channel) = guard.as_ref() else { return }; + let body = match event { + AgentEvent::Output(bytes) => InvokeResponseBody::Raw(bytes), + AgentEvent::State(snapshot) => match serde_json::to_string(&snapshot) { + Ok(json) => InvokeResponseBody::Json(json), + Err(_) => return, + }, + }; + let _ = channel.send(body); + }) +} + +// The manager for the current project, made on first use. A manager for a +// different folder replaces an idle one. +fn agent_for_project(state: &AppState) -> Result, String> { + let dir = { + let project = state.project.lock().map_err(|e| e.to_string())?; + project.as_ref().map(|p| p.dir.clone()).ok_or("no project folder chosen")? + }; + let mut guard = state.agent.lock().map_err(|e| e.to_string())?; + if let Some(agent) = guard.as_ref() { + // Only the same folder's manager is reused: an active agent for a + // folder the project has since moved away from must not be handed + // back as if it belonged to the new one. + if agent.folder() == &dir { + return Ok(Arc::clone(agent)); + } + } + let sink = page_sink(Arc::clone(&state.page), Arc::clone(&state.context)); + let agent = Arc::new(AgentManager::new(dir, sink)); + // A Restart leaves the brief for the dashboard, from the console that is running now. + let console = Arc::clone(&state.console); + agent.set_before_fresh(Arc::new(move || { + let sid = console.lock().ok()?.as_ref()?.session().sid.clone(); + restart_brief::note_for_restart(&sid) + })); + *guard = Some(Arc::clone(&agent)); + Ok(agent) +} + +fn current_agent(state: &AppState) -> Option> { + state.agent.lock().ok().and_then(|guard| guard.clone()) +} + +// The origin the app page has, which the console must allow as its frame +// parent. In a release build that is a constant, but `tauri dev` serves the +// page from a loopback dev server, so the window is asked for its real URL. +fn window_origin(app: &tauri::AppHandle) -> String { + app.get_webview_window("main") + .and_then(|window| window.url().ok()) + .and_then(|url| origin_of(url.as_str())) + .unwrap_or_else(|| app_origin().to_string()) +} + +// Gives the agent the in-app signal: this window's announce endpoint and the +// origin its console must allow. The agent's own `open` then shows its pages +// here (it asks the window which session is current). Without an endpoint the +// agent gets nothing and opens pages the plain way. +fn sync_agent_env(app: &tauri::AppHandle) { + let state = app.state::(); + let Some(agent) = current_agent(&state) else { return }; + let env = match state.announce.lock().ok() { + Some(guard) => guard + .as_ref() + .map(|server| server.agent_env(&window_origin(app), &app.package_info().version.to_string())) + .unwrap_or_default(), + None => Vec::new(), + }; + agent.set_env(env); +} + +#[tauri::command] +fn agent_start( + app: tauri::AppHandle, + state: State<'_, AppState>, + kind: String, + model: Option, + effort: Option, + mode: String, + cols: u16, + rows: u16, + on_output: Channel, +) -> Result<(), String> { + let kind = AgentKind::from_id(&kind).ok_or_else(|| format!("unknown agent: {kind}"))?; + let mode = PermissionMode::from_id(&mode).ok_or_else(|| format!("unknown permission mode: {mode}"))?; + *state.page.lock().map_err(|e| e.to_string())? = Some(on_output); + let agent = agent_for_project(&state)?; + agent.resize(cols, rows)?; + sync_agent_env(&app); + agent.start(kind, model, effort, mode, None)?; + // A settings file that cannot be written must not stop the agent. + if let Some(file) = settings::settings_file() { + let _ = settings::save_last_agent(&file, kind); + } + Ok(()) +} + +#[tauri::command] +fn agent_input(state: State<'_, AppState>, data: String) -> Result<(), String> { + if let Ok(mut meter) = state.context.lock() { + meter.add(data.len()); + } + match current_agent(&state) { + Some(agent) => agent.input(data.as_bytes()), + None => Ok(()), + } +} + +#[tauri::command] +fn agent_resize(state: State<'_, AppState>, cols: u16, rows: u16) -> Result<(), String> { + match current_agent(&state) { + Some(agent) => agent.resize(cols, rows), + None => Ok(()), + } +} + +#[tauri::command] +fn agent_restart(state: State<'_, AppState>) -> Result<(), String> { + current_agent(&state).ok_or("no agent has been started")?.restart() +} + +#[tauri::command] +fn agent_state(state: State<'_, AppState>) -> serde_json::Value { + match current_agent(&state) { + Some(agent) => serde_json::to_value(agent.snapshot()).unwrap_or_default(), + None => idle_snapshot_json(), + } +} + +fn idle_snapshot_json() -> serde_json::Value { + serde_json::json!({ "state": "idle", "kind": null, "mode": null, "generation": 0 }) +} + +/// A page that just mounted (a reload, or this window's first paint while an +/// agent survived it) registers its output channel here instead of through +/// `agent_start`, which would try to start a second agent. Replays the +/// current generation's recent output on it at once, so the terminal does +/// not come up blank, and returns the same shape `agent_state` does. +#[tauri::command] +fn agent_reattach(state: State<'_, AppState>, on_output: Channel) -> Result { + let agent = current_agent(&state); + *state.page.lock().map_err(|e| e.to_string())? = Some(on_output.clone()); + if let Some(agent) = &agent { + let replay = agent.replay(); + if !replay.is_empty() { + let _ = on_output.send(InvokeResponseBody::Raw(replay)); + } + } + Ok(match &agent { + Some(agent) => serde_json::to_value(agent.snapshot()).unwrap_or_default(), + None => idle_snapshot_json(), + }) +} + +// The bar's meter, polled at most every two seconds: how full the running +// agent's context looks, labeled by how it was read. +#[tauri::command] +fn agent_context(state: State<'_, AppState>) -> serde_json::Value { + let (estimate, kind, since) = match state.context.lock() { + Ok(meter) => (meter.read(), meter.kind(), meter.since()), + Err(_) => (ContextReading::Unknown, None, None), + }; + let agent = current_agent(&state); + let model = agent.as_ref().and_then(|agent| agent.model_and_effort().0); + // Claude's own transcript, or Codex's own log, is read when there is one; + // an unknown reading from either falls back to the labeled estimate. + // Nothing is read while no agent runs. + let reading = match (estimate, kind, agent, since) { + (ContextReading::Unknown, _, _, _) => ContextReading::Unknown, + (_, Some(AgentKind::Claude), Some(agent), Some(since)) => { + // `window_for` always has a window for Claude; the fallback here only + // guards against a future change to that rule. + let window = context::window_for(kind, model.as_deref()).unwrap_or(context::ESTIMATE_TOKEN_WINDOW); + let claude = ClaudeReader { projects_dir: claude_projects_dir(), folder: agent.folder().clone(), since, window }; + match claude.read() { + ContextReading::Unknown => estimate, + read => read, + } + } + (_, Some(AgentKind::Codex), Some(agent), Some(since)) => { + let codex = CodexReader { + sessions_dir: codex_sessions_dir(), + folder: agent.folder().clone(), + since, + }; + match codex.read() { + ContextReading::Unknown => estimate, + read => read, + } + } + _ => estimate, + }; + serde_json::to_value(reading).unwrap_or_default() +} + +// Claude Code's transcripts folder: `CLAUDE_CONFIG_DIR` when it is set, else `~/.claude`. +fn claude_projects_dir() -> std::path::PathBuf { + let home = std::env::var_os("CLAUDE_CONFIG_DIR") + .map(std::path::PathBuf::from) + .or_else(|| std::env::home_dir().map(|home| home.join(".claude"))) + .unwrap_or_default(); + home.join("projects") +} + +// Codex's sessions folder: `CODEX_HOME` when it is set, else `~/.codex`. +fn codex_sessions_dir() -> std::path::PathBuf { + let home = std::env::var_os("CODEX_HOME") + .map(std::path::PathBuf::from) + .or_else(|| std::env::home_dir().map(|home| home.join(".codex"))) + .unwrap_or_default(); + home.join("sessions") +} + +// Asks before quitting while an agent runs; "no" keeps the app open. +fn confirm_quit(app: &tauri::AppHandle) { + let app = app.clone(); + app.dialog() + .message("An agent is still running. Quit and stop it?") + .title("Quit Plan2Code") + .kind(MessageDialogKind::Warning) + .buttons(MessageDialogButtons::YesNo) + .show({ + let app = app.clone(); + move |quit| { + if quit { + quit_app(&app); + } + } + }); +} + +fn agent_is_active(app: &tauri::AppHandle) -> bool { + current_agent(&app.state::()).is_some_and(|agent| agent.is_active()) +} + +// Stops the agent, then the console, then exits. +fn quit_app(app: &tauri::AppHandle) { + let state = app.state::(); + if let Some(agent) = current_agent(&state) { + agent.stop(); + } + if let Ok(mut guard) = state.console.lock() { + if let Some(mut console) = guard.take() { + let _ = console.stop(); + } + } + app.exit(0); +} + +/// What the page draws its bar from: the folder (or that none is chosen yet) +/// and the agent the picker starts on. +#[tauri::command] +fn app_state(state: State<'_, AppState>) -> serde_json::Value { + let project = state.project.lock().ok().and_then(|p| p.clone()); + let settings_file = settings::settings_file(); + // The agent picked in the launcher starts the bar's picker, ahead of the app's own last one. + let last_agent = state + .launch + .agent + .or_else(|| settings_file.as_ref().and_then(|file| settings::load_last_agent(file))) + .or_else(project::remembered_agent); + let nudge = settings_file + .as_ref() + .map_or(settings::DEFAULT_NUDGE_PERCENT, |file| settings::load_nudge_percent(file)); + let term_panel = settings_file.as_ref().map_or( + settings::TermPanelSettings { + dock: settings::DEFAULT_TERM_DOCK.to_string(), + fraction: settings::DEFAULT_TERM_FRACTION, + collapsed: false, + }, + |file| settings::load_term_panel(file), + ); + let first_run_done = settings_file.as_ref().is_some_and(|file| settings::load_first_run_done(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.map(|kind| kind.id()), + "launchModel": state.launch.model, + "contextNudgePercent": nudge, + // 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, + "skillsVersion": versions::installed_skills_version(), + "firstRunDone": first_run_done, + // The launcher always passes `--project` alongside `--agent`, so an + // explicit `--agent` means skip straight to starting it, no checklist + // or launch card shown. + "autoStart": state.launch.agent.map(|kind| kind.id()), + "termPanel": term_panel, + }) +} + +/// The terminal pane's toolbar remembers its shape here: dock side, size and +/// whether it was left collapsed. A settings file that cannot be written is +/// reported to the caller; the pane itself keeps working either way. +#[tauri::command] +fn save_term_panel(dock: String, fraction: f64, collapsed: bool) -> Result<(), String> { + let file = settings::settings_file().ok_or("no home folder found")?; + settings::save_term_panel(&file, &dock, fraction, collapsed) +} + +/// The first-run checklist passed once: later launches go straight to the +/// launch card (Task 9.4). +#[tauri::command] +fn save_first_run_done() -> Result<(), String> { + let file = settings::settings_file().ok_or("no home folder found")?; + settings::save_first_run_done(&file) +} + +/// The app's version (`tauri.conf.json`'s, which Tauri puts in the package info) beside the +/// installed skills' version. The bar shows its Update line when they differ (FR-14). +#[tauri::command] +fn version_status(app: tauri::AppHandle) -> versions::VersionStatus { + versions::status(&app.package_info().version.to_string(), versions::installed_skills_version()) +} + +/// What `update_skills` resolves with: the installer's last line, and the version status +/// re-read afterwards, so the bar can say plainly whether the mismatch is actually gone. +#[derive(serde::Serialize)] +struct UpdateOutcome { + message: String, + status: versions::VersionStatus, +} + +/// Run the existing installer's update, pinned to this app's own release tag. Only the bar's +/// button asks for it: never silently. `progress` carries each line of the installer's own +/// output live, for the bar to show while it runs. +#[tauri::command] +async fn update_skills(app: tauri::AppHandle, progress: Channel) -> Result { + let version = app.package_info().version.to_string(); + let message = tauri::async_runtime::spawn_blocking(move || { + versions::run_update(&version, |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 }) +} + +/// The OS folder picker, shown when no folder is known; a choice becomes the +/// launcher's remembered folder. +#[tauri::command] +fn pick_project_folder(app: tauri::AppHandle, state: State<'_, AppState>) -> Result, String> { + let picked = app + .dialog() + .file() + .blocking_pick_folder() + .and_then(|p| p.as_path().map(|dir| dir.to_path_buf())); + let Some(dir) = picked else { + return Ok(None); + }; + let choice = project::remember_folder(&dir)?; + let text = choice.dir.to_string_lossy().into_owned(); + *state.project.lock().map_err(|e| e.to_string())? = Some(choice); + Ok(Some(text)) +} + +/// Stops the old project's agent and console and clears both from state, so +/// neither `agent_for_project` nor `console_start` can hand either back once +/// the project has moved on (Task 9.5). The old agent's `Idle` state still +/// reaches the page's current channel here; only after that does this take +/// the channel away. +fn teardown_project(state: &AppState) -> Result<(), String> { + if let Some(agent) = current_agent(state) { + agent.stop(); + } + *state.agent.lock().map_err(|e| e.to_string())? = None; + *state.page.lock().map_err(|e| e.to_string())? = None; + if let Ok(mut guard) = state.console.lock() { + if let Some(mut sup) = guard.take() { + let _ = sup.stop(); + } + } + Ok(()) +} + +/// Switch to a different project folder, picked fresh: a clean teardown of +/// the old one (its agent stopped, its console stopped) before the new +/// folder is remembered, so `agent_for_project` and `console_start` start +/// fresh for it rather than reusing anything from the one just left. Picking +/// nothing (cancelled) leaves the current project untouched. One project per +/// window stays; this replaces it, it does not add a second. +#[tauri::command] +fn change_project(app: tauri::AppHandle, state: State<'_, AppState>) -> Result, String> { + let picked = app + .dialog() + .file() + .blocking_pick_folder() + .and_then(|p| p.as_path().map(|dir| dir.to_path_buf())); + let Some(dir) = picked else { + return Ok(None); + }; + + teardown_project(&state)?; + + let choice = project::remember_folder(&dir)?; + let text = choice.dir.to_string_lossy().into_owned(); + *state.project.lock().map_err(|e| e.to_string())? = Some(choice); + Ok(Some(text)) +} + +/// The console the agent opened, alive and as it is now, or restarted on the + /// same session when it died. The app never starts a dashboard of its own: +/// the agent does, by running the skill, and announces it. Nothing to show yet +/// is an error the page words for the person. +#[tauri::command] +fn console_start(state: State<'_, AppState>) -> Result { + console_start_impl(&state) +} + +fn console_start_impl(state: &AppState) -> Result { + let mut guard = state.console.lock().map_err(|e| e.to_string())?; + let sup = guard.as_mut().ok_or("The agent has not opened the dashboard yet.")?; + if !sup.health() { + sup.restart_if_dead()?; + } + serde_json::to_value(sup.session()).map_err(|e| e.to_string()) +} + +/// The bar's poll: none (never started or stopped on purpose), running, or +/// dead (started but not answering). +#[tauri::command] +fn console_status(state: State<'_, AppState>) -> serde_json::Value { + let Ok(guard) = state.console.lock() else { + return serde_json::json!({ "state": "none", "url": null }); + }; + match guard.as_ref() { + Some(sup) if sup.stopped() => serde_json::json!({ "state": "none", "url": null }), + Some(sup) if sup.health() => serde_json::json!({ "state": "running", "url": sup.session().url }), + Some(sup) => serde_json::json!({ "state": "dead", "url": sup.session().url }), + None => serde_json::json!({ "state": "none", "url": null }), + } +} + +#[tauri::command] +fn console_stop(state: State<'_, AppState>) -> Result<(), String> { + let mut guard = state.console.lock().map_err(|e| e.to_string())?; + if let Some(mut sup) = guard.take() { + sup.stop()?; + } + Ok(()) +} + +fn main() { + // Without Node 18+ the console and skills cannot run: say so and stop (FR-13). + let status = node_check::check_node(); + let node_problem = node_check::problem_message(&status); + let node_version = match &status { + node_check::NodeStatus::Ok(version) => Some(version.clone()), + _ => None, + }; + let node_binary = node_version.as_ref().and_then(|_| node_check::node_binary_path()); + + let args = std::env::args().collect::>(); + tauri::Builder::default() + .plugin(tauri_plugin_dialog::init()) + .manage(AppState { + project: Mutex::new(project::resolve(&args)), + launch: project::launch_choice(&args), + node_version, + node_binary, + ..AppState::default() + }) + .invoke_handler(tauri::generate_handler![ + platform_info, + agent_availability, + agent_start, + agent_input, + agent_resize, + agent_restart, + agent_state, + agent_reattach, + agent_context, + app_state, + save_term_panel, + save_first_run_done, + version_status, + update_skills, + pick_project_folder, + change_project, + console_start, + console_status, + console_stop + ]) + .on_window_event(|window, event| { + // Closing with an agent running asks first; "no" keeps the window open. + if let tauri::WindowEvent::CloseRequested { api, .. } = event { + let app = window.app_handle().clone(); + if agent_is_active(&app) { + api.prevent_close(); + confirm_quit(&app); + } + } + }) + .setup(move |app| { + // Pages the agent's `open` announces: the supervisor and the agent's + // environment follow the console, and the page frame shows it. + let handle = app.handle().clone(); + let server = AnnounceServer::start(Arc::new(move |notice| { + let state = handle.state::(); + if let Ok(mut guard) = state.console.lock() { + match guard.as_mut() { + Some(sup) => sup.follow(¬ice.url, ¬ice.sid), + // The agent started the console: the app owns its stop from here. + None => { + let dir = state.project.lock().ok().and_then(|p| p.as_ref().map(|p| p.dir.clone())); + if let Some(dir) = dir { + if let Ok(sup) = + ConsoleSupervisor::adopt(dir, window_origin(&handle), ¬ice.url, ¬ice.sid) + { + *guard = Some(sup); + } + } + } + } + } + let _ = handle.emit("console-page", ¬ice); + })); + match server { + Ok(server) => { + if let Ok(mut slot) = app.state::().announce.lock() { + *slot = Some(server); + } + } + // 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); + } + Ok(()) + }) + .build(tauri::generate_context!()) + .expect("error while building the Plan2Code app") + .run(|app, event| { + // Cmd+Q and the app menu's Quit on macOS end the app without closing the + // window first. An exit asked for in code (`code` is set) is `quit_app`'s own. + if let tauri::RunEvent::ExitRequested { api, code: None, .. } = event { + if agent_is_active(app) { + api.prevent_exit(); + confirm_quit(app); + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::PathBuf; + + fn state_for(dir: &str) -> AppState { + AppState { + project: Mutex::new(Some(ProjectDir { dir: PathBuf::from(dir), source: project::ProjectSource::Picked })), + ..AppState::default() + } + } + + // Covers the folder-matching rule itself (Task 9.5's fix); a genuinely + // *active* agent for the old folder needs a real spawned process to + // prove against, which only the `tests/agent_manager.rs` harness (the + // fake agent) can build — out of reach for an inline test here. The + // by-hand "Change project" check (RELEASE-CHECKLIST.md) covers that case. + #[test] + fn a_different_folder_never_gets_the_old_manager_back() { + let state = state_for("project-a"); + let first = agent_for_project(&state).expect("a manager for project-a"); + assert_eq!(first.folder(), &PathBuf::from("project-a")); + + // The project moved on; the slot still holds project-a's manager + // until a fresh call replaces it. + *state.project.lock().unwrap() = Some(ProjectDir { dir: PathBuf::from("project-b"), source: project::ProjectSource::Picked }); + let second = agent_for_project(&state).expect("a manager for project-b"); + assert_eq!(second.folder(), &PathBuf::from("project-b")); + assert!(!Arc::ptr_eq(&first, &second), "project-a's manager must never stand in for project-b's"); + } + + #[test] + fn the_same_folder_reuses_the_same_manager() { + let state = state_for("project-a"); + let first = agent_for_project(&state).unwrap(); + let second = agent_for_project(&state).unwrap(); + assert!(Arc::ptr_eq(&first, &second), "the same folder should not make a second manager"); + } + + fn have_node() -> bool { + std::process::Command::new("node").arg("--version").output().map(|o| o.status.success()).unwrap_or(false) + } + + /// A real console, the same way `tests/console_supervisor.rs` sets one + /// up: `PLAN2CODE_CONSOLE_DIR` points at the repo's own console source, + /// `PLAN2CODE_CONSOLE_HOME` keeps its session files out of the real one. + fn real_console() -> Option { + if !have_node() { + eprintln!("skipping: node is not on PATH"); + return None; + } + let console_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console"); + if !console_dir.join("console.mjs").is_file() { + eprintln!("skipping: console source missing at {}", console_dir.display()); + return None; + } + let pid = std::process::id(); + let project = std::env::temp_dir().join(format!("p2c-main-test-project-{pid}")); + std::fs::create_dir_all(&project).unwrap(); + std::env::set_var("PLAN2CODE_CONSOLE_DIR", &console_dir); + std::env::set_var("PLAN2CODE_CONSOLE_HOME", std::env::temp_dir().join(format!("p2c-main-test-home-{pid}"))); + std::env::set_var("PLAN2CODE_NO_BROWSER", "1"); + Some( + plan2code_app_lib::console_supervisor::ConsoleSupervisor::start( + project, + plan2code_app_lib::console_supervisor::app_origin().to_string(), + ) + .expect("start a real console for the test"), + ) + } + + #[test] + fn teardown_clears_the_console_so_console_start_refuses_not_reconnects() { + let Some(sup) = real_console() else { return }; + let state = state_for("project-a"); + *state.console.lock().unwrap() = Some(sup); + assert!(console_start_impl(&state).is_ok(), "console_start should work before the project changes"); + + teardown_project(&state).unwrap(); + + let err = console_start_impl(&state).expect_err("console_start must refuse, not reconnect to the old session"); + assert!(err.contains("has not opened the dashboard"), "unexpected message: {err:?}"); + } +} diff --git a/plan2code-app/src-tauri/src/node_check.rs b/plan2code-app/src-tauri/src/node_check.rs new file mode 100644 index 0000000..44cf0a5 --- /dev/null +++ b/plan2code-app/src-tauri/src/node_check.rs @@ -0,0 +1,175 @@ +//! The Node 18+ check (FR-13). The console and the skills run on Node, so the +//! app refuses to start without it and says what to install. +//! +//! An app started from the Dock, Finder or a `.desktop` file, rather than a +//! terminal, inherits a minimal PATH: none of nvm, Homebrew or Volta's +//! directories, which a login shell's own profile adds. `resolved_path` +//! (Task 9.9) is what every process this app spawns (the console, an update, +//! an agent CLI) should run with, not the bare inherited one; `node_check`, +//! `console_supervisor`, `versions` and `agents` all use it. + +use std::process::Command; +use std::sync::OnceLock; + +pub const MIN_NODE_MAJOR: u32 = 18; + +#[derive(Debug, PartialEq, Eq)] +pub enum NodeStatus { + Ok(String), + TooOld(String), + Missing, +} + +/// Major version from `node --version` output such as `v20.11.1`. +pub fn parse_node_major(output: &str) -> Option { + let text = output.trim().strip_prefix('v')?; + text.split('.').next()?.parse().ok() +} + +/// Classify the output of `node --version`. +pub fn classify(output: &str) -> NodeStatus { + let version = output.trim().to_string(); + match parse_node_major(output) { + Some(major) if major >= MIN_NODE_MAJOR => NodeStatus::Ok(version), + Some(_) => NodeStatus::TooOld(version), + None => NodeStatus::Missing, + } +} + +pub fn check_node() -> NodeStatus { + match Command::new("node").env("PATH", resolved_path()).arg("--version").output() { + Ok(out) if out.status.success() => classify(&String::from_utf8_lossy(&out.stdout)), + _ => NodeStatus::Missing, + } +} + +/// `--node ` or `--node=`: the launcher's own `node`, already +/// resolved under the person's real shell. Only its directory is used here, +/// so it joins the PATH the normal way rather than replacing every lookup. +fn node_override_dir(args: &[String]) -> Option { + let mut i = 1; // args[0] is the program name + while i < args.len() { + let value = if args[i] == "--node" { + args.get(i + 1).cloned() + } else { + args[i].strip_prefix("--node=").map(str::to_string) + }; + if let Some(path) = value.filter(|v| !v.is_empty()) { + return std::path::Path::new(&path).parent().map(|dir| dir.to_string_lossy().into_owned()); + } + i += 1; + } + None +} + +/// The login shell's own PATH: running it as a login shell sources +/// `.zprofile`, `.bash_profile` or `.profile`, which a GUI launch never does. +/// Windows sets PATH outside any shell's startup files, so this is unix only. +#[cfg(unix)] +fn login_shell_path() -> Option { + let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string()); + let out = Command::new(&shell).args(["-lc", "echo $PATH"]).output().ok()?; + let path = String::from_utf8_lossy(&out.stdout).trim().to_string(); + (out.status.success() && !path.is_empty()).then_some(path) +} + +/// The PATH every process this app spawns should run with: an explicit +/// `--node`'s directory first, then (macOS and Linux) the login shell's own +/// PATH, then this process's own PATH, each included only once. Resolved +/// once per launch: none of these change while the app runs. +pub fn resolved_path() -> &'static str { + static PATH: OnceLock = OnceLock::new(); + PATH.get_or_init(|| { + let args: Vec = std::env::args().collect(); + let inherited = std::env::var("PATH").unwrap_or_default(); + let mut parts = Vec::new(); + if let Some(dir) = node_override_dir(&args) { + parts.push(dir); + } + #[cfg(unix)] + if let Some(login) = login_shell_path() { + parts.push(login); + } + if !inherited.is_empty() { + parts.push(inherited); + } + parts.join(if cfg!(windows) { ";" } else { ":" }) + }) +} + +/// Where `node` actually resolves, with `resolved_path`: for the first-run +/// checklist to name (Task 9.9), not for `check_node` itself to decide with. +pub fn node_binary_path() -> Option { + let (program, arg) = if cfg!(windows) { ("where", "node") } else { ("which", "node") }; + let out = Command::new(program).env("PATH", resolved_path()).arg(arg).output().ok()?; + if !out.status.success() { + return None; + } + String::from_utf8_lossy(&out.stdout).lines().next().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string) +} + +/// The plain message shown when the check fails; `None` when Node is fine. +pub fn problem_message(status: &NodeStatus) -> Option { + 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." + )), + 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." + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn accepts_node_18_and_newer() { + assert_eq!(classify("v18.0.0\n"), NodeStatus::Ok("v18.0.0".into())); + assert_eq!(classify("v20.11.1"), NodeStatus::Ok("v20.11.1".into())); + assert_eq!(classify("v24.12.0\r\n"), NodeStatus::Ok("v24.12.0".into())); + } + + #[test] + fn rejects_node_older_than_18() { + assert_eq!(classify("v16.20.2"), NodeStatus::TooOld("v16.20.2".into())); + assert_eq!(classify("v17.9.1"), NodeStatus::TooOld("v17.9.1".into())); + } + + #[test] + fn treats_garbage_as_missing() { + assert_eq!(classify("not a version"), NodeStatus::Missing); + assert_eq!(classify(""), NodeStatus::Missing); + assert_eq!(classify("v"), NodeStatus::Missing); + assert_eq!(classify("vx.1.2"), NodeStatus::Missing); + } + + #[test] + fn message_only_for_a_problem() { + assert!(problem_message(&NodeStatus::Ok("v20.0.0".into())).is_none()); + assert!(problem_message(&NodeStatus::Missing).unwrap().contains("nodejs.org")); + assert!(problem_message(&NodeStatus::TooOld("v16.0.0".into())).unwrap().contains("v16.0.0")); + } + + fn args(list: &[&str]) -> Vec { + std::iter::once("plan2code-app").chain(list.iter().copied()).map(str::to_string).collect() + } + + #[test] + fn the_node_override_names_its_directory_in_both_forms() { + let want = if cfg!(windows) { "C:\\nvm\\v20" } else { "/home/x/.nvm/v20" }; + let bin = if cfg!(windows) { "C:\\nvm\\v20\\node.exe" } else { "/home/x/.nvm/v20/node" }; + assert_eq!(node_override_dir(&args(&["--node", bin])).as_deref(), Some(want)); + assert_eq!(node_override_dir(&args(&[&format!("--node={bin}")])).as_deref(), Some(want)); + } + + #[test] + fn no_override_or_a_missing_value_is_none() { + assert_eq!(node_override_dir(&args(&[])), None); + assert_eq!(node_override_dir(&args(&["--node"])), None); + assert_eq!(node_override_dir(&args(&["--node="])), None); + assert_eq!(node_override_dir(&args(&["--agent", "claude"])), None); + } +} diff --git a/plan2code-app/src-tauri/src/project.rs b/plan2code-app/src-tauri/src/project.rs new file mode 100644 index 0000000..8248a73 --- /dev/null +++ b/plan2code-app/src-tauri/src/project.rs @@ -0,0 +1,191 @@ +//! Which project folder the app works on: the folder the launcher passes in, +//! else the one the launcher remembers, else the person picks. The launcher's +//! memory is `~/.plan2code/launcher.json` (`lastFolder`, `lastCli`), shared so +//! the app and `plan2code` agree on both. + +use std::path::{Path, PathBuf}; + +use serde::Serialize; + +use crate::agents::AgentKind; + +/// Where the project folder came from, in the order it is tried. +#[derive(Clone, Copy, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum ProjectSource { + Argument, + Remembered, + Picked, +} + +#[derive(Clone)] +pub struct ProjectDir { + pub dir: PathBuf, + pub source: ProjectSource, +} + +fn err(e: E) -> String { + e.to_string() +} + +fn launcher_file() -> Option { + Some(std::env::home_dir()?.join(".plan2code").join("launcher.json")) +} + +fn read_launcher() -> serde_json::Map { + launcher_file() + .and_then(|file| std::fs::read_to_string(file).ok()) + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_default() +} + +/// The folder the launcher remembers, when it is still a directory. +fn remembered_folder() -> Option { + let dir = PathBuf::from(read_launcher().get("lastFolder")?.as_str()?); + dir.is_dir().then_some(dir) +} + +/// The agent the launcher last ran. The bar's picker starts on it until the +/// app has a choice of its own (`settings.rs`). +pub fn remembered_agent() -> Option { + AgentKind::from_id(read_launcher().get("lastCli")?.as_str()?) +} + +/// `--project `, `--project=` or the first bare argument: the folder +/// the launcher passed in when it started the app. +fn argument_folder(args: &[String]) -> Option { + let mut i = 1; // args[0] is the program name + while i < args.len() { + let arg = &args[i]; + if arg == "--agent" || arg == "--model" { + // Their values are not folders, even when a folder of that name exists. + i += 2; + continue; + } + if arg == "--project" { + i += 1; + if i < args.len() { + let dir = PathBuf::from(&args[i]); + return dir.is_dir().then_some(dir); + } + } else if let Some(dir) = arg.strip_prefix("--project=") { + let dir = PathBuf::from(dir); + return dir.is_dir().then_some(dir); + } else if !arg.starts_with('-') { + let dir = PathBuf::from(arg); + return dir.is_dir().then_some(dir); + } + i += 1; + } + None +} + +/// What the launcher chose before it opened the app: `--agent ` and `--model ` (or the +/// `=` forms). An unknown agent or a missing value is ignored, and a model only counts beside +/// an agent, since a model name belongs to one agent. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct LaunchChoice { + pub agent: Option, + pub model: Option, +} + +fn flag_value(args: &[String], flag: &str) -> Option { + let prefix = format!("{flag}="); + let mut i = 1; + while i < args.len() { + let arg = &args[i]; + if arg == flag { + return args.get(i + 1).filter(|v| !v.is_empty() && !v.starts_with('-')).cloned(); + } + if let Some(value) = arg.strip_prefix(&prefix) { + return (!value.is_empty()).then(|| value.to_string()); + } + i += 1; + } + None +} + +pub fn launch_choice(args: &[String]) -> LaunchChoice { + let agent = flag_value(args, "--agent").and_then(|id| AgentKind::from_id(&id.to_lowercase())); + let model = agent.and_then(|_| flag_value(args, "--model")); + LaunchChoice { agent, model } +} + +/// The folder to open on: the launcher's argument wins, then its memory, then +/// nothing (the page asks with the folder picker). +pub fn resolve(args: &[String]) -> Option { + if let Some(dir) = argument_folder(args) { + return Some(ProjectDir { dir, source: ProjectSource::Argument }); + } + remembered_folder().map(|dir| ProjectDir { dir, source: ProjectSource::Remembered }) +} + +/// A folder the person picked becomes the remembered one, so the next start +/// (app or launcher) opens on it. The launcher's other keys are kept. +pub fn remember_folder(dir: &Path) -> Result { + let file = launcher_file().ok_or("no home folder found")?; + let mut state = read_launcher(); + state.insert( + "lastFolder".to_string(), + serde_json::Value::String(dir.to_string_lossy().into_owned()), + ); + if let Some(parent) = file.parent() { + std::fs::create_dir_all(parent).map_err(err)?; + } + let json = serde_json::to_string_pretty(&serde_json::Value::Object(state)).map_err(err)?; + std::fs::write(file, json).map_err(err)?; + Ok(ProjectDir { dir: dir.to_path_buf(), source: ProjectSource::Picked }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(list: &[&str]) -> Vec { + std::iter::once("plan2code-app").chain(list.iter().copied()).map(str::to_string).collect() + } + + #[test] + fn the_launcher_choice_reads_agent_and_model_in_both_forms() { + let want = LaunchChoice { agent: Some(AgentKind::Codex), model: Some("gpt-5".into()) }; + assert_eq!(launch_choice(&args(&["--project", ".", "--agent", "codex", "--model", "gpt-5"])), want); + assert_eq!(launch_choice(&args(&["--agent=codex", "--model=gpt-5"])), want); + assert_eq!(launch_choice(&args(&["--agent", "CODEX", "--model", "gpt-5"])), want); + } + + #[test] + fn an_agent_alone_is_a_choice_and_a_model_alone_is_not() { + assert_eq!( + launch_choice(&args(&["--agent", "claude"])), + LaunchChoice { agent: Some(AgentKind::Claude), model: None } + ); + assert_eq!(launch_choice(&args(&["--model", "opus"])), LaunchChoice::default()); + } + + #[test] + fn an_unknown_agent_or_a_missing_value_is_ignored() { + assert_eq!(launch_choice(&args(&["--agent", "emacs", "--model", "x"])), LaunchChoice::default()); + assert_eq!(launch_choice(&args(&["--agent"])), LaunchChoice::default()); + assert_eq!(launch_choice(&args(&["--agent", "--model", "x"])), LaunchChoice::default()); + assert_eq!(launch_choice(&args(&["--agent=", "--model=x"])), LaunchChoice::default()); + assert_eq!(launch_choice(&args(&[])), LaunchChoice::default()); + assert_eq!( + launch_choice(&args(&["--agent", "devin", "--model"])), + LaunchChoice { agent: Some(AgentKind::Devin), model: None } + ); + } + + #[test] + fn the_agent_and_model_values_are_never_taken_for_a_folder() { + // A folder named like the agent exists right here, so a bare-argument reading would pick it. + let cwd = std::env::temp_dir().join(format!("p2c-project-args-{}", std::process::id())); + std::fs::create_dir_all(cwd.join("codex")).unwrap(); + let named = cwd.join("codex").to_string_lossy().into_owned(); + let found = argument_folder(&args(&["--agent", &named, "--model", &named])); + assert_eq!(found, None); + // Beside --project, the folder wins as before. + let found = argument_folder(&args(&["--project", &named, "--agent", "codex"])); + assert_eq!(found, Some(cwd.join("codex"))); + let _ = std::fs::remove_dir_all(&cwd); + } +} diff --git a/plan2code-app/src-tauri/src/pty_host.rs b/plan2code-app/src-tauri/src/pty_host.rs new file mode 100644 index 0000000..3a37356 --- /dev/null +++ b/plan2code-app/src-tauri/src/pty_host.rs @@ -0,0 +1,280 @@ +//! A command running in a pseudo-terminal, so full-screen agent programs see a +//! real terminal. Knows nothing about Tauri: output goes to a callback. + +use std::io::{Read, Write}; +use std::path::PathBuf; +#[cfg(unix)] +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::{Duration, Instant}; + +use portable_pty::{native_pty_system, Child, ChildKiller, CommandBuilder, MasterPty, PtySize}; + +/// Output is sent to the page at most once per this long, so a flood of text +/// does not stall the web view. +pub const BATCH_INTERVAL: Duration = Duration::from_millis(16); + +/// On macOS and Linux the kill is a hang-up signal, which a program can ignore. +/// This long after it, a command that is still running is killed outright. +#[cfg(unix)] +const HANGUP_GRACE: Duration = Duration::from_secs(2); + +/// What to run, where, and how big the terminal starts. +pub struct StartOptions { + pub program: String, + pub args: Vec, + pub env: Vec<(String, String)>, + pub cwd: Option, + pub cols: u16, + pub rows: u16, +} + +/// A running command in a pseudo-terminal. +pub struct PtyHost { + master: Mutex>, + writer: Mutex>, + child: Arc>>, + killer: Mutex>, + #[cfg(unix)] + pid: Option, + /// Set once the command has been waited for, so a late kill never signals + /// a process id that may have been given to something else. + #[cfg(unix)] + exited: Arc, + /// A Windows Job Object the spawned process was assigned to, so ending + /// it (`kill`, or this host simply being dropped) ends every process + /// still in it, not just the one directly spawned: a `cmd /c` npm shim's + /// real agent process is a child of that child, invisible to a plain + /// `TerminateProcess`. A raw handle value, not `HANDLE`, so the struct + /// stays `Send`. `None` when the job could not be made; `kill` then + /// falls back to ending just the one process, as before. + #[cfg(windows)] + job: Option, +} + +fn size(cols: u16, rows: u16) -> PtySize { + PtySize { rows, cols, pixel_width: 0, pixel_height: 0 } +} + +fn err(e: E) -> String { + e.to_string() +} + +impl PtyHost { + /// Start the command. `on_output` gets the output in chunks, at most one per + /// `BATCH_INTERVAL`, until the command's output ends. + pub fn start(options: StartOptions, mut on_output: F) -> Result + where + F: FnMut(Vec) + Send + 'static, + { + let pair = native_pty_system() + .openpty(size(options.cols, options.rows)) + .map_err(err)?; + + let mut command = CommandBuilder::new(&options.program); + command.args(&options.args); + // What the agent CLIs expect from a terminal that can show colour. + command.env("TERM", "xterm-256color"); + command.env("COLORTERM", "truecolor"); + for (key, value) in &options.env { + command.env(key, value); + } + if let Some(cwd) = &options.cwd { + command.cwd(cwd); + } + let child = pair.slave.spawn_command(command).map_err(err)?; + // The child holds its own end; keeping ours open would stop the reader + // from ever seeing the end of the output. + drop(pair.slave); + + let mut reader = pair.master.try_clone_reader().map_err(err)?; + let writer = pair.master.take_writer().map_err(err)?; + let killer = child.clone_killer(); + #[cfg(unix)] + let pid = child.process_id(); + #[cfg(windows)] + let job = windows_job::assign(child.as_ref()); + + // One thread reads as fast as the terminal produces; another gathers + // what arrived into one send per interval. + let (tx, rx) = mpsc::channel::>(); + thread::spawn(move || { + let mut buf = [0u8; 8192]; + loop { + match reader.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => { + if tx.send(buf[..n].to_vec()).is_err() { + break; + } + } + } + } + }); + thread::spawn(move || { + // Blocks for the first chunk, then collects until the interval is up. + while let Ok(first) = rx.recv() { + let mut batch = first; + let deadline = Instant::now() + BATCH_INTERVAL; + loop { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + break; + } + match rx.recv_timeout(left) { + Ok(more) => batch.extend_from_slice(&more), + Err(mpsc::RecvTimeoutError::Timeout) => break, + Err(mpsc::RecvTimeoutError::Disconnected) => { + on_output(batch); + return; + } + } + } + on_output(batch); + } + }); + + Ok(PtyHost { + master: Mutex::new(pair.master), + writer: Mutex::new(writer), + child: Arc::new(Mutex::new(child)), + killer: Mutex::new(killer), + #[cfg(unix)] + pid, + #[cfg(unix)] + exited: Arc::new(AtomicBool::new(false)), + #[cfg(windows)] + job, + }) + } + + /// Send keystrokes (or pasted text) to the command. + pub fn write(&self, bytes: &[u8]) -> Result<(), String> { + let mut writer = self.writer.lock().map_err(err)?; + writer.write_all(bytes).map_err(err)?; + writer.flush().map_err(err) + } + + /// Tell the command the terminal changed size. + pub fn resize(&self, cols: u16, rows: u16) -> Result<(), String> { + self.master.lock().map_err(err)?.resize(size(cols, rows)).map_err(err) + } + + /// End the command. Safe to call while `wait` is blocked in another thread. + pub fn kill(&self) -> Result<(), String> { + let result = self.killer.lock().map_err(err)?.kill().map_err(err); + // The job object, when there is one, ends the whole process tree: + // killing just the directly spawned process (above) leaves a + // `cmd /c` npm shim's real agent process running. + #[cfg(windows)] + if let Some(job) = self.job { + windows_job::terminate(job); + } + // portable-pty 0.9 on Windows has the TerminateProcess result inverted: it + // returns Err (a stale error) when the kill worked and Ok when it failed, so + // its answer says nothing there. + if cfg!(windows) { + return Ok(()); + } + // portable-pty only sends SIGHUP on macOS and Linux; follow it with + // SIGKILL if the command is still there after the grace period. + #[cfg(unix)] + if let Some(pid) = self.pid { + let exited = Arc::clone(&self.exited); + thread::spawn(move || { + thread::sleep(HANGUP_GRACE); + if !exited.load(Ordering::SeqCst) { + // SAFETY: plain signal to a process id the command still holds. + unsafe { libc::kill(pid as i32, libc::SIGKILL) }; + } + }); + } + result + } + + /// Block until the command ends and return its exit code. A command ended by + /// a signal reports 1. + pub fn wait(&self) -> Result { + self.wait_described().map(|(code, _)| code) + } + + /// Like `wait`, with the name of the signal that ended the command, when + /// there was one (macOS and Linux). + pub fn wait_described(&self) -> Result<(u32, Option), String> { + let child = Arc::clone(&self.child); + let mut child = child.lock().map_err(err)?; + let status = child.wait().map_err(err)?; + #[cfg(unix)] + self.exited.store(true, Ordering::SeqCst); + Ok((status.exit_code(), status.signal().map(str::to_string))) + } +} + +/// Closing the job's last handle ends every process still in it (`job` was +/// made with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`): a safety net for a host +/// dropped without `kill` ever being called, on top of `kill`'s own explicit +/// `TerminateJobObject`. +#[cfg(windows)] +impl Drop for PtyHost { + fn drop(&mut self) { + if let Some(job) = self.job { + windows_job::close(job); + } + } +} + +/// A Windows Job Object groups a spawned process with every process it goes +/// on to spawn itself (a child joins its parent's job automatically, unless +/// it asks to break away, which `cmd /c` does not), so ending the job ends +/// the whole tree. Nothing here calls back into `PtyHost`. +#[cfg(windows)] +mod windows_job { + use portable_pty::Child; + use std::os::windows::io::RawHandle; + use winapi::shared::minwindef::DWORD; + use winapi::shared::ntdef::HANDLE; + use winapi::um::handleapi::CloseHandle; + use winapi::um::jobapi2::{AssignProcessToJobObject, CreateJobObjectW, SetInformationJobObject, TerminateJobObject}; + use winapi::um::winnt::{JobObjectExtendedLimitInformation, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE}; + + /// Create a job, set it to kill everything in it when its last handle + /// closes, and assign `child` to it. `None` on any failure (an older + /// Windows without nested-job support, say): `kill` then falls back to + /// ending just the one process, as it always did. + pub fn assign(child: &(dyn Child + Send + Sync)) -> Option { + let process: RawHandle = child.as_raw_handle()?; + unsafe { + let job = CreateJobObjectW(std::ptr::null_mut(), std::ptr::null()); + if job.is_null() { + return None; + } + let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed(); + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + let set = SetInformationJobObject( + job, + JobObjectExtendedLimitInformation, + &mut info as *mut _ as *mut _, + std::mem::size_of::() as DWORD, + ); + if set == 0 || AssignProcessToJobObject(job, process as HANDLE) == 0 { + CloseHandle(job); + return None; + } + Some(job as usize) + } + } + + pub fn terminate(job: usize) { + unsafe { + TerminateJobObject(job as HANDLE, 1); + } + } + + pub fn close(job: usize) { + unsafe { + CloseHandle(job as HANDLE); + } + } +} diff --git a/plan2code-app/src-tauri/src/restart_brief.rs b/plan2code-app/src-tauri/src/restart_brief.rs new file mode 100644 index 0000000..e69cd30 --- /dev/null +++ b/plan2code-app/src-tauri/src/restart_brief.rs @@ -0,0 +1,182 @@ +//! What a Restart leaves for the dashboard: the restart brief, written as a +//! pick-up handoff, so the fresh agent (which starts on the plain `/plan2code` +//! prompt and lands on the dashboard) finds the chip waiting. Nothing new is +//! stored anywhere: the brief is built from the session's files each time. + +use std::path::Path; +use std::sync::Mutex; + +use chrono::{DateTime, Local}; +use serde_json::Value; + +use crate::brief; +use crate::handoff; +use crate::session_reader; + +pub const READY_NOTE: &str = "Brief ready on the dashboard"; + +/// The handoff the last Restart wrote. The next Restart retires it if the person +/// has not picked it up, so unused briefs do not pile up as chips. +static LAST_BRIEF: Mutex> = Mutex::new(None); + +/// The skill named on a handoff record for a workflow `brief::skill_for_workflow` +/// does not map, such as `dashboard`: the console's own name for that pseudo-skill. +const UNMAPPED_SKILL: &str = "plan2code"; + +/// Write the brief for session `sid` as a handoff. A workflow with no mapped +/// skill (a dashboard, or one not yet known) still gets a short, honest chip +/// rather than nothing. Returns the handoff's id, or `None` when there is +/// truly nothing to write (the session names no worktree is an error, not a +/// `None`, since that is a broken session rather than an empty one). +pub fn leave_brief(console_home: &Path, handoffs: &Path, sid: &str, when: DateTime) -> Result, String> { + let session = session_reader::load(console_home, sid).map_err(|e| e.to_string())?; + let state = &session.state; + let workflow = text(state, "workflow").unwrap_or(""); + let skill = brief::skill_for_workflow(workflow); + let worktree = text(state, "worktree").ok_or("the session names no worktree")?; + let project = text(state, "project").unwrap_or(worktree); + let spec = text(state, "specDir").filter(|s| valid_spec(s)); + let spec_dir = spec.map(|s| Path::new(worktree).join(s)); + let git = brief::git_summary(Path::new(worktree)); + let events = session_reader::read_ndjson(&session.dir.join("events.ndjson")); + let body = brief::build_brief(state, spec_dir.as_deref(), git.as_ref(), &events); + let title = match skill { + Some(skill) => match spec { + Some(spec) => format!("Restart of {skill} on {spec}"), + None => format!("Restart of {skill}"), + }, + None => format!("Restart while on {workflow}"), + }; + let record = handoff::Record { title: &title, worktree, project, spec, workflow, skill: skill.unwrap_or(UNMAPPED_SKILL) }; + handoff::write(handoffs, when, &record, &body).map(Some) +} + +/// The bar's line for a Restart on session `sid`, written to the real console +/// and handoff folders. `None` when there was nothing to leave. +pub fn note_for_restart(sid: &str) -> Option { + let console_home = session_reader::console_home()?; + let handoffs = handoff::handoffs_dir()?; + match leave_brief(&console_home, &handoffs, sid, handoff::now()) { + Ok(Some(id)) => { + let previous = LAST_BRIEF.lock().ok().and_then(|mut last| last.replace(id.clone())); + if let Some(previous) = previous.filter(|p| *p != id) { + let _ = handoff::retire_if_unused(&handoffs, &previous); + } + Some(READY_NOTE.to_string()) + } + Ok(None) => None, + Err(why) => Some(format!("The brief could not be written: {why}")), + } +} + +fn text<'a>(state: &'a Value, key: &str) -> Option<&'a str> { + state.get(key).and_then(Value::as_str).filter(|s| !s.is_empty()) +} + +fn valid_spec(spec: &str) -> bool { + spec.strip_prefix("specs/").is_some_and(|name| !name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\'])) +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::TimeZone; + use std::fs; + use std::path::PathBuf; + + fn fixture(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("plan2code-restart-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir + } + + /// A console home with one session on `workflow`, and a project with a spec. + fn session(name: &str, workflow: &str, spec: Option<&str>) -> (PathBuf, PathBuf, PathBuf) { + let root = fixture(name); + let home = root.join("console"); + let project = root.join("project"); + let dir = home.join("sessions").join("s1"); + fs::create_dir_all(&dir).unwrap(); + fs::create_dir_all(&project).unwrap(); + let state = serde_json::json!({ + "schema": 1, + "workflow": workflow, + "specDir": spec, + "worktree": project.to_string_lossy(), + "project": project.to_string_lossy(), + "headline": { "stage": "Phase 5: Restart brief", "cleared": 4, "total": 11 }, + "items": [], + }); + fs::write(dir.join("state.json"), state.to_string()).unwrap(); + (home, project, root.join("handoffs")) + } + + fn when() -> DateTime { + Local.with_ymd_and_hms(2026, 10, 21, 14, 5, 0).unwrap() + } + + #[test] + fn a_mid_implement_session_leaves_a_pick_up_the_dashboard_lists() { + let (home, project, handoffs) = session("pickup", "implement", Some("specs/feature")); + let spec = project.join("specs").join("feature"); + fs::create_dir_all(&spec).unwrap(); + fs::write(spec.join("overview.md"), "- [/] [Phase 5: Restart](./phase-5.md)\n").unwrap(); + fs::write(spec.join("phase-5.md"), "- [ ] **Task 5.1:** Create the reader\n").unwrap(); + + let id = leave_brief(&home, &handoffs, "s1", when()).unwrap().expect("a handoff"); + assert_eq!(id, "2026-10-21-1405-handoff"); + let record: Value = serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap()).unwrap(); + assert_eq!(record["workflow"], "implement"); + assert_eq!(record["spec"], "specs/feature"); + let doc = fs::read_to_string(handoffs.join(format!("{id}.md"))).unwrap(); + assert!(doc.contains("## Next task\n\nTask 5.1: Create the reader")); + assert!(doc.contains("Phase 5: Restart brief: 4 of 11 done.")); + } + + #[test] + fn a_dashboard_session_still_leaves_a_chip() { + let (home, _, handoffs) = session("dashboard", "dashboard", None); + let id = leave_brief(&home, &handoffs, "s1", when()).unwrap().expect("a handoff"); + let record: Value = serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap()).unwrap(); + assert_eq!(record["title"], "Restart while on dashboard"); + assert_eq!(record["skill"], "plan2code"); + assert_eq!(record["workflow"], "dashboard"); + let doc = fs::read_to_string(handoffs.join(format!("{id}.md"))).unwrap(); + assert!(doc.contains("- Workflow: `dashboard`")); + assert!(doc.contains("## Next task\n\nOpen the dashboard")); + } + + #[test] + fn the_brief_carries_the_agent_activity_and_recent_events() { + let (home, _project, handoffs) = session("activity", "implement", None); + let dir = home.join("sessions").join("s1"); + let mut state: Value = serde_json::from_str(&fs::read_to_string(dir.join("state.json")).unwrap()).unwrap(); + state["agent"] = serde_json::json!({ "status": "working", "activity": "Spiking Claude's context signal (Task 10.1)" }); + fs::write(dir.join("state.json"), state.to_string()).unwrap(); + fs::write( + dir.join("events.ndjson"), + "{\"at\":\"2026-10-23T01:08:47.152Z\",\"type\":\"post\",\"items\":0}\n{\"at\":\"2026-10-23T01:09:00.000Z\",\"type\":\"consume\",\"kind\":\"submit\"}\n", + ) + .unwrap(); + + let id = leave_brief(&home, &handoffs, "s1", when()).unwrap().expect("a handoff"); + let doc = fs::read_to_string(handoffs.join(format!("{id}.md"))).unwrap(); + assert!(doc.contains("Doing: Spiking Claude's context signal (Task 10.1)")); + assert!(doc.contains("## Recent activity\n\n- post (0 items)\n- consume: submit\n")); + } + + #[test] + fn a_session_that_does_not_exist_is_an_error_not_a_brief() { + let (home, _, handoffs) = session("missing", "implement", None); + assert!(leave_brief(&home, &handoffs, "nope", when()).is_err()); + } + + #[test] + fn a_spec_that_is_not_one_folder_is_left_out_of_the_record() { + let (home, _, handoffs) = session("badspec", "pathfinder", Some("specs/a/b")); + let id = leave_brief(&home, &handoffs, "s1", when()).unwrap().unwrap(); + let record: Value = serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap()).unwrap(); + assert!(record["spec"].is_null()); + } +} diff --git a/plan2code-app/src-tauri/src/session_reader.rs b/plan2code-app/src-tauri/src/session_reader.rs new file mode 100644 index 0000000..14bbac0 --- /dev/null +++ b/plan2code-app/src-tauri/src/session_reader.rs @@ -0,0 +1,217 @@ +//! Reads a console session's files without disturbing them. The console owns +//! `~/.plan2code/console/sessions//`: this module only opens files for +//! reading. It never creates, locks, renames or removes anything there, so the +//! console's own writes are never blocked by the app (NFR-3). + +use std::io; +use std::path::{Path, PathBuf}; +use std::thread::sleep; +use std::time::Duration; + +use serde_json::Value; + +/// The one session schema this reader understands (`state.json`'s `schema`). +pub const SCHEMA: u64 = 1; + +/// How many times a locked `state.json` is tried again. The console renames +/// the file while it writes, so Windows can refuse a read for a moment. +const LOCKED_RETRIES: u32 = 5; +const RETRY_EVERY: Duration = Duration::from_millis(50); + +/// Windows: ERROR_SHARING_VIOLATION and ERROR_LOCK_VIOLATION. +const WINDOWS_SHARING: [i32; 2] = [32, 33]; + +#[derive(Debug, PartialEq, Eq)] +pub enum ReadError { + /// The file is not there. + Missing(PathBuf), + /// Still locked after every retry. + Busy, + /// Some other read failure. + Unreadable(String), + /// Not a JSON object. + Malformed(String), + /// A schema this app does not read. + Schema(u64), +} + +impl std::fmt::Display for ReadError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ReadError::Missing(file) => write!(f, "{} is missing", file.display()), + ReadError::Busy => write!(f, "session busy: the console is still writing its state"), + ReadError::Unreadable(why) => write!(f, "could not read the session: {why}"), + ReadError::Malformed(why) => write!(f, "the session file is not valid: {why}"), + ReadError::Schema(found) => { + write!(f, "session schema {found} is not supported (this app reads schema {SCHEMA})") + } + } + } +} + +/// A session's `state.json`, read once. Nothing else in the session folder is +/// read here: the Ask chat lives in `chat.ndjson` and stays out of the brief. +pub struct Session { + pub dir: PathBuf, + pub state: Value, +} + +/// `~/.plan2code/console`, or `PLAN2CODE_CONSOLE_HOME` when the console is +/// relocated (the same rule the console and the supervisor follow). +pub fn console_home() -> Option { + if let Ok(home) = std::env::var("PLAN2CODE_CONSOLE_HOME") { + return Some(PathBuf::from(home)); + } + Some(std::env::home_dir()?.join(".plan2code").join("console")) +} + +/// `/sessions/`. +pub fn session_dir(console_home: &Path, sid: &str) -> PathBuf { + console_home.join("sessions").join(sid) +} + +/// Open and parse the session `sid` under `console_home`. +pub fn load(console_home: &Path, sid: &str) -> Result { + let dir = session_dir(console_home, sid); + let text = read_with_retry(&dir.join("state.json"), |file| std::fs::read_to_string(file))?; + let state = parse_state(&text)?; + Ok(Session { dir, state }) +} + +/// Read `file` through `read`. A locked file (a sharing or permission error) is +/// tried again up to `LOCKED_RETRIES` times, `RETRY_EVERY` apart; then the +/// session is reported busy. `read` is a parameter so a test can stand in a +/// reader that fails a few times. +pub fn read_with_retry(file: &Path, mut read: F) -> Result +where + F: FnMut(&Path) -> io::Result, +{ + let mut retries = 0; + loop { + match read(file) { + Ok(text) => return Ok(text), + Err(e) if e.kind() == io::ErrorKind::NotFound => return Err(ReadError::Missing(file.to_path_buf())), + Err(e) if is_locked(&e) => { + if retries == LOCKED_RETRIES { + return Err(ReadError::Busy); + } + retries += 1; + sleep(RETRY_EVERY); + } + Err(e) => return Err(ReadError::Unreadable(e.to_string())), + } + } +} + +fn is_locked(e: &io::Error) -> bool { + e.kind() == io::ErrorKind::PermissionDenied || e.raw_os_error().is_some_and(|code| WINDOWS_SHARING.contains(&code)) +} + +/// Parse `state.json` text: a JSON object whose `schema` is `SCHEMA`. +pub fn parse_state(text: &str) -> Result { + let state: Value = serde_json::from_str(text).map_err(|e| ReadError::Malformed(e.to_string()))?; + if !state.is_object() { + return Err(ReadError::Malformed("not a JSON object".to_string())); + } + let schema = state + .get("schema") + .and_then(Value::as_u64) + .ok_or_else(|| ReadError::Malformed("no schema number".to_string()))?; + if schema != SCHEMA { + return Err(ReadError::Schema(schema)); + } + Ok(state) +} + +/// Each line of a `.ndjson` file that parses as JSON, in order. A partial last +/// line (the console was mid-write) does not parse and is dropped; so is any +/// other line that does not parse. A missing file has no lines. +pub fn read_ndjson(file: &Path) -> Vec { + match std::fs::read_to_string(file) { + Ok(text) => parse_ndjson(&text), + Err(_) => Vec::new(), + } +} + +pub fn parse_ndjson(text: &str) -> Vec { + text.lines().filter(|line| !line.trim().is_empty()).filter_map(|line| serde_json::from_str(line).ok()).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + fn fixture(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("plan2code-reader-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + const STATE: &str = r#"{"schema": 1, "sid": "s1", "workflow": "implement", "specDir": "specs/x"}"#; + + #[test] + fn a_complete_session_loads() { + let home = fixture("complete"); + let dir = session_dir(&home, "s1"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("state.json"), STATE).unwrap(); + let session = load(&home, "s1").unwrap(); + assert_eq!(session.state["workflow"], "implement"); + assert_eq!(session.dir, dir); + } + + #[test] + fn a_partial_last_line_is_dropped() { + let lines = parse_ndjson("{\"a\":1}\n{\"b\":2}\n{\"c\":"); + assert_eq!(lines, vec![serde_json::json!({"a": 1}), serde_json::json!({"b": 2})]); + } + + #[test] + fn a_missing_ndjson_file_has_no_lines() { + assert!(read_ndjson(&fixture("no-ndjson").join("events.ndjson")).is_empty()); + } + + #[test] + fn a_missing_state_file_is_reported() { + let home = fixture("missing"); + match load(&home, "nope") { + Err(ReadError::Missing(file)) => assert!(file.ends_with("state.json")), + other => panic!("expected Missing, got {:?}", other.map(|s| s.dir)), + } + } + + #[test] + fn another_schema_is_rejected_with_a_clear_message() { + let err = parse_state(r#"{"schema": 2}"#).unwrap_err(); + assert_eq!(err, ReadError::Schema(2)); + assert!(err.to_string().contains("schema 2 is not supported")); + } + + #[test] + fn a_locked_file_that_frees_up_on_the_third_retry_is_read() { + let tries = Cell::new(0); + let text = read_with_retry(Path::new("state.json"), |_| { + tries.set(tries.get() + 1); + if tries.get() < 4 { + Err(io::Error::from(io::ErrorKind::PermissionDenied)) + } else { + Ok(STATE.to_string()) + } + }); + assert_eq!(text.unwrap(), STATE); + assert_eq!(tries.get(), 4); + } + + #[test] + fn a_file_that_stays_locked_is_busy_not_a_failure() { + let tries = Cell::new(0); + let result = read_with_retry(Path::new("state.json"), |_| { + tries.set(tries.get() + 1); + Err(io::Error::from_raw_os_error(32)) + }); + assert_eq!(result, Err(ReadError::Busy)); + assert_eq!(tries.get(), LOCKED_RETRIES + 1); + } +} diff --git a/plan2code-app/src-tauri/src/settings.rs b/plan2code-app/src-tauri/src/settings.rs new file mode 100644 index 0000000..01ba78e --- /dev/null +++ b/plan2code-app/src-tauri/src/settings.rs @@ -0,0 +1,242 @@ +//! The app's own settings file, `~/.plan2code/app.json`. It holds what only the +//! app remembers (today: the agent last picked in the bar). The console's +//! folders under `~/.plan2code/console/` are never written to from here. + +use std::path::{Path, PathBuf}; + +use crate::agents::AgentKind; + +const LAST_AGENT_KEY: &str = "lastAgent"; +const NUDGE_KEY: &str = "CONTEXT_NUDGE_PERCENT"; +const TERM_DOCK_KEY: &str = "termDock"; +const TERM_FRACTION_KEY: &str = "termFraction"; +const TERM_COLLAPSED_KEY: &str = "termCollapsed"; +const FIRST_RUN_DONE_KEY: &str = "firstRunDone"; + +/// The context percent at which the bar suggests a Restart, when the file +/// names no other. +pub const DEFAULT_NUDGE_PERCENT: u8 = 70; + +/// 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 +/// it was left collapsed. +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +pub struct TermPanelSettings { + pub dock: String, + pub fraction: f64, + pub collapsed: bool, +} + +pub const DEFAULT_TERM_DOCK: &str = "bottom"; +pub const DEFAULT_TERM_FRACTION: f64 = 0.25; +const TERM_FRACTION_MIN: f64 = 0.05; +const TERM_FRACTION_MAX: f64 = 0.9; + +pub fn settings_file() -> Option { + Some(std::env::home_dir()?.join(".plan2code").join("app.json")) +} + +fn read(file: &Path) -> serde_json::Map { + std::fs::read_to_string(file) + .ok() + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_default() +} + +/// The agent saved in `file`, when it still names one the app can run. +pub fn load_last_agent(file: &Path) -> Option { + AgentKind::from_id(read(file).get(LAST_AGENT_KEY)?.as_str()?) +} + +/// The context percent that triggers the Restart suggestion. A value outside +/// 1 to 100, or one that is not a number, means the default. +pub fn load_nudge_percent(file: &Path) -> u8 { + read(file) + .get(NUDGE_KEY) + .and_then(|value| value.as_u64()) + .filter(|percent| (1..=100).contains(percent)) + .map_or(DEFAULT_NUDGE_PERCENT, |percent| percent as u8) +} + +/// Save the pick, keeping any other key the file holds. +pub fn save_last_agent(file: &Path, kind: AgentKind) -> Result<(), String> { + let mut settings = read(file); + settings.insert(LAST_AGENT_KEY.to_string(), serde_json::Value::String(kind.id().to_string())); + write(file, settings) +} + +/// The terminal pane's shape, from the file or the defaults. A dock other +/// than `bottom` or `right`, or a fraction outside its range, is the default. +pub fn load_term_panel(file: &Path) -> TermPanelSettings { + let settings = read(file); + let dock = settings + .get(TERM_DOCK_KEY) + .and_then(|v| v.as_str()) + .filter(|d| *d == "bottom" || *d == "right") + .unwrap_or(DEFAULT_TERM_DOCK) + .to_string(); + let fraction = settings + .get(TERM_FRACTION_KEY) + .and_then(|v| v.as_f64()) + .filter(|f| (TERM_FRACTION_MIN..=TERM_FRACTION_MAX).contains(f)) + .unwrap_or(DEFAULT_TERM_FRACTION); + let collapsed = settings.get(TERM_COLLAPSED_KEY).and_then(|v| v.as_bool()).unwrap_or(false); + TermPanelSettings { dock, fraction, collapsed } +} + +/// Save the terminal pane's shape, keeping any other key the file holds. An +/// invalid dock or an out-of-range fraction is rejected rather than saved. +pub fn save_term_panel(file: &Path, dock: &str, fraction: f64, collapsed: bool) -> Result<(), String> { + if dock != "bottom" && dock != "right" { + return Err(format!("unknown dock: {dock}")); + } + if !(TERM_FRACTION_MIN..=TERM_FRACTION_MAX).contains(&fraction) { + return Err(format!("fraction out of range: {fraction}")); + } + let mut settings = read(file); + settings.insert(TERM_DOCK_KEY.to_string(), serde_json::Value::String(dock.to_string())); + settings.insert( + TERM_FRACTION_KEY.to_string(), + serde_json::Number::from_f64(fraction).map(serde_json::Value::Number).unwrap_or(serde_json::Value::Null), + ); + settings.insert(TERM_COLLAPSED_KEY.to_string(), serde_json::Value::Bool(collapsed)); + 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 { + read(file).get(FIRST_RUN_DONE_KEY).and_then(|v| v.as_bool()).unwrap_or(false) +} + +/// Remember that the checklist passed, keeping any other key the file holds. +pub fn save_first_run_done(file: &Path) -> Result<(), String> { + let mut settings = read(file); + settings.insert(FIRST_RUN_DONE_KEY.to_string(), serde_json::Value::Bool(true)); + write(file, settings) +} + +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())?; + } + let json = serde_json::to_string_pretty(&serde_json::Value::Object(settings)).map_err(|e| e.to_string())?; + std::fs::write(file, json).map_err(|e| e.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp_file(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("plan2code-settings-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir.join("app.json") + } + + #[test] + fn a_missing_file_has_no_choice() { + assert_eq!(load_last_agent(&temp_file("missing")), None); + } + + #[test] + fn the_choice_round_trips_and_other_keys_survive() { + let file = temp_file("round-trip"); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, r#"{"other": 1}"#).unwrap(); + save_last_agent(&file, AgentKind::Devin).unwrap(); + assert_eq!(load_last_agent(&file), Some(AgentKind::Devin)); + assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\"")); + let _ = std::fs::remove_dir_all(file.parent().unwrap()); + } + + #[test] + fn the_nudge_defaults_to_seventy() { + assert_eq!(load_nudge_percent(&temp_file("nudge-missing")), 70); + } + + #[test] + fn the_nudge_reads_a_named_percent() { + let file = temp_file("nudge-set"); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, r#"{"CONTEXT_NUDGE_PERCENT": 85}"#).unwrap(); + assert_eq!(load_nudge_percent(&file), 85); + let _ = std::fs::remove_dir_all(file.parent().unwrap()); + } + + #[test] + fn a_nudge_outside_one_to_one_hundred_or_not_a_number_is_the_default() { + for text in [ + r#"{"CONTEXT_NUDGE_PERCENT": 0}"#, + r#"{"CONTEXT_NUDGE_PERCENT": 150}"#, + r#"{"CONTEXT_NUDGE_PERCENT": "high"}"#, + ] { + let file = temp_file("nudge-bad"); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, text).unwrap(); + assert_eq!(load_nudge_percent(&file), 70, "{text}"); + let _ = std::fs::remove_dir_all(file.parent().unwrap()); + } + } + + #[test] + fn an_unknown_agent_is_ignored() { + let file = temp_file("unknown"); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, r#"{"lastAgent": "nope"}"#).unwrap(); + assert_eq!(load_last_agent(&file), None); + let _ = std::fs::remove_dir_all(file.parent().unwrap()); + } + + #[test] + fn the_term_panel_defaults_to_bottom_at_a_quarter() { + let want = TermPanelSettings { dock: "bottom".into(), fraction: 0.25, collapsed: false }; + assert_eq!(load_term_panel(&temp_file("term-missing")), want); + } + + #[test] + fn the_term_panel_round_trips_and_other_keys_survive() { + let file = temp_file("term-round-trip"); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, r#"{"other": 1}"#).unwrap(); + save_term_panel(&file, "right", 0.4, true).unwrap(); + assert_eq!( + load_term_panel(&file), + TermPanelSettings { dock: "right".into(), fraction: 0.4, collapsed: true } + ); + assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\"")); + let _ = std::fs::remove_dir_all(file.parent().unwrap()); + } + + #[test] + fn an_unknown_dock_or_an_out_of_range_fraction_is_refused() { + let file = temp_file("term-bad-save"); + assert!(save_term_panel(&file, "top", 0.3, false).is_err()); + assert!(save_term_panel(&file, "bottom", 0.0, false).is_err()); + assert!(save_term_panel(&file, "bottom", 1.0, false).is_err()); + assert!(!file.exists()); + } + + #[test] + fn first_run_is_not_done_until_it_is_saved() { + let file = temp_file("first-run"); + assert!(!load_first_run_done(&file)); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, r#"{"other": 1}"#).unwrap(); + save_first_run_done(&file).unwrap(); + assert!(load_first_run_done(&file)); + assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\"")); + let _ = std::fs::remove_dir_all(file.parent().unwrap()); + } + + #[test] + fn a_bad_dock_or_out_of_range_fraction_on_disk_reads_as_the_default() { + let file = temp_file("term-bad-load"); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, r#"{"termDock": "top", "termFraction": 5}"#).unwrap(); + let loaded = load_term_panel(&file); + assert_eq!(loaded.dock, "bottom"); + assert_eq!(loaded.fraction, 0.25); + let _ = std::fs::remove_dir_all(file.parent().unwrap()); + } +} diff --git a/plan2code-app/src-tauri/src/versions.rs b/plan2code-app/src-tauri/src/versions.rs new file mode 100644 index 0000000..0f7d607 --- /dev/null +++ b/plan2code-app/src-tauri/src/versions.rs @@ -0,0 +1,273 @@ +//! Whether the app and the installed skills are on the same Plan2Code version, and the +//! one-click way to bring them level. The app's own version is the one in `tauri.conf.json` +//! (Tauri reads it into the package info); the skills' version is the `version.json` the +//! installer writes beside the launcher in `~/.plan2code/bin/` on every install and update. + +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +use serde::Serialize; + +/// How long `run_update` lets the installer run before giving up on it. +pub const UPDATE_TIMEOUT: Duration = Duration::from_secs(300); + +#[derive(Debug, PartialEq, Eq, Serialize)] +pub struct VersionStatus { + pub app: String, + /// The installed skills' version, or none when it cannot be read. + pub skills: Option, + /// True only when both are readable `X.Y.Z` versions and they differ: an unknown version is + /// never a reason to nag. + pub mismatch: bool, + /// Only meaningful when `mismatch` is true: the skills are ahead of this app, so another + /// Update skills run cannot fix it (a newer app is what is missing), as against the usual + /// case of the skills sitting behind the app. + pub skills_ahead: bool, +} + +/// `~/.plan2code/bin`, or `PLAN2CODE_LAUNCHER_DIR` when it is set (tests only, the same +/// convention `PLAN2CODE_CONSOLE_HOME` and `PLAN2CODE_APP_AGENT_BIN` already use). +fn launcher_dir() -> Option { + if let Ok(dir) = std::env::var("PLAN2CODE_LAUNCHER_DIR") { + return Some(PathBuf::from(dir)); + } + Some(std::env::home_dir()?.join(".plan2code").join("bin")) +} + +/// `X.Y.Z` as three numbers; anything else (a pre-release tag, a missing part) is none. +fn parse(version: &str) -> Option<(u64, u64, u64)> { + let mut parts = version.trim().split('.'); + let triple = ( + parts.next()?.parse().ok()?, + parts.next()?.parse().ok()?, + parts.next()?.parse().ok()?, + ); + parts.next().is_none().then_some(triple) +} + +/// The `version` field of a `version.json` file. +pub fn version_in(file: &Path) -> Option { + let text = std::fs::read_to_string(file).ok()?; + let json: serde_json::Value = serde_json::from_str(&text).ok()?; + json.get("version")?.as_str().map(str::to_string) +} + +/// The skills' version as the installer last wrote it. +pub fn installed_skills_version() -> Option { + version_in(&launcher_dir()?.join("version.json")) +} + +pub fn status(app: &str, skills: Option) -> VersionStatus { + let (mismatch, skills_ahead) = match (parse(app), skills.as_deref().and_then(parse)) { + (Some(a), Some(s)) => (a != s, s > a), + _ => (false, false), + }; + VersionStatus { app: app.to_string(), skills, mismatch, skills_ahead } +} + +/// 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 +/// until it ends or `UPDATE_TIMEOUT` passes, whichever comes first; the page asks for it with a +/// click, never on its own. `on_line` is called with each line of output as it is produced, for a +/// live progress readout. Returns the installer's last non-empty line on success. +pub fn run_update(app_version: &str, on_line: impl FnMut(&str)) -> Result { + run_update_within(app_version, 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, mut on_line: impl FnMut(&str)) -> Result { + let launcher = launcher_dir().ok_or("no home folder found")?.join("plan2code.js"); + if !launcher.is_file() { + return Err(format!("the plan2code command is not installed ({} is missing)", launcher.display())); + } + let mut command = Command::new("node"); + // A Dock or Start-menu launch often lacks nvm, Homebrew or Volta's + // directories (Task 9.9): the update script itself shells out to `npx` + // and `git`, which need a PATH that finds them too. + command.env("PATH", crate::node_check::resolved_path()); + command + .arg(&launcher) + .arg("update") + .arg("--tag") + .arg(format!("v{app_version}")) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(0x08000000); // CREATE_NO_WINDOW, as the console calls are + } + let mut child = command.spawn().map_err(|e| format!("could not run node: {e}"))?; + let stdout = child.stdout.take().ok_or("no stdout from the update")?; + let stderr = child.stderr.take().ok_or("no stderr from the update")?; + let (tx, rx) = mpsc::channel::(); + let err_tx = tx.clone(); + let out_thread = std::thread::spawn(move || { + for line in BufReader::new(stdout).lines().map_while(Result::ok) { + if tx.send(line).is_err() { + break; + } + } + }); + let err_thread = std::thread::spawn(move || { + for line in BufReader::new(stderr).lines().map_while(Result::ok) { + if err_tx.send(line).is_err() { + break; + } + } + }); + let deadline = Instant::now() + timeout; + let poll = Duration::from_millis(200).min(timeout); + let mut last_line = String::new(); + loop { + match rx.recv_timeout(poll) { + Ok(line) => { + if !line.trim().is_empty() { + last_line = line.clone(); + } + on_line(&line); + } + Err(mpsc::RecvTimeoutError::Timeout) if Instant::now() < deadline => continue, + Err(mpsc::RecvTimeoutError::Timeout) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!("the update timed out after {}s", timeout.as_secs())); + } + Err(mpsc::RecvTimeoutError::Disconnected) => break, + } + } + let _ = out_thread.join(); + let _ = err_thread.join(); + let status = child.wait().map_err(|e| e.to_string())?; + if status.success() { + Ok(last_line) + } else { + Err(format!("the update did not finish: {last_line}")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp_file(name: &str, content: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("p2c-versions-{}-{name}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("version.json"); + std::fs::write(&file, content).unwrap(); + file + } + + #[test] + fn equal_versions_do_not_mismatch() { + let s = status("3.0.0", Some("3.0.0".into())); + assert_eq!( + s, + VersionStatus { app: "3.0.0".into(), skills: Some("3.0.0".into()), mismatch: false, skills_ahead: false } + ); + } + + #[test] + fn different_versions_mismatch_in_either_direction() { + assert!(status("3.0.0", Some("2.11.0".into())).mismatch); + assert!(status("3.0.0", Some("3.1.0".into())).mismatch); + } + + #[test] + fn skills_ahead_names_which_direction_the_mismatch_runs() { + assert!(!status("3.0.0", Some("2.11.0".into())).skills_ahead); + assert!(status("3.0.0", Some("3.1.0".into())).skills_ahead); + assert!(!status("3.0.0", Some("3.0.0".into())).skills_ahead); + } + + #[test] + fn an_unknown_or_odd_version_never_mismatches() { + assert!(!status("3.0.0", None).mismatch); + assert!(!status("3.0.0", Some("3.0.0-beta".into())).mismatch); + assert!(!status("3.0", Some("3.0.0".into())).mismatch); + assert!(!status("3.0.0", Some("".into())).mismatch); + } + + #[test] + fn reads_the_version_field_of_a_version_file() { + let file = temp_file("ok", r#"{ "name": "Plan2Code", "version": "2.11.0" }"#); + assert_eq!(version_in(&file).as_deref(), Some("2.11.0")); + } + + #[test] + fn a_missing_or_broken_version_file_reads_as_none() { + let missing = std::env::temp_dir().join("p2c-versions-does-not-exist").join("version.json"); + assert_eq!(version_in(&missing), None); + assert_eq!(version_in(&temp_file("broken", "{ not json")), None); + assert_eq!(version_in(&temp_file("nover", r#"{ "name": "x" }"#)), None); + } + + // `PLAN2CODE_LAUNCHER_DIR` is process-global, so these tests serialize on it. + static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + /// Points `launcher_dir()` at a fresh folder holding a fake `plan2code.js` (plain Node + /// source, no quoting needed), runs `body`, then restores the environment. + fn with_fake_launcher(name: &str, script: &str, body: impl FnOnce() -> T) -> T { + let _guard = ENV_LOCK.lock().unwrap(); + let dir = std::env::temp_dir().join(format!("p2c-versions-launcher-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("plan2code.js"), script).unwrap(); + std::env::set_var("PLAN2CODE_LAUNCHER_DIR", &dir); + let result = body(); + std::env::remove_var("PLAN2CODE_LAUNCHER_DIR"); + let _ = std::fs::remove_dir_all(&dir); + result + } + + #[test] + fn run_update_streams_lines_live_and_returns_the_last_one_on_success() { + let lines = std::sync::Mutex::new(Vec::::new()); + let result = with_fake_launcher("ok", "console.log('line1'); console.log('line2');", || { + run_update_within("9.9.9", Duration::from_secs(10), |line| lines.lock().unwrap().push(line.to_string())) + }); + assert_eq!(result, Ok("line2".to_string())); + assert_eq!(*lines.lock().unwrap(), vec!["line1".to_string(), "line2".to_string()]); + } + + #[test] + fn run_update_pins_the_install_to_the_app_s_own_release_tag() { + let result = with_fake_launcher( + "tag", + "console.log(process.argv.slice(2).join(' '));", + || run_update_within("9.9.9", Duration::from_secs(10), |_| {}), + ); + assert_eq!(result, Ok("update --tag v9.9.9".to_string())); + } + + #[test] + fn run_update_fails_with_the_installer_s_own_last_line() { + let result = with_fake_launcher("fail", "console.log('oops'); process.exit(1);", || { + run_update_within("9.9.9", Duration::from_secs(10), |_| {}) + }); + assert_eq!(result, Err("the update did not finish: oops".to_string())); + } + + #[test] + fn run_update_gives_up_after_its_timeout_and_kills_the_child() { + let result = with_fake_launcher("hang", "setInterval(() => {}, 1000);", || { + run_update_within("9.9.9", Duration::from_millis(300), |_| {}) + }); + assert_eq!(result, Err("the update timed out after 0s".to_string())); + } + + #[test] + fn a_missing_launcher_is_an_error_not_a_panic() { + let result = with_fake_launcher("missing", "", || { + std::fs::remove_file(launcher_dir().unwrap().join("plan2code.js")).unwrap(); + run_update_within("9.9.9", Duration::from_secs(10), |_| {}) + }); + assert!(result.unwrap_err().contains("is missing")); + } +} diff --git a/plan2code-app/src-tauri/tauri.conf.json b/plan2code-app/src-tauri/tauri.conf.json new file mode 100644 index 0000000..5daa8b9 --- /dev/null +++ b/plan2code-app/src-tauri/tauri.conf.json @@ -0,0 +1,35 @@ +{ + "$schema": "https://schema.tauri.app/config/2", + "productName": "Plan2Code", + "version": "3.0.0", + "identifier": "com.plan2code.app", + "build": { + "frontendDist": "../ui", + "beforeDevCommand": "node scripts/vendor.mjs", + "beforeBuildCommand": "node scripts/vendor.mjs" + }, + "app": { + "windows": [ + { + "title": "Plan2Code", + "width": 1280, + "height": 800, + "url": "index.html" + } + ], + "security": { + "csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src ipc: http://ipc.localhost; frame-src http://127.0.0.1:*; object-src 'none'; base-uri 'none'" + }, + "withGlobalTauri": true + }, + "bundle": { + "active": true, + "targets": "all", + "icon": [ + "icons/32x32.png", + "icons/128x128.png", + "icons/icon.icns", + "icons/icon.ico" + ] + } +} diff --git a/plan2code-app/src-tauri/tests/agent_manager.rs b/plan2code-app/src-tauri/tests/agent_manager.rs new file mode 100644 index 0000000..43c2135 --- /dev/null +++ b/plan2code-app/src-tauri/tests/agent_manager.rs @@ -0,0 +1,301 @@ +//! The agent lifecycle against the fake agent in a real pseudo-terminal. Real +//! agents are never started here: `PLAN2CODE_APP_AGENT_BIN` points every agent +//! kind at the fake one. + +use std::path::PathBuf; +use std::sync::mpsc::{channel, Receiver, RecvTimeoutError}; +use std::sync::{Arc, Mutex, Once}; +use std::time::{Duration, Instant}; + +use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentSnapshot, AgentState}; +use plan2code_app_lib::agents::{AgentKind, PermissionMode, AGENT_BIN_ENV}; + +mod common; +use common::process_alive; + +const TIMEOUT: Duration = Duration::from_secs(20); +const READY: &str = "FAKE-AGENT ready"; + +struct Harness { + manager: AgentManager, + rx: Receiver, + /// Everything the agents printed, in order. + seen: String, + /// Every state change, in order. + states: Vec, + /// How many of `states` `wait_state` has already looked at. + cursor: usize, +} + +impl Harness { + fn new() -> Harness { + static BIN: Once = Once::new(); + BIN.call_once(|| std::env::set_var(AGENT_BIN_ENV, common::fake_agent())); + let (tx, rx) = channel(); + let tx = Mutex::new(tx); + let sink = Arc::new(move |event| { + let _ = tx.lock().unwrap().send(event); + }); + Harness { manager: AgentManager::new(PathBuf::from("."), sink), rx, seen: String::new(), states: Vec::new(), cursor: 0 } + } + + fn take(&mut self, event: AgentEvent) { + match event { + AgentEvent::Output(bytes) => { + let text = String::from_utf8_lossy(&bytes).into_owned(); + // Windows' pseudo-terminal asks where the cursor is (ESC [ 6 n) + // and holds the output until told, as xterm does on its own. + for _ in text.matches("[6n") { + self.manager.input(b"\x1b[1;1R").unwrap(); + } + self.seen.push_str(&text); + } + AgentEvent::State(snapshot) => self.states.push(snapshot), + } + } + + /// Handle events for `how_long`, answering the terminal's questions. + fn pump_for(&mut self, how_long: Duration) { + let deadline = Instant::now() + how_long; + loop { + let left = deadline.saturating_duration_since(Instant::now()); + match self.rx.recv_timeout(left) { + Ok(event) => self.take(event), + Err(_) => return, + } + } + } + + fn wait_for_output(&mut self, needle: &str, times: usize) { + let deadline = Instant::now() + TIMEOUT; + while self.seen.matches(needle).count() < times { + let left = deadline.saturating_duration_since(Instant::now()); + match self.rx.recv_timeout(left) { + Ok(event) => self.take(event), + Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => { + panic!("never saw {needle:?} {times} time(s); got {:?}", self.seen) + } + } + } + } + + /// The next state change (after the last one this returned) that matches. + fn wait_state(&mut self, what: &str, matches: impl Fn(&AgentSnapshot) -> bool) -> AgentSnapshot { + let deadline = Instant::now() + TIMEOUT; + loop { + while self.cursor < self.states.len() { + let snapshot = self.states[self.cursor].clone(); + self.cursor += 1; + if matches(&snapshot) { + return snapshot; + } + } + let left = deadline.saturating_duration_since(Instant::now()); + match self.rx.recv_timeout(left) { + Ok(event) => self.take(event), + Err(_) => panic!("never saw the state {what}; got {:?}", self.states), + } + } + } + + fn start_and_wait_ready(&mut self) { + self.manager.start(AgentKind::Claude, None, None, PermissionMode::Bypass, None).expect("start the fake agent"); + self.wait_for_output(READY, 1); + } + + fn type_line(&self, line: &str) { + self.manager.input(format!("{line}\r").as_bytes()).unwrap(); + } +} + +fn is_running(snapshot: &AgentSnapshot) -> bool { + snapshot.state == AgentState::Running +} + +#[test] +fn a_second_start_while_running_is_refused() { + let mut h = Harness::new(); + h.start_and_wait_ready(); + let generation = h.manager.snapshot().generation; + + let refused = h.manager.start(AgentKind::Devin, None, None, PermissionMode::Bypass, None); + assert!(refused.is_err(), "a second start must be refused"); + let after = h.manager.snapshot(); + assert_eq!(after.state, AgentState::Running); + assert_eq!(after.generation, generation, "the running agent was replaced"); + h.manager.stop(); +} + +#[test] +fn restart_keeps_the_previous_agent_kind_mode_model_and_effort() { + let mut h = Harness::new(); + h.manager + .start(AgentKind::Codex, Some("gpt-5".to_string()), Some("high".to_string()), PermissionMode::Checked, None) + .expect("start the fake agent"); + h.wait_for_output(READY, 1); + let before = h.manager.snapshot(); + assert_eq!(before.kind, Some(AgentKind::Codex)); + assert_eq!(before.mode, Some(PermissionMode::Checked)); + assert_eq!(h.manager.model_and_effort(), (Some("gpt-5".to_string()), Some("high".to_string()))); + + h.manager.restart().unwrap(); + h.wait_for_output(READY, 2); + let after = h.manager.snapshot(); + assert_eq!(after.kind, Some(AgentKind::Codex), "restart must keep the same agent"); + assert_eq!(after.mode, Some(PermissionMode::Checked), "restart must keep the same permission mode"); + assert_eq!( + h.manager.model_and_effort(), + (Some("gpt-5".to_string()), Some("high".to_string())), + "restart must keep the same model and effort" + ); + h.manager.stop(); +} + +#[test] +fn restart_between_steps_replaces_the_agent_at_once() { + let mut h = Harness::new(); + h.start_and_wait_ready(); + let generation = h.manager.snapshot().generation; + + h.manager.restart().unwrap(); + + let now = h.manager.snapshot(); + assert_eq!(now.state, AgentState::Running); + assert!(now.generation > generation, "a fresh agent was not started"); + h.wait_for_output(READY, 2); + h.manager.stop(); +} + +#[test] +fn restart_mid_step_kills_the_step_at_once_instead_of_waiting_for_it() { + let mut h = Harness::new(); + h.start_and_wait_ready(); + h.type_line("STEP 30"); + h.wait_for_output("working 1/30", 1); + + let started = Instant::now(); + h.manager.restart().unwrap(); + + // Running again straight away: no wait for the step to finish. + h.wait_state("Running again", is_running); + h.wait_for_output(READY, 2); + assert!(started.elapsed() < Duration::from_secs(5), "restart must not wait on the step; took {:?}", started.elapsed()); + assert!(!h.seen.contains("STEP DONE"), "the step should have been cut short, not finished"); + h.manager.stop(); +} + +#[test] +fn an_agent_that_exits_by_itself_ends_with_its_code_and_nothing_restarts() { + let mut h = Harness::new(); + h.start_and_wait_ready(); + h.type_line("EXIT 7"); + + let ended = h.wait_state("Ended", |s| matches!(s.state, AgentState::Ended { .. })); + match &ended.state { + AgentState::Ended { reason } => assert!(reason.contains('7'), "reason was {reason:?}"), + other => panic!("expected Ended, got {other:?}"), + } + + // Nothing starts without a press. + h.pump_for(Duration::from_millis(1500)); + assert!(matches!(h.manager.snapshot().state, AgentState::Ended { .. })); + assert_eq!(h.seen.matches(READY).count(), 1, "an agent started by itself"); + assert!(!h.manager.is_active()); + + // A press of Restart starts a fresh one on the same brief. + h.manager.restart().unwrap(); + h.wait_for_output(READY, 2); + assert_eq!(h.manager.snapshot().state, AgentState::Running); + h.manager.stop(); +} + +#[test] +fn quitting_with_a_running_agent_stops_it() { + let mut h = Harness::new(); + h.start_and_wait_ready(); + assert!(h.manager.is_active()); + h.type_line("PID"); + h.wait_for_output("PID ", 1); + let pid = h.seen.rsplit("PID ").next().unwrap().trim_start().split(|c: char| !c.is_ascii_digit()).next().unwrap().parse::().expect("the agent's pid"); + assert!(process_alive(pid), "the agent should be running before the stop"); + + h.manager.stop(); + + assert!(!process_alive(pid), "the agent's process outlived stop()"); + + assert_eq!(h.manager.snapshot().state, AgentState::Idle); + assert!(!h.manager.is_active()); + // The stopped agent does not come back or print again. + let before = h.seen.len(); + h.pump_for(Duration::from_millis(1000)); + assert!(!h.seen[before..].contains(READY), "an agent started after the stop"); + assert!(h.manager.restart().is_err(), "there is nothing left to restart"); +} + +#[test] +fn the_replay_buffer_holds_recent_output_and_clears_on_a_fresh_agent() { + let mut h = Harness::new(); + h.start_and_wait_ready(); + let replay = String::from_utf8_lossy(&h.manager.replay()).into_owned(); + assert!(replay.contains(READY), "replay should hold what was just printed; got {replay:?}"); + + h.manager.restart().unwrap(); + h.wait_for_output(READY, 2); + let replay = String::from_utf8_lossy(&h.manager.replay()).into_owned(); + assert_eq!(replay.matches(READY).count(), 1, "a fresh agent's replay must not carry the old one's output"); + h.manager.stop(); +} + +#[test] +fn a_restart_runs_the_brief_hook_and_the_bar_gets_its_note() { + let mut h = Harness::new(); + let runs = Arc::new(Mutex::new(0)); + let counter = Arc::clone(&runs); + h.manager.set_before_fresh(Arc::new(move || { + *counter.lock().unwrap() += 1; + Some("Brief ready on the dashboard".to_string()) + })); + h.start_and_wait_ready(); + assert_eq!(*runs.lock().unwrap(), 0, "a first start leaves no brief"); + assert_eq!(h.manager.snapshot().brief_note, None); + + h.manager.restart().unwrap(); + + assert_eq!(*runs.lock().unwrap(), 1, "the restart did not run the brief once"); + assert_eq!(h.manager.snapshot().brief_note.as_deref(), Some("Brief ready on the dashboard")); + h.manager.stop(); +} + +#[test] +fn the_agent_gets_the_in_app_signal_and_a_restart_keeps_it() { + let mut h = Harness::new(); + h.manager.set_env(vec![ + ("PLAN2CODE_IN_APP".to_string(), "1".to_string()), + ("PLAN2CODE_CONSOLE_SID".to_string(), "sid-window-a".to_string()), + ]); + h.start_and_wait_ready(); + h.type_line("ENV PLAN2CODE_IN_APP"); + h.wait_for_output("ENV PLAN2CODE_IN_APP=1", 1); + h.type_line("ENV PLAN2CODE_CONSOLE_SID"); + h.wait_for_output("ENV PLAN2CODE_CONSOLE_SID=sid-window-a", 1); + + // The signal changes with the console; a Restart starts on the newest. + h.manager.set_env(vec![("PLAN2CODE_CONSOLE_SID".to_string(), "sid-window-b".to_string())]); + h.manager.restart().unwrap(); + h.wait_for_output(READY, 2); + h.type_line("ENV PLAN2CODE_CONSOLE_SID"); + h.wait_for_output("ENV PLAN2CODE_CONSOLE_SID=sid-window-b", 1); + h.type_line("ENV PLAN2CODE_IN_APP"); + h.wait_for_output("ENV PLAN2CODE_IN_APP=\r", 1); + h.manager.stop(); +} + +#[test] +fn an_agent_with_no_signal_set_gets_none() { + let mut h = Harness::new(); + h.start_and_wait_ready(); + h.type_line("ENV PLAN2CODE_IN_APP"); + h.wait_for_output("ENV PLAN2CODE_IN_APP=", 1); + assert!(!h.seen.contains("ENV PLAN2CODE_IN_APP=1")); + h.manager.stop(); +} diff --git a/plan2code-app/src-tauri/tests/common/mod.rs b/plan2code-app/src-tauri/tests/common/mod.rs new file mode 100644 index 0000000..939cbcb --- /dev/null +++ b/plan2code-app/src-tauri/tests/common/mod.rs @@ -0,0 +1,38 @@ +//! Shared by the integration tests: where the fake agent program is, and +//! whether a process id is still alive. + +use std::path::PathBuf; +use std::process::Command; +use std::sync::Once; + +/// Is a process with this id still there? Asks the operating system. +#[allow(dead_code)] +pub fn process_alive(pid: u32) -> bool { + if cfg!(windows) { + let out = Command::new("tasklist").args(["/FI", &format!("PID eq {pid}"), "/NH"]).output().unwrap(); + String::from_utf8_lossy(&out.stdout).split_whitespace().any(|word| word == pid.to_string()) + } else { + Command::new("kill").args(["-0", &pid.to_string()]).status().map(|s| s.success()).unwrap_or(false) + } +} + +pub fn fake_agent() -> PathBuf { + // `cargo test` does not build another package's program, so build it once. + static BUILD: Once = Once::new(); + BUILD.call_once(|| { + let status = Command::new(env!("CARGO")) + .args(["build", "-p", "fake-agent"]) + .status() + .expect("run cargo"); + assert!(status.success(), "could not build the fake agent"); + }); + // The test binary is in target//deps; the fake agent is one up. + let exe = std::env::current_exe().unwrap(); + let path = exe + .parent() + .and_then(|deps| deps.parent()) + .unwrap() + .join(format!("fake-agent{}", std::env::consts::EXE_SUFFIX)); + assert!(path.exists(), "{} is missing after building the fake agent", path.display()); + path +} diff --git a/plan2code-app/src-tauri/tests/console_supervisor.rs b/plan2code-app/src-tauri/tests/console_supervisor.rs new file mode 100644 index 0000000..7dd5a15 --- /dev/null +++ b/plan2code-app/src-tauri/tests/console_supervisor.rs @@ -0,0 +1,100 @@ +//! The supervisor against the real console: a temp project, no agent, no +//! Tauri. `PLAN2CODE_CONSOLE_DIR` points the lookup at the repo's own console +//! source and `PLAN2CODE_CONSOLE_HOME` keeps the sessions out of the user's +//! real console folder. Skipped entirely when node is not on PATH. + +use std::path::PathBuf; +use std::process::Command; +use std::time::{Duration, Instant}; + +use plan2code_app_lib::console_supervisor::{app_origin, ConsoleSupervisor}; + +fn have_node() -> bool { + Command::new("node") + .arg("--version") + .output() + .map(|o| o.status.success()) + .unwrap_or(false) +} + +fn repo_console_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console") +} + +fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("p2c-sup-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn setup() -> Option { + if !have_node() { + eprintln!("skipping: node is not on PATH"); + return None; + } + let console = repo_console_dir(); + assert!(console.join("console.mjs").is_file(), "console source missing at {}", console.display()); + std::env::set_var("PLAN2CODE_CONSOLE_DIR", &console); + std::env::set_var("PLAN2CODE_CONSOLE_HOME", temp_dir("home")); + std::env::set_var("PLAN2CODE_NO_BROWSER", "1"); + Some(temp_dir("project")) +} + +fn kill_pid(pid: u32) { + #[cfg(windows)] + let _ = Command::new("taskkill") + .args(["/PID", &pid.to_string(), "/F"]) + .output(); + #[cfg(not(windows))] + let _ = Command::new("kill").args(["-9", &pid.to_string()]).output(); +} + +/// The detached server can take a beat to bind or die; ask until `want` holds. +fn until_health(sup: &ConsoleSupervisor, want: bool) -> bool { + let deadline = Instant::now() + Duration::from_secs(15); + while Instant::now() < deadline { + if sup.health() == want { + return true; + } + std::thread::sleep(Duration::from_millis(200)); + } + false +} + +#[test] +fn starts_answers_and_stops() { + let Some(project) = setup() else { return }; + let mut sup = ConsoleSupervisor::start(project, app_origin().to_string()).expect("start"); + assert!(!sup.session().sid.is_empty()); + assert!(sup.session().url.starts_with("http://127.0.0.1:")); + assert!(sup.session().pid > 0); + assert!(until_health(&sup, true), "the console URL never answered"); + + sup.stop().expect("stop"); + assert!(until_health(&sup, false), "the console still answered after stop()"); +} + +#[test] +fn a_killed_console_is_dead_and_restarts() { + let Some(project) = setup() else { return }; + let mut sup = ConsoleSupervisor::start(project, app_origin().to_string()).expect("start"); + assert!(until_health(&sup, true), "the console URL never answered"); + let first_sid = sup.session().sid.clone(); + + kill_pid(sup.session().pid); + assert!(until_health(&sup, false), "a killed console still looked alive"); + + assert!(sup.restart_if_dead().expect("restart"), "restart_if_dead did nothing"); + assert_eq!(sup.session().sid, first_sid, "a dead console comes back on the same session, so its page and place survive"); + assert!(until_health(&sup, true), "the restarted console never answered"); + sup.stop().expect("stop"); +} + +#[test] +fn a_live_console_is_not_restarted() { + let Some(project) = setup() else { return }; + let mut sup = ConsoleSupervisor::start(project, app_origin().to_string()).expect("start"); + assert!(until_health(&sup, true), "the console URL never answered"); + assert!(!sup.restart_if_dead().expect("restart check")); + sup.stop().expect("stop"); +} diff --git a/plan2code-app/src-tauri/tests/pty_host.rs b/plan2code-app/src-tauri/tests/pty_host.rs new file mode 100644 index 0000000..af094d0 --- /dev/null +++ b/plan2code-app/src-tauri/tests/pty_host.rs @@ -0,0 +1,154 @@ +//! The PTY host against the fake agent in a real pseudo-terminal. Real agents +//! are never started here. + +use std::sync::mpsc::{channel, Receiver, RecvTimeoutError}; +use std::time::{Duration, Instant}; + +use plan2code_app_lib::pty_host::{PtyHost, StartOptions}; + +mod common; +use common::{fake_agent, process_alive}; + +fn start_fake() -> (PtyHost, Receiver>) { + let (tx, rx) = channel(); + let host = PtyHost::start( + StartOptions { + program: fake_agent().to_string_lossy().into_owned(), + args: vec![], + env: vec![], + cwd: None, + cols: 80, + rows: 24, + }, + move |bytes| { + let _ = tx.send(bytes); + }, + ) + .expect("start the fake agent"); + (host, rx) +} + +/// Collect output until `needle` appears; panic with what arrived if it does not. +/// Windows' pseudo-terminal asks where the cursor is (ESC [ 6 n) and holds the +/// output until it is told, as a real terminal such as xterm does on its own. +fn wait_for(host: &PtyHost, rx: &Receiver>, seen: &mut String, needle: &str) { + let deadline = Instant::now() + Duration::from_secs(20); + while !seen.contains(needle) { + let left = deadline.saturating_duration_since(Instant::now()); + match rx.recv_timeout(left) { + Ok(bytes) => { + let text = String::from_utf8_lossy(&bytes); + for _ in text.matches("") { + host.write(b"").unwrap(); + } + seen.push_str(&text); + } + Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => { + panic!("never saw {needle:?}; got {seen:?}") + } + } + } +} + +#[test] +fn banner_arrives() { + let (host, rx) = start_fake(); + let mut seen = String::new(); + wait_for(&host, &rx, &mut seen, "FAKE-AGENT ready"); + host.kill().unwrap(); +} + +#[test] +fn typed_line_is_echoed() { + let (host, rx) = start_fake(); + let mut seen = String::new(); + wait_for(&host, &rx, &mut seen, "FAKE-AGENT ready"); + host.write(b"hello there\r").unwrap(); + wait_for(&host, &rx, &mut seen, "echo: hello there"); + host.kill().unwrap(); +} + +#[test] +fn resize_reaches_the_child() { + let (host, rx) = start_fake(); + let mut seen = String::new(); + wait_for(&host, &rx, &mut seen, "SIZE 80x24"); + host.resize(100, 30).unwrap(); + wait_for(&host, &rx, &mut seen, "SIZE 100x30"); + host.kill().unwrap(); +} + +#[test] +fn exit_code_is_returned() { + let (host, rx) = start_fake(); + let mut seen = String::new(); + wait_for(&host, &rx, &mut seen, "FAKE-AGENT ready"); + host.write(b"EXIT 3\r").unwrap(); + assert_eq!(host.wait().unwrap(), 3); +} + +#[test] +fn kill_ends_a_running_step() { + let (host, rx) = start_fake(); + let mut seen = String::new(); + wait_for(&host, &rx, &mut seen, "FAKE-AGENT ready"); + host.write(b"STEP 30\r").unwrap(); + wait_for(&host, &rx, &mut seen, "working 1/30"); + let started = Instant::now(); + host.kill().unwrap(); + host.wait().unwrap(); + assert!(started.elapsed() < Duration::from_secs(10), "kill took too long"); +} + +/// An npm `.cmd` shim: `cmd.exe` is the directly spawned process, the real +/// program (here, the fake agent) its grandchild. `kill` must end both, not +/// just `cmd.exe` (Task 9.8). +#[cfg(windows)] +#[test] +fn kill_ends_a_cmd_wrapped_grandchild_too() { + use plan2code_app_lib::agents::windows_command; + use std::fs; + + let dir = std::env::temp_dir().join(format!("plan2code-pty-cmdshim-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let shim = dir.join("shim.cmd"); + fs::write(&shim, format!("@echo off\r\n\"{}\" %*\r\n", fake_agent().display())).unwrap(); + + let (program, args) = windows_command("shim", vec![], &dir.to_string_lossy()); + let path = format!("{};{}", dir.to_string_lossy(), std::env::var("PATH").unwrap_or_default()); + let (tx, rx) = channel(); + let host = PtyHost::start( + // `cmd /c shim.cmd` is a bare name: like a real npm shim, cmd.exe + // only finds it on PATH, never by the current directory alone. + StartOptions { program, args, env: vec![("PATH".to_string(), path)], cwd: None, cols: 80, rows: 24 }, + move |bytes| { + let _ = tx.send(bytes); + }, + ) + .expect("start the cmd-wrapped fake agent"); + + let mut seen = String::new(); + wait_for(&host, &rx, &mut seen, "FAKE-AGENT ready"); + host.write(b"PID\r").unwrap(); + wait_for(&host, &rx, &mut seen, "PID "); + let pid: u32 = seen + .rsplit("PID ") + .next() + .unwrap() + .trim_start() + .split(|c: char| !c.is_ascii_digit()) + .next() + .unwrap() + .parse() + .expect("the grandchild's pid"); + assert!(process_alive(pid), "the grandchild should be running before kill"); + + host.kill().unwrap(); + let deadline = Instant::now() + Duration::from_secs(10); + while process_alive(pid) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + assert!(!process_alive(pid), "the grandchild outlived kill()"); + let _ = fs::remove_dir_all(&dir); +} diff --git a/plan2code-app/ui/app.js b/plan2code-app/ui/app.js new file mode 100644 index 0000000..90d1ca0 --- /dev/null +++ b/plan2code-app/ui/app.js @@ -0,0 +1,857 @@ +// The app page: the top bar, the console dashboard in an iframe, and the +// agent's terminal panel docked at the bottom with a drag handle. + +import { mountTerminal } from './terminal.js'; +import { nudgeDue } from './meter.js'; + +const { invoke, Channel } = window.__TAURI__.core; + +const projectDirEl = document.getElementById('project-dir'); +const agentNameEl = document.getElementById('agent-name'); +const agentStatusEl = document.getElementById('agent-status'); +const restartBtn = document.getElementById('agent-restart'); +const changeAgentBtn = document.getElementById('change-agent'); +const changeProjectBtn = document.getElementById('change-project'); +const launchCard = document.getElementById('launch-card'); +const launchAgentEl = document.getElementById('launch-agent'); +const launchMissingEl = document.getElementById('launch-missing'); +const launchModelEl = document.getElementById('launch-model'); +const launchEffortRow = document.getElementById('launch-effort-row'); +const launchEffortEl = document.getElementById('launch-effort'); +const launchBypassEl = document.getElementById('launch-bypass'); +const launchBypassWarningEl = document.getElementById('launch-bypass-warning'); +const launchStartBtn = document.getElementById('launch-start'); +const firstRunEl = document.getElementById('first-run'); +const firstRunListEl = document.getElementById('first-run-list'); +const firstRunStartBtn = document.getElementById('first-run-start'); +const meterSlot = document.getElementById('bar-slot-meter'); +const nudgeEl = document.getElementById('context-nudge'); +const nudgeRestartBtn = document.getElementById('context-restart'); +const versionEl = document.getElementById('version-update'); +const versionTextEl = document.getElementById('version-update-text'); +const versionBtn = document.getElementById('version-update-button'); +const versionRestartBtn = document.getElementById('version-update-restart'); +const consoleStatusEl = document.getElementById('console-status'); +const permissionsNoteEl = document.getElementById('permissions-note'); +const consoleAgainBtn = document.getElementById('console-again'); +const frame = document.getElementById('console-frame'); +const stateBox = document.getElementById('dashboard-state'); +const stateText = document.getElementById('dashboard-state-text'); +const stateButton = document.getElementById('dashboard-state-button'); +const stateCancelEl = document.getElementById('dashboard-state-cancel'); +const workspaceEl = document.getElementById('workspace'); +const termPanel = document.getElementById('term-panel'); +const termHandle = document.getElementById('term-handle'); +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 currentPageEl = document.getElementById('current-page'); + +const STATUS_POLL_MS = 5000; +const METER_POLL_MS = 2000; +const BADGE_POLL_MS = 2000; +const MIN_PANE = 0.10; +const MAX_PANE = 0.60; +const MAXIMIZED_PANE = 0.80; +// Below this share of the window, a collapsed-or-small pane can hide a +// question the agent is quietly waiting on. +const SMALL_PANE = 0.15; +const QUIET_BADGE_MS = 10000; + +const AGENT_LABELS = { claude: 'Claude Code', devin: 'Devin', codex: 'Codex' }; +// Devin's model ids already carry their effort (`swe-2-high`); only these two +// take a separate effort, at the levels their own CLI documents. +const EFFORT_OPTIONS = { + claude: ['low', 'medium', 'high', 'xhigh', 'max'], + codex: ['low', 'medium', 'high'], +}; + +// What the Rust agent host last said: idle, running or ended. +let agent = { state: 'idle', kind: null, generation: 0 }; +const agentActive = () => agent.state === 'running'; + +// The context percent that triggers the Restart suggestion, from the app's +// settings (main() reads it), and the agent run the suggestion was shown for: +// it appears once per run, not again after it is dismissed by a Restart. +let nudgePercent = 70; +let nudgeShownFor = null; + +const terminal = await mountTerminal(document.getElementById('term'), { + onInput: (data) => { + if (agentActive()) invoke('agent_input', { data }); + }, + onResize: (cols, rows) => { + if (agentActive()) invoke('agent_resize', { cols, rows }); + }, +}); + +// 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(); +agentChannel.onmessage = (message) => { + if (message instanceof ArrayBuffer) { + terminal.write(new Uint8Array(message)); + lastOutputAt = Date.now(); + updateBadge(); + } else if (message && typeof message === 'object' && 'state' in message) { + applyAgentState(message); + } +}; + +function applyAgentState(next, { skipReset } = {}) { + const wasEnded = agent.state === 'ended'; + // A new generation is a fresh agent: it starts on a clean screen. Skipped + // when catching up to an agent that was already running before this page + // mounted (a reload): its replayed output, not a blank screen, belongs here, + // and the channel that delivers it races this call, not waits for it. + const freshScreen = next.generation !== agent.generation && !skipReset; + if (freshScreen) { + terminal.reset(); + lastOutputAt = Date.now(); + } + agent = next; + const label = AGENT_LABELS[agent.kind] || ''; + const active = agentActive(); + + agentNameEl.textContent = active ? label : ''; + if (active) { + // Only ever auto-*hides* the card (the agent just started); it must + // never auto-*show* it on 'ended' or 'idle' — that is Change agent's + // job alone, so the card does not pop up over the dashboard uninvited. + launchCard.hidden = true; + hideFirstRun(); + } + // One rule throughout: Restart while running or ended (it keeps the + // previous agent, model, effort and mode); Change agent only once ended, + // when there is a real choice to make again. + restartBtn.hidden = !(active || agent.state === 'ended'); + changeAgentBtn.hidden = agent.state !== 'ended'; + // Checked mode needs no banner; bypass always gets one, naming the agent it + // applies to, for exactly as long as that agent runs. + const bypassActive = active && agent.mode === 'bypass'; + permissionsNoteEl.hidden = !bypassActive; + permissionsNoteEl.textContent = bypassActive ? `Permission checks are off for ${label || 'the running agent'}` : ''; + restartBtn.title = agent.state === 'ended' ? 'Start a fresh agent on the same brief' : 'Replace the agent with a fresh one, on a fresh context window'; + if (freshScreen || agent.state !== 'running') nudgeEl.hidden = true; + if (!agentActive()) renderMeter({ kind: 'unknown' }); + // 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') { + terminal.write(' + +[Fresh agent started. Waiting for the dashboard...] + +'); + } + + if (agent.state === 'ended') { + agentStatusEl.textContent = `${label || 'The agent'} ended: ${agent.reason}. Nothing starts until you press Restart.`; + // 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 Restart 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. + agentStatusEl.textContent = agent.briefNote || ''; + } + agentStatusEl.title = agentStatusEl.textContent; + updateBadge(); +} + +// True from a confirmed Restart until the fresh agent's dashboard page is +// announced (showAnnounced below): the frame stays blanked with a message the +// whole time, since the restarted agent must boot and run the skill again +// before anything can show. +let restarting = false; + +function confirmRestart(onYes) { + if (agent.state !== 'running') { + onYes(); + return; + } + showState( + 'Restart the agent on a fresh context window? What it was doing is not saved.', + 'Restart', + () => { + restarting = true; + currentUrl = null; + frameReady = false; + currentPageEl.textContent = ''; + 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.')) + ); +} + +// What the launch card offers for each agent: whether its CLI was found on +// PATH (else how to install it) and whether it takes its own effort. +let agentAvailability = {}; + +async function loadAgentAvailability() { + try { + const list = await invoke('agent_availability'); + agentAvailability = Object.fromEntries(list.map((entry) => [entry.id, entry])); + } catch { + // Nothing to show is not a reason to block the card: Start just tries it. + agentAvailability = {}; + } +} + +function refreshLaunchCard() { + const kind = launchAgentEl.value; + const info = agentAvailability[kind]; + const installed = info ? info.installed : true; + launchStartBtn.disabled = !installed; + launchMissingEl.hidden = installed; + launchMissingEl.replaceChildren(); + if (!installed) { + const label = (info && info.label) || AGENT_LABELS[kind] || kind; + launchMissingEl.append(`${label} was not found on PATH. Install it: `); + const code = document.createElement('code'); + code.textContent = (info && info.installHint) || ''; + launchMissingEl.append(code); + } + const levels = EFFORT_OPTIONS[kind] || []; + launchEffortRow.hidden = levels.length === 0; + launchEffortEl.replaceChildren(); + const def = document.createElement('option'); + def.value = ''; + def.textContent = 'Default'; + launchEffortEl.append(def); + for (const level of levels) { + const option = document.createElement('option'); + option.value = level; + option.textContent = level[0].toUpperCase() + level.slice(1); + launchEffortEl.append(option); + } +} + +launchAgentEl.onchange = refreshLaunchCard; +launchBypassEl.onchange = () => { + launchBypassWarningEl.hidden = !launchBypassEl.checked; +}; + +function showLaunchCard() { + hideState(); + hideFirstRun(); + refreshLaunchCard(); + launchCard.hidden = false; +} + +function hideLaunchCard() { + launchCard.hidden = true; +} + +// One row of the first-run checklist: a pass/fail mark, a title and a detail +// line (plain text or a built node, such as the CLI-by-CLI list). +function firstRunRow(pass, title, detail) { + const row = document.createElement('li'); + row.className = `first-run-row ${pass ? 'is-pass' : 'is-fail'}`; + const mark = document.createElement('span'); + mark.className = 'first-run-mark'; + mark.textContent = pass ? '✓' : '!'; + const body = document.createElement('div'); + body.className = 'first-run-body'; + const titleEl = document.createElement('div'); + titleEl.className = 'first-run-title'; + titleEl.textContent = title; + body.append(titleEl); + if (detail) { + const detailEl = document.createElement('div'); + detailEl.className = 'first-run-detail'; + if (typeof detail === 'string') detailEl.textContent = detail; + else detailEl.append(detail); + body.append(detailEl); + } + row.append(mark, body); + return row; +} + +// Node is always a pass here: `main()` on the Rust side already exits before +// the window opens on anything else (Task 1.7), so this row is a confirmation, +// 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}` : ''}`; + firstRunListEl.append(firstRunRow(true, 'Node.js', nodeDetail)); + + const agentsKnown = Object.values(agentAvailability); + const anyAgentInstalled = agentsKnown.length === 0 || agentsKnown.some((a) => a.installed); + const agentsDetail = document.createElement('span'); + if (agentsKnown.length === 0) { + agentsDetail.textContent = 'Could not check.'; + } else { + agentsKnown.forEach((a, i) => { + if (i > 0) agentsDetail.append(', '); + agentsDetail.append(`${a.label}: ${a.installed ? a.path : 'not found'}`); + }); + } + firstRunListEl.append(firstRunRow(anyAgentInstalled, 'An agent CLI', agentsDetail)); + + firstRunListEl.append(firstRunRow(Boolean(state.projectDir), 'Project folder', state.projectDir || 'not chosen yet')); + + const skillsOk = Boolean(state.skillsVersion); + const skillsDetail = skillsOk ? `v${state.skillsVersion}` : 'not found; run `plan2code update`'; + firstRunListEl.append(firstRunRow(skillsOk, 'Plan2Code skills', skillsDetail)); + + firstRunStartBtn.disabled = !(anyAgentInstalled && state.projectDir && skillsOk); +} + +function showFirstRun(state) { + hideState(); + hideLaunchCard(); + renderFirstRun(state); + firstRunEl.hidden = false; +} + +function hideFirstRun() { + firstRunEl.hidden = true; +} + +firstRunStartBtn.onclick = async () => { + hideFirstRun(); + try { + await invoke('save_first_run_done'); + } catch { + // Not remembered is not fatal: the checklist just shows again next launch. + } + showLaunchCard(); +}; + +async function startAgent(event) { + if (event) event.preventDefault(); + const kind = launchAgentEl.value; + const model = launchModelEl.value.trim() || null; + const effort = (EFFORT_OPTIONS[kind] || []).length > 0 ? launchEffortEl.value || null : null; + const mode = launchBypassEl.checked ? 'bypass' : 'checked'; + agentStatusEl.textContent = ''; + showState('Waiting for the agent to open the dashboard'); + const { cols, rows } = terminal.size(); + try { + await invoke('agent_start', { kind, model, effort, mode, cols, rows, onOutput: agentChannel }); + terminal.focus(); + } catch (error) { + agentStatusEl.textContent = `Could not start the agent: ${error}`; + showLaunchCard(); + } +} + +async function agentAction(command) { + try { + await invoke(command); + terminal.focus(); + } catch (error) { + agentStatusEl.textContent = String(error); + } +} + +launchCard.addEventListener('submit', startAgent); +restartBtn.onclick = () => confirmRestart(() => agentAction('agent_restart')); +nudgeRestartBtn.onclick = () => confirmRestart(() => agentAction('agent_restart')); +// Only ever enabled once the agent has ended: nothing active to lose, so no confirm. +changeAgentBtn.onclick = () => showLaunchCard(); + +// The pane's shape: which edge it docks to, its share of the window when it +// is neither collapsed nor maximized (dragging and the settings file both +// deal in that share, never in pixels), and whether it is collapsed. +// Maximized is a transient view, never saved: the pane comes back at its +// last saved share on the next launch. +let paneDock = 'bottom'; +let paneFraction = 0.25; +let paneCollapsed = false; +let paneMaximized = false; + +const paneExtent = () => (paneDock === 'right' ? window.innerWidth : window.innerHeight); + +function applyPaneLayout() { + workspaceEl.classList.toggle('dock-right', paneDock === 'right'); + termPanel.classList.toggle('collapsed', paneCollapsed); + termHandle.hidden = paneCollapsed; + const sizeProp = paneDock === 'right' ? 'width' : 'height'; + const otherProp = paneDock === 'right' ? 'height' : 'width'; + termPanel.style[otherProp] = ''; + if (paneCollapsed) { + termPanel.style[sizeProp] = ''; + } else { + 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'; + termMaximizeBtn.setAttribute('aria-pressed', String(paneMaximized)); + termCollapseBtn.textContent = paneCollapsed ? 'Expand' : 'Collapse'; + termCollapseBtn.setAttribute('aria-pressed', String(paneCollapsed)); + updateBadge(); +} + +function savePaneSettings() { + invoke('save_term_panel', { dock: paneDock, fraction: paneFraction, collapsed: paneCollapsed }).catch(() => { + // A settings file that cannot be written must not stop the pane from working. + }); +} + +termDockBtn.onclick = () => { + paneDock = paneDock === 'right' ? 'bottom' : 'right'; + applyPaneLayout(); + savePaneSettings(); +}; +termMaximizeBtn.onclick = () => { + paneMaximized = !paneMaximized; + applyPaneLayout(); +}; +termCollapseBtn.onclick = () => { + paneCollapsed = !paneCollapsed; + if (!paneCollapsed) terminal.focus(); + applyPaneLayout(); + savePaneSettings(); +}; + +// Dragging the handle sets the panel's share of the window, along whichever +// edge it is docked to. +termHandle.addEventListener('pointerdown', (event) => { + event.preventDefault(); + termHandle.setPointerCapture(event.pointerId); +}); +termHandle.addEventListener('pointermove', (event) => { + if (!termHandle.hasPointerCapture(event.pointerId)) return; + const extent = paneExtent(); + const wanted = paneDock === 'right' ? window.innerWidth - event.clientX : window.innerHeight - event.clientY; + const clamped = Math.min(Math.max(wanted, extent * MIN_PANE), extent * MAX_PANE); + paneFraction = clamped / extent; + paneMaximized = false; + applyPaneLayout(); +}); +termHandle.addEventListener('pointerup', (event) => { + if (termHandle.hasPointerCapture(event.pointerId)) termHandle.releasePointerCapture(event.pointerId); + savePaneSettings(); +}); + +// When the pane is collapsed or small, the agent's own status line can keep +// redrawing while it is really waiting on a prompt no one is watching: a +// stretch of no new output at all is the giveaway. +let lastOutputAt = Date.now(); + +function updateBadge() { + const small = paneCollapsed || (!paneMaximized && paneFraction < SMALL_PANE); + const quiet = agentActive() && Date.now() - lastOutputAt >= QUIET_BADGE_MS; + termBadgeEl.hidden = !(small && quiet); +} + +// The frame is "showing" only once the console page itself says so (it posts a +// hello to its parent when it draws). The frame's own load event also fires for +// an error page, so it proves nothing: a blocked or dead frame must not look +// like a loaded one. +const HELLO_WAIT_MS = 8000; +let currentUrl = null; +let frameReady = false; +let helloTimer = null; +// Nothing has shown here yet: no agent has opened the dashboard. No polling, +// no "reconnect" button makes sense until that first page lands. +let consoleKnown = false; + +function loadFrame(url) { + currentUrl = url; + frameReady = false; + clearTimeout(helloTimer); + helloTimer = setTimeout(onNoHello, HELLO_WAIT_MS); + frame.src = url; +} + +window.addEventListener('message', (event) => { + if (event.source !== frame.contentWindow) return; + if (!event.data || event.data.plan2code !== 'console-ready') return; + frameReady = true; + clearTimeout(helloTimer); + hideState(); +}); + +// No hello in time: ask the console why, and say so with a way forward. +async function onNoHello() { + if (frameReady || !consoleKnown || restarting) return; + let status = null; + try { + status = await invoke('console_status'); + } catch { + // The status check itself failed; treat it as a console that is not answering. + } + if (!status || status.state !== 'running') { + showState('The console stopped, so the page could not show.', 'Restart 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); + }); + } +} + +function showState(text, buttonLabel, onButton, onCancel) { + hideLaunchCard(); + hideFirstRun(); + stateText.textContent = text; + stateButton.hidden = !buttonLabel; + stateButton.textContent = buttonLabel || ''; + stateButton.onclick = onButton || null; + stateCancelEl.hidden = !onCancel; + stateCancelEl.onclick = onCancel || null; + stateBox.hidden = false; +} + +function hideState() { + stateBox.hidden = true; +} + +let pollTimer = null; + +// Only once the agent has opened a page: brings an idle or dead console back +// on its own session. The app never opens a dashboard on its own (the agent +// does, by running the skill), so there is nothing to start before that. +async function reconnectConsole() { + markConsoleAlive(); + 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); + // An old console cannot be framed: the fix is the skills update, so offer it. + if (String(error).includes('too old')) { + versionTextEl.textContent = 'The installed console is too old for the app'; + versionEl.hidden = false; + } + } +} + +// Health check on a timer. A console that dies after its page showed (it idles +// out, or something ended it) is brought back on the same session, a few times +// at most; before the page ever showed, the person decides with a button. +const RECONNECT_LIMIT = 3; +let reconnects = 0; + +async function pollConsole() { + try { + const status = await invoke('console_status'); + if (status.state === 'running') { + markConsoleAlive(); + return; + } + markConsoleDead(); + if (frameReady && reconnects < RECONNECT_LIMIT) { + reconnects += 1; + showState('The console stopped. Reconnecting'); + await reconnectConsole(); + } else if (!frameReady) { + onNoHello(); + } + } catch { + // A failed check is not proof the console died; look again next tick. + } +} + +// The meter: a bar and a percent for a real or best-effort reading, a dashed +// bar with "about N%" and an "estimate" tag for an estimate, "unknown" when +// nothing is available. Built with DOM calls, never innerHTML. +function renderMeter(reading) { + meterSlot.replaceChildren(); + // Left empty, not even an "unknown" label: #bar-slot-meter:empty hides it, + // so the bar carries nothing until the reading means something. + if (reading.kind === 'unknown') return; + const label = document.createElement('span'); + const track = document.createElement('span'); + track.className = `meter-track ${reading.kind}`; + const fill = document.createElement('span'); + fill.className = 'meter-fill'; + fill.style.width = `${reading.percent}%`; + track.append(fill); + label.textContent = reading.kind === 'estimate' ? `about ${reading.percent}%` : `${reading.percent}%`; + meterSlot.append(track, label); + if (reading.kind === 'estimate') { + const tag = document.createElement('span'); + tag.className = 'meter-tag'; + tag.textContent = 'estimate'; + meterSlot.append(tag); + meterSlot.title = 'Estimated from the text so far: the agent does not report its context size'; + } else if (reading.kind === 'besteffort') { + meterSlot.title = 'Read from the agent\'s session log: undocumented, so it may stop working after an update'; + } else { + meterSlot.title = 'How full the agent context is, as the agent reports it'; + } +} + +// Every two seconds while an agent runs: draw the meter and, once per run, +// suggest a Restart when the context reaches the nudge percent. +async function pollMeter() { + if (!agentActive()) return; + try { + // The reading may land after a Restart: only a reading for the same run counts. + const { generation, state } = agent; + const reading = await invoke('agent_context'); + if (agent.generation !== generation || agent.state !== state) return; + renderMeter(reading); + if (nudgeDue(reading, nudgePercent) && state === 'running' && nudgeShownFor !== generation) { + nudgeShownFor = generation; + nudgeEl.hidden = false; + } + } catch { + // A failed read is not a reading: look again on the next tick. + } +} + +// Once, at start: when the app and the installed skills are on different versions the bar +// says so and offers Update skills. Nothing runs until that button is pressed. +async function checkVersions() { + try { + const status = await invoke('version_status'); + if (!status.mismatch) return; + if (status.skills_ahead) { + // The skills are ahead of this app: another Update skills run cannot help. + versionTextEl.textContent = `The installed skills are v${status.skills}, newer than this app (v${status.app}). Get the new app.`; + versionBtn.hidden = true; + } else { + versionTextEl.textContent = `Skills are v${status.skills}, this app is v${status.app}`; + versionBtn.hidden = false; + } + versionEl.hidden = false; + } catch { + // No version to compare is no reason to nag. + } +} + +versionBtn.onclick = async () => { + versionBtn.disabled = true; + versionRestartBtn.hidden = true; + versionTextEl.textContent = 'Updating Plan2Code...'; + const progress = new Channel(); + progress.onmessage = (line) => { + if (line) versionTextEl.textContent = line; + }; + try { + const outcome = await invoke('update_skills', { progress }); + versionTextEl.textContent = outcome.status.mismatch + ? `Updated, but the mismatch remains (skills v${outcome.status.skills}, app v${outcome.status.app}).` + : 'Updated. Restart the console to use the new version.'; + versionBtn.hidden = true; + versionRestartBtn.hidden = outcome.status.mismatch; + } catch (error) { + versionTextEl.textContent = String(error); + versionBtn.disabled = false; + } +}; + +versionRestartBtn.onclick = async () => { + versionRestartBtn.disabled = true; + try { + await invoke('console_stop'); + } catch { + // Nothing to stop is fine: reconnectConsole starts a fresh one either way. + } + versionEl.hidden = true; + await reconnectConsole(); +}; + +// A page the agent's `console.mjs open` asked this window to show. +const pageLabel = (workflow) => (workflow || '').replace(/-/g, ' ').replace(/^./, (c) => c.toUpperCase()); + +function showAnnounced(notice) { + restarting = false; + currentPageEl.textContent = pageLabel(notice.workflow); + if (!consoleKnown) { + consoleKnown = true; + if (!pollTimer) pollTimer = setInterval(pollConsole, STATUS_POLL_MS); + } + markConsoleAlive(); + if (notice.url !== currentUrl) { + showState('Opening the page'); + loadFrame(notice.url); + } +} + +window.__TAURI__.event.listen('console-page', (event) => showAnnounced(event.payload)); + +function markConsoleAlive() { + consoleStatusEl.textContent = ''; + consoleAgainBtn.hidden = true; +} + +function markConsoleDead() { + consoleStatusEl.textContent = 'The console stopped.'; + consoleAgainBtn.hidden = false; +} + +consoleAgainBtn.onclick = () => reconnectConsole(); + +function setProjectDir(dir) { + projectDirEl.textContent = dir; + projectDirEl.title = dir; +} + +// The state `main()` read at startup: `pickFolder()` and the first-run +// checklist both need it once a folder lands, after the fact. +let appState = null; + +// Opens the OS folder picker. A cancelled pick (or a failed one) lands on the +// "No project folder chosen" state with a button that tries again. +async function pickFolder() { + try { + const dir = await invoke('pick_project_folder'); + if (!dir) { + showState('No project folder chosen', 'Choose folder', pickFolder); + return; + } + setProjectDir(dir); + if (appState) appState.projectDir = dir; + afterProjectKnown(); + } catch (error) { + showState(`Could not open the folder picker: ${error}`, 'Choose folder', pickFolder); + } +} + +// Once a project folder is known: the first-run checklist (once, until it +// passes) or straight to the launch card. +function afterProjectKnown() { + if (appState && !appState.firstRunDone) { + showFirstRun(appState); + } else { + showLaunchCard(); + } +} + +// Switches to a folder picked fresh: the Rust side tears the old project's +// agent and console down before the new one is remembered, so nothing from +// it carries over. Picking nothing (cancelled) leaves the current project as +// it was. +async function doChangeProject() { + showState('Choose the new project folder...'); + try { + const dir = await invoke('change_project'); + if (!dir) { + if (agentActive()) hideState(); + else afterProjectKnown(); + return; + } + setProjectDir(dir); + if (appState) appState.projectDir = dir; + restarting = false; + currentUrl = null; + frameReady = false; + currentPageEl.textContent = ''; + afterProjectKnown(); + } catch (error) { + showState(`Could not switch project: ${error}`, 'Try again', doChangeProject); + } +} + +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; + } + doChangeProject(); +} + +changeProjectBtn.onclick = changeProject; + +// The launcher passed `--agent`: start it at once, on its model, with the +// same bypass flags the terminal launcher itself always runs that agent with +// (it offers no permission-mode choice of its own). +async function autoStartAgent(state) { + launchAgentEl.value = state.autoStart; + if (typeof state.launchModel === 'string' && state.launchModel) launchModelEl.value = state.launchModel; + agentStatusEl.textContent = ''; + showState('Starting the agent...'); + const { cols, rows } = terminal.size(); + try { + await invoke('agent_start', { + kind: state.autoStart, + model: state.launchModel || null, + effort: null, + mode: 'bypass', + cols, + rows, + onOutput: agentChannel, + }); + terminal.focus(); + } catch (error) { + agentStatusEl.textContent = `Could not start the agent: ${error}`; + showLaunchCard(); + } +} + +// A page that just mounted registers its output channel and, if an agent +// already ran before it (a reload, or this is the window's first paint +// after one survived a restart), gets its recent output replayed onto a +// clean xterm at once instead of starting blank. +async function recoverAfterReload(snapshot) { + applyAgentState(snapshot, { skipReset: true }); + terminal.focus(); + hideState(); + consoleKnown = true; + if (!pollTimer) pollTimer = setInterval(pollConsole, STATUS_POLL_MS); + try { + const status = await invoke('console_status'); + if (status.state === 'running' && status.url) { + loadFrame(status.url); + } else { + onNoHello(); + } + } catch { + onNoHello(); + } +} + +async function main() { + let state; + try { + state = await invoke('app_state'); + } catch (error) { + showState(`Could not read the app state: ${error}`, 'Retry', main); + return; + } + appState = state; + if (AGENT_LABELS[state.lastAgent]) launchAgentEl.value = state.lastAgent; + if (typeof state.launchModel === 'string' && state.launchModel) launchModelEl.value = state.launchModel; + if (Number.isInteger(state.contextNudgePercent)) nudgePercent = state.contextNudgePercent; + if (state.termPanel) { + paneDock = state.termPanel.dock === 'right' ? 'right' : 'bottom'; + paneFraction = state.termPanel.fraction; + paneCollapsed = Boolean(state.termPanel.collapsed); + } + applyPaneLayout(); + await loadAgentAvailability(); + refreshLaunchCard(); + setInterval(pollMeter, METER_POLL_MS); + setInterval(updateBadge, BADGE_POLL_MS); + checkVersions(); + + let reattach = null; + try { + reattach = await invoke('agent_reattach', { onOutput: agentChannel }); + } catch { + // Nothing to reattach to is not fatal: carry on as a plain first paint. + } + if (reattach && reattach.state !== 'idle') { + if (state.projectDir) setProjectDir(state.projectDir); + await recoverAfterReload(reattach); + return; + } + + if (state.autoStart) { + if (state.projectDir) setProjectDir(state.projectDir); + await autoStartAgent(state); + return; + } + if (state.projectDir) { + setProjectDir(state.projectDir); + afterProjectKnown(); + } else { + pickFolder(); + } +} + +main(); diff --git a/plan2code-app/ui/index.html b/plan2code-app/ui/index.html new file mode 100644 index 0000000..c816ad7 --- /dev/null +++ b/plan2code-app/ui/index.html @@ -0,0 +1,212 @@ + + + + + + + Plan2Code + + + + +
+
+ Plan2Code + + + + +
+
+ + + + + + + + + + + +
+
+
+
+ + + + +
+
+
+
+ + + + + +
+
+
+
+ + + + + diff --git a/plan2code-app/ui/meter.js b/plan2code-app/ui/meter.js new file mode 100644 index 0000000..f48cf40 --- /dev/null +++ b/plan2code-app/ui/meter.js @@ -0,0 +1,15 @@ +// The context meter's pure decisions, kept out of app.js so they can be +// imported and tested without a DOM or `window.__TAURI__` (app.js touches +// both at module scope, the same reason the web console keeps its own pure +// logic in answers.js rather than app.js). + +/** + * Whether `reading` (what the `agent_context` command returns) should fire + * the Restart nudge at `nudgePercent`. Only a real or best-effort number + * counts, per the context policy (pathfinder Question 11): an estimate is + * not precise enough for "about 70%" to mean the window really is close to + * full, so an estimate-only agent gets the meter but never the nudge. + */ +export function nudgeDue(reading, nudgePercent) { + return (reading.kind === 'real' || reading.kind === 'besteffort') && reading.percent >= nudgePercent; +} diff --git a/plan2code-app/ui/terminal.js b/plan2code-app/ui/terminal.js new file mode 100644 index 0000000..a223830 --- /dev/null +++ b/plan2code-app/ui/terminal.js @@ -0,0 +1,89 @@ +// The terminal panel: an xterm instance. It knows nothing about agents; the +// page decides what goes in and where the keystrokes and size changes go. +// Needs xterm.js and addon-fit.js loaded first (they set window.Terminal and +// window.FitAddon), and withGlobalTauri for window.__TAURI__. + +const { invoke } = window.__TAURI__.core; + +export async function mountTerminal(container, { onInput, onResize }) { + // Windows' pseudo-terminal rewraps lines itself; xterm needs to know the + // backend and build to cope with that. + const platform = await invoke('platform_info'); + const windowsPty = platform.os === 'windows' + ? { backend: 'conpty', buildNumber: platform.windowsBuild } + : undefined; + + const term = new window.Terminal({ + cursorBlink: true, + fontFamily: 'Consolas, Menlo, "DejaVu Sans Mono", monospace', + fontSize: 13, + scrollback: 5000, + windowsPty, + }); + const fit = new window.FitAddon.FitAddon(); + term.loadAddon(fit); + term.open(container); + fit.fit(); + + // Keystrokes and pasted text go on as typed. + term.onData((data) => onInput(data)); + + // A size change in the page becomes a size change in the pseudo-terminal. + // The window's own resize event and the container's ResizeObserver both + // fire for the same change, and a drag can fire either one many times a + // second: `fit.fit()` stays immediate (cheap, local, keeps the screen + // looking right as it happens), but the pty resize call is debounced to + // one, on the settled size, so xterm and the pty always end up agreeing. + const RESIZE_DEBOUNCE_MS = 100; + let resizeTimer = null; + const refit = () => { + fit.fit(); + clearTimeout(resizeTimer); + resizeTimer = setTimeout(() => { + resizeTimer = null; + onResize(term.cols, term.rows); + }, RESIZE_DEBOUNCE_MS); + }; + window.addEventListener('resize', refit); + new ResizeObserver(refit).observe(container); + + // Copy on selection, and an explicit shortcut for it: Ctrl+C is the pty's + // own interrupt, so Ctrl+Shift+C (Windows, Linux) or Cmd+C (macOS) copies + // instead, without being typed. Ctrl+V / Cmd+V paste from the clipboard + // explicitly, rather than depending on the hidden textarea's own native + // paste making it through every webview the same way. + term.onSelectionChange(() => { + const text = term.getSelection(); + if (text && navigator.clipboard) navigator.clipboard.writeText(text).catch(() => {}); + }); + term.attachCustomKeyEventHandler((event) => { + if (event.type !== 'keydown' || !navigator.clipboard) return true; + const key = event.key.toLowerCase(); + if (key === 'c' && ((event.ctrlKey && event.shiftKey) || (event.metaKey && !event.ctrlKey))) { + const text = term.getSelection(); + if (text) navigator.clipboard.writeText(text).catch(() => {}); + return false; + } + if (key === 'v' && (event.ctrlKey || event.metaKey)) { + navigator.clipboard + .readText() + .then((text) => { + if (text) onInput(text); + }) + .catch(() => {}); + return false; + } + return true; + }); + + return { + size: () => ({ cols: term.cols, rows: term.rows }), + // A fresh agent starts on a clean screen. + reset() { + term.reset(); + fit.fit(); + }, + write: (data) => term.write(data), + focus: () => term.focus(), + }; +} diff --git a/scripts/check-versions.mjs b/scripts/check-versions.mjs new file mode 100644 index 0000000..dac2a54 --- /dev/null +++ b/scripts/check-versions.mjs @@ -0,0 +1,78 @@ +// Checks that every file carrying the product's version agrees, the desktop app's included: +// version.json, package.json, CHANGELOG.md's top heading, and the app's tauri.conf.json, +// package.json and Cargo.toml. The release-app workflow runs it before building, with +// --tag , so a release cannot ship an app that names another version. +// +// node scripts/check-versions.mjs [--tag v3.0.0] +// +// Exit 0 when they agree, 1 when they do not (each file and its version is printed). + +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + +const readJson = (file) => JSON.parse(fs.readFileSync(file, "utf8")).version; +const CARGO_VERSION = /^\s*version\s*=\s*"([^"]+)"/m; +const CHANGELOG_HEADING = /^##\s+v?(\d+\.\d+\.\d+)\b/m; + +/** Each file that carries the version, with how to read it. Paths are relative to the repo root. */ +const SOURCES = [ + { file: "version.json", read: readJson }, + { file: "package.json", read: readJson }, + { file: "CHANGELOG.md", read: (file) => fs.readFileSync(file, "utf8").match(CHANGELOG_HEADING)?.[1] }, + { file: "plan2code-app/src-tauri/tauri.conf.json", read: readJson }, + { file: "plan2code-app/package.json", read: readJson }, + { + file: "plan2code-app/src-tauri/Cargo.toml", + // The first `version =` line is the [package] one; dependencies come after it. + read: (file) => fs.readFileSync(file, "utf8").match(CARGO_VERSION)?.[1], + }, +]; + +/** + * `{ ok, versions: [{ file, version }], problems: [string] }` for the tree at `root`. A file that + * is missing or has no readable version is a problem, as is any disagreement, and a `tag` + * (`v3.0.0` or `3.0.0`) that names another version. + */ +export function checkVersions(root = ROOT, { tag } = {}) { + const versions = []; + const problems = []; + for (const { file, read } of SOURCES) { + let version; + try { + version = read(path.join(root, file)); + } catch (error) { + problems.push(`${file}: cannot be read (${error.code || error.message})`); + continue; + } + if (!version) { + problems.push(`${file}: no version found`); + continue; + } + versions.push({ file, version }); + } + const expected = versions.find((v) => v.file === "version.json")?.version; + for (const { file, version } of versions) { + if (expected && version !== expected) problems.push(`${file} says ${version}, version.json says ${expected}`); + } + if (tag && expected && tag.replace(/^v/, "") !== expected) { + problems.push(`the release tag ${tag} names ${tag.replace(/^v/, "")}, version.json says ${expected}`); + } + return { ok: problems.length === 0, versions, problems }; +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const args = process.argv.slice(2); + const tagAt = args.indexOf("--tag"); + const tag = tagAt >= 0 ? args[tagAt + 1] : undefined; + if (tagAt >= 0 && !tag) { + console.error("Usage: node scripts/check-versions.mjs [--tag v3.0.0]"); + process.exit(2); + } + const { ok, versions, problems } = checkVersions(ROOT, { tag }); + for (const { file, version } of versions) console.log(`${version.padEnd(10)} ${file}`); + for (const problem of problems) console.error(`MISMATCH: ${problem}`); + process.exit(ok ? 0 : 1); +} diff --git a/scripts/test-app-meter.mjs b/scripts/test-app-meter.mjs new file mode 100644 index 0000000..c166573 --- /dev/null +++ b/scripts/test-app-meter.mjs @@ -0,0 +1,26 @@ +// Tests for plan2code-app/ui/meter.js. Run with: node --test scripts/test-app-meter.mjs +// +// app.js itself cannot be imported here (it touches `document` and +// `window.__TAURI__` at module scope), which is why the nudge decision lives +// in its own pure module. + +import test from "node:test"; +import assert from "node:assert/strict"; +import { nudgeDue } from "../plan2code-app/ui/meter.js"; + +test("meter: a real reading at or past the threshold nudges", () => { + assert.equal(nudgeDue({ kind: "real", percent: 70 }, 70), true); + assert.equal(nudgeDue({ kind: "real", percent: 69 }, 70), false); +}); + +test("meter: a best-effort reading nudges the same as a real one", () => { + assert.equal(nudgeDue({ kind: "besteffort", percent: 80 }, 70), true); +}); + +test("meter: an estimate never nudges, however high its percent", () => { + assert.equal(nudgeDue({ kind: "estimate", percent: 99 }, 70), false); +}); + +test("meter: unknown never nudges", () => { + assert.equal(nudgeDue({ kind: "unknown" }, 70), false); +}); diff --git a/scripts/test-check-versions.mjs b/scripts/test-check-versions.mjs new file mode 100644 index 0000000..26e3553 --- /dev/null +++ b/scripts/test-check-versions.mjs @@ -0,0 +1,88 @@ +// Tests for scripts/check-versions.mjs. Run with: node --test scripts/test-check-versions.mjs +// +// Each test builds a small tree in a temp folder holding the six files that carry the version, +// so the check is exercised without depending on what the real repo says today. + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { checkVersions } from "./check-versions.mjs"; + +const SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), "check-versions.mjs"); + +/** A tree with every version file at `version`, each overridable by its path in `over`. */ +function tree(t, version = "3.0.0", over = {}) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-versions-")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const files = { + "version.json": JSON.stringify({ name: "Plan2Code", version }), + "package.json": JSON.stringify({ name: "plan2code", version }), + "CHANGELOG.md": `# Changelog\n\n## v${version}\n\n### Added\n\n- something\n\n## v0.0.1\n`, + "plan2code-app/src-tauri/tauri.conf.json": JSON.stringify({ productName: "Plan2Code", version }), + "plan2code-app/package.json": JSON.stringify({ name: "plan2code-app", version }), + "plan2code-app/src-tauri/Cargo.toml": `[package]\nname = "plan2code-app"\nversion = "${version}"\n\n[dependencies]\nserde = { version = "1" }\n`, + ...over, + }; + for (const [file, content] of Object.entries(files)) { + if (content === null) continue; + fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); + fs.writeFileSync(path.join(root, file), content); + } + return root; +} + +test("versions: six files at one version pass, and each is listed", (t) => { + const result = checkVersions(tree(t)); + assert.equal(result.ok, true, result.problems.join("; ")); + assert.equal(result.versions.length, 6); + assert.ok(result.versions.every((v) => v.version === "3.0.0")); +}); + +test("versions: the app's tauri.conf.json disagreeing is named", (t) => { + const root = tree(t, "3.0.0", { + "plan2code-app/src-tauri/tauri.conf.json": JSON.stringify({ version: "2.11.0" }), + }); + const result = checkVersions(root); + assert.equal(result.ok, false); + assert.deepEqual(result.problems, ["plan2code-app/src-tauri/tauri.conf.json says 2.11.0, version.json says 3.0.0"]); +}); + +test("versions: Cargo.toml's package version counts, a dependency's does not", (t) => { + const root = tree(t, "3.0.0", { + "plan2code-app/src-tauri/Cargo.toml": '[package]\nname = "x"\nversion = "3.1.0"\n', + }); + assert.match(checkVersions(root).problems[0], /Cargo\.toml says 3\.1\.0/); +}); + +test("versions: the changelog's top heading is the one read", (t) => { + const root = tree(t, "3.0.0", { "CHANGELOG.md": "# Changelog\n\n## v3.1.0\n\n## v3.0.0\n" }); + assert.match(checkVersions(root).problems[0], /CHANGELOG\.md says 3\.1\.0/); +}); + +test("versions: a missing file or an unreadable version is a problem, not a throw", (t) => { + const root = tree(t, "3.0.0", { "plan2code-app/package.json": null, "CHANGELOG.md": "# Changelog\n" }); + const problems = checkVersions(root).problems; + assert.ok(problems.some((p) => p.startsWith("plan2code-app/package.json: cannot be read")), problems.join("; ")); + assert.ok(problems.includes("CHANGELOG.md: no version found"), problems.join("; ")); +}); + +test("versions: a release tag must name the same version, with or without the v", (t) => { + const root = tree(t); + assert.equal(checkVersions(root, { tag: "v3.0.0" }).ok, true); + assert.equal(checkVersions(root, { tag: "3.0.0" }).ok, true); + const bad = checkVersions(root, { tag: "v3.0.1" }); + assert.equal(bad.ok, false); + assert.match(bad.problems[0], /release tag v3\.0\.1 names 3\.0\.1/); +}); + +test("versions: the command exits 0 on agreement and 1 on a mismatch", () => { + // The real tree: the exit code and the output agree with each other, whatever it says today. + const real = spawnSync(process.execPath, [SCRIPT], { encoding: "utf8" }); + assert.equal(real.status, real.stderr.includes("MISMATCH") ? 1 : 0); + const noTag = spawnSync(process.execPath, [SCRIPT, "--tag"], { encoding: "utf8" }); + assert.equal(noTag.status, 2); +}); diff --git a/scripts/test-standalone-check.mjs b/scripts/test-standalone-check.mjs new file mode 100644 index 0000000..2ba7df3 --- /dev/null +++ b/scripts/test-standalone-check.mjs @@ -0,0 +1,48 @@ +// Standalone check: with PLAN2CODE_EMBED_ORIGIN unset the console page's +// Content-Security-Policy is byte for byte the value it always was. Guards +// the embed opt-in from ever narrowing or widening the default header. +// Shared setup: ./web-console-test-helpers.mjs. + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { spawn } from "node:child_process"; +import { cookieFor, ENV, HOME, ROOT } from "./web-console-test-helpers.mjs"; + +const SERVER_JS = path.join(ROOT, "src", "web-console", "server.mjs"); + +const EXPECTED_CSP = + "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; " + + "font-src 'self'; connect-src 'self'; media-src 'self'; " + + "base-uri 'none'; form-action 'none'; frame-ancestors 'none'"; + +test("with PLAN2CODE_EMBED_ORIGIN unset the page CSP is the pre-embed string byte for byte", async () => { + const dir = fs.mkdtempSync(path.join(HOME, "standalone-")); + fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ sid: path.basename(dir), phase: "collecting" })); + const env = { ...ENV }; + delete env.PLAN2CODE_EMBED_ORIGIN; + const child = spawn(process.execPath, [SERVER_JS, `--session=${dir}`, "--token=t", `--project=${dir}`], { + env, + stdio: ["ignore", "pipe", "ignore"], + windowsHide: true, + }); + try { + const ready = await new Promise((resolve, reject) => { + let buf = ""; + child.stdout.on("data", (c) => { + buf += c; + const line = buf.split("\n").find((l) => l.includes('"ready"')); + if (line) resolve(JSON.parse(line)); + }); + child.on("exit", () => reject(new Error("server exited before it was ready"))); + }); + const base = `http://127.0.0.1:${ready.port}`; + const res = await fetch(base + "/", { headers: { cookie: cookieFor(base, "t"), connection: "close" } }); + assert.equal(res.status, 200); + await res.arrayBuffer(); + assert.equal(res.headers.get("content-security-policy"), EXPECTED_CSP); + } finally { + child.kill(); + } +}); diff --git a/scripts/test-web-console-embed.mjs b/scripts/test-web-console-embed.mjs new file mode 100644 index 0000000..ae0d06e --- /dev/null +++ b/scripts/test-web-console-embed.mjs @@ -0,0 +1,105 @@ +// Web console tests: PLAN2CODE_EMBED_ORIGIN opt-in embed mode. With the +// variable unset the page's CSP keeps frame-ancestors 'none'; set to exactly +// one allowed origin it names that origin; set to anything else it is ignored +// and 'none' stands. Each case boots its own server with the variable in its +// environment. Shared setup: ./web-console-test-helpers.mjs. + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { spawn } from "node:child_process"; +import { cookieFor, ENV, HOME, ROOT } from "./web-console-test-helpers.mjs"; + +const SERVER_JS = path.join(ROOT, "src", "web-console", "server.mjs"); + +// Boot a session server whose environment carries PLAN2CODE_EMBED_ORIGIN set +// to `origin` (or does not carry it at all when origin is undefined). Returns +// the child and its base URL; the caller always kills the child. +async function bootServer(origin) { + const dir = fs.mkdtempSync(path.join(HOME, "embed-")); + fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ sid: path.basename(dir), phase: "collecting" })); + const env = { ...ENV }; + if (origin === undefined) delete env.PLAN2CODE_EMBED_ORIGIN; + else env.PLAN2CODE_EMBED_ORIGIN = origin; + const child = spawn(process.execPath, [SERVER_JS, `--session=${dir}`, "--token=t", `--project=${dir}`], { + env, + stdio: ["ignore", "pipe", "ignore"], + windowsHide: true, + }); + const ready = await new Promise((resolve, reject) => { + let buf = ""; + child.stdout.on("data", (c) => { + buf += c; + const line = buf.split("\n").find((l) => l.includes('"ready"')); + if (line) resolve(JSON.parse(line)); + }); + child.on("exit", () => reject(new Error("server exited before it was ready"))); + }); + return { child, base: `http://127.0.0.1:${ready.port}` }; +} + +// Fetch the session page with its token cookie and resolve to the page's +// content-security-policy header. +async function cspWith(origin) { + const { child, base } = await bootServer(origin); + try { + const res = await fetch(base + "/", { headers: { cookie: cookieFor(base, "t"), connection: "close" } }); + assert.equal(res.status, 200); + await res.arrayBuffer(); + return res.headers.get("content-security-policy"); + } finally { + child.kill(); + } +} + +// Fetch the sign-in redirect and resolve to its set-cookie header. +async function cookieWith(origin) { + const { child, base } = await bootServer(origin); + try { + const res = await fetch(`${base}/s/t/`, { redirect: "manual" }); + assert.equal(res.status, 302); + await res.arrayBuffer(); + return res.headers.get("set-cookie"); + } finally { + child.kill(); + } +} + +test("with PLAN2CODE_EMBED_ORIGIN unset the header keeps frame-ancestors 'none'", async () => { + const csp = await cspWith(undefined); + assert.match(csp, /frame-ancestors 'none'$/); +}); + +test("each allowed origin is named in frame-ancestors", async () => { + for (const origin of ["http://127.0.0.1:5173", "http://localhost:8080", "http://tauri.localhost", "https://tauri.localhost", "tauri://localhost"]) { + const csp = await cspWith(origin); + assert.ok(csp.endsWith(`frame-ancestors ${origin}`), `${origin}: ${csp}`); + } +}); + +test("the session cookie is Strict standalone and None; Secure under embed", async () => { + const plain = await cookieWith(undefined); + assert.match(plain, /SameSite=Strict/); + assert.doesNotMatch(plain, /SameSite=None/); + const embedded = await cookieWith("http://tauri.localhost"); + assert.match(embedded, /SameSite=None; Secure/); +}); + +test("anything but exactly one allowed origin keeps frame-ancestors 'none'", async () => { + const rejected = [ + "https://example.com", + "", + "http://127.0.0.1:5173 https://example.com", + "http://127.0.0.1:5173;evil", + "http://127.0.0.1:0", + "http://127.0.0.1:99999", + "http://127.0.0.1", + "https://127.0.0.1:443", + "*", + ]; + for (const origin of rejected) { + const csp = await cspWith(origin); + assert.match(csp, /frame-ancestors 'none'$/, `${JSON.stringify(origin)}: ${csp}`); + } +}); diff --git a/scripts/test-web-console-in-app.mjs b/scripts/test-web-console-in-app.mjs new file mode 100644 index 0000000..c553d0a --- /dev/null +++ b/scripts/test-web-console-in-app.mjs @@ -0,0 +1,270 @@ +// Web console tests: the desktop app's in-app signal for `open`. Under the app +// (PLAN2CODE_IN_APP=1) `open` never launches a browser, reuses the app's +// session and tells the app's announce URL which page to show; with the +// variable unset it behaves as it always did. Shared setup: +// ./web-console-test-helpers.mjs. + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import http from "node:http"; +import path from "node:path"; +import { spawn } from "node:child_process"; +import { CONSOLE_CLI, ENV, HOME, cli } from "./web-console-test-helpers.mjs"; +import { announcePage, inAppSignal } from "../src/web-console/in-app.mjs"; + +// A stand-in for the app's announce endpoint: records every POST it accepts. +// `current` is the session the window shows now: what `GET /session` answers. +async function announceServer(token, current = null) { + const seen = []; + const server = http.createServer((req, res) => { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", () => { + if (req.headers["x-plan2code-token"] !== token) { + res.writeHead(403).end(); + return; + } + if (req.method === "GET" && req.url === "/session") { + res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(current)); + return; + } + seen.push(JSON.parse(body)); + res.writeHead(204).end(); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return { seen, url: `http://127.0.0.1:${server.address().port}/page`, close: () => server.close() }; +} + +// `open` run asynchronously (the announce server lives in this process, so a +// blocking spawn would deadlock). Resolves { status, json }. +function openAsync(args, { cwd, env }) { + return new Promise((resolve) => { + const child = spawn(process.execPath, [CONSOLE_CLI, ...args], { cwd, env: { ...ENV, ...env }, windowsHide: true }); + let out = ""; + child.stdout.on("data", (c) => (out += c)); + child.on("close", (status) => { + const line = out.trim().split("\n").filter((l) => l.startsWith("{")).pop(); + resolve({ status, json: line ? JSON.parse(line) : null }); + }); + }); +} + +function project(name) { + const dir = fs.mkdtempSync(path.join(HOME, `${name}-`)); + return dir; +} + +// A browser stand-in: PLAN2CODE_BROWSER runs this with the link appended. +function browserRecorder() { + const log = path.join(HOME, `browser-${Date.now()}-${Math.random().toString(16).slice(2)}.log`); + const script = path.join(HOME, `record-${path.basename(log)}.mjs`); + fs.writeFileSync(script, `import fs from "node:fs"; fs.appendFileSync(${JSON.stringify(log)}, process.argv[2] + "\\n");`); + const command = `"${process.execPath}" "${script}"`; + return { command, calls: () => (fs.existsSync(log) ? fs.readFileSync(log, "utf8").trim().split("\n") : []) }; +} + +const withBrowser = (recorder) => { + const env = { PLAN2CODE_BROWSER: recorder.command, PLAN2CODE_NO_BROWSER: "" }; + return env; +}; + +test("inAppSignal is null unless PLAN2CODE_IN_APP is 1", () => { + assert.equal(inAppSignal({}), null); + assert.equal(inAppSignal({ PLAN2CODE_IN_APP: "0" }), null); + assert.deepEqual( + inAppSignal({ PLAN2CODE_IN_APP: "1", PLAN2CODE_CONSOLE_SID: "s", PLAN2CODE_APP_ANNOUNCE: "http://127.0.0.1:1/x", PLAN2CODE_APP_TOKEN: "t" }), + { sid: "s", announce: "http://127.0.0.1:1/x", token: "t" } + ); +}); + +test("announcePage sends the token, and fails quietly on a wrong token, a dead port and a non-loopback host", async () => { + const app = await announceServer("good"); + try { + assert.equal(await announcePage({ announce: app.url, token: "good" }, { url: "u" }), true); + assert.deepEqual(app.seen, [{ url: "u" }]); + assert.equal(await announcePage({ announce: app.url, token: "bad" }, { url: "u" }), false); + assert.equal(await announcePage({ announce: "http://127.0.0.1:1/x", token: "t" }, { url: "u" }), false); + assert.equal(await announcePage({ announce: "http://example.com/x", token: "t" }, { url: "u" }), false); + assert.equal(await announcePage({ announce: "not a url", token: "t" }, { url: "u" }), false); + } finally { + app.close(); + } +}); + +test("under the app, open reuses the app's session, announces the page and launches no browser", async () => { + const cwd = project("inapp"); + const first = cli(["open", "--workflow", "dashboard", "--no-open"], { cwd }); + const appSid = first.json.sid; + const app = await announceServer("tok", { sid: appSid, url: first.json.url, workflow: "dashboard" }); + const browser = browserRecorder(); + try { + const res = await openAsync(["open", "--workflow", "dashboard"], { + cwd, + env: { + ...withBrowser(browser), + PLAN2CODE_IN_APP: "1", + PLAN2CODE_APP_ANNOUNCE: app.url, + PLAN2CODE_APP_TOKEN: "tok", + }, + }); + assert.equal(res.status, 0); + assert.equal(res.json.sid, appSid, "the window's own session is reused, not a second console"); + assert.equal(res.json.reused, true); + assert.equal(res.json.inApp, true); + assert.equal(res.json.announced, true); + assert.equal(app.seen.length, 1); + assert.equal(app.seen[0].sid, appSid); + assert.equal(app.seen[0].url, first.json.url); + assert.equal(app.seen[0].workflow, "dashboard"); + await new Promise((r) => setTimeout(r, 700)); + assert.deepEqual(browser.calls(), [], "no browser is launched under the app"); + } finally { + app.close(); + cli(["stop", "--session", appSid], { cwd, expectFail: true }); + } +}); + +test("under the app, a hop on the app's session keeps the same url and reports the new workflow", async () => { + const cwd = project("inapp-hop"); + const first = cli(["open", "--workflow", "dashboard", "--no-open"], { cwd }); + const app = await announceServer("tok", { sid: first.json.sid, url: first.json.url, workflow: "dashboard" }); + try { + const res = await openAsync(["open", "--workflow", "pathfinder"], { + cwd, + env: { PLAN2CODE_IN_APP: "1", PLAN2CODE_APP_ANNOUNCE: app.url, PLAN2CODE_APP_TOKEN: "tok" }, + }); + assert.equal(res.json.url, first.json.url); + assert.equal(app.seen[0].workflow, "pathfinder"); + } finally { + app.close(); + cli(["stop", "--session", first.json.sid], { cwd, expectFail: true }); + } +}); + +test("under the app, a wrong token is reported and the page is not sent to a browser", async () => { + const cwd = project("inapp-bad"); + const first = cli(["open", "--workflow", "dashboard", "--no-open"], { cwd }); + const app = await announceServer("right"); + const browser = browserRecorder(); + try { + const res = await openAsync(["open", "--workflow", "dashboard"], { + cwd, + env: { + ...withBrowser(browser), + PLAN2CODE_IN_APP: "1", + PLAN2CODE_CONSOLE_SID: first.json.sid, + PLAN2CODE_APP_ANNOUNCE: app.url, + PLAN2CODE_APP_TOKEN: "wrong", + }, + }); + assert.equal(res.json.inApp, true); + assert.equal(res.json.announced, false); + assert.equal(app.seen.length, 0); + await new Promise((r) => setTimeout(r, 700)); + assert.deepEqual(browser.calls(), []); + } finally { + app.close(); + cli(["stop", "--session", first.json.sid], { cwd, expectFail: true }); + } +}); + +test("under the app, a session that is gone gets a fresh one and its address announced", async () => { + const cwd = project("inapp-gone"); + const app = await announceServer("tok"); + try { + const res = await openAsync(["open", "--workflow", "dashboard"], { + cwd, + env: { PLAN2CODE_IN_APP: "1", PLAN2CODE_CONSOLE_SID: "20200101-000000-nothere", PLAN2CODE_APP_ANNOUNCE: app.url, PLAN2CODE_APP_TOKEN: "tok" }, + }); + assert.equal(res.status, 0); + assert.notEqual(res.json.sid, "20200101-000000-nothere"); + assert.equal(app.seen[0].url, res.json.url); + cli(["stop", "--session", res.json.sid], { cwd, expectFail: true }); + } finally { + app.close(); + } +}); + +test("two app windows never receive each other's pages", async () => { + const cwdA = project("win-a"); + const cwdB = project("win-b"); + const a = cli(["open", "--workflow", "dashboard", "--no-open"], { cwd: cwdA }); + const b = cli(["open", "--workflow", "dashboard", "--no-open"], { cwd: cwdB }); + const appA = await announceServer("ta", { sid: a.json.sid, url: a.json.url, workflow: "dashboard" }); + const appB = await announceServer("tb", { sid: b.json.sid, url: b.json.url, workflow: "dashboard" }); + try { + const envFor = (r, app, token) => ({ PLAN2CODE_IN_APP: "1", PLAN2CODE_APP_ANNOUNCE: app.url, PLAN2CODE_APP_TOKEN: token }); + await openAsync(["open", "--workflow", "plan"], { cwd: cwdA, env: envFor(a, appA, "ta") }); + await openAsync(["open", "--workflow", "quick-task"], { cwd: cwdB, env: envFor(b, appB, "tb") }); + assert.deepEqual(appA.seen.map((p) => [p.sid, p.workflow]), [[a.json.sid, "plan"]]); + assert.deepEqual(appB.seen.map((p) => [p.sid, p.workflow]), [[b.json.sid, "quick-task"]]); + } finally { + appA.close(); + appB.close(); + cli(["stop", "--session", a.json.sid], { cwd: cwdA, expectFail: true }); + cli(["stop", "--session", b.json.sid], { cwd: cwdB, expectFail: true }); + } +}); + +test("without the signal, open still launches the browser and reports nothing about an app", async () => { + const cwd = project("bare"); + const browser = browserRecorder(); + const res = await openAsync(["open", "--workflow", "dashboard"], { cwd, env: withBrowser(browser) }); + try { + assert.equal(res.status, 0); + assert.equal(res.json.inApp, undefined); + assert.equal(res.json.announced, undefined); + let calls = []; + for (let i = 0; i < 30 && calls.length === 0; i++) { + await new Promise((r) => setTimeout(r, 100)); + calls = browser.calls(); + } + assert.ok(calls.length >= 1, "the browser command ran"); + assert.match(calls[0], /^http:\/\/127\.0\.0\.1:\d+\/s\//); + } finally { + cli(["stop", "--session", res.json.sid], { cwd, expectFail: true }); + } +}); + +test("the window's session, not the environment's, decides what open resumes", async () => { + const cwd = project("inapp-ask"); + const stale = cli(["open", "--workflow", "dashboard", "--no-open"], { cwd }); + const live = cli(["open", "--workflow", "dashboard", "--no-open"], { cwd }); + const app = await announceServer("tok", { sid: live.json.sid, url: live.json.url, workflow: "dashboard" }); + try { + const res = await openAsync(["open", "--workflow", "plan"], { + cwd, + env: { PLAN2CODE_IN_APP: "1", PLAN2CODE_CONSOLE_SID: stale.json.sid, PLAN2CODE_APP_ANNOUNCE: app.url, PLAN2CODE_APP_TOKEN: "tok" }, + }); + assert.equal(res.json.sid, live.json.sid); + assert.equal(app.seen[0].sid, live.json.sid); + } finally { + app.close(); + cli(["stop", "--session", stale.json.sid], { cwd, expectFail: true }); + cli(["stop", "--session", live.json.sid], { cwd, expectFail: true }); + } +}); + +test("with nothing shown in the window yet, open makes the first session and announces it", async () => { + const cwd = project("inapp-first"); + const app = await announceServer("tok", null); + const browser = browserRecorder(); + try { + const res = await openAsync(["open", "--workflow", "dashboard"], { + cwd, + env: { ...withBrowser(browser), PLAN2CODE_IN_APP: "1", PLAN2CODE_APP_ANNOUNCE: app.url, PLAN2CODE_APP_TOKEN: "tok" }, + }); + assert.equal(res.status, 0); + assert.equal(res.json.announced, true); + assert.equal(app.seen.length, 1); + assert.equal(app.seen[0].sid, res.json.sid); + assert.equal(app.seen[0].url, res.json.url); + await new Promise((r) => setTimeout(r, 700)); + assert.deepEqual(browser.calls(), [], "the first page goes to the app too, not a browser"); + cli(["stop", "--session", res.json.sid], { cwd, expectFail: true }); + } finally { + app.close(); + } +}); diff --git a/src/web-console/in-app.mjs b/src/web-console/in-app.mjs new file mode 100644 index 0000000..8de3e9d --- /dev/null +++ b/src/web-console/in-app.mjs @@ -0,0 +1,74 @@ +// The desktop app's signal to an agent it runs: when the agent's own process +// carries these variables, `open` shows its page inside the app window instead +// of the system browser. Unset (every plain terminal), nothing here does anything. +// +// PLAN2CODE_IN_APP "1" turns it on +// PLAN2CODE_CONSOLE_SID (optional) a session to fall back on when the app cannot be asked +// PLAN2CODE_APP_ANNOUNCE this window's loopback URL to tell about a page +// PLAN2CODE_APP_TOKEN the token that URL wants +// +// Every value belongs to one app window, so two windows never meet. + +import http from "node:http"; + +/** The signal, or null outside the app. */ +export function inAppSignal(env = process.env) { + if (env.PLAN2CODE_IN_APP !== "1") return null; + return { + sid: env.PLAN2CODE_CONSOLE_SID || "", + announce: env.PLAN2CODE_APP_ANNOUNCE || "", + token: env.PLAN2CODE_APP_TOKEN || "", + }; +} + +function request(signal, method, path, body, timeoutMs) { + return new Promise((resolve) => { + let target; + try { + target = new URL(path, signal.announce); + } catch { + return resolve(null); + } + if (target.protocol !== "http:" || !["127.0.0.1", "localhost"].includes(target.hostname)) { + return resolve(null); + } + const headers = { "x-plan2code-token": signal.token }; + if (body !== undefined) { + headers["content-type"] = "application/json"; + headers["content-length"] = Buffer.byteLength(body); + } + const req = http.request(target, { method, timeout: timeoutMs, headers }, (res) => { + let text = ""; + res.on("data", (c) => (text += c)); + res.on("end", () => resolve({ status: res.statusCode, text })); + }); + req.on("timeout", () => req.destroy()); + req.on("error", () => resolve(null)); + req.end(body); + }); +} + +/** + * The session the app's window shows right now, asked of the app: an agent's + * environment is fixed when it starts, the window's session is not. "" when the + * app has nothing to show yet or cannot be reached. + */ +export async function currentSession(signal, timeoutMs = 1500) { + const res = await request(signal, "GET", "/session", undefined, timeoutMs); + if (!res || res.status !== 200) return ""; + try { + return String(JSON.parse(res.text)?.sid || ""); + } catch { + return ""; + } +} + +/** + * Tell the app which page to show. Resolves true when the app answered 2xx, + * false on any failure (no app listening, wrong token, a timeout): the caller + * says so and prints the URL, it never falls back to a browser. + */ +export async function announcePage(signal, page, timeoutMs = 1500) { + const res = await request(signal, "POST", "/page", JSON.stringify(page), timeoutMs); + return Boolean(res && res.status >= 200 && res.status < 300); +}